<?php

namespace App\Http\Controllers\Admin\Meal;

use App\Http\Controllers\Controller;
use App\Models\Meal\DailyMealPlan;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DailyMealPlanController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = DailyMealPlan::query()->with(['customer', 'review']);
        $query->when($request->customer_id, fn($q, $v) => $q->where('customer_id', $v));
        $query->when($request->plan_date, fn($q, $v) => $q->whereDate('plan_date', $v));
        $query->when($request->meal_type, fn($q, $v) => $q->where('meal_type', $v));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));

        return $this->paginate($query->latest()->paginate($request->input('per_page', 30)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'plan_date' => 'required|date',
            'meal_type' => 'required|integer|in:1,2,3,4,5',
            'dishes' => 'nullable|array',
            'special_note' => 'nullable|string',
        ]);
        $validated['status'] = 0;

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

    public function show(DailyMealPlan $dailyMealPlan): JsonResponse
    {
        return $this->success($dailyMealPlan->load(['customer', 'review']));
    }

    public function update(Request $request, DailyMealPlan $dailyMealPlan): JsonResponse
    {
        if ($dailyMealPlan->status >= 2) {
            return $this->error('已送达的排餐不可修改', 40001);
        }
        $validated = $request->validate([
            'meal_type' => 'sometimes|integer|in:1,2,3,4,5',
            'dishes' => 'nullable|array',
            'special_note' => 'nullable|string',
        ]);
        $dailyMealPlan->update($validated);
        return $this->success($dailyMealPlan);
    }

    public function destroy(DailyMealPlan $dailyMealPlan): JsonResponse
    {
        if ($dailyMealPlan->status >= 1) {
            return $this->error('已备餐的排餐不可删除', 40001);
        }
        $dailyMealPlan->delete();
        return $this->success(null);
    }

    public function deliver(DailyMealPlan $dailyMealPlan): JsonResponse
    {
        if ($dailyMealPlan->status >= 2) {
            return $this->error('已送达', 40001);
        }
        $dailyMealPlan->update([
            'status' => 2,
            'deliver_at' => now(),
        ]);
        return $this->success($dailyMealPlan);
    }

    public function updateStatus(Request $request, DailyMealPlan $dailyMealPlan): JsonResponse
    {
        $validated = $request->validate([
            'status' => 'required|integer|in:0,1,2,3',
        ]);
        $dailyMealPlan->update($validated);
        return $this->success($dailyMealPlan);
    }
}
