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

$stores = normalizeStoresList(readJsonFile('stores.json'));
$found = false;
foreach ($stores as $i => $s) {
    if (($s['id'] ?? '') === $id) {
        $stores[$i]['name'] = $name;
        if (isset($body['sort']) && is_numeric($body['sort'])) {
            $stores[$i]['sort'] = (int) $body['sort'];
        }
        $found = true;
        break;
    }
}
if (!$found) {
    sendJson(['success' => false, 'error' => 'Store not found'], 404);
}

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

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