<?php

require_once __DIR__ . '/../includes/api_bootstrap.php';
require_once __DIR__ . '/../includes/grocery_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'));
if (count($stores) === 0) {
    sendJson(['success' => false, 'error' => 'No stores available'], 400);
}

$body = readJsonBody();
$storeId = isset($body['storeId']) ? trim((string) $body['storeId']) : '';
if ($storeId === '' || findStoreById($stores, $storeId) === null) {
    sendJson(['success' => false, 'error' => 'Invalid store'], 400);
}

$name = isset($body['name']) ? trim((string) $body['name']) : '';
$description = isset($body['description']) ? trim((string) $body['description']) : '';
$size = isset($body['size']) ? trim((string) $body['size']) : '';
$quantity = isset($body['quantity']) ? trim((string) $body['quantity']) : '1';
$price = isset($body['price']) ? trim((string) $body['price']) : '';
$image = isset($body['image']) ? trim((string) $body['image']) : '';
$source = isset($body['source']) ? (string) $body['source'] : 'manual';
if (!in_array($source, ['manual', 'meal_plan', 'pending_review'], true)) {
    $source = 'manual';
}
$recurring = isset($body['recurringIntervalDays']) ? max(0, (int) $body['recurringIntervalDays']) : 0;

$catalogPickId = isset($body['catalogPickId']) ? trim((string) $body['catalogPickId']) : '';
$catalog = normalizeCatalogList(readJsonFile('grocery_catalog.json'));

if ($catalogPickId !== '') {
    $pick = findCatalogById($catalog, $catalogPickId);
    if ($pick !== null && (string) ($pick['storeId'] ?? '') === $storeId) {
        if ($name === '') {
            $name = trim((string) ($pick['name'] ?? ''));
        }
        if ($description === '') {
            $description = trim((string) ($pick['description'] ?? ''));
        }
        if ($size === '') {
            $size = trim((string) ($pick['defaultSize'] ?? ''));
        }
        if ($image === '') {
            $image = trim((string) ($pick['defaultImage'] ?? ''));
        }
    }
}

$result = groceryAppendShoppingLine(
    $stores,
    $storeId,
    $name,
    $description,
    $size,
    $quantity,
    $price,
    $image,
    $source,
    $recurring,
    null,
    null
);

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

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