<?php
// student/exam.php - Complete Exam Engine with Timer
require_once '../config/config.php';

if (!isset($_SESSION['student_id'])) {
    redirect('student/register.php');
}

$student_id = $_SESSION['student_id'];
$exam_id = $_SESSION['exam_id'];

// Get student exam
$stmt = $pdo->prepare("SELECT *, DATE_ADD(start_time, INTERVAL 9 HOUR) AS start_time_plus_9 FROM student_exams WHERE student_id = ? AND exam_id = ?");
$stmt->execute([$student_id, $exam_id]);
$student_exam = $stmt->fetch();

// Start exam if not started
if ($student_exam->status === 'not_started') {
    $stmt = $pdo->prepare("UPDATE student_exams SET status = 'in_progress', start_time = NOW() WHERE id = ?");
    $stmt->execute([$student_exam->id]);
    
    // Reload
    $stmt = $pdo->prepare("SELECT *, DATE_ADD(start_time, INTERVAL 9 HOUR) AS start_time_plus_9 FROM student_exams WHERE id = ?");
    $stmt->execute([$student_exam->id]);
    $student_exam = $stmt->fetch();
    
    // Initialize answers
    $stmt = $pdo->prepare("
        SELECT q.id FROM exam_questions eq 
        JOIN questions q ON eq.question_id = q.id 
        WHERE eq.exam_id = ? 
        ORDER BY eq.question_order
    ");
    $stmt->execute([$exam_id]);
    $questions = $stmt->fetchAll();
    
    foreach ($questions as $q) {
        $stmt = $pdo->prepare("INSERT INTO student_answers (student_exam_id, question_id) VALUES (?, ?)");
        $stmt->execute([$student_exam->id, $q->id]);
    }
}

// Check if completed
if ($student_exam->status === 'completed') {
    redirect('student/result.php');
}

// Get exam details
$stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ?");
$stmt->execute([$exam_id]);
$exam = $stmt->fetch();

// Calculate remaining time
$start_time = strtotime($student_exam->start_time_plus_9);
$duration_seconds = $exam->duration * 60;
$elapsed = time() - $start_time;
$remaining = max(0, $duration_seconds - $elapsed);

// Auto submit if time expired
if ($remaining <= 0) {
    // Calculate and save results
    $stmt = $pdo->prepare("
        UPDATE student_answers sa
        JOIN questions q ON sa.question_id = q.id
        SET sa.is_correct = (sa.selected_answer = q.correct_answer)
        WHERE sa.student_exam_id = ?
    ");
    $stmt->execute([$student_exam->id]);
    
    // Calculate totals
    $stmt = $pdo->prepare("
        SELECT 
            COUNT(CASE WHEN is_correct = 1 THEN 1 END) as correct,
            COUNT(CASE WHEN is_correct = 0 AND selected_answer IS NOT NULL THEN 1 END) as wrong,
            COUNT(CASE WHEN selected_answer IS NULL THEN 1 END) as unanswered,
            SUM(CASE WHEN sa.is_correct = 1 THEN q.marks ELSE 0 END) as obtained_marks
        FROM student_answers sa
        JOIN questions q ON sa.question_id = q.id
        WHERE sa.student_exam_id = ?
    ");
    $stmt->execute([$student_exam->id]);
    $stats = $stmt->fetch();
    
    $percentage = ($exam->total_marks > 0) ? ($stats->obtained_marks / $exam->total_marks) * 100 : 0;
    $pass_percentage = ($exam->total_marks > 0) ? ($exam->passing_marks / $exam->total_marks) * 100 : 0;
    $result = ($percentage >= $pass_percentage) ? 'pass' : 'fail';
    
    $stmt = $pdo->prepare("
        UPDATE student_exams 
        SET status = 'completed', end_time = NOW(), time_taken = ?, 
            obtained_marks = ?, percentage = ?, correct_answers = ?, 
            wrong_answers = ?, unanswered = ?, result = ?, submitted_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([
        $elapsed, $stats->obtained_marks, round($percentage, 2),
        $stats->correct, $stats->wrong, $stats->unanswered, $result, $student_exam->id
    ]);
    
    redirect('student/result.php');
}

// Get questions
$stmt = $pdo->prepare("
    SELECT q.*, eq.question_order, sa.selected_answer, sa.marked_for_review
    FROM exam_questions eq
    JOIN questions q ON eq.question_id = q.id
    LEFT JOIN student_answers sa ON q.id = sa.question_id AND sa.student_exam_id = ?
    WHERE eq.exam_id = ?
    ORDER BY eq.question_order
");
$stmt->execute([$student_exam->id, $exam_id]);
$questions = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo escape($exam->title); ?> - Exam</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* Custom animations and styles */
        @keyframes slideDown {
            from { transform: translateY(-10px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        
        .question-container {
            animation: slideDown 0.3s ease-out;
        }
        
        .nav-btn, .nav-btn-mobile {
            transition: all 0.2s ease;
        }
        
        @media (min-width: 768px) {
            .nav-btn:hover {
                transform: scale(1.1);
            }
        }
        
        /* Mobile menu styles */
        .mobile-nav {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease-out;
        }
        
        .mobile-nav.open {
            max-height: 70vh;
        }
        
        /* Timer warning animation */
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }
        
        .timer-warning {
            animation: pulse 1s ease-in-out infinite;
        }
        
        /* Custom scrollbar */
        .custom-scrollbar::-webkit-scrollbar {
            width: 6px;
        }
        
        .custom-scrollbar::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
        
        .custom-scrollbar::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 10px;
        }
        
        .custom-scrollbar::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
        
        /* Prevent text selection during exam */
        .no-select {
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        }
        
        /* Better mobile touch */
        @media (max-width: 768px) {
            .nav-btn-mobile {
                min-height: 44px;
                min-width: 44px;
            }
            
            button {
                -webkit-tap-highlight-color: transparent;
            }
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Header -->
    <div class="bg-gradient-to-r from-blue-600 to-purple-600 text-white shadow-xl sticky top-0 z-50">
        <div class="w-full px-3 sm:px-4 lg:px-6 py-3 sm:py-4">
            <!-- Desktop Header -->
            <div class="hidden md:flex max-w-7xl mx-auto justify-between items-center">
                <div class="flex-1">
                    <h1 class="text-xl lg:text-2xl font-bold"><?php echo escape($exam->title); ?></h1>
                    <p class="text-sm text-blue-100 mt-1">
                        Question <span id="current-q">1</span> of <?php echo count($questions); ?>
                    </p>
                </div>
                <div class="text-center px-4">
                    <p class="text-xs sm:text-sm text-blue-100">Time Remaining</p>
                    <p class="text-2xl lg:text-3xl font-bold" id="timer">00:00:00</p>
                </div>
                <div class="flex-shrink-0">
                    <button onclick="toggleMobileNav()" class="px-4 py-2 bg-white/20 rounded-lg hover:bg-white/30 transition whitespace-nowrap">
                        <i class="fas fa-grip mr-2"></i> Navigator
                    </button>
                </div>
            </div>
            
            <!-- Mobile Header -->
            <div class="md:hidden flex items-center justify-between gap-2">
                <div class="flex-1 min-w-0">
                    <h1 class="text-sm font-bold truncate leading-tight"><?php echo escape($exam->title); ?></h1>
                    <p class="text-xs text-blue-100">
                        Q <span id="current-q-mobile">1</span>/<?php echo count($questions); ?>
                    </p>
                </div>
                <div class="text-center flex-shrink-0 px-2">
                    <p class="text-xs text-blue-100 leading-tight">Time</p>
                    <p class="text-base sm:text-lg font-bold leading-tight" id="timer-mobile">00:00:00</p>
                </div>
                <button onclick="toggleMobileNav()" class="p-2.5 bg-white/20 rounded-lg hover:bg-white/30 transition flex-shrink-0">
                    <i class="fas fa-bars text-lg"></i>
                </button>
            </div>
        </div>
    </div>
    
    <!-- Mobile Navigation Panel -->
    <div id="mobileNav" class="mobile-nav bg-white shadow-lg md:hidden border-b-4 border-blue-500 fixed left-0 right-0 z-40" style="top: 73px;">
        <div class="p-4 overflow-y-auto custom-scrollbar" style="max-height: calc(70vh - 73px);">
            <div class="flex justify-between items-center mb-3 pb-3 border-b sticky top-0 bg-white z-10">
                <h3 class="font-bold text-gray-800 text-sm">Question Navigator</h3>
                <button onclick="toggleMobileNav()" class="text-gray-500 hover:text-gray-700 p-1">
                    <i class="fas fa-times text-lg"></i>
                </button>
            </div>
            <div class="grid grid-cols-5 gap-2.5 mb-4">
                <?php foreach ($questions as $index => $q): ?>
                <?php
                    $nav_class = 'bg-gray-200 text-gray-700';
                    if ($q->selected_answer) {
                        $nav_class = 'bg-green-500 text-white';
                    }
                    if ($q->marked_for_review) {
                        $nav_class = 'bg-yellow-500 text-white';
                    }
                ?>
                <button onclick="goToQuestion(<?php echo $index; ?>); toggleMobileNav();" 
                        class="nav-btn-mobile w-full h-12 rounded-lg font-semibold text-sm transition shadow-sm <?php echo $nav_class; ?>"
                        data-nav-mobile="<?php echo $index; ?>"
                        data-question-id="<?php echo $q->id; ?>"
                        data-answered="<?php echo $q->selected_answer ? '1' : '0'; ?>"
                        data-review="<?php echo $q->marked_for_review ? '1' : '0'; ?>">
                    <?php echo $index + 1; ?>
                </button>
                <?php endforeach; ?>
            </div>
            
            <div class="space-y-2 text-xs border-t pt-3">
                <div class="flex items-center gap-2">
                    <div class="w-4 h-4 bg-green-500 rounded flex-shrink-0"></div>
                    <span>Answered</span>
                </div>
                <div class="flex items-center gap-2">
                    <div class="w-4 h-4 bg-yellow-500 rounded flex-shrink-0"></div>
                    <span>Marked for Review</span>
                </div>
                <div class="flex items-center gap-2">
                    <div class="w-4 h-4 bg-gray-200 rounded flex-shrink-0"></div>
                    <span>Not Answered</span>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Mobile Navigation Overlay -->
    <div id="navOverlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden" onclick="toggleMobileNav()"></div>
    
    <!-- Main Content -->
    <div class="max-w-7xl mx-auto px-3 sm:px-4 py-4 sm:py-6">
        <div class="grid grid-cols-1 lg:grid-cols-4 gap-4 sm:gap-6">
            <!-- Question Area -->
            <div class="lg:col-span-3">
                <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                    <?php foreach ($questions as $index => $q): ?>
                    <div class="question-container p-4 sm:p-6 <?php echo $index > 0 ? 'hidden' : ''; ?>" data-question="<?php echo $index; ?>">
                        <div class="flex items-center justify-between mb-4 pb-3 border-b">
                            <h2 class="text-lg sm:text-xl font-bold text-gray-800">
                                Question <?php echo $index + 1; ?>
                            </h2>
                            <span class="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-xs font-semibold">
                                <?php echo $q->marks; ?> Mark<?php echo $q->marks > 1 ? 's' : ''; ?>
                            </span>
                        </div>
                        
                        <div class="mb-6 p-4 bg-gray-50 rounded-lg">
                            <p class="text-base sm:text-lg text-gray-800 leading-relaxed"><?php echo escape($q->question_text); ?></p>
                        </div>
                        
                        <div class="space-y-3">
                            <?php 
                            $options = [
                                'a' => $q->option_a,
                                'b' => $q->option_b,
                                'c' => $q->option_c,
                                'd' => $q->option_d
                            ];
                            foreach ($options as $key => $value): 
                            ?>
                            <label class="flex items-start p-3 sm:p-4 border-2 rounded-lg cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-all active:scale-98
                                <?php echo $q->selected_answer === $key ? 'border-blue-500 bg-blue-50 shadow-md' : 'border-gray-200'; ?>">
                                <input type="radio" name="answer_<?php echo $q->id; ?>" value="<?php echo $key; ?>" 
                                       data-question-id="<?php echo $q->id; ?>"
                                       <?php echo $q->selected_answer === $key ? 'checked' : ''; ?>
                                       class="w-4 h-4 sm:w-5 sm:h-5 text-blue-600 mt-0.5 flex-shrink-0">
                                <span class="ml-2.5 sm:ml-3 text-sm sm:text-base text-gray-700 flex-1 leading-relaxed">
                                    <strong class="text-gray-900"><?php echo strtoupper($key); ?>.</strong> <?php echo escape($value); ?>
                                </span>
                            </label>
                            <?php endforeach; ?>
                        </div>
                        
                        <!-- Navigation Buttons -->
                        <div class="flex flex-col sm:flex-row gap-2.5 sm:gap-3 mt-6 pt-6 border-t">
                            <button onclick="prevQuestion()" 
                                    class="flex-1 sm:flex-none px-4 sm:px-6 py-3 sm:py-3 bg-gray-500 text-white rounded-lg hover:bg-gray-600 active:bg-gray-700 transition font-medium disabled:opacity-50 disabled:cursor-not-allowed text-sm sm:text-base"
                                    <?php echo $index === 0 ? 'disabled' : ''; ?>>
                                <i class="fas fa-arrow-left mr-2"></i> Previous
                            </button>
                            
                            <button onclick="markReview(<?php echo $q->id; ?>)" 
                                    class="flex-1 sm:flex-none px-4 sm:px-6 py-3 sm:py-3 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 active:bg-yellow-700 transition font-medium text-sm sm:text-base">
                                <i class="fas fa-bookmark mr-2"></i> <span class="hidden xs:inline">Mark for </span>Review
                            </button>
                            
                            <?php if ($index < count($questions) - 1): ?>
                            <button onclick="nextQuestion()" 
                                    class="flex-1 sm:flex-none px-4 sm:px-6 py-3 sm:py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 active:bg-blue-800 transition font-medium sm:ml-auto text-sm sm:text-base">
                                Next <i class="fas fa-arrow-right ml-2"></i>
                            </button>
                            <?php else: ?>
                            <button onclick="submitExam()" 
                                    class="flex-1 sm:flex-none px-4 sm:px-6 py-3 sm:py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 active:bg-green-800 transition font-medium sm:ml-auto text-sm sm:text-base">
                                <i class="fas fa-check-circle mr-2"></i> Submit Exam
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- Mobile Submit Button -->
                <div class="mt-4 md:hidden">
                    <button onclick="submitExam()" 
                            class="w-full px-6 py-4 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-xl hover:from-red-700 hover:to-red-800 transition font-bold text-lg shadow-lg">
                        <i class="fas fa-paper-plane mr-2"></i> Submit Exam
                    </button>
                </div>
            </div>
            
            <!-- Desktop Navigator Sidebar -->
            <div class="hidden lg:block lg:col-span-1">
                <div class="bg-white rounded-xl shadow-lg p-4 sticky top-24">
                    <h3 class="font-bold text-gray-800 mb-4 text-center">Question Navigator</h3>
                    <div class="grid grid-cols-5 gap-2 max-h-96 overflow-y-auto custom-scrollbar pr-2">
                        <?php foreach ($questions as $index => $q): ?>
                        <?php
                            $nav_class = 'bg-gray-200 text-gray-700';
                            if ($q->selected_answer) {
                                $nav_class = 'bg-green-500 text-white';
                            }
                            if ($q->marked_for_review) {
                                $nav_class = 'bg-yellow-500 text-white';
                            }
                        ?>
                        <button onclick="goToQuestion(<?php echo $index; ?>)" 
                                class="nav-btn w-10 h-10 rounded-lg font-semibold transition <?php echo $nav_class; ?>"
                                data-nav="<?php echo $index; ?>"
                                data-question-id="<?php echo $q->id; ?>"
                                data-answered="<?php echo $q->selected_answer ? '1' : '0'; ?>"
                                data-review="<?php echo $q->marked_for_review ? '1' : '0'; ?>">
                            <?php echo $index + 1; ?>
                        </button>
                        <?php endforeach; ?>
                    </div>
                    
                    <div class="mt-4 text-xs space-y-2 border-t pt-4">
                        <div class="flex items-center">
                            <div class="w-4 h-4 bg-green-500 rounded mr-2"></div>
                            <span>Answered</span>
                        </div>
                        <div class="flex items-center">
                            <div class="w-4 h-4 bg-yellow-500 rounded mr-2"></div>
                            <span>Marked for Review</span>
                        </div>
                        <div class="flex items-center">
                            <div class="w-4 h-4 bg-gray-200 rounded mr-2"></div>
                            <span>Not Answered</span>
                        </div>
                    </div>
                    
                    <button onclick="submitExam()" 
                            class="w-full mt-4 px-4 py-3 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-lg hover:from-red-700 hover:to-red-800 transition font-semibold shadow-md">
                        <i class="fas fa-paper-plane mr-2"></i> Submit Exam
                    </button>
                </div>
            </div>
        </div>
    </div>
    
  <script>
let currentQuestion = 0;
let totalQuestions = <?php echo count($questions); ?>;
let remainingTime = <?php echo $remaining; ?>;
let studentExamId = <?php echo $student_exam->id; ?>;
let warningShown = false;

// Base URL for AJAX calls
const baseUrl = '<?php echo rtrim(base_url(), "/"); ?>';

function getExamStatus() {
    let answered = 0;
    let unanswered = 0;
    let markedForReview = 0;

    const buttons = window.innerWidth >= 1024 
        ? document.querySelectorAll('.nav-btn') 
        : document.querySelectorAll('.nav-btn-mobile');

    buttons.forEach(btn => {
        let isAnswered = btn.dataset.answered === '1';
        let isReviewed = btn.dataset.review === '1';

        if (isAnswered) {
            answered++;
        } else {
            unanswered++;
        }

        if (isReviewed) {
            markedForReview++;
        }
    });

    return { answered, unanswered, markedForReview };
}

function startTimer() {
    setInterval(function() {
        if (remainingTime <= 0) {
            alert('Time is up! Submitting exam...');
            window.location.reload();
            return;
        }
        
        remainingTime--;
        
        if (remainingTime === 300 && !warningShown) {
            alert('⚠️ Warning: Only 5 minutes remaining!');
            document.getElementById('timer').classList.add('timer-warning');
            document.getElementById('timer-mobile').classList.add('timer-warning');
            warningShown = true;
        }
        
        let hours = Math.floor(remainingTime / 3600);
        let minutes = Math.floor((remainingTime % 3600) / 60);
        let seconds = remainingTime % 60;
        
        let timeString = String(hours).padStart(2, '0') + ':' + 
                       String(minutes).padStart(2, '0') + ':' + 
                       String(seconds).padStart(2, '0');
        
        document.getElementById('timer').textContent = timeString;
        document.getElementById('timer-mobile').textContent = timeString;
        
        if (remainingTime < 300) {
            document.getElementById('timer').classList.add('text-red-300');
            document.getElementById('timer-mobile').classList.add('text-red-300');
        }
    }, 1000);
}

function toggleMobileNav() {
    const nav = document.getElementById('mobileNav');
    const overlay = document.getElementById('navOverlay');
    const isOpen = nav.classList.contains('open');
    
    if (isOpen) {
        nav.classList.remove('open');
        overlay.classList.add('hidden');
        document.body.style.overflow = '';
    } else {
        nav.classList.add('open');
        overlay.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }
}

function goToQuestion(index) {
    document.querySelectorAll('.question-container').forEach(q => q.classList.add('hidden'));
    document.querySelector(`[data-question="${index}"]`).classList.remove('hidden');
    document.getElementById('current-q').textContent = index + 1;
    document.getElementById('current-q-mobile').textContent = index + 1;
    currentQuestion = index;
    updateNavButtons();
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function nextQuestion() {
    if (currentQuestion < totalQuestions - 1) {
        goToQuestion(currentQuestion + 1);
    }
}

function prevQuestion() {
    if (currentQuestion > 0) {
        goToQuestion(currentQuestion - 1);
    }
}

function updateNavButtons() {
    document.querySelectorAll('.nav-btn, .nav-btn-mobile').forEach(btn => {
        btn.classList.remove('ring-4', 'ring-blue-400', 'ring-offset-2');
    });
    document.querySelectorAll(`[data-nav="${currentQuestion}"], [data-nav-mobile="${currentQuestion}"]`).forEach(btn => {
        btn.classList.add('ring-4', 'ring-blue-400', 'ring-offset-2');
    });
}

// Save answer function
// Save answer function - without .php extension
function saveAnswer(questionId, answer, markForReview = 0) {
    const formData = new FormData();
    formData.append('student_exam_id', studentExamId);
    formData.append('question_id', questionId);
    if (answer !== null) {
        formData.append('selected_answer', answer);
    }
    formData.append('marked_for_review', markForReview);
    
    console.log('Saving answer:', {
        student_exam_id: studentExamId,
        question_id: questionId,
        selected_answer: answer,
        marked_for_review: markForReview
    });
    
    // Use URL without .php extension (matches .htaccess rewrite rules)
    return fetch('save_answer', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        console.log('Response status:', response.status);
        console.log('Response URL:', response.url);
        return response.text();
    })
    .then(text => {
        console.log('Raw response:', text);
        try {
            const data = JSON.parse(text);
            console.log('Parsed response:', data);
            return data;
        } catch(e) {
            console.error('Failed to parse JSON:', e);
            console.error('Response was:', text);
            return { success: false, error: 'Invalid response from server' };
        }
    })
    .catch(error => {
        console.error('Fetch error:', error);
        throw error;
    });
}

// Handle radio button changes
document.querySelectorAll('input[type=radio]').forEach(radio => {
    radio.addEventListener('change', function() {
        let questionId = this.dataset.questionId;
        let answer = this.value;
        
        saveAnswer(questionId, answer, 0)
            .then(data => {
                if (data.success) {
                    console.log('✓ Answer saved successfully');
                    
                    // Update navigation buttons
                    let qIndex = Array.from(document.querySelectorAll('.question-container')).findIndex(
                        q => q.querySelector(`[data-question-id="${questionId}"]`)
                    );
                    
                    document.querySelectorAll(`[data-nav="${qIndex}"], [data-nav-mobile="${qIndex}"]`).forEach(navButton => {
                        navButton.dataset.answered = '1';
                        navButton.dataset.review = '0';
                        navButton.classList.remove('bg-gray-200', 'text-gray-700', 'bg-yellow-500');
                        navButton.classList.add('bg-green-500', 'text-white');
                    });
                } else {
                    console.error('✗ Failed to save:', data);
                    alert('Failed to save answer: ' + (data.error || data.message));
                }
            })
            .catch(error => {
                console.error('✗ Error saving answer:', error);
                alert('Network error. Please check your connection.');
            });
    });
});

function markReview(questionId) {
    saveAnswer(questionId, null, 1)
        .then(data => {
            if (data.success) {
                console.log('✓ Marked for review');
                
                let qIndex = Array.from(document.querySelectorAll('.question-container')).findIndex(
                    q => q.querySelector(`[data-question-id="${questionId}"]`)
                );
                
                document.querySelectorAll(`[data-nav="${qIndex}"], [data-nav-mobile="${qIndex}"]`).forEach(navButton => {
                    navButton.dataset.review = '1';
                    navButton.classList.remove('bg-green-500', 'bg-gray-200', 'text-gray-700');
                    navButton.classList.add('bg-yellow-500', 'text-white');
                });
                
                alert('Question marked for review!');
            } else {
                console.error('✗ Failed to mark:', data);
                alert('Failed to mark for review: ' + (data.error || data.message));
            }
        })
        .catch(error => {
            console.error('✗ Error marking for review:', error);
            alert('Network error. Please check your connection.');
        });
}

function submitExam() {
    const status = getExamStatus();
    let message = 'Are you sure you want to submit the exam? You cannot change answers after submission.';

    if (status.markedForReview > 0) {
        message = `⚠️ You have ${status.markedForReview} question(s) marked for review.`;
    }
    
    if (status.unanswered > 0) {
         message += (status.markedForReview > 0 ? ' Also, ' : ' ') + `You have ${status.unanswered} question(s) UNANSWERED.`;
    }
    
    message += '\n\nDo you still wish to submit?';

    if (!confirm(message)) {
        return;
    }
    
    // Use URL without .php extension
    window.location.href = 'submit_exam';
}

// Initialize
startTimer();
updateNavButtons();

// Prevent accidental close
window.addEventListener('beforeunload', function(e) {
    e.preventDefault();
    e.returnValue = '';
});

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    if (e.key === 'ArrowRight') nextQuestion();
    if (e.key === 'ArrowLeft') prevQuestion();
});
</script>
</body>
</html>