<?php
// Deletes an income entry. Mirrors api/expense_delete.php.

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/helpers.php';

require_login();

function respond_json(array $payload, int $status = 200): void
{
    http_response_code($status);
    header('Content-Type: application/json');
    echo json_encode($payload);
    exit;
}

if (!current_user_is_admin()) {
    respond_json(['success' => false, 'error' => 'Income isn\'t available on this account.'], 403);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond_json(['success' => false, 'error' => 'Invalid request.'], 405);
}

if (!csrf_verify($_POST['csrf_token'] ?? null)) {
    respond_json([
        'success' => false,
        'session_expired' => true,
        'error' => 'Your session expired — please log in again.',
    ], 400);
}

$id = (int) ($_POST['id'] ?? 0);
$db = get_db();

$existsStmt = $db->prepare('SELECT 1 FROM incomes WHERE id = :id');
$existsStmt->execute(['id' => $id]);

if ($id <= 0 || !$existsStmt->fetchColumn()) {
    respond_json(['success' => false, 'error' => 'That entry no longer exists — it may have been deleted.'], 404);
}

$db->prepare('DELETE FROM incomes WHERE id = :id')->execute(['id' => $id]);

// Refresh whichever month income.php currently has open.
$month = resolve_viewed_month($_POST['viewed_month'] ?? null);

respond_json([
    'success' => true,
    'summary' => [
        'total_formatted' => format_money(get_month_income_total($month)),
    ],
    'incomes' => array_map('format_recent_income_row', get_month_incomes($month)),
]);
