<?php
// Deletes an expense after the edit modal's confirmation step. JS-only —
// there is no plain-form fallback for delete (Section 25.3, Phase 4).

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 ($_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 user_id FROM expenses WHERE id = :id');
$existsStmt->execute(['id' => $id]);
$ownerId = $existsStmt->fetchColumn();

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

if (!current_user_is_admin() && (int) $ownerId !== (int) current_user()['id']) {
    respond_json(['success' => false, 'error' => 'You can only delete your own expenses.'], 403);
}

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

// Refresh whichever month the dashboard currently has open — not
// necessarily today's month (Phase 5 month browsing).
$month = resolve_viewed_month($_POST['viewed_month'] ?? null);

respond_json([
    'success' => true,
    'summary' => [
        'total_formatted' => format_money(get_month_expense_total($month)),
        'bdt_formatted'   => format_bdt_equivalent(get_month_expense_total($month)),
        'budget'          => get_budget_summary($month),
        'savings'         => get_month_savings($month),
    ],
    'categories' => build_category_chart_data(get_month_category_totals($month)),
    'recent'     => array_map('format_recent_expense_row', get_recent_expenses($month, 5)),
]);
