<?php
declare(strict_types=1);

require_once '../includes/auth.php';
require_once '../includes/security.php';
require_once '../includes/session.php';
require_once '../includes/csrf.php';
require_once '../config/database.php';
require_once '../includes/upload.php';

verify_csrf();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

    header('Location: ../admin/add-entry.php');
    exit;

}

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

if ($universityId <= 0) {

    $_SESSION['error'] = 'Please select a university.';

    header('Location: ../admin/add-entry.php');
    exit;

}

if (!isset($_FILES['pdf'])) {

    $_SESSION['error'] = 'Please choose a PDF file.';

    header('Location: ../admin/add-entry.php');
    exit;

}

try {

    $pdfName = securePdfUpload($_FILES['pdf']);

    $stmt = $pdo->prepare("
        INSERT INTO entries
        (
            university_id,
            pdf_name
        )
        VALUES
        (
            ?,
            ?
        )
    ");

    $stmt->execute([

        $universityId,

        $pdfName

    ]);

    $_SESSION['success'] = 'PDF uploaded successfully.';

} catch (Throwable $e) {

    $_SESSION['error'] = $e->getMessage();

}

header('Location: ../admin/add-entry.php');
exit;