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

class NannyOrderController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = NannyOrder::query()->with(['customer','nanny']);
        $query->when($request->customer_id, fn($q, $v) => $q->where('customer_id', $v));
        $query->when($request->nanny_id, fn($q, $v) => $q->where('nanny_id', $v));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));
        return $this->paginate($query->latest()->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'customer_id'=>'required|exists:customers,id','nanny_id'=>'nullable|exists:nannies,id',
            'order_no'=>'required|string|max:50|unique:nanny_orders','service_type'=>'nullable|integer|in:1,2',
            'start_date'=>'nullable|date','end_date'=>'nullable|date|after_or_equal:start_date',
            'days'=>'nullable|integer|min:1','price'=>'nullable|numeric|min:0','remark'=>'nullable|string',
        ]);
        $validated['status'] = 0;
        $validated['created_by'] = auth()->id();
        return $this->success(NannyOrder::create($validated));
    }

    public function show(NannyOrder $nannyOrder): JsonResponse { return $this->success($nannyOrder->load(['customer','nanny','reviews'])); }

    public function update(Request $request, NannyOrder $nannyOrder): JsonResponse
    {
        if ($nannyOrder->status >= 4) return $this->error('已完成/取消的订单不可修改', 40001);
        $validated = $request->validate([
            'nanny_id'=>'nullable|exists:nannies,id','start_date'=>'nullable|date','end_date'=>'nullable|date',
            'days'=>'nullable|integer|min:1','price'=>'nullable|numeric|min:0','status'=>'sometimes|integer|in:0,1,2,3,4,5',
            'match_candidates'=>'nullable|array','remark'=>'nullable|string',
        ]);
        $nannyOrder->update($validated);
        if (isset($validated['nanny_id']) && $validated['nanny_id']) {
            $nannyOrder->nanny->update(['status' => 2]);
        }
        return $this->success($nannyOrder);
    }

    public function destroy(NannyOrder $nannyOrder): JsonResponse
    {
        if ($nannyOrder->status >= 2) return $this->error('已签约后不可删除', 40001);
        $nannyOrder->delete();
        return $this->success(null);
    }
}
