<?php
declare(strict_types=1);

require_once '../includes/auth.php';
require_once '../includes/security.php';
require_once '../config/database.php';

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    $_SESSION['error'] = 'Invalid entry.';
    header('Location: ../admin/entries.php');
    exit;
}

$stmt = $pdo->prepare("SELECT pdf_name FROM entries WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    $_SESSION['error'] = 'Entry not found.';
    header('Location: ../admin/entries.php');
    exit;
}

$pdf = dirname(__DIR__,2) . '/resultfiles/' . $row['pdf_name'];

$pdo->beginTransaction();

try {
    $del = $pdo->prepare("DELETE FROM entries WHERE id=?");
    $del->execute([$id]);

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

    $pdo->commit();

    $_SESSION['success'] = 'Entry deleted successfully.';
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    $_SESSION['error'] = 'Unable to delete entry.';
}

header('Location: ../admin/entries.php');
exit;
