<?php
declare(strict_types=1);

require_once __DIR__ . '/_auth.php';

financial_require_access();

$pdo = financial_db();

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || $id <= 0) {
    header('Location: import_files.php?err=' . urlencode('طلب غير صحيح'));
    exit;
}

try {
    $st = $pdo->prepare("SELECT file_path FROM financial_import_files WHERE id = ? LIMIT 1");
    $st->execute([$id]);
    $row = $st->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        header('Location: import_files.php?err=' . urlencode('الكشف غير موجود'));
        exit;
    }

    $filePath = (string)($row['file_path'] ?? '');

    $del = $pdo->prepare("DELETE FROM financial_import_files WHERE id = ? LIMIT 1");
    $del->execute([$id]);

    if ($filePath !== '') {
        $fullPath = __DIR__ . '/' . ltrim($filePath, '/');

        if (is_file($fullPath)) {
            @unlink($fullPath);
        }
    }

    header('Location: import_files.php?msg=' . urlencode('تم حذف الكشف بنجاح'));
    exit;

} catch (Throwable $e) {
    header('Location: import_files.php?err=' . urlencode('تعذر حذف الكشف'));
    exit;
}