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

$stores = normalizeStoresList(readJsonFile('stores.json'));
$newId = bin2hex(random_bytes(8));
$sort = count($stores);
$stores[] = ['id' => $newId, 'name' => $name, 'sort' => $sort];

if (!writeJsonFile('stores.json', $stores)) {
    sendJson(['success' => false, 'error' => 'Failed to save stores'], 500);
}

$lists = normalizeGroceryLists(readJsonFile('grocery_lists.json'));
if (!isset($lists['byStore'][$newId])) {
    $lists['byStore'][$newId] = [];
}
if (!writeJsonFile('grocery_lists.json', $lists)) {
    sendJson(['success' => false, 'error' => 'Failed to init store list'], 500);
}

sendJson(['success' => true, 'store' => ['id' => $newId, 'name' => $name, 'sort' => $sort]]);
