<?php

namespace App\Http\Controllers\Admin\Meal;

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

class MealPlanTemplateController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = MealPlanTemplate::query();
        $query->when($request->name, fn($q, $v) => $q->where('name', 'like', "%{$v}%"));
        $query->when($request->stage, fn($q, $v) => $q->where('stage', $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([
            'name' => 'required|string|max:50',
            'stage' => 'nullable|string|max:30',
            'meals' => 'nullable|array',
            'status' => 'sometimes|integer|in:0,1',
        ]);
        return $this->success(MealPlanTemplate::create($validated));
    }

    public function show(MealPlanTemplate $mealPlanTemplate): JsonResponse
    {
        return $this->success($mealPlanTemplate);
    }

    public function update(Request $request, MealPlanTemplate $mealPlanTemplate): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:50',
            'stage' => 'nullable|string|max:30',
            'meals' => 'nullable|array',
            'status' => 'sometimes|integer|in:0,1',
        ]);
        $mealPlanTemplate->update($validated);
        return $this->success($mealPlanTemplate);
    }

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