<?php

namespace App\Http\Controllers\Admin\Care;

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

class CareRecordController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = CareRecord::query()->with(['profile.customer', 'nurse']);
        $query->when($request->care_profile_id, fn($q, $v) => $q->where('care_profile_id', $v));
        $query->when($request->care_plan_id, fn($q, $v) => $q->where('care_plan_id', $v));
        $query->when($request->type, fn($q, $v) => $q->where('type', $v));
        $query->when($request->nurse_id, fn($q, $v) => $q->where('nurse_id', $v));

        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',
            'care_plan_id' => 'nullable|exists:care_plans,id',
            'type' => 'nullable|integer|in:1,2',
            'items' => 'nullable|array',
            'remark' => 'nullable|string',
            'images' => 'nullable|array',
            'recorded_at' => 'sometimes|date',
        ]);
        $validated['nurse_id'] = auth()->id();
        $validated['recorded_at'] = $validated['recorded_at'] ?? now();

        return $this->success(CareRecord::create($validated));
    }

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

    public function update(Request $request, CareRecord $careRecord): JsonResponse
    {
        $validated = $request->validate([
            'type' => 'nullable|integer|in:1,2',
            'items' => 'nullable|array',
            'remark' => 'nullable|string',
            'images' => 'nullable|array',
        ]);
        $careRecord->update($validated);
        return $this->success($careRecord);
    }

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