<?php

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

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

$people = normalizePeopleList(readJsonFile('people.json'));
$actor = requireActivePerson($people);

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

$rawChores = normalizeChoresList(readJsonFile('chores.json'));
$chores = migrateAllChores($rawChores, $people);

$idx = findChoreIndexById($chores, $id);
if ($idx === null) {
    sendJson(['success' => false, 'error' => 'Chore not found'], 404);
}

$existing = $chores[$idx];
$isAuthor = ($existing['author_id'] ?? '') === ($actor['id'] ?? '');
$isHoH = ($actor['role'] ?? '') === ROLE_HEAD && isHohVerified();
if (!$isAuthor && !$isHoH) {
    sendJson(['success' => false, 'error' => 'You cannot delete this chore'], 403);
}

array_splice($chores, $idx, 1);

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

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