<?php

namespace App\Http\Controllers\Admin\Care;

use App\Http\Controllers\Controller;
use App\Models\Care\CarePlan;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CarePlanController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = CarePlan::query()->with(['profile.customer', 'nurse']);
        $query->when($request->care_profile_id, fn($q, $v) => $q->where('care_profile_id', $v));
        $query->when($request->plan_date, fn($q, $v) => $q->whereDate('plan_date', $v));
        $query->when($request->nurse_id, fn($q, $v) => $q->where('nurse_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([
            'care_profile_id' => 'required|exists:care_profiles,id',
            'plan_date' => 'required|date',
            'stage' => 'nullable|string|max:50',
            'items' => 'nullable|array',
            'nurse_id' => 'nullable|exists:users,id',
        ]);
        $validated['status'] = 0;
        return $this->success(CarePlan::create($validated));
    }

    public function show(CarePlan $carePlan): JsonResponse
    {
        return $this->success($carePlan->load(['profile.customer', 'nurse', 'records']));
    }

    public function update(Request $request, CarePlan $carePlan): JsonResponse
    {
        $validated = $request->validate([
            'plan_date' => 'sometimes|date',
            'stage' => 'nullable|string|max:50',
            'items' => 'nullable|array',
            'nurse_id' => 'nullable|exists:users,id',
            'status' => 'sometimes|integer|in:0,1,2',
        ]);
        $carePlan->update($validated);
        return $this->success($carePlan);
    }

    public function destroy(CarePlan $carePlan): JsonResponse
    {
        $carePlan->delete();
        return $this->success(null);
    }
}
