<?php
declare(strict_types=1);

require_once __DIR__ . '/_auth.php';

financial_require_access();

$pdo = financial_db();

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

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

if ($id <= 0) {
    header('Location: import_files.php');
    exit;
}

try {

    $st = $pdo->prepare("
        SELECT *
        FROM financial_import_files
        WHERE id = ?
        LIMIT 1
    ");

    $st->execute([$id]);

    $file = $st->fetch(PDO::FETCH_ASSOC);

    if ($file) {

        $fullPath = __DIR__ . '/' . ltrim((string)$file['file_path'], '/');

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

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

        $del->execute([$id]);
    }

} catch (Throwable $e) {
}

header('Location: import_files.php');
exit;