<?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'));
$actor = requireActivePerson($people);
if (($actor['role'] ?? '') !== ROLE_HEAD || !isHohVerified()) {
    sendJson(['success' => false, 'error' => 'Only a verified Head of household can manage stores'], 403);
}

$body = readJsonBody();
$id = isset($body['id']) ? trim((string) $body['id']) : '';
if ($id === '') {
    sendJson(['success' => false, 'error' => 'id is required'], 400);
}

$stores = normalizeStoresList(readJsonFile('stores.json'));
if (count($stores) <= 1) {
    sendJson(['success' => false, 'error' => 'You must keep at least one store'], 400);
}

$lists = normalizeGroceryLists(readJsonFile('grocery_lists.json'));
if (groceryStoreHasItems($lists, $id)) {
    sendJson(['success' => false, 'error' => 'Remove or purchase all items in this store before deleting it'], 400);
}

$next = [];
foreach ($stores as $s) {
    if (($s['id'] ?? '') === $id) {
        continue;
    }
    $next[] = $s;
}

unset($lists['byStore'][$id]);

$catalog = normalizeCatalogList(readJsonFile('grocery_catalog.json'));
$catalogNext = [];
foreach ($catalog as $row) {
    if ((string) ($row['storeId'] ?? '') === $id) {
        continue;
    }
    $catalogNext[] = $row;
}

if (!writeJsonFile('stores.json', $next)) {
    sendJson(['success' => false, 'error' => 'Failed to save stores'], 500);
}
if (!writeJsonFile('grocery_lists.json', $lists)) {
    sendJson(['success' => false, 'error' => 'Failed to save grocery lists'], 500);
}
if (!writeJsonFile('grocery_catalog.json', $catalogNext)) {
    sendJson(['success' => false, 'error' => 'Failed to save catalog'], 500);
}

sendJson(['success' => true]);
