<?php

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

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

$people = migrateAllPeople(normalizePeopleList(readJsonFile('people.json')));
$familySettings = loadFamilySettings();
$people = bankingApplySavingsInterestToPeople($people, $familySettings);
$actor = requireActivePerson($people);
if (($actor['role'] ?? '') !== ROLE_HEAD || !isHohVerified()) {
    sendJson(['success' => false, 'error' => 'Only a verified Head of household can review chores'], 403);
}

$body = readJsonBody();
$id = isset($body['id']) ? trim((string) $body['id']) : '';
$decision = isset($body['decision']) ? trim((string) $body['decision']) : '';
if ($id === '') {
    sendJson(['success' => false, 'error' => 'id is required'], 400);
}
if (!in_array($decision, ['approve', 'reject'], true)) {
    sendJson(['success' => false, 'error' => 'decision must be approve or reject'], 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);
}

$row = $chores[$idx];
$pending = $row['pending_submission'] ?? null;
if (!is_array($pending)) {
    sendJson(['success' => false, 'error' => 'Nothing is waiting for approval on this chore'], 400);
}

if ($decision === 'reject') {
    $row['pending_submission'] = null;
    $chores[$idx] = migrateLegacyChoreRow($row, $people);
    if (!writeJsonFile('chores.json', $chores)) {
        sendJson(['success' => false, 'error' => 'Failed to save chores'], 500);
    }
    sendJson(['success' => true]);
}

$submittedBy = trim((string) ($pending['submitted_by'] ?? ''));
$value = (float) ($row['value'] ?? 0);
$creditedEach = 0.0;
$creditedRecipients = 0;

$row['pending_submission'] = null;

if (($row['schedule'] ?? CHORE_SCHEDULE_ONCE) === CHORE_SCHEDULE_RECURRING) {
    $days = (int) ($row['recurrence_days'] ?? 7);
    $days = max(1, $days);
    $row['due_date'] = gmdate('Y-m-d', time() + ($days * 86400));
    $row['status'] = 'active';
} else {
    $row['status'] = 'completed';
}

$chores[$idx] = migrateLegacyChoreRow($row, $people);

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

foreach ($people as $pi => $p) {
    $pid = (string) ($p['id'] ?? '');
    if ($pid === '') {
        continue;
    }
    if ($submittedBy !== '') {
        if ($pid !== $submittedBy) {
            continue;
        }
        $creditedEach = $value;
    } else {
        $assignees = $row['assignee_ids'] ?? [];
        if (!is_array($assignees) || !in_array($pid, $assignees, true)) {
            continue;
        }
        $n = count($assignees);
        $creditedEach = $n > 0 ? round($value / $n, 2) : 0.0;
    }
    if (bankingEnabled($familySettings)) {
        $result = bankingCreditCheckingByRule($people[$pi], $creditedEach, $familySettings);
        $people[$pi] = $result['person'];
        appendBankTransaction([
            'id' => bin2hex(random_bytes(8)),
            'type' => 'income_chore',
            'person_id' => $pid,
            'amount' => bankingRoundMoney($creditedEach),
            'allocations' => $result['allocations'],
            'category' => 'chore',
            'note' => (string) ($row['title'] ?? ''),
            'created_at' => gmdate('c'),
            'created_by' => (string) ($actor['id'] ?? ''),
        ]);
    } else {
        $bal = $p['currency_balance'] ?? 0;
        $people[$pi]['currency_balance'] = (is_numeric($bal) ? (float) $bal : 0.0) + $creditedEach;
        $people[$pi]['checking_balance'] = $people[$pi]['currency_balance'];
    }
    $creditedRecipients++;
}

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

sendJson([
    'success' => true,
    'credited_each' => $creditedEach,
    'credited_recipients' => $creditedRecipients,
]);
