<?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();

// Verify user is logged in and has selected an exam
if (!isset($_SESSION['student']) || !isset($_GET['exam_subject_id'])) {
    header("Location: cbt_index.php");
    exit();
}

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

// Get exam subject details with assessment type
try {
    $stmt = $DBH->prepare("
        SELECT 
            es.*, 
            s.subject, 
            e.exam_name, 
            e.exam_description, 
            ec.class,
            ec.term,
            ec.session,
            es.assessment_type
        FROM tbl_exam_subject es
        JOIN tbl_subject s ON es.subject_id = s.id
        JOIN tbl_exam e ON es.exam_id = e.id
        JOIN tbl_exam_class ec ON es.exam_id = ec.exam_id
        WHERE es.id = :exam_subject_id
        AND ec.class = :class
        AND ec.term = :term
        AND ec.session = :session
        AND es.assessment_type = :assessment_type
    ");
    
    $stmt->execute([
        'exam_subject_id' => $_GET['exam_subject_id'],
        'class' => $_SESSION['exam_info']['class'],
        'term' => $_SESSION['exam_info']['term'],
        'session' => $_SESSION['exam_info']['session'],
        'assessment_type' => $_SESSION['exam_info']['assessment_type']
    ]);
    
    $examSubject = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$examSubject) {
        throw new Exception("Invalid exam selected for your class");
    }
    
    // Check if exam is already completed - now with assessment type
    $stmt = $DBH->prepare("
        SELECT id FROM tbl_cbt_results
        WHERE registration_no = :reg_no
        AND subject = :subject
        AND term = :term
        AND session = :session
        AND assessment_type = :assessment_type
    ");
    $stmt->execute([
        'reg_no' => $_SESSION['student']['registration_no'],
        'subject' => $examSubject['subject'],
        'term' => $_SESSION['exam_info']['term'],
        'session' => $_SESSION['exam_info']['session'],
        'assessment_type' => $_SESSION['exam_info']['assessment_type']
    ]);
    
    if ($stmt->fetch()) {
        $_SESSION['error'] = "You have already completed this " . $_SESSION['exam_info']['assessment_type'] . " exam for " . $examSubject['subject'];
        header("Location: welcome.php");
        exit();
    }
    
    // Check if exam date is valid (not expired)
    $examDate = new DateTime($examSubject['exam_date']);
    $currentDate = new DateTime();
    $examDate->setTime(23, 59, 59); // End of exam day
    
    if ($currentDate > $examDate) {
        throw new Exception("This exam has expired. It was scheduled for " . $examSubject['exam_date']);
    }
    
} catch (Exception $e) {
    die("Error: " . $e->getMessage());
}

// 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';
    }
}

// Function to get assessment contribution
function getAssessmentContribution($type) {
    switch($type) {
        case 'CA1':
        case 'CA2':
        case 'CA3':
            return 20;
        case 'Term Exam':
            return 60;
        case 'Mock Exam':
            return 100;
        default:
            return 0;
    }
}

