<?php

require_once __DIR__ . '/../includes/api_bootstrap.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendJson(['success' => false, 'error' => 'Method not allowed'], 405);
}

$people = migrateAllPeople(normalizePeopleList(readJsonFile('people.json')));
assertHoHCanManagePeople($people);

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

$next = [];
$removed = null;
foreach ($people as $p) {
    if (($p['id'] ?? '') === $id) {
        $removed = $p;
        continue;
    }
    $next[] = $p;
}

if ($removed === null) {
    sendJson(['success' => false, 'error' => 'Person not found'], 404);
}

$headCount = 0;
foreach ($next as $p) {
    if (($p['role'] ?? '') === ROLE_HEAD) {
        $headCount++;
    }
}
if ($headCount < 1) {
    sendJson(['success' => false, 'error' => 'Cannot remove the last Head of Household'], 400);
}

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

if (getActivePersonId() === $id) {
    clearPersonaSession();
}

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