<?php
// Set timezone to West African Time (Lagos)
date_default_timezone_set('Africa/Lagos');
require_once('source/dbconfig.php');
require_once('source/function.php');
session_start();

// Add this at the top of cbt_exam.php after session_start()
if (!isset($_SESSION['verified_access_key']) || 
    $_SESSION['verified_access_key']['exam_subject_id'] != $_GET['exam_subject_id']) {
    $_SESSION['error'] = "Please verify your access key first";
    header("Location: cbt_exam_now.php?exam_subject_id=" . $_GET['exam_subject_id']);
    exit();
}

// Get the access code from session
$accessCode = $_SESSION['verified_access_key']['code'];

// Clear the verified key from session (optional - you might want to keep it for the duration)
// unset($_SESSION['verified_access_key']);

// Verify exam session
if (!isset($_SESSION['current_exam']) || !isset($_GET['exam_subject_id'])) {
    header("Location: welcome.php");
    exit();
}

// School information
$schoolName = "Henzy Royal International School";
$schoolMotto = "Excellence, Integrity, Service";

// Load exam questions
try {
    // First get the subject_id and assessment_type from exam_subject table
    $stmt = $DBH->prepare("
        SELECT subject_id, exam_id, assessment_type 
        FROM tbl_exam_subject 
        WHERE id = :exam_subject_id
        LIMIT 1
    ");
    $stmt->execute(['exam_subject_id' => $_GET['exam_subject_id']]);
    $examSubject = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$examSubject) {
        throw new Exception("Invalid exam subject selected");
    }
    
    // Now get the exam_class_id from exam_class table
    $stmt = $DBH->prepare("
        SELECT id 
        FROM tbl_exam_class 
        WHERE exam_id = :exam_id
        AND class = :class
        AND term = :term
        AND session = :session
        LIMIT 1
    ");
    $stmt->execute([
        'exam_id' => $examSubject['exam_id'],
        'class' => $_SESSION['current_exam']['class'],
        'term' => $_SESSION['exam_info']['term'],
        'session' => $_SESSION['exam_info']['session']
    ]);
    $examClass = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$examClass) {
        throw new Exception("Exam not configured for your class");
    }
    
    // Now get the questions
    $stmt = $DBH->prepare("
        SELECT 
            q.id,
            q.question_text,
            q.option_a,
            q.option_b,
            q.option_c,
            q.option_d,
            q.correct_answer,
            q.file_path,
            q.marks
        FROM tbl_question q
        WHERE q.subject_id = :subject_id
        AND q.exam_class_id = :exam_class_id
        ORDER BY RAND()
        LIMIT 1000
    ");
    
    $stmt->execute([
        'subject_id' => $examSubject['subject_id'],
        'exam_class_id' => $examClass['id']
    ]);
    
    $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (empty($questions)) {
        throw new Exception("No questions available for this exam. Please contact your instructor.");
    }
    
    // Update session with correct IDs and assessment type
    $_SESSION['current_exam']['subject_id'] = $examSubject['subject_id'];
    $_SESSION['current_exam']['exam_class_id'] = $examClass['id'];
    $_SESSION['current_exam']['question_ids'] = array_column($questions, 'id');
    $_SESSION['current_exam']['assessment_type'] = $examSubject['assessment_type'];
    $_SESSION['current_exam']['total_questions'] = count($questions);
    
    // Calculate total marks
    $totalMarks = array_sum(array_column($questions, 'marks')) ?: count($questions);
    $_SESSION['current_exam']['total_marks'] = $totalMarks;
    
} catch (Exception $e) {
    die("Error: " . $e->getMessage());
}

// Calculate end time
$endTime = $_SESSION['current_exam']['start_time'] + ($_SESSION['current_exam']['duration'] * 60);
$timeLeft = $endTime - time();

// Function to get assessment type badge class
function getAssessmentBadgeClass($type) {
    switch($type) {
        case 'CA1': return 'badge-ca1';
        case 'CA2': return 'badge-ca2';
        case 'CA3': return 'badge-ca3';
        case 'Term Exam': return 'badge-term';
        case 'Mock Exam': return 'badge-mock';
        default: return 'badge-secondary';
    }
}

// Determine which column to save result in based on assessment type
function getResultColumn($assessmentType) {
    switch($assessmentType) {
        case 'CA1': return 'test1';
        case 'CA2': return 'test2';
        case 'CA3': return 'project';
        case 'Term Exam': return 'exam';
        case 'Mock Exam': return 'mock';
        default: return 'exam';
    }
}

$resultColumn = getResultColumn($_SESSION['current_exam']['assessment_type']);

// Function to properly decode double-encoded HTML content
function decodeHtmlContent($content) {
    if (empty($content)) return $content;
    
    // First, decode HTML entities (this converts &lt;p&gt; to <p>)
    $decoded = html_entity_decode($content, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    
    // Some content might be double-encoded, so decode again if necessary
    // Check if there are still HTML entities after first decode
    if (preg_match('/&[#a-zA-Z0-9]+;/', $decoded)) {
        $decoded = html_entity_decode($decoded, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    }
    
    // Remove any extra slashes
    $decoded = stripslashes($decoded);
    
    return $decoded;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exam - <?= htmlspecialchars($_SESSION['current_exam']['subject_name']) ?></title>
    <link rel="icon" type="image/png" href="../coll_logo.png">
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- KaTeX CSS for math rendering -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.7/dist/katex.min.css">
    
    <style>
        :root {
            --primary-blue: #1a4b8c;
            --secondary-gold: #FFD700;
            --dark-blue: #0f2b4f;
            --light-blue: #4a7db5;
            --light-gold: #FFF1B8;
            --bg-light: #f5f9ff;
            --success-green: #28a745;
            --danger-red: #dc3545;
            --warning-orange: #fd7e14;
            --info-teal: #17a2b8;
        }
        
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
            font-family: 'Poppins', sans-serif;
            padding-bottom: 100px;
        }
        
        /* Header */
        .exam-header {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            padding: 0.75rem 0;
            border-bottom: 3px solid var(--secondary-gold);
        }
        
        .logo-container {
            display: flex;
            align-items: center;
        }
        
        .school-logo {
            width: 40px;
            height: 40px;
            object-fit: contain;
            background: white;
            padding: 5px;
            border-radius: 50%;
            border: 2px solid var(--secondary-gold);
            margin-right: 10px;
        }
        
        /* Assessment Type Badge */
        .assessment-badge {
            display: inline-block;
            padding: 0.4rem 1rem;
            border-radius: 50px;
            font-size: 0.8rem;
            font-weight: 600;
            margin-left: 0.5rem;
        }
        
        .badge-ca1 { background: linear-gradient(135deg, #17a2b8, #138496); color: white; }
        .badge-ca2 { background: linear-gradient(135deg, #28a745, #218838); color: white; }
        .badge-ca3 { background: linear-gradient(135deg, #ffc107, #e0a800); color: var(--dark-blue); }
        .badge-term { background: linear-gradient(135deg, #6610f2, #520dc2); color: white; }
        .badge-mock { background: linear-gradient(135deg, #fd7e14, #e56b08); color: white; }
        
        /* Timer Container */
        .timer-container {
            position: sticky;
            top: 0;
            background: white;
            z-index: 1000;
            box-shadow: 0 4px 15px rgba(26, 75, 140, 0.1);
            padding: 1rem 0;
            border-bottom: 3px solid var(--secondary-gold);
        }
        
        .timer-display {
            font-size: 1.5rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--light-gold), #ffffff);
            padding: 0.5rem 1.5rem;
            border-radius: 50px;
            display: inline-block;
            border: 2px solid var(--secondary-gold);
        }
        
        .timer-danger {
            color: var(--danger-red);
            animation: pulse 1s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        .progress {
            height: 8px;
            border-radius: 4px;
            background-color: #e0e0e0;
            margin-top: 0.5rem;
        }
        
        .progress-bar {
            background: linear-gradient(90deg, var(--secondary-gold), var(--primary-blue));
            border-radius: 4px;
        }
        
        /* Question Container */
        .question-container {
            max-width: 900px;
            margin: 2rem auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(26, 75, 140, 0.1);
            padding: 2rem;
            border: 1px solid rgba(255, 215, 0, 0.2);
        }
        
        /* Question Cards */
        .question-card {
            margin-bottom: 25px;
            border-left: 5px solid var(--primary-blue);
            transition: all 0.3s ease;
            display: none;
            border-radius: 10px;
            overflow: hidden;
            border: 1px solid rgba(255, 215, 0, 0.2);
        }
        
        .question-card.active {
            display: block;
            animation: fadeIn 0.5s ease;
            box-shadow: 0 5px 20px rgba(26, 75, 140, 0.1);
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .card-header {
            background: linear-gradient(135deg, #f8f9fa, #ffffff);
            border-bottom: 2px solid var(--secondary-gold);
            font-weight: 600;
            padding: 1rem 1.5rem;
        }
        
        .card-header h5 {
            color: var(--dark-blue);
            font-weight: 600;
        }
        
        .card-body {
            padding: 1.5rem;
        }
        
        /* Question Text - Allow HTML formatting */
        .question-text {
            font-size: 1.1rem;
            line-height: 1.6;
            color: var(--dark-blue);
            margin-bottom: 1.5rem;
            padding: 1rem;
            background: linear-gradient(135deg, #f8f9fa, #ffffff);
            border-radius: 10px;
            border-left: 3px solid var(--secondary-gold);
        }
        
        .question-text p {
            margin-bottom: 0.5rem;
        }
        
        .question-text strong, .question-text b {
            font-weight: 600;
            color: var(--dark-blue);
        }
        
        .question-text em, .question-text i {
            font-style: italic;
        }
        
        .question-text u {
            text-decoration: underline;
        }
        
        .question-text h1, .question-text h2, .question-text h3, 
        .question-text h4, .question-text h5, .question-text h6 {
            color: var(--primary-blue);
            margin-bottom: 0.5rem;
        }
        
        .question-text img {
            max-width: 100%;
            height: auto;
            border-radius: 5px;
            margin: 0.5rem 0;
        }
        
        .question-text table {
            width: 100%;
            border-collapse: collapse;
            margin: 0.5rem 0;
        }
        
        .question-text table, .question-text th, .question-text td {
            border: 1px solid #ddd;
            padding: 0.5rem;
        }
        
        .question-text th {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
        }
        
        .question-text ul, .question-text ol {
            padding-left: 1.5rem;
            margin-bottom: 0.5rem;
        }
        
        .question-text li {
            margin-bottom: 0.25rem;
        }
        
        /* Math rendering */
        .katex-display {
            margin: 0.5rem 0;
            overflow-x: auto;
            overflow-y: hidden;
        }
        
        /* Options */
        .option-label {
            display: flex;
            align-items: flex-start;
            padding: 1rem 1.5rem;
            margin: 0.5rem 0;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.2s;
            font-size: 1rem;
        }
        
        .option-label:hover {
            background: var(--light-gold);
            border-color: var(--secondary-gold);
        }
        
        .option-input:checked + .option-label {
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 75, 140, 0.2);
        }
        
        .option-prefix {
            background: var(--primary-blue);
            color: white;
            width: 30px;
            height: 30px;
            min-width: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            margin-right: 1rem;
            font-weight: 600;
        }
        
        .option-input:checked + .option-label .option-prefix {
            background: var(--secondary-gold);
            color: var(--dark-blue);
        }
        
        .option-content {
            flex: 1;
        }
        
        .option-content p {
            margin-bottom: 0.25rem;
        }
        
        .option-content p:last-child {
            margin-bottom: 0;
        }
        
        .option-content strong, .option-content b {
            font-weight: 600;
        }
        
        .option-content img {
            max-width: 100%;
            max-height: 100px;
            object-fit: contain;
            border-radius: 5px;
            margin: 0.25rem 0;
        }
        
        /* Question Media */
        .question-media {
            margin-bottom: 1.5rem;
            text-align: center;
            background: linear-gradient(135deg, #f8f9fa, #ffffff);
            padding: 1.5rem;
            border-radius: 10px;
            border: 1px solid rgba(255, 215, 0, 0.2);
        }
        
        .question-media img, .question-media video {
            max-width: 100%;
            max-height: 300px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        /* Navigation Buttons */
        .navigation-btns {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            padding: 1rem;
            box-shadow: 0 -4px 15px rgba(26, 75, 140, 0.1);
            z-index: 1000;
            border-top: 3px solid var(--secondary-gold);
        }
        
        .btn-nav {
            min-width: 120px;
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-prev {
            background: transparent;
            border: 2px solid var(--primary-blue);
            color: var(--primary-blue);
        }
        
        .btn-prev:hover {
            background: var(--primary-blue);
            color: white;
            transform: translateY(-2px);
        }
        
        .btn-next {
            background: var(--primary-blue);
            border: 2px solid var(--primary-blue);
            color: white;
        }
        
        .btn-next:hover {
            background: var(--dark-blue);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(26, 75, 140, 0.3);
        }
        
        .btn-submit {
            background: linear-gradient(135deg, var(--success-green), #218838);
            border: none;
            color: white;
            padding: 0.75rem 2rem;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
        }
        
        .progress-indicator {
            background: linear-gradient(135deg, var(--light-gold), #ffffff);
            padding: 0.5rem 1.5rem;
            border-radius: 50px;
            font-weight: 600;
            color: var(--dark-blue);
            border: 1px solid var(--secondary-gold);
        }
        
        /* Fullscreen warning */
        #fullscreen-warning {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, rgba(26, 75, 140, 0.95), rgba(15, 43, 79, 0.95));
            color: white;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            font-size: 1.5rem;
            text-align: center;
            padding: 20px;
            backdrop-filter: blur(5px);
        }
        
        #fullscreen-warning i {
            color: var(--secondary-gold);
            font-size: 4rem;
            margin-bottom: 1rem;
        }
        
        /* Submit Confirmation Modal */
        .modal-content {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            border: 2px solid var(--secondary-gold);
        }
        
        .modal-header {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            border-bottom: 2px solid var(--secondary-gold);
            padding: 1.5rem;
        }
        
        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }
        
        .modal-footer {
            border-top: 1px solid var(--light-gold);
            padding: 1.5rem;
        }
        
        .modal-body {
            padding: 2rem;
        }
        
        .warning-icon {
            color: var(--secondary-gold);
            font-size: 3rem;
            margin-bottom: 1rem;
        }
        
        /* Footer */
        .exam-footer {
            background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
            color: white;
            padding: 0.75rem 0;
            font-size: 0.8rem;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .timer-display {
                font-size: 1.2rem;
            }
            
            .btn-nav {
                min-width: 80px;
                padding: 0.5rem 1rem;
            }
            
            .progress-indicator {
                padding: 0.5rem;
                font-size: 0.9rem;
            }
            
            .option-label {
                padding: 0.75rem;
            }
        }
    </style>
</head>
<body>
    <!-- Fullscreen warning (initially hidden) -->
    <div id="fullscreen-warning" style="display: none;">
        <i class="fas fa-expand"></i>
        <h2 class="mb-3">Fullscreen Mode Required</h2>
        <p class="mb-4">You must be in fullscreen mode to continue with the exam.</p>
        <button id="enter-fullscreen" class="btn btn-lg" style="background: var(--secondary-gold); color: var(--dark-blue); padding: 0.75rem 2rem; border-radius: 50px; font-weight: 600;">
            <i class="fas fa-expand me-2"></i> Enter Fullscreen
        </button>
    </div>

    <!-- Header -->
    <div class="exam-header">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <div class="logo-container">
                    <img src="../coll_logo.png" alt="<?= $schoolName ?>" class="school-logo">
                    <div>
                        <small><?= $schoolName ?></small>
                    </div>
                </div>
                <div>
                    <span class="assessment-badge <?= getAssessmentBadgeClass($_SESSION['current_exam']['assessment_type']) ?>">
                        <i class="fas fa-tag me-1"></i> <?= $_SESSION['current_exam']['assessment_type'] ?>
                    </span>
                </div>
            </div>
        </div>
    </div>

    <!-- Timer Section -->
    <div class="timer-container">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-clock me-3" style="color: var(--secondary-gold); font-size: 1.5rem;"></i>
                        <div>
                            <small class="text-muted">Time Remaining</small>
                            <div id="timer" class="timer-display <?= $timeLeft < 300 ? 'timer-danger' : '' ?>">
                                <?= gmdate("H:i:s", $timeLeft) ?>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="text-md-end">
                        <span class="badge bg-primary p-2">
                            <i class="fas fa-book-open me-1"></i> <?= htmlspecialchars($_SESSION['current_exam']['subject_name']) ?>
                        </span>
                        <span class="badge bg-secondary p-2 ms-2">
                            <i class="fas fa-star me-1"></i> Total Marks: <?= $_SESSION['current_exam']['total_marks'] ?>
                        </span>
                    </div>
                </div>
            </div>
            <div class="progress mt-2">
                <div id="time-progress" class="progress-bar" role="progressbar" style="width: 100%"></div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="container">
        <div class="question-container">
            <form id="exam-form" action="submit_exam.php" method="post">
                <input type="hidden" name="exam_subject_id" value="<?= $_SESSION['current_exam']['exam_subject_id'] ?>">
                <input type="hidden" name="subject" value="<?= htmlspecialchars($_SESSION['current_exam']['subject_name']) ?>">
                <input type="hidden" name="class" value="<?= htmlspecialchars($_SESSION['current_exam']['class']) ?>">
                <input type="hidden" name="term" value="<?= htmlspecialchars($_SESSION['exam_info']['term']) ?>">
                <input type="hidden" name="session" value="<?= htmlspecialchars($_SESSION['exam_info']['session']) ?>">
                <input type="hidden" name="assessment_type" value="<?= $_SESSION['current_exam']['assessment_type'] ?>">
                <input type="hidden" name="result_column" value="<?= $resultColumn ?>">
                
                <?php foreach ($questions as $index => $question): ?>
                    <div class="question-card" id="question-<?= $index ?>" <?= $index === 0 ? 'style="display:block;"' : '' ?>>
                        <div class="card-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">
                                    <i class="fas fa-question-circle me-2" style="color: var(--secondary-gold);"></i>
                                    Question <?= $index + 1 ?>
                                </h5>
                                <span class="badge bg-info">Marks: <?= $question['marks'] ?? 1 ?></span>
                            </div>
                        </div>
                        
                        <div class="card-body">
                            <?php if (!empty($question['file_path'])): ?>
                                <div class="question-media">
                                    <?php if (preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $question['file_path'])): ?>
                                        <img src="<?= htmlspecialchars($question['file_path']) ?>" class="img-fluid" alt="Question Image">
                                    <?php elseif (preg_match('/\.(mp4|webm|ogg)$/i', $question['file_path'])): ?>
                                        <video controls class="img-fluid">
                                            <source src="<?= htmlspecialchars($question['file_path']) ?>">
                                            Your browser does not support the video tag.
                                        </video>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Question Text - Fully Decoded and Rendered as HTML -->
                            <div class="question-text">
                                <?= decodeHtmlContent($question['question_text']) ?>
                            </div>
                            
                            <div class="options mt-4">
                                <?php foreach (['A' => 'option_a', 'B' => 'option_b', 'C' => 'option_c', 'D' => 'option_d'] as $letter => $option): ?>
                                    <?php if (!empty($question[$option])): ?>
                                        <div class="form-check">
                                            <input class="form-check-input option-input" 
                                                   type="radio" 
                                                   name="answers[<?= $question['id'] ?>]" 
                                                   id="q<?= $question['id'] ?>-<?= $letter ?>" 
                                                   value="<?= $letter ?>"
                                                   style="display: none;">
                                            <label class="option-label" for="q<?= $question['id'] ?>-<?= $letter ?>">
                                                <span class="option-prefix"><?= $letter ?></span>
                                                <!-- Option Content - Fully Decoded and Rendered as HTML -->
                                                <div class="option-content">
                                                    <?= decodeHtmlContent($question[$option]) ?>
                                                </div>
                                            </label>
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </form>
        </div>
    </div>

    <!-- Navigation Buttons -->
    <div class="navigation-btns">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <button type="button" class="btn btn-nav btn-prev" id="prev-btn" disabled>
                    <i class="bi bi-chevron-left me-2"></i> Previous
                </button>
                
                <div class="progress-indicator">
                    <span id="current-q">1</span> / <?= count($questions) ?>
                </div>
                
                <button type="button" class="btn btn-nav btn-next" id="next-btn">
                    Next <i class="bi bi-chevron-right ms-2"></i>
                </button>
                
                <button type="button" class="btn btn-submit" id="submit-btn" style="display:none;">
                    <i class="bi bi-check-circle me-2"></i> Submit Exam
                </button>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <div class="exam-footer">
        <div class="container text-center">
            <small>&copy; <?= date('Y') ?> <?= $schoolName ?>. All Rights Reserved.</small>
        </div>
    </div>

    <!-- Submit Confirmation Modal -->
    <div class="modal fade" id="submitConfirmModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-exclamation-triangle me-2" style="color: var(--secondary-gold);"></i>
                        Submit Confirmation
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center py-4">
                    <i class="fas fa-check-circle warning-icon"></i>
                    <h4 class="mb-3">Ready to Submit?</h4>
                    
                    <div class="alert alert-warning text-start mb-4">
                        <i class="bi bi-check-circle-fill me-2"></i>
                        <strong>Please verify:</strong>
                        <ul class="mt-2 mb-0">
                            <li>You have answered all questions</li>
                            <li>You've reviewed your answers</li>
                            <li>Time remaining: <span id="remaining-time-display" class="fw-bold"><?= gmdate("H:i:s", $timeLeft) ?></span></li>
                            <li>Assessment Type: <span class="fw-bold"><?= $_SESSION['current_exam']['assessment_type'] ?></span></li>
                        </ul>
                    </div>
                    
                    <p class="text-muted">Once submitted, you cannot change your answers.</p>
                </div>
                <div class="modal-footer justify-content-center">
                    <button type="button" class="btn btn-outline-secondary px-4" data-bs-dismiss="modal">
                        <i class="bi bi-arrow-left-circle me-2"></i> Continue Exam
                    </button>
                    <button type="button" class="btn btn-success px-4" id="confirmSubmit">
                        <i class="bi bi-check-circle me-2"></i> Submit Now
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- KaTeX for math rendering -->
    <script src="https://cdn.jsdelivr.net/npm/katex@0.16.7/dist/katex.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/katex@0.16.7/dist/contrib/auto-render.min.js"></script>
    
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Render math in questions and options
            renderMathInElement(document.body, {
                delimiters: [
                    {left: '$$', right: '$$', display: true},
                    {left: '$', right: '$', display: false},
                    {left: '\\(', right: '\\)', display: false},
                    {left: '\\[', right: '\\]', display: true}
                ],
                throwOnError: false
            });

            // Fullscreen enforcement
            const fullscreenWarning = document.getElementById('fullscreen-warning');
            const enterFullscreenBtn = document.getElementById('enter-fullscreen');
            
            function checkFullscreen() {
                if (!document.fullscreenElement) {
                    fullscreenWarning.style.display = 'flex';
                    return false;
                }
                fullscreenWarning.style.display = 'none';
                return true;
            }
            
            function requestFullscreen() {
                if (!document.fullscreenElement) {
                    document.documentElement.requestFullscreen().catch(err => {
                        console.error(`Error attempting to enable fullscreen: ${err.message}`);
                    });
                }
            }
            
            enterFullscreenBtn.addEventListener('click', function() {
                requestFullscreen();
            });
            
            document.addEventListener('fullscreenchange', checkFullscreen);
            document.addEventListener('webkitfullscreenchange', checkFullscreen);
            document.addEventListener('mozfullscreenchange', checkFullscreen);
            document.addEventListener('MSFullscreenChange', checkFullscreen);
            
            // Initial check
            if (!checkFullscreen()) {
                requestFullscreen();
            }
            
            // Timer functionality
            const endTime = <?= $endTime ?>;
            const totalDuration = <?= $_SESSION['current_exam']['duration'] * 60 ?>;
            const timerElement = document.getElementById('timer');
            const progressBar = document.getElementById('time-progress');
            
            function updateTimer() {
                const now = Math.floor(Date.now() / 1000);
                const remaining = endTime - now;
                
                if (remaining <= 0) {
                    timerElement.textContent = "00:00:00";
                    progressBar.style.width = "0%";
                    // Auto-submit when time expires
                    document.getElementById('exam-form').submit();
                    return;
                }
                
                const hours = Math.floor(remaining / 3600);
                const minutes = Math.floor((remaining % 3600) / 60);
                const seconds = remaining % 60;
                
                timerElement.textContent = 
                    `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                
                const progressPercent = (remaining / totalDuration) * 100;
                progressBar.style.width = `${progressPercent}%`;
                
                if (remaining < 300) {
                    timerElement.classList.add('timer-danger');
                }
                
                // Update remaining time in modal
                const remainingDisplay = document.getElementById('remaining-time-display');
                if (remainingDisplay) {
                    remainingDisplay.textContent = 
                        `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                }
            }
            
            const timerInterval = setInterval(updateTimer, 1000);
            updateTimer();

            // Question navigation
            const questions = Array.from(document.querySelectorAll('.question-card'));
            const totalQuestions = questions.length;
            let currentQuestion = 0;
            
            const prevBtn = document.getElementById('prev-btn');
            const nextBtn = document.getElementById('next-btn');
            const submitBtn = document.getElementById('submit-btn');
            const currentQIndicator = document.getElementById('current-q');
            
            // Initialize navigation
            function showQuestion(index) {
                questions.forEach((question, i) => {
                    question.style.display = i === index ? 'block' : 'none';
                });
                
                updateButtonStates();
            }
            
            function updateButtonStates() {
                prevBtn.disabled = currentQuestion === 0;
                
                if (currentQuestion >= totalQuestions - 1) {
                    nextBtn.style.display = 'none';
                    submitBtn.style.display = 'block';
                } else {
                    nextBtn.style.display = 'block';
                    submitBtn.style.display = 'none';
                }
                
                currentQIndicator.textContent = currentQuestion + 1;
            }
            
            function goToPreviousQuestion() {
                if (currentQuestion > 0) {
                    currentQuestion--;
                    showQuestion(currentQuestion);
                }
            }
            
            function goToNextQuestion() {
                if (currentQuestion < totalQuestions - 1) {
                    currentQuestion++;
                    showQuestion(currentQuestion);
                }
            }
            
            // Event listeners
            prevBtn.addEventListener('click', goToPreviousQuestion);
            nextBtn.addEventListener('click', goToNextQuestion);
            
            // Keyboard navigation
            document.addEventListener('keydown', function(e) {
                if (e.key === 'ArrowLeft') {
                    e.preventDefault();
                    goToPreviousQuestion();
                } else if (e.key === 'ArrowRight') {
                    e.preventDefault();
                    goToNextQuestion();
                }
            });
            
            // Auto-save answers
            document.querySelectorAll('.option-input').forEach(input => {
                input.addEventListener('change', function() {
                    // Visual feedback for saved answer
                    const label = this.nextElementSibling;
                    label.style.background = 'linear-gradient(135deg, #e8f5e9, #c8e6c9)';
                    setTimeout(() => {
                        label.style.background = '';
                    }, 500);
                });
            });
            
            // Submit confirmation handling
            const examForm = document.getElementById('exam-form');
            const submitModal = new bootstrap.Modal(document.getElementById('submitConfirmModal'));
            
            submitBtn.addEventListener('click', function(e) {
                e.preventDefault();
                submitModal.show();
            });
            
            document.getElementById('confirmSubmit').addEventListener('click', function() {
                submitModal.hide();
                examForm.submit();
            });
            
            // Prevent accidental navigation
            window.addEventListener('beforeunload', function(e) {
                e.preventDefault();
                e.returnValue = 'Are you sure you want to leave? Your answers will be lost.';
            });
            
            // Remove warning when submitting
            examForm.addEventListener('submit', function() {
                window.removeEventListener('beforeunload', function(){});
            });
            
            // Initialize first question
            showQuestion(currentQuestion);
        });
        
        // Track if user has made changes
let hasChanges = false;

// Mark changes when answers are selected
document.querySelectorAll('.option-input').forEach(input => {
    input.addEventListener('change', function() {
        hasChanges = true;
        // Visual feedback for saved answer
        const label = this.nextElementSibling;
        label.style.background = 'linear-gradient(135deg, #e8f5e9, #c8e6c9)';
        setTimeout(() => {
            label.style.background = '';
        }, 500);
    });
});

// Modified beforeunload handler
window.addEventListener('beforeunload', function(e) {
    if (hasChanges) {
        e.preventDefault();
        e.returnValue = 'You have unsaved answers. Are you sure you want to leave?';
    }
});

// Clear changes flag when submitting
examForm.addEventListener('submit', function() {
    hasChanges = false;
    window.removeEventListener('beforeunload', function(){});
});

// Also clear when navigating to next/previous (answers are auto-saved)
document.getElementById('next-btn').addEventListener('click', function() {
    hasChanges = false;
});

document.getElementById('prev-btn').addEventListener('click', function() {
    hasChanges = false;
});
        
    </script>
</body>
</html>