<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    die('Unauthorized access');
}

require_once 'config.php';
require_once 'lib/exam_utils.php';
require_once 'lib/exam_document.php';
require_once 'templates/registry.php';
require_once '../vendor/autoload.php';

$examId  = isset($_GET['id']) ? intval($_GET['id']) : 0;
$version = ($_GET['version'] ?? 'student') === 'teacher' ? 'teacher' : 'student';
if (!$examId) {
    die('Invalid exam ID');
}

$conn = getDBConnection();
$query = "SELECT e.*, u.full_name as creator_name
          FROM generated_exams e
          LEFT JOIN users u ON e.created_by = u.id
          WHERE e.id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $examId);
$stmt->execute();
$exam = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$exam) {
    die('Exam not found');
}

$stmt = $conn->prepare('UPDATE generated_exams SET download_count = download_count + 1 WHERE id = ?');
$stmt->bind_param('i', $examId);
$stmt->execute();
$stmt->close();

$exam['exam_data'] = enrichExamAssessmentData(json_decode($exam['exam_data'], true) ?: [], [
    'subject_name' => $exam['subject_name'],
    'exam_title'   => $exam['title'],
    'class_name'   => $exam['class_name'],
    'duration'     => $exam['duration_minutes'],
]);

// School identity + the school's chosen exam template
$school = examSchoolInfo($conn);

// A per-download ?template= override wins; otherwise use the school default.
$templateKey = $_GET['template'] ?? $school['template'];

$doc = examDocFromGeneratedExam($exam, $version === 'teacher', $school);

$mpdf = new \Mpdf\Mpdf([
    'format'        => 'A4',
    'margin_left'   => 15,
    'margin_right'  => 15,
    'margin_top'    => 14,
    'margin_bottom' => 16,
]);
$mpdf->SetTitle((string) $doc['title']);

$render = resolveExamRenderer($templateKey);
$mpdf->WriteHTML($render($doc));

$filename = str_replace(' ', '_', preg_replace('/[^A-Za-z0-9 _-]/', '', (string) $exam['title']))
          . '_' . $version . '_' . date('Ymd') . '.pdf';

$mpdf->Output($filename, \Mpdf\Output\Destination::DOWNLOAD);
exit;
