<?php

require_once __DIR__ . '/../includes/api_bootstrap.php';
require_once __DIR__ . '/../includes/meal_helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendJson(['success' => false, 'error' => 'Method not allowed'], 405);
}

$people = normalizePeopleList(readJsonFile('people.json'));
requireActivePerson($people);

$mealId = isset($_GET['mealId']) ? trim((string) $_GET['mealId']) : '';
if ($mealId === '') {
    sendJson(['success' => false, 'error' => 'mealId is required'], 400);
}

$meals = migrateLegacyMealsList(normalizeMealsList(readJsonFile('meals.json')));
$meal = findMealById($meals, $mealId);
if ($meal === null) {
    sendJson(['success' => false, 'error' => 'Meal not found'], 404);
}

$meal = normalizeMealRow($meal);
$plan = normalizeMealPlan(readJsonFile('meal_plans.json'));
$weekStart = $plan['weekStart'];
$slots = $plan['slots'] ?? [];
$pruned = mealDefaultEmptySlots();
for ($i = 0; $i < 7; $i++) {
    $key = (string) $i;
    $day = $slots[$key] ?? [];
    if (!is_array($day)) {
        continue;
    }
    foreach (mealSlotTypes() as $mt) {
        $v = $day[$mt] ?? null;
        $pruned[$key][$mt] = (is_string($v) && $v === $mealId) ? $mealId : null;
    }
}

sendJson([
    'success' => true,
    'version' => '1',
    'meals' => [$meal],
    'meal_plans' => [
        'weekStart' => $weekStart,
        'slots' => $pruned,
    ],
]);
