<?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();
$id = isset($body['id']) ? trim((string) $body['id']) : '';
if ($id === '') {
    sendJson(['success' => false, 'error' => 'id is required'], 400);
}

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

if (count($stores) === 0) {
    sendJson(['success' => false, 'error' => 'Add a grocery store first'], 400);
}

$n = pushMealItemsToGrocery(normalizeMealRow($meal), $stores);
sendJson(['success' => true, 'groceryLinesAdded' => $n]);
