<?php
declare(strict_types=1);
session_start();
require_once '../../config.php';
require_once dirname(__DIR__) . '/includes/pdf_builder.php';
require_once dirname(__DIR__) . '/helpers.php';
if (!isset($_SESSION['user_id'])) { http_response_code(401); exit('Unauthorized'); }
$conn = getDBConnection();
if (!$conn instanceof mysqli) { http_response_code(500); exit('DB failed'); }
if (!is_dir(EXAM_EXPORT_DIR)) { @mkdir(EXAM_EXPORT_DIR, 0777, true); }
$type = ($_GET['type'] ?? 'exam') === 'key' ? 'key' : 'exam';
$paperId = (int) ($_GET['paper_id'] ?? 0);
$jobId = (int) ($_GET['job_id'] ?? 0);
$questions = [];
$config = [
    'title' => 'AI Generated Exam',
    'class_name' => '',
    'subject_name' => '',
    'term' => '',
    'academic_year' => '',
    'duration_minutes' => 60,
    'total_marks' => 0,
    'instructions' => '',
];

if ($paperId > 0) {
    $paperStmt = $conn->prepare("SELECT ep.*, s.subject_name FROM exam_papers ep LEFT JOIN subjects s ON s.id = ep.subject_id WHERE ep.id = ? LIMIT 1");
    $paperStmt->bind_param('i', $paperId);
    $paperStmt->execute();
    $paper = $paperStmt->get_result()->fetch_assoc();
    $paperStmt->close();
    if (!$paper) { http_response_code(404); exit('Paper not found'); }
    $config = [
        'title' => (string) $paper['title'],
        'class_name' => (string) $paper['class_name'],
        'subject_name' => (string) ($paper['subject_name'] ?? ''),
        'term' => (string) $paper['term'],
        'academic_year' => (string) $paper['academic_year'],
        'duration_minutes' => (int) $paper['duration_minutes'],
        'total_marks' => (int) $paper['total_marks'],
        'instructions' => (string) ($paper['instructions'] ?? ''),
        'section_config' => isset($paper['section_config']) ? (json_decode((string) $paper['section_config'], true) ?: []) : [],
    ];
    $qStmt = $conn->prepare("SELECT eq.*, epq.marks FROM exam_paper_questions epq INNER JOIN exam_questions eq ON eq.id = epq.question_id WHERE epq.paper_id = ? ORDER BY epq.order_no ASC, epq.id ASC");
    $qStmt->bind_param('i', $paperId);
    $qStmt->execute();
    $res = $qStmt->get_result();
    while ($row = $res->fetch_assoc()) { $questions[] = $row; }
    $qStmt->close();
} else {
    $jobStmt = $conn->prepare("SELECT agj.*, s.subject_name FROM ai_generation_jobs agj LEFT JOIN subjects s ON s.id = agj.subject_id WHERE agj.id = ? AND agj.created_by = ? LIMIT 1");
    $jobStmt->bind_param('ii', $jobId, $_SESSION['user_id']);
    $jobStmt->execute();
    $job = $jobStmt->get_result()->fetch_assoc();
    $jobStmt->close();
    if (!$job) { http_response_code(404); exit('Job not found'); }
    $config = [
        'title' => 'AI Generated ' . ((string) ($job['subject_name'] ?? 'Exam')),
        'class_name' => (string) $job['class_name'],
        'subject_name' => (string) ($job['subject_name'] ?? ''),
        'term' => (string) ($job['term'] ?? ''),
        'academic_year' => (string) ($job['academic_year'] ?? ''),
        'duration_minutes' => 60,
        'total_marks' => 0,
        'instructions' => 'Answer all questions.',
    ];
    $qStmt = $conn->prepare("SELECT * FROM exam_questions WHERE generation_job_id = ? AND created_by = ? ORDER BY id ASC");
    $qStmt->bind_param('ii', $jobId, $_SESSION['user_id']);
    $qStmt->execute();
    $res = $qStmt->get_result();
    while ($row = $res->fetch_assoc()) { $questions[] = $row; }
    $qStmt->close();
}
$config['total_marks'] = (int) array_sum(array_map(static fn($q) => (int) ($q['marks'] ?? 0), $questions));
$filename = $type === 'key' ? generateAnswerKeyPDF($questions, $config, EXAM_EXPORT_DIR) : generateExamPDF($questions, $config, EXAM_EXPORT_DIR);
if ($paperId > 0) {
    if ($type === 'key') {
        $update = $conn->prepare("UPDATE exam_papers SET answer_key_file_path = ? WHERE id = ?");
    } else {
        $update = $conn->prepare("UPDATE exam_papers SET paper_file_path = ? WHERE id = ?");
    }
    $relative = 'exams_generator/exports/' . $filename;
    $update->bind_param('si', $relative, $paperId);
    $update->execute();
    $update->close();
}
$filePath = rtrim(EXAM_EXPORT_DIR, '/\\') . DIRECTORY_SEPARATOR . $filename;
if (!is_file($filePath)) { http_response_code(404); exit('PDF generation failed — file not found.'); }
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . addslashes($filename) . '"');
header('Content-Length: ' . (string) filesize($filePath));
header('Cache-Control: no-store');
readfile($filePath);
