<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Meal;
use App\Models\Menu;
use Illuminate\Http\Request;

class MealController extends Controller
{
    /**
     * List all available meals, optionally filtered.
     */
    public function index(Request $request)
    {
        $query = Meal::available();

        if ($request->has('category')) {
            $query->byCategory($request->category);
        }

        if ($request->has('dietary')) {
            $dietary = is_array($request->dietary) ? $request->dietary : [$request->dietary];
            foreach ($dietary as $diet) {
                $query->whereJsonContains('dietary_info', $diet);
            }
        }

        if ($request->has('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', "%{$request->search}%")
                  ->orWhere('description', 'like', "%{$request->search}%");
            });
        }

        $meals = $query->orderBy('name')->get();

        return response()->json(['meals' => $meals]);
    }

    /**
     * Get a single meal by slug.
     */
    public function show(string $slug)
    {
        $meal = Meal::where('slug', $slug)->firstOrFail();

        return response()->json(['meal' => $meal]);
    }

    /**
     * Get upcoming menus with their meals.
     */
    public function upcomingMenus(Request $request)
    {
        $menus = Menu::published()
            ->upcoming()
            ->with('meals')
            ->orderBy('available_date')
            ->orderBy('meal_time')
            ->limit(21) // 3 meals/day x 7 days
            ->get()
            ->groupBy('available_date');

        return response()->json(['menus' => $menus]);
    }

    /**
     * Get menu for a specific date.
     */
    public function menuForDate(Request $request, string $date)
    {
        $menus = Menu::published()
            ->forDate($date)
            ->with('meals')
            ->get();

        return response()->json(['menus' => $menus]);
    }
}
