<?php
declare(strict_types=1);

require_once __DIR__ . '/_auth.php';
financial_require_access();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ' . financial_u('expenses.php'));
    exit;
}

$pdo      = financial_db();
$branchId = financial_branch_id();
$id       = (int)($_POST['id'] ?? 0);

if ($id <= 0) {
    header('Location: ' . financial_u('expenses.php?err=' . urlencode('رقم المصروف غير صحيح')));
    exit;
}

try {
    $attachment = null;
    if (financial_has_column($pdo, 'financial_expenses', 'attachment_path')) {
        $q = $pdo->prepare('SELECT attachment_path FROM financial_expenses WHERE id = ? AND branch_id = ? LIMIT 1');
        $q->execute([$id, $branchId]);
        $attachment = $q->fetchColumn() ?: null;
    }

    $st = $pdo->prepare('DELETE FROM financial_expenses WHERE id = ? AND branch_id = ? LIMIT 1');
    $st->execute([$id, $branchId]);

    if ($st->rowCount() > 0) {
        financial_delete_attachment_file($attachment ? (string)$attachment : null);
        header('Location: ' . financial_u('expenses.php?msg=' . urlencode('تم حذف المصروف بنجاح')));
        exit;
    }

    header('Location: ' . financial_u('expenses.php?err=' . urlencode('المصروف غير موجود أو لا تملك صلاحية حذفه')));
    exit;
} catch (Throwable $e) {
    header('Location: ' . financial_u('expenses.php?err=' . urlencode('تعذر حذف المصروف')));
    exit;
}
