<?php

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

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

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

migrateLegacyGroceriesIfNeeded();
ensureDefaultGroceryStore();
$stores = normalizeStoresList(readJsonFile('stores.json'));

$body = readJsonBody();
$weekStart = isset($body['weekStart']) ? trim((string) $body['weekStart']) : '';
$day = isset($body['day']) ? (int) $body['day'] : -1;
$mealType = isset($body['mealType']) ? trim((string) $body['mealType']) : '';
$mealId = isset($body['mealId']) ? trim((string) $body['mealId']) : '';
$mealId = $mealId === '' ? null : $mealId;
$pushGrocery = array_key_exists('pushGrocery', $body) ? !empty($body['pushGrocery']) : true;

if ($weekStart === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $weekStart)) {
    sendJson(['success' => false, 'error' => 'weekStart must be YYYY-MM-DD'], 400);
}
if ($day < 0 || $day > 6) {
    sendJson(['success' => false, 'error' => 'day must be 0–6 (0 = week start day)'], 400);
}
if (!in_array($mealType, mealSlotTypes(), true)) {
    sendJson(['success' => false, 'error' => 'Invalid mealType'], 400);
}

$plan = normalizeMealPlan(readJsonFile('meal_plans.json'));
if ($plan['weekStart'] !== $weekStart) {
    sendJson(['success' => false, 'error' => 'That week is not the active plan. Set the week first (Head of household).'], 400);
}

$key = (string) $day;
if (!isset($plan['slots'][$key])) {
    $plan['slots'][$key] = [
        MEAL_SLOT_BREAKFAST => null,
        MEAL_SLOT_LUNCH => null,
        MEAL_SLOT_DINNER => null,
    ];
}

$meals = migrateLegacyMealsList(normalizeMealsList(readJsonFile('meals.json')));
$pushed = 0;
if ($mealId !== null) {
    $meal = findMealById($meals, $mealId);
    if ($meal === null) {
        sendJson(['success' => false, 'error' => 'Meal not found'], 404);
    }
    $plan['slots'][$key][$mealType] = $mealId;
    if ($pushGrocery && count($stores) > 0) {
        $pushed = pushMealItemsToGrocery(normalizeMealRow($meal), $stores);
    }
} else {
    $plan['slots'][$key][$mealType] = null;
}

if (!writeJsonFile('meal_plans.json', $plan)) {
    sendJson(['success' => false, 'error' => 'Failed to save meal plan'], 500);
}

sendJson(['success' => true, 'plan' => $plan, 'groceryLinesAdded' => $pushed]);
