<?php
declare(strict_types=1);

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

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

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

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

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

    $st = $pdo->prepare('DELETE FROM financial_income 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('income.php?msg=' . urlencode('تم حذف المدخول بنجاح')));
        exit;
    }

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