<?php
require_once '../../config/database.php';
require_once '../../config/auth.php';
require_once '../../config/rbac.php';
require_once '../../includes/functions.php';
require_once '../../includes/middleware.php';

// Check if user is student or higher
studentOrHigher();

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

$examId = $_GET['id'] ?? 0;
if (!$examId) {
    header('Location: ../exams.php');
    exit;
}

// Get exam details
$stmt = $db->prepare("
    SELECT e.*, c.title as course_title,
           CASE WHEN ea.id IS NOT NULL THEN 1 ELSE 0 END as has_attempted,
           COALESCE(ea.attempt_number, 0) + 1 as next_attempt_number,
           COALESCE(ea.status, 'none') as last_attempt_status
    FROM exams e
    LEFT JOIN courses c ON e.course_id = c.id
    LEFT JOIN exam_attempts ea ON e.id = ea.exam_id AND ea.student_id = ? AND ea.attempt_number = (
        SELECT MAX(attempt_number) FROM exam_attempts WHERE exam_id = e.id AND student_id = ?
    )
    WHERE e.id = ? AND e.status = 'published'
");
$stmt->execute([$userId, $userId, $examId]);
$exam = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$exam) {
    $_SESSION['error_message'] = 'Exam not found or not available.';
    header('Location: ../exams.php');
    exit;
}

// Check if student is enrolled in the course (if exam is course-specific)
if ($exam['course_id']) {
    $stmt = $db->prepare("SELECT id FROM course_enrollments WHERE course_id = ? AND student_id = ? AND status IN ('enrolled', 'in_progress')");
    $stmt->execute([$exam['course_id'], $userId]);
    if (!$stmt->fetch()) {
        $_SESSION['error_message'] = 'You must be enrolled in this course to take this exam.';
        header('Location: ../exams.php');
        exit;
    }
}

// Check exam availability (start/end dates)
$currentTime = new DateTime();
$startDate = $exam['start_date'] ? new DateTime($exam['start_date']) : null;
$endDate = $exam['end_date'] ? new DateTime($exam['end_date']) : null;

if ($startDate && $currentTime < $startDate) {
    $_SESSION['error_message'] = 'This exam is not yet available.';
    header('Location: ../exams.php');
    exit;
}

if ($endDate && $currentTime > $endDate) {
    $_SESSION['error_message'] = 'This exam has ended.';
    header('Location: ../exams.php');
    exit;
}

// Check attempt limits
if ($exam['max_attempts'] > 0 && $exam['next_attempt_number'] > $exam['max_attempts']) {
    $_SESSION['error_message'] = 'You have reached the maximum number of attempts for this exam.';
    header('Location: ../exams.php');
    exit;
}

