<?php
namespace App\Http\Controllers\Admin\Nanny;
use App\Http\Controllers\Controller;
use App\Models\Nanny\Nanny;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class NannyController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Nanny::query();
        $query->when($request->name, fn($q, $v) => $q->where('name', 'like', "%{$v}%"));
        $query->when($request->level, fn($q, $v) => $q->where('level', $v));
        $query->when($request->status, fn($q, $v) => $q->where('status', $v));
        $query->when($request->cooperation_type, fn($q, $v) => $q->where('cooperation_type', $v));
        return $this->paginate($query->latest()->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name'=>'required|string|max:50','phone'=>'nullable|string|max:20','id_card'=>'nullable|string|max:20',
            'level'=>'nullable|integer|in:1,2,3,4','skills'=>'nullable|array','experience_years'=>'nullable|integer|min:0',
            'health_cert'=>'nullable|string|max:255','cooperation_type'=>'nullable|integer|in:1,2,3',
            'base_salary'=>'nullable|numeric|min:0','introduction'=>'nullable|string','status'=>'sometimes|integer|in:1,2,3,4',
        ]);
        return $this->success(Nanny::create($validated));
    }

    public function show(Nanny $nanny): JsonResponse { return $this->success($nanny->load(['orders.customer','schedules'])); }

    public function update(Request $request, Nanny $nanny): JsonResponse
    {
        $validated = $request->validate([
            'name'=>'sometimes|string|max:50','phone'=>'nullable|string|max:20','level'=>'nullable|integer|in:1,2,3,4',
            'skills'=>'nullable|array','experience_years'=>'nullable|integer|min:0','cooperation_type'=>'nullable|integer|in:1,2,3',
            'base_salary'=>'nullable|numeric|min:0','introduction'=>'nullable|string','status'=>'sometimes|integer|in:1,2,3,4',
        ]);
        $nanny->update($validated);
        return $this->success($nanny);
    }

    public function destroy(Nanny $nanny): JsonResponse
    {
        if ($nanny->status === 2) return $this->error('服务中的月嫂无法删除', 40001);
        $nanny->delete();
        return $this->success(null);
    }
}
