<?php

require_once __DIR__ . '/../includes/api_bootstrap.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')));
$actor = requireActivePerson($people);
if (($actor['role'] ?? '') !== ROLE_HEAD || !isHohVerified()) {
    sendJson(['success' => false, 'error' => 'Only a verified Head of household can log charity outflow'], 403);
}
$settings = loadFamilySettings();
if (!bankingEnabled($settings)) {
    sendJson(['success' => false, 'error' => 'Banking mode is not enabled'], 400);
}
$people = bankingApplySavingsInterestToPeople($people, $settings);
$body = readJsonBody();
$personId = trim((string) ($body['person_id'] ?? ''));
$note = trim((string) ($body['note'] ?? ''));
$category = bankingCategoryOrDefault((string) ($body['category'] ?? ''), 'donation');
$amountRaw = $body['amount'] ?? null;

if ($personId === '') {
    sendJson(['success' => false, 'error' => 'person_id is required'], 400);
}
if (!is_numeric($amountRaw)) {
    sendJson(['success' => false, 'error' => 'amount must be numeric'], 400);
}
$amount = bankingRoundMoney((float) $amountRaw);
if ($amount <= 0) {
    sendJson(['success' => false, 'error' => 'amount must be greater than zero'], 400);
}

$idx = null;
foreach ($people as $i => $p) {
    if (($p['id'] ?? '') === $personId) {
        $idx = $i;
        break;
    }
}
if ($idx === null) {
    sendJson(['success' => false, 'error' => 'Person not found'], 404);
}

$pending = (float) ($people[$idx]['charity_pending_balance'] ?? 0);
if ($pending < $amount) {
    sendJson(['success' => false, 'error' => 'Insufficient charity pending balance'], 400);
}
$people[$idx]['charity_pending_balance'] = bankingRoundMoney($pending - $amount);
$people[$idx]['charity_donated_total'] = bankingRoundMoney((float) ($people[$idx]['charity_donated_total'] ?? 0) + $amount);

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

$tx = [
    'id' => bin2hex(random_bytes(8)),
    'type' => 'charity_outflow',
    'person_id' => $personId,
    'amount' => $amount,
    'category' => $category,
    'note' => $note,
    'created_at' => gmdate('c'),
    'created_by' => (string) ($actor['id'] ?? ''),
];
if (!appendBankTransaction($tx)) {
    sendJson(['success' => false, 'error' => 'Saved outflow but failed to write transaction log'], 500);
}

sendJson(['success' => true, 'transaction' => $tx, 'person' => $people[$idx]]);
