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

if ($mealId === '') {
    sendJson(['success' => false, 'error' => 'mealId is required'], 400);
}
if ($itemIndex < 0) {
    sendJson(['success' => false, 'error' => 'itemIndex is required'], 400);
}
if (count($stores) === 0) {
    sendJson(['success' => false, 'error' => 'Add a grocery store first'], 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);
$items = $meal['items'] ?? [];
if (!is_array($items) || $itemIndex >= count($items)) {
    sendJson(['success' => false, 'error' => 'Invalid shopping item'], 400);
}

$row = $items[$itemIndex];
if (!is_array($row)) {
    sendJson(['success' => false, 'error' => 'Invalid shopping item'], 400);
}

$name = trim((string) ($row['name'] ?? ''));
if ($name === '') {
    sendJson(['success' => false, 'error' => 'Item has no name'], 400);
}

$mealTitle = (string) ($meal['title'] ?? '');
$desc = trim((string) ($row['description'] ?? ''));
if ($desc === '') {
    $desc = $mealTitle !== '' ? 'From meal: ' . $mealTitle : 'From meal shopping list';
}

if ($storeId === '' || findStoreById($stores, $storeId) === null) {
    $rowStore = trim((string) ($row['storeId'] ?? ''));
    if ($rowStore !== '' && findStoreById($stores, $rowStore) !== null) {
        $storeId = $rowStore;
    } else {
        $storeId = groceryFirstStoreId($stores);
    }
}
if ($storeId === '') {
    sendJson(['success' => false, 'error' => 'No valid store'], 400);
}

$res = groceryAppendShoppingLine(
    $stores,
    $storeId,
    $name,
    $desc,
    trim((string) ($row['size'] ?? '')),
    trim((string) ($row['quantity'] ?? '1')) ?: '1',
    trim((string) ($row['price'] ?? '')),
    trim((string) ($row['image'] ?? '')),
    'meal_plan',
    0,
    $mealId,
    $mealTitle !== '' ? $mealTitle : null
);

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

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