<?php

namespace App\Http\Controllers\Admin\Meal;

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

class DishController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Dish::query();
        $query->when($request->name, fn($q, $v) => $q->where('name', 'like', "%{$v}%"));
        $query->when($request->category, fn($q, $v) => $q->where('category', $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',
            'category' => 'nullable|string|max:30',
            'description' => 'nullable|string',
            'image' => 'nullable|string|max:255',
            'ingredients' => 'nullable|array',
            'contraindications' => 'nullable|array',
            'price' => 'sometimes|numeric|min:0',
            'status' => 'sometimes|integer|in:0,1',
        ]);
        return $this->success(Dish::create($validated));
    }

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

    public function update(Request $request, Dish $dish): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:50',
            'category' => 'nullable|string|max:30',
            'description' => 'nullable|string',
            'image' => 'nullable|string|max:255',
            'ingredients' => 'nullable|array',
            'contraindications' => 'nullable|array',
            'price' => 'sometimes|numeric|min:0',
            'status' => 'sometimes|integer|in:0,1',
        ]);
        $dish->update($validated);
        return $this->success($dish);
    }

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