<?php
// Enable error reporting 
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '../logs/php_errors.log');

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../includes/db_connect.php';

// Check student session
if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'student') {
    header("Location: ../login.php");
    exit;
}

// Check if exam_id is provided
if (!isset($_GET['exam_id']) || !is_numeric($_GET['exam_id'])) {
    header("Location: student_dashboard.php?error=invalid_exam");
    exit;
}

$exam_id = (int)$_GET['exam_id'];
$student_id = (int)$_SESSION['user_id'];

// Fetch student details
$student_name = 'Student';
try {
    $stmt = $pdo->prepare("SELECT full_name FROM applicants WHERE id = ?");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($student) {
        $student_name = $student['full_name'];
    }
} catch (PDOException $e) {
    error_log("Error fetching student: " . $e->getMessage());
    header("Location: student_dashboard.php?error=db_error");
    exit;
}

// Fetch exam details and verify access
$exam = [];
$questions_by_subject = [];
$time_remaining = 0;
$exam_started = false;

try {
    // Verify exam access and get details
    $stmt = $pdo->prepare("
        SELECT e.*, ec.class_id 
        FROM exams e
        JOIN exam_classes ec ON e.id = ec.exam_id
        JOIN applicants a ON ec.class_id = a.class_id
        WHERE e.id = ? AND a.id = ? AND e.is_active = 1
        AND (e.exam_date = CURDATE() OR e.exam_date < CURDATE())
    ");
    $stmt->execute([$exam_id, $student_id]);
    $exam = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$exam) {
        throw new Exception("You are not authorized to take this exam or it's not available");
    }

    // Check for existing exam session
    $stmt = $pdo->prepare("
        SELECT * FROM student_exams 
        WHERE exam_id = ? AND student_id = ?
    ");
    $stmt->execute([$exam_id, $student_id]);
    $exam_session = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$exam_session) {
        // Start new exam session
        $time_remaining = $exam['duration_minutes'] * 60;
        $start_time = date('Y-m-d H:i:s');
        
        $stmt = $pdo->prepare("
            INSERT INTO student_exams 
            (student_id, exam_id, start_time, time_remaining, status)
            VALUES (?, ?, ?, ?, 'in_progress')
        ");
        $stmt->execute([$student_id, $exam_id, $start_time, $time_remaining]);
    } else {
        // Resume existing session
        if ($exam_session['status'] == 'completed') {
            header("Location: results.php?exam_id=" . $exam_id);
            exit;
        }
        $time_remaining = $exam_session['time_remaining'];
        $exam_started = true;
    }

    // Fetch questions grouped by subject
    $stmt = $pdo->prepare("
        SELECT q.*, s.name as subject_name, s.id as subject_id
        FROM questions q
        JOIN subjects s ON q.subject_id = s.id
        WHERE q.exam_id = ?
        ORDER BY s.id, q.question_number
    ");
    $stmt->execute([$exam_id]);
    $all_questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($all_questions)) {
        throw new Exception("No questions found for this exam");
    }

    // Group questions by subject
    $questions_by_subject = [];
    foreach ($all_questions as $q) {
        $subject_id = $q['subject_id'];
        if (!isset($questions_by_subject[$subject_id])) {
            $questions_by_subject[$subject_id] = [
                'subject_name' => $q['subject_name'],
                'questions' => []
            ];
        }
        $questions_by_subject[$subject_id]['questions'][] = $q;
    }

    // Get list of subject IDs in order
    $subject_ids = array_keys($questions_by_subject);

    // Initialize completed subjects array in session if not exists
    if (!isset($_SESSION['completed_subjects'])) {
        $_SESSION['completed_subjects'] = [];
    }

    // Get current subject and question index
    $show_subject_selection = !isset($_GET['subject_id']) || !in_array((int)$_GET['subject_id'], $subject_ids);
    
    if (!$show_subject_selection) {
        $current_subject_id = (int)$_GET['subject_id'];
        $current_question_index = isset($_GET['question']) ? max(0, (int)$_GET['question'] - 1) : 
                                (isset($_SESSION['current_question_index']) ? (int)$_SESSION['current_question_index'] : 0);

        // Validate current subject
        if (!in_array($current_subject_id, $subject_ids)) {
            $current_subject_id = $subject_ids[0];
            $current_question_index = 0;
            $show_subject_selection = true;
        } else {
            // Get current subject and questions
            $current_subject = $questions_by_subject[$current_subject_id];
            $questions = $current_subject['questions'];
            $total_questions = count($questions);
            $current_subject_index = array_search($current_subject_id, $subject_ids);
            $total_subjects = count($subject_ids);

            // Validate current question index
            $current_question_index = max(0, min($current_question_index, $total_questions - 1));
            $_SESSION['current_subject_id'] = $current_subject_id;
            $_SESSION['current_question_index'] = $current_question_index;

            // Get current question data
            $current_q = $questions[$current_question_index];

            // Check for existing answer
            $stmt = $pdo->prepare("
                SELECT answer FROM student_answers
                WHERE student_id = ? AND exam_id = ? AND question_id = ?
            ");
            $stmt->execute([$student_id, $exam_id, $current_q['id']]);
            $existing_answer = $stmt->fetchColumn();

            // Check if subject is completed
            $stmt = $pdo->prepare("
                SELECT COUNT(*) as answered_count
                FROM student_answers sa
                JOIN questions q ON sa.question_id = q.id
                WHERE sa.student_id = ? AND sa.exam_id = ? AND q.subject_id = ?
            ");
            $stmt->execute([$student_id, $exam_id, $current_subject_id]);
            $answered_count = $stmt->fetchColumn();

            if ($answered_count >= $total_questions && !in_array($current_subject_id, $_SESSION['completed_subjects'])) {
                $_SESSION['completed_subjects'][] = $current_subject_id;
            }
        }
    }

} catch (Exception $e) {
    error_log("Exam Error: " . $e->getMessage());
    header("Location: student_dashboard.php?error=" . urlencode($e->getMessage()));
    exit;
}

// Handle answer submission via AJAX
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    try {
        $question_id = (int)$_POST['question_id'];
        $answer = isset($_POST['answer']) ? strtoupper(trim($_POST['answer'])) : null;
        
        if ($answer && !in_array($answer, ['A', 'B', 'C', 'D'])) {
            throw new Exception("Invalid answer");
        }

        // Save answer
        $stmt = $pdo->prepare("
            INSERT INTO student_answers 
            (student_id, exam_id, question_id, answer, created_at, updated_at)
            VALUES (?, ?, ?, ?, NOW(), NOW())
            ON DUPLICATE KEY UPDATE answer = VALUES(answer), updated_at = NOW()
        ");
        $stmt->execute([$student_id, $exam_id, $question_id, $answer]);

        // Update exam session timestamp
        $stmt = $pdo->prepare("
            UPDATE student_exams 
            SET updated_at = NOW() 
            WHERE student_id = ? AND exam_id = ?
        ");
        $stmt->execute([$student_id, $exam_id]);

        // Check if current subject is completed
        $stmt = $pdo->prepare("
            SELECT COUNT(*) as answered_count
            FROM student_answers sa
            JOIN questions q ON sa.question_id = q.id
            WHERE sa.student_id = ? AND sa.exam_id = ? AND q.subject_id = ?
        ");
        $stmt->execute([$student_id, $exam_id, $_POST['subject_id']]);
        $answered_count = $stmt->fetchColumn();
        
        $stmt = $pdo->prepare("
            SELECT COUNT(*) as total_count
            FROM questions
            WHERE exam_id = ? AND subject_id = ?
        ");
        $stmt->execute([$exam_id, $_POST['subject_id']]);
        $total_count = $stmt->fetchColumn();

        if ($answered_count >= $total_count && !in_array((int)$_POST['subject_id'], $_SESSION['completed_subjects'])) {
            $_SESSION['completed_subjects'][] = (int)$_POST['subject_id'];
        }

        echo json_encode(['status' => 'success']);
        exit;

    } catch (Exception $e) {
        error_log("Answer Save Error: " . $e->getMessage());
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Take Exam - <?= htmlspecialchars($exam['exam_name']) ?> - Verbum Dei Academy</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <style>
        :root {
            --primary: #1a73e8;
            --primary-light: #e8f0fe;
            --success: #34a853;
            --warning: #f9ab00;
            --danger: #d93025;
        }
        
        body {
            background-color: #f8f9fc;
            font-family: 'Google Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .exam-header {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(66, 133, 244, 0.1);
            border-left: 5px solid var(--primary);
        }
        
        .question-card {
            background: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(66, 133, 244, 0.1);
            border: 1px solid #e8f0fe;
        }
        
        .timer-container {
            background: linear-gradient(135deg, var(--primary) 0%, #1565c0 100%);
            color: white;
            border-radius: 15px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .question-nav {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: 0 0.15rem 1.75rem 0 rgba(66, 133, 244, 0.1);
        }
        
        .option-item {
            border: 2px solid #e8f0fe;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .option-item:hover {
            border-color: var(--primary);
            background-color: var(--primary-light);
        }
        
        .option-item.selected {
            border-color: var(--primary);
            background-color: var(--primary-light);
        }
        
        .progress-bar {
            background-color: var(--primary);
            height: 8px;
        }
        
        .question-number {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background: var(--primary-light);
            color: var(--primary);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 1rem;
        }
        
        .question-number.active {
            background: var(--primary);
            color: white;
        }
        
        .question-number.answered {
            background: var(--success);
            color: white;
        }
        
        #exitModal .modal-content {
            border-radius: 15px;
        }
        
        .subject-button {
            font-size: 1.2rem;
            font-weight: bold;
            padding: 1rem;
            margin: 0.5rem;
        }
        
        .subject-button.completed {
            background-color: var(--success);
            border-color: var(--success);
        }
        
        @media (max-width: 576px) {
            .question-card {
                padding: 1rem;
            }
            
            .option-item {
                padding: 0.75rem;
            }
        }
    </style>
</head>
<body>
    <div class="container py-4">
        <!-- Exam Header -->
        <div class="exam-header">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="h3 fw-bold text-primary mb-2">
                        <i class="bi bi-journal-text me-2"></i>
                        <?= htmlspecialchars($exam['exam_name']) ?>
                        <?php if (!$show_subject_selection): ?>
                            - <?= htmlspecialchars($current_subject['subject_name']) ?>
                        <?php endif; ?>
                    </h1>
                    <p class="text-muted mb-0">
                        <i class="bi bi-person me-1"></i> <?= htmlspecialchars($student_name) ?> • 
                        <i class="bi bi-clock me-1"></i> Duration: <?= $exam['duration_minutes'] ?> minutes
                    </p>
                </div>
                <div class="col-md-4 text-md-end">
                    <div id="examTimer" class="h4 fw-bold text-primary"></div>
                </div>
            </div>
        </div>

        <?php if ($show_subject_selection): ?>
            <!-- Subject Selection -->
            <div class="question-card">
                <h3 class="fw-bold mb-4">Select a Subject</h3>
                <div class="d-flex flex-wrap justify-content-center">
                    <?php foreach ($questions_by_subject as $subject_id => $subject_data): ?>
                        <a href="?exam_id=<?= $exam_id ?>&subject_id=<?= $subject_id ?>&question=1" 
                           class="btn btn-primary subject-button <?= in_array($subject_id, $_SESSION['completed_subjects']) ? 'completed' : '' ?>">
                            <?= htmlspecialchars($subject_data['subject_name']) ?>
                        </a>
                    <?php endforeach; ?>
                </div>
                <?php if (count($_SESSION['completed_subjects']) === count($subject_ids)): ?>
                    <div class="text-center mt-4">
                        <button class="btn btn-success btn-lg" id="finishExamBtn">
                            <i class="bi bi-check-circle me-1"></i> Submit Exam
                        </button>
                    </div>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="row">
                <!-- Main Question Area -->
                <div class="col-lg-8">
                    <div class="question-card">
                        <!-- Progress Bar -->
                        <div class="progress mt-3" style="height: 8px;">
                            <div class="progress-bar" role="progressbar" 
                                 style="width: <?= (($current_question_index + 1) / $total_questions) * 100 ?>%" 
                                 aria-valuenow="<?= $current_question_index + 1 ?>" 
                                 aria-valuemin="1" 
                                 aria-valuemax="<?= $total_questions ?>">
                            </div>
                        </div>
                        <div class="d-flex justify-content-between mt-2 small text-muted">
                            <span>Question <?= $current_question_index + 1 ?> of <?= $total_questions ?> (<?= htmlspecialchars($current_subject['subject_name']) ?>)</span>
                            <span><?= round((($current_question_index + 1) / $total_questions) * 100) ?>% Complete</span>
                        </div>

                        <!-- Question -->
                        <div class="question-content mb-4 mt-4">
                            <h5 class="fw-bold mb-3">
                                <span class="question-number active"><?= $current_question_index + 1 ?></span>
                                Question
                            </h5>
                            
                            <?php if (!empty($current_q['picture_url'])): ?>
                                <div class="text-center mb-4">
                                    <img src="../Uploads/questions/<?= htmlspecialchars($current_q['picture_url']) ?>" 
                                         class="img-fluid rounded" style="max-height: 250px;">
                                </div>
                            <?php endif; ?>
                            
                            <div class="question-text fs-5">
                                <?= nl2br(htmlspecialchars($current_q['question_text'])) ?>
                            </div>
                        </div>

                        <!-- Options -->
                        <div class="options-container">
                            <?php
                            $options = [
                                'A' => $current_q['option_a'],
                                'B' => $current_q['option_b'], 
                                'C' => $current_q['option_c'],
                                'D' => $current_q['option_d']
                            ];
                            
                            foreach ($options as $letter => $text):
                                if (!empty(trim($text))):
                            ?>
                                <div class="option-item <?= $existing_answer == $letter ? 'selected' : '' ?>" 
                                     data-option="<?= $letter ?>">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" 
                                               name="answer" id="option<?= $letter ?>" 
                                               value="<?= $letter ?>" 
                                               <?= $existing_answer == $letter ? 'checked' : '' ?>>
                                        <label class="form-check-label fw-bold" for="option<?= $letter ?>">
                                            <?= $letter ?>. <?= htmlspecialchars($text) ?>
                                        </label>
                                    </div>
                                </div>
                            <?php endif; endforeach; ?>
                        </div>
                    </div>

                    <!-- Navigation Buttons -->
                    <div class="d-flex justify-content-between">
                        <button class="btn btn-outline-primary px-4" id="prevBtn" 
                                <?= $current_question_index <= 0 ? 'disabled' : '' ?>>
                            <i class="bi bi-chevron-left me-1"></i> Previous
                        </button>
                        
                        <?php if ($current_question_index < $total_questions - 1): ?>
                            <button class="btn btn-primary px-4" id="nextBtn">
                                Next <i class="bi bi-chevron-right ms-1"></i>
                            </button>
                        <?php else: ?>
                            <button class="btn btn-primary px-4" id="finishSubjectBtn">
                                Finish Subject <i class="bi bi-check-circle ms-1"></i>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Sidebar -->
                <div class="col-lg-4">
                    <!-- Timer -->
                    <div class="timer-container text-center mb-4">
                        <h4 class="mb-1">Time Remaining</h4>
                        <div id="timerDisplay" class="h2 fw-bold"><?= gmdate("H:i:s", $time_remaining) ?></div>
                        <small>Hours:Minutes:Seconds</small>
                    </div>

                    <!-- Question Navigator -->
                    <div class="question-nav">
                        <h5 class="fw-bold mb-3">
                            <i class="bi bi-grid me-2"></i>Question Navigator (<?= htmlspecialchars($current_subject['subject_name']) ?>)
                        </h5>
                        <div class="questions-grid">
                            <?php for ($i = 0; $i < $total_questions; $i++): 
                                // Check if question is answered
                                $stmt = $pdo->prepare("
                                    SELECT 1 FROM student_answers 
                                    WHERE student_id = ? AND exam_id = ? AND question_id = ?
                                ");
                                $stmt->execute([$student_id, $exam_id, $questions[$i]['id']]);
                                $is_answered = $stmt->fetch();
                            ?>
                                <a href="?exam_id=<?= $exam_id ?>&subject_id=<?= $current_subject_id ?>&question=<?= $i + 1 ?>" 
                                   class="question-number <?= $i == $current_question_index ? 'active' : '' ?> <?= $is_answered ? 'answered' : '' ?>">
                                    <?= $i + 1 ?>
                                </a>
                            <?php endfor; ?>
                        </div>
                        
                        <div class="mt-3 p-3 bg-light rounded">
                            <small class="d-block mb-1">
                                <span class="question-number active me-2"></span> Current Question
                            </small>
                            <small class="d-block mb-1">
                                <span class="question-number answered me-2"></span> Answered
                            </small>
                            <small class="d-block">
                                <span class="question-number me-2"></span> Not Answered
                            </small>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="text-center mt-3">
                        <button class="btn btn-outline-danger w-100" data-bs-toggle="modal" data-bs-target="#exitModal">
                            <i class="bi bi-box-arrow-left me-1"></i> Exit Exam
                        </button>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Exit Exam Modal -->
    <div class="modal fade" id="exitModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">
                        <i class="bi bi-exclamation-triangle me-2"></i>Exit Exam
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to exit the exam? Your progress will be saved automatically.</p>
                    <div class="alert alert-warning">
                        <i class="bi bi-info-circle me-2"></i>
                        Time will continue counting down until you resume the exam.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <a href="student_dashboard.php" class="btn btn-danger">Exit Exam</a>
                </div>
            </div>
        </div>
    </div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Flag to track internal navigation
    let isInternalNavigation = false;

    // Timer functionality
    let timeRemaining = <?= $time_remaining ?>;
    const timerElement = document.getElementById('timerDisplay');
    const examTimer = document.getElementById('examTimer');
    
    function updateTimer() {
        const hours = Math.floor(timeRemaining / 3600);
        const minutes = Math.floor((timeRemaining % 3600) / 60);
        const seconds = timeRemaining % 60;
        
        const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        if (timerElement) timerElement.textContent = timeString;
        if (examTimer) examTimer.textContent = timeString;
        
        if (timeRemaining <= 0) {
            clearInterval(timerInterval);
            finishExam();
        } else {
            timeRemaining--;
            
            // Save time every 30 seconds
            if (timeRemaining % 30 === 0) {
                saveTimeRemaining(timeRemaining);
            }
        }
    }
    
    function saveTimeRemaining(time) {
        fetch('save_time.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `exam_id=<?= $exam_id ?>&time_remaining=${time}`
        }).catch(error => console.error('Error saving time:', error));
    }
    
    // Start timer
    updateTimer();
    const timerInterval = setInterval(updateTimer, 1000);
    
    <?php if (!$show_subject_selection): ?>
        // Option selection
        document.querySelectorAll('.option-item').forEach(item => {
            item.addEventListener('click', function() {
                // Remove selection from all options
                document.querySelectorAll('.option-item').forEach(opt => {
                    opt.classList.remove('selected');
                });
                
                // Select clicked option
                this.classList.add('selected');
                const radio = this.querySelector('input[type="radio"]');
                radio.checked = true;
                
                // Save answer
                saveAnswer(radio.value);
            });
        });
        
        // Save answer function
        function saveAnswer(answer) {
            const formData = new FormData();
            formData.append('action', 'save_answer');
            formData.append('question_id', <?= $current_q['id'] ?>);
            formData.append('answer', answer);
            formData.append('subject_id', <?= $current_subject_id ?>);
            
            return fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status !== 'success') {
                    console.error('Error saving answer:', data.message);
                    throw new Error(data.message);
                }
                return data;
            })
            .catch(error => {
                console.error('Error:', error);
                throw error;
            });
        }
        
        // Navigation
        function navigateToQuestion(subjectId, questionIndex) {
            // Check if an answer is selected
            const selectedAnswer = document.querySelector('input[name="answer"]:checked');
            if (selectedAnswer) {
                // Save answer before navigating
                return saveAnswer(selectedAnswer.value).then(() => {
                    isInternalNavigation = true;
                    window.location.href = `?exam_id=<?= $exam_id ?>&subject_id=${subjectId}&question=${questionIndex + 1}`;
                }).catch(error => {
                    alert('Error saving answer: ' + error.message);
                });
            } else {
                // No answer selected, navigate directly
                isInternalNavigation = true;
                window.location.href = `?exam_id=<?= $exam_id ?>&subject_id=${subjectId}&question=${questionIndex + 1}`;
            }
        }

        document.getElementById('prevBtn')?.addEventListener('click', function() {
            let nextQuestionIndex = <?= $current_question_index ?> - 1;
            
            if (nextQuestionIndex >= 0) {
                navigateToQuestion(<?= $current_subject_id ?>, nextQuestionIndex);
            }
        });
        
        document.getElementById('nextBtn')?.addEventListener('click', function() {
            let nextQuestionIndex = <?= $current_question_index ?> + 1;
            
            if (nextQuestionIndex < <?= $total_questions ?>) {
                navigateToQuestion(<?= $current_subject_id ?>, nextQuestionIndex);
            }
        });

        document.getElementById('finishSubjectBtn')?.addEventListener('click', function() {
            const selectedAnswer = document.querySelector('input[name="answer"]:checked');
            const finishSubject = () => {
                isInternalNavigation = true;
                window.location.href = `?exam_id=<?= $exam_id ?>`;
            };
            if (selectedAnswer) {
                saveAnswer(selectedAnswer.value).then(finishSubject).catch(error => {
                    alert('Error saving answer: ' + error.message);
                });
            } else {
                finishSubject();
            }
        });

        // Question navigator links
        document.querySelectorAll('.question-number').forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                isInternalNavigation = true;
                const questionNumber = parseInt(this.textContent) - 1;
                navigateToQuestion(<?= $current_subject_id ?>, questionNumber);
            });
        });
    <?php endif; ?>
    
    // Subject selection links
    document.querySelectorAll('.subject-button').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            isInternalNavigation = true;
            window.location.href = this.getAttribute('href');
        });
    });

    document.getElementById('finishExamBtn')?.addEventListener('click', function() {
        if (confirm('Are you sure you want to submit the exam? This action cannot be undone.')) {
            isInternalNavigation = true;
            finishExam();
        }
    });
    
    function finishExam() {
        // Mark exam as completed
        fetch('finish_exam.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `exam_id=<?= $exam_id ?>`
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                isInternalNavigation = true;
                window.location.href = 'results.php?exam_id=<?= $exam_id ?>';
            } else {
                alert('Error finishing exam: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Network error. Please try again.');
        });
    }
    
    // Handle beforeunload
    window.addEventListener('beforeunload', function(e) {
        if (timeRemaining > 0 && !isInternalNavigation) {
            e.preventDefault();
            e.returnValue = 'Your exam progress will be saved, but are you sure you want to leave?';
            return e.returnValue;
        }
    });
    
    // Reset isInternalNavigation after navigation
    window.addEventListener('load', function() {
        isInternalNavigation = false;
    });
    
    // Keyboard shortcuts
    <?php if (!$show_subject_selection): ?>
        document.addEventListener('keydown', function(e) {
            // Number keys 1-4 for options
            if (e.key >= '1' && e.key <= '4') {
                const option = String.fromCharCode(64 + parseInt(e.key)); // 1->A, 2->B, etc.
                const radio = document.querySelector(`input[value="${option}"]`);
                if (radio) {
                    radio.checked = true;
                    document.querySelectorAll('.option-item').forEach(opt => {
                        opt.classList.remove('selected');
                    });
                    radio.closest('.option-item').classList.add('selected');
                    saveAnswer(option);
                }
            }
            
            // Arrow keys for navigation
            if (e.key === 'ArrowLeft' && <?= $current_question_index ?> > 0) {
                document.getElementById('prevBtn').click();
            }
            if (e.key === 'ArrowRight' && <?= $current_question_index ?> < <?= $total_questions - 1 ?>) {
                document.getElementById('nextBtn').click();
            }
        });
    <?php endif; ?>
});
</script>
</body>
</html>