// Check for existing attempt
$stmt = $db->prepare("
    SELECT ea.*, e.max_attempts
    FROM exam_attempts ea
    JOIN exams e ON ea.exam_id = e.id
    WHERE ea.exam_id = ? AND ea.student_id = ?
    ORDER BY ea.started_at DESC LIMIT 1
");
$stmt->execute([$examId, $userId]);
$lastAttempt = $stmt->fetch(PDO::FETCH_ASSOC);

// Check attempt limits
$attemptCount = 0;
if ($lastAttempt) {
    $stmt = $db->prepare("SELECT COUNT(*) as count FROM exam_attempts WHERE exam_id = ? AND student_id = ?");
    $stmt->execute([$examId, $userId]);
    $attemptCount = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
}

$canTakeExam = true;
$message = '';

if ($exam['max_attempts'] > 0 && $attemptCount >= $exam['max_attempts']) {
    $canTakeExam = false;
    $message = 'You have reached the maximum number of attempts for this exam.';
} elseif ($lastAttempt && $lastAttempt['status'] === 'in_progress') {
    // Resume existing attempt
    $attemptId = $lastAttempt['id'];
    $message = 'Resuming your previous attempt.';
} elseif ($lastAttempt && $lastAttempt['status'] === 'completed' && $lastAttempt['percentage'] >= $exam['passing_score']) {
    $canTakeExam = false;
    $message = 'You have already passed this exam.';
}

// Get exam questions if exam can be taken
$questions = [];
if ($canTakeExam) {
    // FIX: Use proper ordering and grouping to ensure unique sequential questions
    // The subquery first deduplicates exam_questions entries ordered by sort_order
    $stmt = $db->prepare("
        SELECT q.id, q.content, q.question_type, q.points as question_points, 
               q.difficulty, q.category_id, q.status, q.created_at, q.updated_at,
               eq.points, eq.sort_order
        FROM exam_questions eq
        JOIN questions q ON eq.question_id = q.id
        WHERE eq.exam_id = ?
        GROUP BY eq.exam_id, eq.question_id, eq.sort_order
        ORDER BY eq.sort_order, q.id
    ");
    $stmt->execute([$examId]);
    $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Get question options
    foreach ($questions as &$question) {
        $stmt = $db->prepare("
            SELECT * FROM question_options
            WHERE question_id = ?
            ORDER BY sort_order
        ");
        $stmt->execute([$question['id']]);
        $question['options'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

$page_title = htmlspecialchars($exam['title']) . ' - Take Exam';
$use_tailwind = true;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> | Mutalex Academy</title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Configure Tailwind -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A',
                        'background-light': '#F8FAFC',
                        'text-dark': '#1F2937',
                        'accent-subtle': '#E5E7EB',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Summernote -->
    <link href="../../vendor/summernote-0.9.0-dist/summernote-lite.min.css" rel="stylesheet">
    <script src="../../vendor/summernote-0.9.0-dist/summernote-lite.min.js"></script>
    <style>
        html, body { height: 100%; }
        ::-webkit-scrollbar { width: 8px; height: 8px; }
        ::-webkit-scrollbar-thumb { background-color: #D1D5DB; border-radius: 4px; }
        ::-webkit-scrollbar-track { background-color: transparent; }

        .question-card { transition: all 0.3s ease; display: none; }
        .question-card.active { border-color: #1E3A8A; box-shadow: 0 0 0 2px rgba(30, 58, 138, 0.1); display: block; }
        .timer-warning { animation: pulse 1s infinite; }
        @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

    <div class="min-h-screen flex flex-col">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b border-accent-subtle">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
                <div class="flex justify-between items-center">
                    <div>
                        <h1 class="text-2xl font-bold text-text-dark"><?php echo htmlspecialchars($exam['title']); ?></h1>
                        <?php if ($exam['course_title']): ?>
                            <p class="text-sm text-gray-600">Course: <?php echo htmlspecialchars($exam['course_title']); ?></p>
                        <?php endif; ?>
                    </div>
                    <div class="flex items-center space-x-4">
                        <!-- Timer -->
                        <div id="timer" class="text-lg font-mono font-bold text-primary-blue">
                            <?php echo $exam['time_limit'] ? gmdate('H:i:s', $exam['time_limit'] * 60) : 'No limit'; ?>
                        </div>
                        <button
                            type="button"
                            onclick="submitExam()"
                            class="bg-red-600 text-white px-4 py-2 rounded-lg font-semibold hover:bg-red-700 transition disabled:opacity-50 disabled:cursor-not-allowed"
                            id="submitBtn"
                        >
                            Submit Exam
                        </button>
                        <a href="../dashboard.php" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition">
                            Exit Exam
                        </a>
                    </div>
                </div>
            </header>

        <!-- Main Content -->
        <main class="flex-1 overflow-hidden">
            <?php if (!$canTakeExam): ?>
                <!-- Cannot take exam message -->
                <div class="h-full flex items-center justify-center p-8">
                    <div class="bg-white rounded-xl shadow-lg p-8 text-center max-w-md">
                        <div class="text-6xl mb-4">⚠️</div>
                        <h2 class="text-2xl font-bold text-gray-800 mb-4">Cannot Take Exam</h2>
                        <p class="text-gray-600 mb-6"><?php echo $message; ?></p>
                        <a href="../exams.php" class="inline-block bg-primary-blue text-white px-6 py-3 rounded-lg font-semibold hover:bg-indigo-700 transition">
                            Back to Exams
                        </a>
                    </div>
                </div>
            <?php else: ?>
                <!-- Exam Details -->
                <div id="examDetails" class="h-full flex items-center justify-center p-8">
                    <div class="bg-white rounded-xl shadow-lg p-8 max-w-2xl w-full">
                        <h2 class="text-2xl font-bold mb-4"><?php echo htmlspecialchars($exam['title']); ?></h2>
                        <p class="mb-4"><?php echo nl2br(htmlspecialchars($exam['description'] ?? 'No description available.')); ?></p>
                        <div class="mb-4">
                            <p><strong>Time Limit:</strong> <?php echo $exam['time_limit'] ? $exam['time_limit'] . ' minutes' : 'No limit'; ?></p>
                            <p><strong>Number of Questions:</strong> <?php echo count($questions); ?></p>
                            <p><strong>Passing Score:</strong> <?php echo $exam['passing_score']; ?>%</p>
                        </div>
                        <?php if (!empty($exam['instructions'])): ?>
                            <div class="mb-4">
                                <h3 class="font-semibold">Instructions:</h3>
                                <p><?php echo nl2br(htmlspecialchars($exam['instructions'])); ?></p>
                            </div>
                        <?php endif; ?>
                        <button onclick="startExam()" class="bg-primary-blue text-white px-6 py-3 rounded-lg font-semibold hover:bg-indigo-700 transition">
                            Start Exam
                        </button>
                    </div>
                </div>

                <!-- Exam Content -->
                <div class="h-full flex flex-col" id="examContent" style="display: none;">
                    <!-- Exam Content -->
                    <div class="flex-1 overflow-y-auto">
                        <div class="p-6">
                            <form id="examForm">
                                <input type="hidden" name="exam_id" value="<?php echo $examId; ?>">
                                <input type="hidden" id="attempt_id" name="attempt_id" value="<?php echo $attemptId ?? ''; ?>">
                                <input type="hidden" id="time_spent" name="time_spent" value="0">

                                <div id="questionsContainer">
                                    <?php foreach ($questions as $index => $question): ?>
                                        <div class="question-card bg-white rounded-xl shadow-sm border border-accent-subtle p-8 min-h-[70vh] <?php echo $index === 0 ? 'active' : ''; ?>" data-index="<?php echo $index; ?>">
                                            <div class="flex justify-between items-start mb-4">
                                                <h3 class="text-lg font-semibold text-gray-800">Question <?php echo $index + 1; ?></h3>
                                                <div class="flex items-center gap-2">
                                                    <span class="text-sm text-gray-500"><?php echo $question['points']; ?> points</span>
                                                    <button onclick="flagQuestion(<?php echo $index; ?>)" id="flag-btn-<?php echo $index; ?>" class="text-gray-400 hover:text-yellow-500 transition text-sm">🚩 Flag</button>
                                                </div>
                                            </div>

                                            <div class="mb-6 question-content-wrapper">
                                                <!-- Question Title (if exists) -->
                                                <?php if (!empty($question['title'])): ?>
                                                    <h4 class="text-xl font-bold text-gray-800 mb-3 leading-tight">
                                                        <?php echo htmlspecialchars($question['title']); ?>
                                                    </h4>
                                                <?php endif; ?>
                                                
                                                <!-- Question Content -->
                                                <div class="prose max-w-none <?php echo !empty($question['title']) ? 'text-gray-600' : 'text-gray-800 font-medium text-lg'; ?>">
                                                    <?php echo nl2br($question['content']); ?>
                                                </div>
                                            </div>

                                            <div class="space-y-3">
                                                <?php if ($question['question_type'] === 'mcq_single' || $question['question_type'] === 'true_false'): ?>
                                                    <?php foreach ($question['options'] as $option): ?>
                                                        <label class="flex items-center space-x-3 p-3 rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer">
                                                            <input type="radio" name="answers[<?php echo $question['id']; ?>]" value="<?php echo $option['id']; ?>" class="text-primary-blue focus:ring-primary-blue">
                                                            <span class="text-gray-700"><?php echo htmlspecialchars($option['option_text']); ?></span>
                                                        </label>
                                                    <?php endforeach; ?>

                                                <?php elseif ($question['question_type'] === 'mcq_multiple'): ?>
                                                    <?php foreach ($question['options'] as $option): ?>
                                                        <label class="flex items-center space-x-3 p-3 rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer">
                                                            <input type="checkbox" name="answers[<?php echo $question['id']; ?>][]" value="<?php echo $option['id']; ?>" class="text-primary-blue focus:ring-primary-blue">
                                                            <span class="text-gray-700"><?php echo htmlspecialchars($option['option_text']); ?></span>
                                                        </label>
                                                    <?php endforeach; ?>

                                                <?php elseif ($question['question_type'] === 'essay' || $question['question_type'] === 'short_answer'): ?>
                                                    <label for="summernote_<?php echo $question['id']; ?>" class="block text-sm font-medium text-gray-700 mb-2">Your Answer</label>
                                                    <textarea id="summernote_<?php echo $question['id']; ?>" name="answers[<?php echo $question['id']; ?>]" class="summernote-editor" data-type="<?php echo $question['question_type']; ?>"></textarea>
                                                    <div class="flex justify-between items-center mt-2">
                                                        <div id="count_<?php echo $question['id']; ?>" class="text-sm text-gray-500"></div>
                                                        <button type="button" onclick="saveDraft(<?php echo $question['id']; ?>)" class="text-sm bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600 transition">Save Draft</button>
                                                    </div>

                                                <?php elseif ($question['question_type'] === 'code'): ?>
                                                    <textarea id="summernote_<?php echo $question['id']; ?>" data-type="<?php echo $question['question_type']; ?>"
                                                        name="answers[<?php echo $question['id']; ?>]"
                                                        rows="12"
                                                        class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-blue focus:border-transparent font-mono text-sm"
                                                        placeholder="Enter your code here..."
                                                    ></textarea>

                                                <?php elseif ($question['question_type'] === 'matching'): ?>
                                                    <div class="matching-question space-y-4">
                                                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                                            <div class="matching-column">
                                                                <h4 class="font-semibold text-gray-800 mb-3">Terms</h4>
                                                                <?php foreach ($question['options'] as $index => $option): ?>
                                                                    <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg mb-2">
                                                                        <span class="text-gray-700"><?php echo htmlspecialchars($option['option_text']); ?></span>
                                                                        <select name="answers[<?php echo $question['id']; ?>][<?php echo $option['id']; ?>]" class="ml-3 px-3 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-primary-blue focus:border-transparent">
                                                                            <option value="">Select match</option>
                                                                            <?php foreach ($question['options'] as $rightOption): ?>
                                                                                <option value="<?php echo $rightOption['id']; ?>"><?php echo htmlspecialchars($rightOption['option_value']); ?></option>
                                                                            <?php endforeach; ?>
                                                                        </select>
                                                                    </div>
                                                                <?php endforeach; ?>
                                                            </div>
                                                            <div class="matching-column">
                                                                <h4 class="font-semibold text-gray-800 mb-3">Definitions</h4>
                                                                <?php foreach ($question['options'] as $option): ?>
                                                                    <div class="p-3 bg-blue-50 rounded-lg mb-2">
                                                                        <span class="text-gray-700"><?php echo htmlspecialchars($option['option_value']); ?></span>
                                                                    </div>
                                                                <?php endforeach; ?>
                                                            </div>
                                                        </div>
                                                    </div>

                                                <?php elseif ($question['question_type'] === 'fill_blanks'): ?>
                                                    <div class="fill-blanks-question">
                                                        <div class="prose max-w-none mb-4">
                                                            <?php
                                                            $content = $question['content'];
                                                            // Replace [blank] with input fields
                                                            $blankCount = 0;
                                                            $content = preg_replace_callback('/\[blank\]/i', function($matches) use ($question, &$blankCount) {
                                                                $blankCount++;
                                                                return '<input type="text" name="answers[' . $question['id'] . '][' . $blankCount . ']" class="inline-block mx-1 px-2 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-primary-blue focus:border-transparent" placeholder="Blank ' . $blankCount . '" style="width: 120px;">';
                                                            }, $content);
                                                            echo nl2br($content);
                                                            ?>
                                                        </div>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Question Navigation -->
                    <div class="bg-white border-t border-accent-subtle p-2">
                        <h3 class="font-semibold text-gray-800 text-sm mb-2">Questions (<?php echo count($questions); ?>)</h3>
                        <div class="flex justify-center items-center gap-2">
                            <button onclick="previousQuestion()" class="px-3 py-1 rounded border border-gray-300 text-sm hover:bg-gray-50 transition">Previous</button>
                            <div class="flex gap-1">
                                <?php for ($i = 0; $i < count($questions); $i++): ?>
                                    <button
                                        onclick="jumpToQuestion(<?php echo $i; ?>)"
                                        class="question-nav-btn w-10 h-10 rounded border-2 border-gray-300 text-xs font-medium hover:border-primary-blue transition <?php echo $i === 0 ? 'active' : ''; ?>"
                                        data-index="<?php echo $i; ?>"
                                    >
                                        <?php echo $i + 1; ?>
                                    </button>
                                <?php endfor; ?>
                            </div>
                            <button onclick="nextQuestion()" class="px-3 py-1 rounded border border-gray-300 text-sm hover:bg-gray-50 transition">Next</button>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </main>
    </div>

    <!-- Loading Overlay -->
    <div id="loadingOverlay" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-xl shadow-lg p-8 text-center">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-blue mx-auto mb-4"></div>
            <p class="text-gray-600">Processing...</p>
        </div>
    </div>

    <script>
        let examData = {
            examId: <?php echo $examId; ?>,
            timeLimit: <?php echo $exam['time_limit'] ? $exam['time_limit'] * 60 : 0; ?>,
            attemptId: '<?php echo $attemptId ?? ''; ?>',
            questions: <?php echo json_encode($questions); ?>
        };

        // Helper to read response text and parse JSON safely, logging raw responses on failure
        function handleApiResponse(response) {
            return response.text().then(text => {
                // Try to parse JSON
                try {
                    const json = text ? JSON.parse(text) : null;
                    return json;
                } catch (err) {
                    console.error('Non-JSON response from API:', text);
                    // Throw a descriptive error so callers can handle it
                    throw new Error('Invalid JSON response from server');
                }
            });
        }

        let timer = examData.timeLimit;
        let timerInterval;
        let timeSpent = 0;
        let currentQuestionIndex = 0;
        let flaggedQuestions = [];
        let examStarted = false;

        function initializeSummernote() {
            $('.summernote-editor').each(function() {
                const $this = $(this);
                const type = $this.data('type');
                const questionId = $this.attr('id').replace('summernote_', '');
                let config = {
                    placeholder: "Write your content here",
                    callbacks: {
                        onChange: function(contents, $editable) {
                            updateCount(questionId, contents);
                        },
                        onInit: function() {
                            updateCount(questionId, $this.summernote('code'));
                        }
                    }
                };

                if (type === 'short_answer') {
                    config.height = 200;
                    config.toolbar = [
                        ['style', ['bold', 'italic', 'underline']],
                        ['para', ['ul', 'ol']],
                        ['insert', ['link']],
                        ['view', ['codeview']]
                    ];
                } else if (type === 'essay') {
                    config.minHeight = 300;
                    config.maxHeight = 600;
                    config.toolbar = [
                        ['style', ['bold', 'italic', 'underline', 'strikethrough']],
                        ['para', ['ul', 'ol', 'paragraph']],
                        ['table', ['table']],
                        ['insert', ['link', 'picture', 'video']],
                        ['view', ['fullscreen', 'codeview', 'help']]
                    ];
                }

                try {
                    $this.summernote(config);
                } catch (error) {
                    console.error('Error initializing Summernote for question ' + questionId + ':', error);
                }
            });
        }

        function updateCount(questionId, contents) {
            const text = $(contents).text() || '';
            const words = text.trim().split(/\s+/).filter(word => word.length > 0).length;
            const chars = text.length;
            $('#count_' + questionId).text(`Words: ${words} | Characters: ${chars}`);
        }

        function saveDraft(questionId) {
            const content = $(`#summernote_${questionId}`).summernote('code');
            const answers = {};
            answers[questionId] = content;

            fetch('../../api/exams/attempts.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'same-origin',
                body: JSON.stringify({
                    exam_id: examData.examId,
                    action: 'save',
                    answers: answers,
                    time_spent: timeSpent,
                    flagged: flaggedQuestions
                })
            })
            .then(handleApiResponse)
            .then(data => {
                if (data.success) {
                    alert('Draft saved successfully!');
                } else {
                    alert('Error saving draft: ' + (data.message || 'Unknown error'));
                }
            })
            .catch(error => {
                console.error('Error saving draft:', error);
                alert('Error saving draft. Please try again.');
            });
        }

        // Initialize exam
        document.addEventListener('DOMContentLoaded', function() {
            // Start in fullscreen mode
            if (document.documentElement.requestFullscreen) {
                document.documentElement.requestFullscreen().catch(err => {
                    console.log('Fullscreen not supported or denied:', err);
                });
            }

            // Load saved answers if resuming
            if (examData.attemptId) {
                loadSavedAnswers();
                // If resuming, show content directly
                examStarted = true;
                document.getElementById('examDetails').style.display = 'none';
                document.getElementById('examContent').style.display = 'block';
                if (examData.timeLimit > 0) {
                    startTimer();
                }
                updateNavButtons();
                // Initialize text editors
                initializeSummernote();
            }

            // Auto-save every 30 seconds
            window.autoSaveInterval = setInterval(autoSave, 30000);

            // Handle browser close/refresh
            window.addEventListener('beforeunload', function(e) {
                if (examStarted) {
                    autoSave();
                    e.returnValue = 'Are you sure you want to leave? Your progress will be saved.';
                }
            });
        });

        function startTimer() {
            timerInterval = setInterval(() => {
                timer--;
                timeSpent++;

                updateTimerDisplay();

                if (timer <= 0) {
                    clearInterval(timerInterval);
                    autoSubmitExam();
                } else if (timer <= 300) { // 5 minutes warning
                    document.getElementById('timer').classList.add('timer-warning', 'text-red-600');
                }
            }, 1000);
        }

        function updateTimerDisplay() {
            const hours = Math.floor(timer / 3600);
            const minutes = Math.floor((timer % 3600) / 60);
            const seconds = timer % 60;

            document.getElementById('timer').textContent =
                String(hours).padStart(2, '0') + ':' +
                String(minutes).padStart(2, '0') + ':' +
                String(seconds).padStart(2, '0');
        }

        function jumpToQuestion(index) {
            currentQuestionIndex = index;

            // Update active question card
            document.querySelectorAll('.question-card').forEach((card, i) => {
                card.classList.toggle('active', i === index);
            });

            // Update navigation buttons
            document.querySelectorAll('.question-nav-btn').forEach((btn, i) => {
                btn.classList.toggle('active', i === index);
                btn.classList.toggle('border-primary-blue', i === index);
                btn.classList.toggle('bg-primary-blue', i === index);
                btn.classList.toggle('text-white', i === index);
            });

            // Update prev/next buttons
            updateNavButtons();
        }

        function previousQuestion() {
            if (currentQuestionIndex > 0) {
                jumpToQuestion(currentQuestionIndex - 1);
            }
        }

        function nextQuestion() {
            if (currentQuestionIndex < examData.questions.length - 1) {
                jumpToQuestion(currentQuestionIndex + 1);
            }
        }

        function updateNavButtons() {
            const prevBtn = document.querySelector('button[onclick="previousQuestion()"]');
            const nextBtn = document.querySelector('button[onclick="nextQuestion()"]');

            if (prevBtn) {
                prevBtn.disabled = currentQuestionIndex === 0;
                prevBtn.classList.toggle('opacity-50', currentQuestionIndex === 0);
            }

            if (nextBtn) {
                if (currentQuestionIndex === examData.questions.length - 1) {
                    nextBtn.textContent = 'Submit Exam';
                    nextBtn.onclick = () => submitExam();
                    nextBtn.classList.remove('hover:bg-gray-50', 'border-gray-300');
                    nextBtn.classList.add('bg-red-600', 'text-white', 'hover:bg-red-700', 'border-red-600');
                } else {
                    nextBtn.textContent = 'Next';
                    nextBtn.onclick = () => nextQuestion();
                    nextBtn.classList.remove('bg-red-600', 'text-white', 'hover:bg-red-700', 'border-red-600');
                    nextBtn.classList.add('hover:bg-gray-50', 'border-gray-300');
                }
            }
        }

        function flagQuestion(index) {
            const flagBtn = document.getElementById(`flag-btn-${index}`);
            const navBtn = document.querySelector(`.question-nav-btn[data-index="${index}"]`);

            if (flaggedQuestions.includes(index)) {
                flaggedQuestions = flaggedQuestions.filter(i => i !== index);
                flagBtn.classList.remove('text-yellow-500');
                flagBtn.classList.add('text-gray-400');
                navBtn.classList.remove('border-yellow-500', 'text-yellow-700');
            } else {
                flaggedQuestions.push(index);
                flagBtn.classList.remove('text-gray-400');
                flagBtn.classList.add('text-yellow-500');
                navBtn.classList.add('border-yellow-500', 'text-yellow-700');
            }
        }

        function updateFlaggedUI() {
            flaggedQuestions.forEach(index => {
                const flagBtn = document.getElementById(`flag-btn-${index}`);
                const navBtn = document.querySelector(`.question-nav-btn[data-index="${index}"]`);
                flagBtn.classList.remove('text-gray-400');
                flagBtn.classList.add('text-yellow-500');
                navBtn.classList.add('border-yellow-500', 'text-yellow-700');
            });
        }

        function startExam() {
            // Show loading state
            const startBtn = document.querySelector('button[onclick="startExam()"]');
            if (startBtn) {
                startBtn.disabled = true;
                startBtn.textContent = 'Starting Exam...';
            }

            // Validate prerequisites
            if (!examData.examId) {
                alert('Exam data is invalid. Please refresh the page.');
                if (startBtn) {
                    startBtn.disabled = false;
                    startBtn.textContent = 'Start Exam';
                }
                return;
            }

            // Start the exam attempt first
            fetch('../../api/exams/attempts.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'same-origin',
                body: JSON.stringify({
                    exam_id: examData.examId,
                    action: 'start'
                })
            })
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => {
                        console.error('API start attempt returned non-OK response:', text);
                        // Try to extract error message from JSON response
                        try {
                            const json = JSON.parse(text);
                            throw new Error(json.message || 'Server error: ' + response.status);
                        } catch (e) {
                            if (e instanceof SyntaxError) {
                                throw new Error('Network response was not ok (HTTP ' + response.status + ')');
                            }
                            throw e;
                        }
                    });
                }
                return handleApiResponse(response);
            })
            .then(data => {
                if (data.success) {
                    examData.attemptId = data.attempt_id;
                    document.getElementById('attempt_id').value = data.attempt_id;
                    examStarted = true;

                    // Hide details and show exam content
                    document.getElementById('examDetails').style.display = 'none';
                    document.getElementById('examContent').style.display = 'block';

                    // Start timer if time limit exists
                    if (examData.timeLimit > 0) {
                        startTimer();
                    }

                    // Update navigation
                    updateNavButtons();

                    // Initialize text editors after DOM is ready
                    setTimeout(() => {
                        initializeSummernote();
                    }, 100);

                    // Enable auto-save
                    setInterval(autoSave, 30000);

                } else {
                    throw new Error(data.message || 'Failed to start exam');
                }
            })
            .catch(error => {
                console.error('Error starting exam:', error);
                alert('Error starting exam: ' + error.message + '. Please try again.');
                if (startBtn) {
                    startBtn.disabled = false;
                    startBtn.textContent = 'Start Exam';
                }
            });
        }

        function loadSavedAnswers() {
            fetch('../../api/exams/attempts.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'same-origin',
                body: JSON.stringify({
                    exam_id: examData.examId,
                    action: 'get'
                })
            })
            .then(handleApiResponse)
            .then(data => {
                if (data.success && data.attempt.answers) {
                    const answers = JSON.parse(data.attempt.answers);
                    populateAnswers(answers);
                    if (data.attempt.flagged) {
                        flaggedQuestions = JSON.parse(data.attempt.flagged);
                        updateFlaggedUI();
                    }
                }
            })
            .catch(error => console.error('Error loading saved answers:', error));
        }

        function populateAnswers(answers) {
            Object.keys(answers).forEach(questionId => {
                const answer = answers[questionId];

                if (typeof answer === 'object' && answer !== null) {
                    // Handle nested objects/arrays (matching, fill_blanks)
                    Object.keys(answer).forEach(key => {
                        const value = answer[key];
                        const inputs = document.querySelectorAll(`[name="answers[${questionId}][${key}]"]`);
                        inputs.forEach(input => {
                            if (input.type === 'radio' || input.type === 'checkbox') {
                                if (input.value === value) {
                                    input.checked = true;
                                }
                            } else {
                                input.value = value;
                            }
                        });
                    });
                } else if (Array.isArray(answer)) {
                    // Multiple choice
                    const inputs = document.querySelectorAll(`[name="answers[${questionId}][]"]`);
                    inputs.forEach(input => {
                        if (answer.includes(input.value)) {
                            input.checked = true;
                        }
                    });
                } else {
                    // Single choice or text
                    const inputs = document.querySelectorAll(`[name="answers[${questionId}]"]`);
                    inputs.forEach(input => {
                        if (input.type === 'radio' || input.type === 'checkbox') {
                            if (input.value === answer) {
                                input.checked = true;
                            }
                        } else if (input.tagName.toLowerCase() === 'textarea') {
                            if ($(input).hasClass('summernote-editor')) {
                                $(input).summernote('code', answer);
                            } else {
                                input.value = answer;
                            }
                        } else {
                            input.value = answer;
                        }
                    });
                }
            });
        }

        function autoSave() {
            return new Promise((resolve, reject) => {
                if (!examStarted || !examData.attemptId) {
                    resolve(); // No attempt to save
                    return;
                }

                const formData = new FormData(document.getElementById('examForm'));
                const answers = {};

                for (let [key, value] of formData.entries()) {
                    if (key.startsWith('answers[')) {
                        const matches = key.match(/answers\[(\d+)\](?:\[([^\]]+)\])?/);
                        if (matches) {
                            const questionId = matches[1];
                            const subKey = matches[2];

                            if (subKey !== undefined) {
                                // Nested array/object (matching, fill_blanks)
                                if (!answers[questionId]) answers[questionId] = {};
                                answers[questionId][subKey] = value;
                            } else if (key.includes('[]')) {
                                // Multiple choice
                                if (!answers[questionId]) answers[questionId] = [];
                                if (!answers[questionId].includes(value)) {
                                    answers[questionId].push(value);
                                }
                            } else {
                                // Single answer
                                answers[questionId] = value;
                            }
                        }
                    }
                }

                document.getElementById('time_spent').value = timeSpent;

                fetch('../../api/exams/attempts.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'same-origin',
                    body: JSON.stringify({
                        exam_id: examData.examId,
                        action: 'save',
                        answers: answers,
                        time_spent: timeSpent,
                        flagged: flaggedQuestions
                    })
                })
                .then(handleApiResponse)
                .then(data => {
                    if (data && data.success) {
                        console.log('Progress saved');
                        resolve();
                    } else {
                        reject(new Error((data && data.message) ? data.message : 'Save failed'));
                    }
                })
                .catch(error => {
                    console.error('Error saving progress:', error);
                    reject(error);
                });
            });
        }

        function submitExam() {
            // Prevent multiple submissions
            if (document.getElementById('submitBtn').disabled) {
                return;
            }

            if (!confirm('Are you sure you want to submit this exam? You cannot change your answers after submission.')) {
                return;
            }

            // Validate that exam has started
            if (!examStarted || !examData.attemptId) {
                alert('Exam has not been started properly. Please refresh the page.');
                return;
            }

            // Stop the timer if running
            if (timerInterval) {
                clearInterval(timerInterval);
            }

            // Update all Summernote textareas with their current content
            $('.summernote-editor').each(function() {
                const $this = $(this);
                try {
                    const content = $this.summernote('code');
                    $this.val(content);
                } catch (e) {
                    console.warn('Error getting Summernote content:', e);
                }
            });

            const submitBtn = document.getElementById('submitBtn');
            submitBtn.disabled = true;
            submitBtn.textContent = 'Submitting...';

            document.getElementById('loadingOverlay').classList.remove('hidden');

            // Collect form data
            const formData = new FormData(document.getElementById('examForm'));
            const answers = {};

            for (let [key, value] of formData.entries()) {
                if (key.startsWith('answers[')) {
                    const matches = key.match(/answers\[(\d+)\](?:\[([^\]]+)\])?/);
                    if (matches) {
                        const questionId = matches[1];
                        const subKey = matches[2];

                        if (subKey !== undefined) {
                            // Nested array/object (matching, fill_blanks)
                            if (!answers[questionId]) answers[questionId] = {};
                            answers[questionId][subKey] = value;
                        } else if (key.includes('[]')) {
                            // Multiple choice
                            if (!answers[questionId]) answers[questionId] = [];
                            if (!answers[questionId].includes(value)) {
                                answers[questionId].push(value);
                            }
                        } else {
                            // Single answer
                            answers[questionId] = value;
                        }
                    }
                }
            }

            // Submit the exam directly
            fetch('../../api/exams/attempts.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'same-origin',
                body: JSON.stringify({
                    exam_id: examData.examId,
                    action: 'submit',
                    answers: answers,
                    time_spent: timeSpent,
                    flagged: flaggedQuestions
                })
            })
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => {
                        console.error('API submit attempt returned non-OK response:', text);
                        // Try to extract error message from JSON response
                        try {
                            const json = JSON.parse(text);
                            throw new Error(json.message || 'Server error: ' + response.status);
                        } catch (e) {
                            if (e instanceof SyntaxError) {
                                throw new Error('Network response was not ok (HTTP ' + response.status + ')');
                            }
                            throw e;
                        }
                    });
                }
                return handleApiResponse(response);
            })
            .then(data => {
                if (data.success) {
                    // Clear any auto-save intervals
                    if (window.autoSaveInterval) {
                        clearInterval(window.autoSaveInterval);
                    }

                    alert(`Exam submitted successfully!\n\nScore: ${data.score}/${data.max_score} (${data.percentage}%)\nResult: ${data.passed ? 'PASSED' : 'FAILED'}`);
                    // Redirect to review page
                    window.location.href = '../exams/review.php?id=' + examData.attemptId;
                } else {
                    throw new Error(data.message || 'Submission failed');
                }
            })
            .catch(error => {
                console.error('Error submitting exam:', error);
                alert('Error submitting exam: ' + error.message + '. Please try again.');
                submitBtn.disabled = false;
                submitBtn.textContent = 'Submit Exam';
            })
            .finally(() => {
                document.getElementById('loadingOverlay').classList.add('hidden');
            });
        }

        function autoSubmitExam() {
            alert('Time is up! Your exam will be submitted automatically.');
            submitExam();
        }

        // Update navigation button colors based on answers
        document.addEventListener('change', function(e) {
            if (e.target.name && e.target.name.startsWith('answers[')) {
                const questionId = e.target.name.match(/answers\[(\d+)\]/)[1];
                const questionIndex = examData.questions.findIndex(q => q.id == questionId);

                if (questionIndex !== -1) {
                    const navBtn = document.querySelector(`.question-nav-btn[data-index="${questionIndex}"]`);
                    if (navBtn) {
                        navBtn.classList.add('bg-green-100', 'border-green-500', 'text-green-800');
                    }
                }
            }
        });
    </script>
</body>
</html>