<?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 approve pending items'], 403);
}

$body = readJsonBody();
$storeId = isset($body['storeId']) ? trim((string) $body['storeId']) : '';
$itemId = isset($body['itemId']) ? trim((string) $body['itemId']) : '';
if ($storeId === '' || $itemId === '') {
    sendJson(['success' => false, 'error' => 'storeId and itemId are required'], 400);
}

$lists = normalizeGroceryLists(readJsonFile('grocery_lists.json'));
$items = $lists['byStore'][$storeId] ?? [];
$idx = null;
foreach ($items as $i => $it) {
    if (($it['id'] ?? '') === $itemId) {
        $idx = $i;
        break;
    }
}
if ($idx === null) {
    sendJson(['success' => false, 'error' => 'Item not found'], 404);
}

$row = $items[$idx];
if (($row['status'] ?? '') !== 'pending_review') {
    sendJson(['success' => false, 'error' => 'Item is not pending review'], 400);
}

$row['status'] = 'active';
$row = normalizeGroceryLineItem($row);
$items[$idx] = $row;
$lists['byStore'][$storeId] = $items;

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

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