<?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();
$mealId = isset($body['mealId']) ? trim((string) $body['mealId']) : '';
$ingredient = isset($body['ingredient']) ? trim((string) $body['ingredient']) : '';
$storeId = isset($body['storeId']) ? trim((string) $body['storeId']) : '';

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

$meals = migrateLegacyMealsList(normalizeMealsList(readJsonFile('meals.json')));
$meal = $mealId !== '' ? findMealById($meals, $mealId) : null;
$mealTitle = $meal !== null ? (string) ($meal['title'] ?? '') : '';

if ($storeId === '' || findStoreById($stores, $storeId) === null) {
    $storeId = groceryFirstStoreId($stores);
}
if ($storeId === '') {
    sendJson(['success' => false, 'error' => 'No valid store'], 400);
}

$res = groceryAppendShoppingLine(
    $stores,
    $storeId,
    $ingredient,
    $mealTitle !== '' ? 'From meal: ' . $mealTitle : 'From meal ingredient',
    '',
    '1',
    '',
    '',
    'meal_plan',
    0,
    $mealId !== '' ? $mealId : null,
    $mealTitle !== '' ? $mealTitle : null
);

if (!$res['ok']) {
    sendJson(['success' => false, 'error' => $res['error'] ?? 'Failed'], 400);
}

sendJson(['success' => true, 'item' => $res['item']]);
