<?php

declare(strict_types=1);

require_once __DIR__ . '/../Core/Database.php';

session_start();

$pdo = Database::connection();

if (empty($_SESSION['admin_id'])) {
    header('Location: ../public/login.php');
    exit;
}

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

if ($id <= 0) {
    header(
        'Location: dashboard.php?error=Invalid+application'
    );
    exit;
}

try {

    $pdo->beginTransaction();

    $stmt = $pdo->prepare("
        SELECT
            id,
            application_number
        FROM applications
        WHERE id = ?
        LIMIT 1
    ");

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

    $application =
        $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$application) {
        throw new RuntimeException(
            'Application not found.'
        );
    }

    /*
    |--------------------------------------------------------------------------
    | DELETE
    |--------------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        DELETE FROM applications
        WHERE id = ?
    ");

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

    $pdo->commit();

    header(
        'Location: dashboard.php?success=' .
        urlencode(
            'Application deleted successfully.'
        )
    );

    exit;

} catch (Throwable $e) {

    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    header(
        'Location: dashboard.php?error=' .
        urlencode(
            'Unable to delete application: ' .
            $e->getMessage()
        )
    );

    exit;
}