$contribution = getAssessmentContribution($_SESSION['exam_info']['assessment_type']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exam Instructions - <?= $schoolName ?> CBT</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">
    
    <!-- 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">
    
    <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 {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
            color: #333;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        /* Header */
        .header {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            padding: 1rem 0;
            border-bottom: 3px solid var(--secondary-gold);
            margin-bottom: 2rem;
        }
        
        .logo-container {
            display: flex;
            align-items: center;
        }
        
        .school-logo {
            width: 50px;
            height: 50px;
            object-fit: contain;
            background: white;
            padding: 5px;
            border-radius: 50%;
            border: 2px solid var(--secondary-gold);
            margin-right: 15px;
        }
        
        .school-title h1 {
            font-size: 1.3rem;
            font-weight: 700;
            margin-bottom: 0;
        }
        
        .school-title small {
            color: var(--secondary-gold);
            font-size: 0.8rem;
        }
        
        /* Instruction Card */
        .instruction-card {
            max-width: 900px;
            margin: 0 auto;
            border: none;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(26, 75, 140, 0.15);
            overflow: hidden;
            border: 1px solid rgba(255, 215, 0, 0.2);
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
            border-bottom: 2px solid var(--secondary-gold);
            padding: 1.5rem;
        }
        
        .card-header h3 {
            margin: 0;
            font-weight: 600;
        }
        
        .card-header i {
            color: var(--secondary-gold);
            margin-right: 0.5rem;
        }
        
        .card-body {
            padding: 2rem;
            background: white;
        }
        
        /* Assessment Type Badge */
        .assessment-badge {
            display: inline-block;
            padding: 0.5rem 1.5rem;
            border-radius: 50px;
            font-size: 0.9rem;
            font-weight: 600;
        }
        
        .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; }
        
        /* Subject Title */
        .subject-title {
            font-size: 2rem;
            font-weight: 700;
            color: var(--dark-blue);
            margin-bottom: 0.5rem;
        }
        
        .exam-meta {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
            margin: 1rem 0;
        }
        
        .meta-item {
            background: linear-gradient(135deg, #f8f9fa, #ffffff);
            border: 1px solid rgba(255, 215, 0, 0.3);
            border-radius: 50px;
            padding: 0.5rem 1.5rem;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .meta-item i {
            color: var(--secondary-gold);
        }
        
        /* Access Key Section */
        .access-key-section {
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            border-radius: 10px;
            padding: 1.5rem;
            margin: 1.5rem 0;
            border-left: 4px solid var(--secondary-gold);
        }
        
        .access-key-input {
            border: 2px solid var(--secondary-gold);
            border-radius: 50px;
            padding: 0.75rem 1.5rem;
            font-size: 1.1rem;
            letter-spacing: 2px;
            text-transform: uppercase;
        }
        
        .access-key-input:focus {
            box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
            border-color: var(--secondary-gold);
        }
        
        .btn-verify {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            border: none;
            color: white;
            padding: 0.75rem 2rem;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s ease;
            width: 100%;
        }
        
        .btn-verify:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(26, 75, 140, 0.3);
        }
        
        /* Rules Section */
        .rules-section {
            background: linear-gradient(135deg, #f8f9fa, #ffffff);
            border-radius: 10px;
            padding: 1.5rem;
            margin: 1.5rem 0;
            border-left: 4px solid var(--secondary-gold);
        }
        
        .rules-title {
            color: var(--dark-blue);
            font-weight: 600;
            margin-bottom: 1rem;
        }
        
        .rule-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .rule-list li {
            padding: 0.75rem 0;
            border-bottom: 1px solid rgba(255, 215, 0, 0.2);
            display: flex;
            align-items: center;
        }
        
        .rule-list li:last-child {
            border-bottom: none;
        }
        
        .rule-list i {
            width: 30px;
            font-size: 1.1rem;
        }
        
        .rule-allowed i {
            color: var(--success-green);
        }
        
        .rule-forbidden i {
            color: var(--danger-red);
        }
        
        /* Warning Alert */
        .warning-alert {
            background: linear-gradient(135deg, #fff3cd, #ffeaa7);
            border-left: 4px solid #ffc107;
            border-radius: 10px;
            padding: 1.5rem;
            margin: 1.5rem 0;
        }
        
        .warning-alert i {
            color: #ffc107;
            font-size: 2rem;
            margin-right: 1rem;
        }
        
        /* Modal Styles */
        .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);
        }
        
        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }
        
        .modal-body {
            padding: 2rem;
        }
        
        .modal-footer {
            border-top: 1px solid var(--light-gold);
            padding: 1.5rem;
        }
        
        .verification-success {
            color: var(--success-green);
            font-size: 3rem;
            margin-bottom: 1rem;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
            margin: 1.5rem 0;
        }
        
        .info-item {
            background: linear-gradient(135deg, #f8f9fa, #ffffff);
            border-radius: 10px;
            padding: 1rem;
            border-left: 3px solid var(--secondary-gold);
        }
        
        .info-label {
            font-size: 0.85rem;
            color: #666;
            margin-bottom: 0.25rem;
        }
        
        .info-value {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--dark-blue);
        }
        
        .info-value i {
            color: var(--secondary-gold);
            margin-right: 0.5rem;
        }
        
        .btn-proceed {
            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-proceed:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
        }
        
        /* Footer */
        .footer {
            background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
            color: white;
            padding: 1rem 0;
            margin-top: 3rem;
            border-top: 3px solid var(--secondary-gold);
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .subject-title {
                font-size: 1.5rem;
            }
            
            .exam-meta {
                flex-direction: column;
                gap: 0.5rem;
            }
            
            .meta-item {
                width: 100%;
            }
            
            .info-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="header">
        <div class="container">
            <div class="logo-container">
                <img src="../coll_logo.png" alt="<?= $schoolName ?>" class="school-logo">
                <div class="school-title">
                    <h1><?= $schoolName ?></h1>
                    <small><?= $schoolMotto ?></small>
                </div>
            </div>
        </div>
    </div>

    <!-- Access Key Verification Modal -->
    <div class="modal fade" id="accessKeyModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-key me-2" style="color: var(--secondary-gold);"></i>
                        Exam Access Key Required
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="verification-form">
                        <p class="text-center mb-4">Please enter your exam access key to continue.</p>
                        <div class="mb-3">
                            <input type="text" class="form-control access-key-input" id="accessCode" 
                                   placeholder="Enter Access Key" maxlength="20" autocomplete="off">
                        </div>
                        <div id="accessKeyError" class="alert alert-danger d-none"></div>
                        <button type="button" class="btn btn-verify" onclick="verifyAccessKey()">
                            <i class="fas fa-check-circle me-2"></i> Verify Access Key
                        </button>
                    </div>
                    
                    <div id="verification-success" style="display: none;">
                        <div class="text-center">
                            <i class="fas fa-check-circle verification-success"></i>
                            <h4 class="mb-4">Access Key Verified!</h4>
                        </div>
                        
                        <div class="info-grid">
                            <div class="info-item">
                                <div class="info-label">Student Name</div>
                                <div class="info-value">
                                    <i class="fas fa-user-graduate"></i>
                                    <?= htmlspecialchars($_SESSION['student']['fullname']) ?>
                                </div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Registration No</div>
                                <div class="info-value">
                                    <i class="fas fa-id-card"></i>
                                    <?= htmlspecialchars($_SESSION['student']['registration_no']) ?>
                                </div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Subject</div>
                                <div class="info-value">
                                    <i class="fas fa-book"></i>
                                    <?= htmlspecialchars($examSubject['subject']) ?>
                                </div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Assessment Type</div>
                                <div class="info-value">
                                    <span class="assessment-badge <?= getAssessmentBadgeClass($_SESSION['exam_info']['assessment_type']) ?>" style="margin-left: 0;">
                                        <?= $_SESSION['exam_info']['assessment_type'] ?>
                                    </span>
                                </div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Class</div>
                                <div class="info-value">
                                    <i class="fas fa-users"></i>
                                    <?= htmlspecialchars($examSubject['class']) ?>
                                </div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Exam Date</div>
                                <div class="info-value">
                                    <i class="fas fa-calendar-alt"></i>
                                    <?= date('F j, Y', strtotime($examSubject['exam_date'])) ?>
                                </div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Duration</div>
                                <div class="info-value">
                                    <i class="fas fa-clock"></i>
                                    <?= $examSubject['duration_minutes'] ?> minutes
                                </div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">Contribution</div>
                                <div class="info-value">
                                    <i class="fas fa-percent"></i>
                                    <?= $contribution ?>% of term result
                                </div>
                            </div>
                        </div>
                        
                        <div class="alert alert-warning mt-3">
                            <i class="fas fa-info-circle me-2"></i>
                            This access key can only be used once and will expire after the exam.
                        </div>
                    </div>
                </div>
                <div class="modal-footer" id="modalFooter" style="display: none;">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-2"></i> Cancel
                    </button>
                    <a href="cbt_exam.php?exam_subject_id=<?= $examSubject['id'] ?>" class="btn btn-proceed" id="proceedBtn">
                        <i class="fas fa-arrow-right me-2"></i> Proceed to Exam
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="instruction-card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h3><i class="fas fa-clipboard-list"></i> Exam Instructions</h3>
                    <span class="assessment-badge <?= getAssessmentBadgeClass($_SESSION['exam_info']['assessment_type']) ?>">
                        <?= htmlspecialchars($_SESSION['exam_info']['assessment_type']) ?>
                    </span>
                </div>
            </div>
            
            <div class="card-body">
                <!-- Subject and Exam Info -->
                <div class="text-center mb-4">
                    <h2 class="subject-title"><?= htmlspecialchars($examSubject['subject']) ?></h2>
                    <p class="text-muted"><?= htmlspecialchars($examSubject['exam_description'] ?: 'Computer Based Test Examination') ?></p>
                </div>
                
                <!-- Exam Metadata -->
                <div class="exam-meta justify-content-center">
                    <span class="meta-item">
                        <i class="fas fa-users"></i> <?= htmlspecialchars($examSubject['class']) ?>
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-calendar-alt"></i> <?= htmlspecialchars($_SESSION['exam_info']['term']) ?>
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-calendar"></i> <?= htmlspecialchars($_SESSION['exam_info']['session']) ?>
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-clock"></i> Duration: <?= $examSubject['duration_minutes'] ?> minutes
                    </span>
                    <span class="meta-item">
                        <i class="fas fa-percent"></i> Contributes <?= $contribution ?>%
                    </span>
                </div>
                
                <!-- Access Key Section -->
                <div class="access-key-section">
                    <h5 class="mb-3"><i class="fas fa-key me-2" style="color: var(--secondary-gold);"></i>Access Key Required</h5>
                    <p class="mb-3">You need a valid access key to start this exam. The access key:</p>
                    <ul>
                        <li>Can only be used once</li>
                        <li>Expires at the end of the exam day</li>
                        <li>Is specific to this subject and assessment type</li>
                        <li>Cannot be shared with other students</li>
                    </ul>
                    
                    <!-- Start Exam Button -->
                    <div class="text-center mt-4">
                        <button type="button" class="btn-verify" style="width: auto; padding: 0.75rem 3rem;" data-bs-toggle="modal" data-bs-target="#accessKeyModal">
                            <i class="fas fa-play me-2"></i> START EXAM
                        </button>
                    </div>
                </div>
                
                <!-- Rules Section -->
                <div class="rules-section">
                    <h5 class="rules-title"><i class="fas fa-list-check me-2" style="color: var(--secondary-gold);"></i>Important Rules & Guidelines</h5>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <ul class="rule-list">
                                <li class="rule-allowed">
                                    <i class="fas fa-check-circle"></i>
                                    The exam contains multiple choice questions
                                </li>
                                <li class="rule-allowed">
                                    <i class="fas fa-check-circle"></i>
                                    Timer starts when you click "Begin Exam"
                                </li>
                                <li class="rule-allowed">
                                    <i class="fas fa-check-circle"></i>
                                    Use Next/Previous buttons to navigate
                                </li>
                                <li class="rule-allowed">
                                    <i class="fas fa-check-circle"></i>
                                    Answers are saved automatically
                                </li>
                                <li class="rule-allowed">
                                    <i class="fas fa-check-circle"></i>
                                    Exam auto-submits when time expires
                                </li>
                            </ul>
                        </div>
                        <div class="col-md-6">
                            <ul class="rule-list">
                                <li class="rule-forbidden">
                                    <i class="fas fa-times-circle"></i>
                                    Do not refresh the page during exam
                                </li>
                                <li class="rule-forbidden">
                                    <i class="fas fa-times-circle"></i>
                                    Do not navigate away from exam page
                                </li>
                                <li class="rule-forbidden">
                                    <i class="fas fa-times-circle"></i>
                                    No switching between browser tabs
                                </li>
                                <li class="rule-forbidden">
                                    <i class="fas fa-times-circle"></i>
                                    No copying or printing questions
                                </li>
                                <li class="rule-forbidden">
                                    <i class="fas fa-times-circle"></i>
                                    No communication with others
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <!-- Warning Alert -->
                <div class="warning-alert">
                    <div class="d-flex align-items-center">
                        <i class="fas fa-exclamation-triangle"></i>
                        <div>
                            <h5 class="alert-heading mb-1">⚠️ Important Warning</h5>
                            <p class="mb-0">Any attempt to cheat, refresh the page, or navigate away will result in automatic disqualification. Your exam will be submitted immediately and you will not be allowed to continue.</p>
                        </div>
                    </div>
                </div>
                
                <!-- Back Button -->
                <div class="text-center mt-4">
                    <a href="welcome.php" class="btn btn-outline-secondary px-4 py-2">
                        <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
                    </a>
                </div>
            </div>
        </div>
    </div>

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

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        let verifiedAccessCode = null;
        
        function verifyAccessKey() {
            const accessCode = document.getElementById('accessCode').value.trim();
            const errorDiv = document.getElementById('accessKeyError');
            
            if (!accessCode) {
                errorDiv.textContent = 'Please enter an access key';
                errorDiv.classList.remove('d-none');
                return;
            }
            
            // Show loading state
            const verifyBtn = event.target;
            const originalText = verifyBtn.innerHTML;
            verifyBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Verifying...';
            verifyBtn.disabled = true;
            
            // AJAX request to verify access key
            fetch('verify_access_key.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    access_code: accessCode,
                    exam_subject_id: <?= $examSubject['id'] ?>,
                    registration_no: '<?= $_SESSION['student']['registration_no'] ?>',
                    subject: '<?= $examSubject['subject'] ?>',
                    assessment_type: '<?= $_SESSION['exam_info']['assessment_type'] ?>'
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Hide verification form, show success
                    document.getElementById('verification-form').style.display = 'none';
                    document.getElementById('verification-success').style.display = 'block';
                    document.getElementById('modalFooter').style.display = 'flex';
                    errorDiv.classList.add('d-none');
                    verifiedAccessCode = accessCode;
                    
                    // Store verified access key in session
                    fetch('store_verified_key.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            access_code: accessCode,
                            exam_subject_id: <?= $examSubject['id'] ?>
                        })
                    });
                } else {
                    errorDiv.textContent = data.message;
                    errorDiv.classList.remove('d-none');
                }
            })
            .catch(error => {
                errorDiv.textContent = 'Error verifying access key. Please try again.';
                errorDiv.classList.remove('d-none');
            })
            .finally(() => {
                verifyBtn.innerHTML = originalText;
                verifyBtn.disabled = false;
            });
        }
        
        // Clear error when typing
        document.getElementById('accessCode').addEventListener('input', function() {
            document.getElementById('accessKeyError').classList.add('d-none');
        });
        
        // Allow Enter key to submit
        document.getElementById('accessCode').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                verifyAccessKey();
            }
        });
        
        // Reset modal when closed
        document.getElementById('accessKeyModal').addEventListener('hidden.bs.modal', function() {
            document.getElementById('verification-form').style.display = 'block';
            document.getElementById('verification-success').style.display = 'none';
            document.getElementById('modalFooter').style.display = 'none';
            document.getElementById('accessCode').value = '';
            document.getElementById('accessKeyError').classList.add('d-none');
        });
        
        // Update the proceed button click handler
document.getElementById('proceedBtn').addEventListener('click', function(e) {
    e.preventDefault();
    
    // Show loading state
    const proceedBtn = this;
    const originalText = proceedBtn.innerHTML;
    proceedBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Starting Exam...';
    proceedBtn.disabled = true;
    
    // Mark the key as used before proceeding
    fetch('mark_key_used.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            access_code: verifiedAccessCode,
            registration_no: '<?= $_SESSION['student']['registration_no'] ?>'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Clear the modal and proceed
            bootstrap.Modal.getInstance(document.getElementById('accessKeyModal')).hide();
            window.location.href = 'cbt_exam.php?exam_subject_id=<?= $examSubject['id'] ?>';
        } else {
            alert('Error: ' + data.message);
            proceedBtn.innerHTML = originalText;
            proceedBtn.disabled = false;
        }
    })
    .catch(error => {
        alert('Error marking key as used. Please try again.');
        proceedBtn.innerHTML = originalText;
        proceedBtn.disabled = false;
    });
});
});
        
    </script>
</body>
</html>