<?php
/**
 * Exam Taking Interface — Gmind Institute
 *
 * Full exam interface with timer, progress bar, question display,
 * radio options, navigation, question navigator sidebar, and
 * auto-submit on timer expiry.
 *
 * Expected PHP variables:
 *   $exam       — exam record array
 *   $questions  — array of exam question records
 *   $csrfToken  — CSRF token string
 *   $currentPage — string 'online-exam'
 *   $title      — page title
 */

$exam      = $exam      ?? [];
$questions = $questions ?? [];

$examId       = $exam['id'] ?? 0;
$examTitle    = $exam['title'] ?? 'Exam';
$examDuration = (int) ($exam['duration'] ?? 30); // minutes
$totalMarks   = (int) ($exam['total_marks'] ?? 0);
$totalQ       = count($questions);
?>

<?php include __DIR__ . '/../layouts/header.php'; ?>

<!-- ============================================================
     Exam Interface
     ============================================================ -->
<section class="exam-take-section" aria-label="Exam taking interface">
    <div class="container">
        <!-- Exam Header Bar -->
        <div class="exam-header-bar">
            <div class="exam-header-left">
                <h1><?= htmlspecialchars($examTitle, ENT_QUOTES, 'UTF-8') ?></h1>
                <span class="exam-q-count"><?= $totalQ ?> Questions | <?= $totalMarks ?> Marks</span>
            </div>
            <div class="exam-header-right">
                <div class="exam-timer" id="examTimer" aria-label="Time remaining">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                    <span id="timerDisplay"><?= sprintf('%02d:%02d', $examDuration, 0) ?></span>
                </div>
            </div>
        </div>

        <!-- Progress Bar -->
        <div class="exam-progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
            <div class="exam-progress-fill" id="examProgress" style="width:0%"></div>
        </div>

        <div class="exam-layout">
            <!-- Main Question Area -->
            <div class="exam-main">
                <form id="examForm" method="POST" action="<?= url('/exam/' . $examId . '/submit') ?>">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8') ?>">

                    <?php foreach ($questions as $index => $question): ?>
                    <div class="exam-question<?= $index === 0 ? ' active' : '' ?>" data-question="<?= $index ?>" id="question-<?= $index ?>">
                        <div class="question-header">
                            <span class="question-number">Question <?= $index + 1 ?> of <?= $totalQ ?></span>
                            <span class="question-marks">[<?= (int) ($question['marks'] ?? 1) ?> Marks]</span>
                        </div>
                        <div class="question-text">
                            <?= htmlspecialchars($question['question_text'] ?? 'Question text', ENT_QUOTES, 'UTF-8') ?>
                        </div>
                        <div class="question-options">
                            <?php
                            $options = [
                                'a' => $question['option_a'] ?? '',
                                'b' => $question['option_b'] ?? '',
                                'c' => $question['option_c'] ?? '',
                                'd' => $question['option_d'] ?? '',
                            ];
                            ?>
                            <?php foreach ($options as $key => $option): ?>
                            <?php if (!empty($option)): ?>
                            <label class="option-label" for="q<?= $index ?>_<?= $key ?>">
                                <input type="radio" name="answers[<?= $index ?>]" id="q<?= $index ?>_<?= $key ?>" value="<?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>" class="option-radio">
                                <span class="option-marker"><?= strtoupper($key) ?></span>
                                <span class="option-text"><?= htmlspecialchars($option, ENT_QUOTES, 'UTF-8') ?></span>
                            </label>
                            <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>

                    <!-- Navigation Buttons -->
                    <div class="exam-nav-buttons">
                        <button type="button" id="prevBtn" class="btn-outline exam-nav-btn" disabled>
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>
                            Previous
                        </button>
                        <button type="button" id="nextBtn" class="btn-primary exam-nav-btn">
                            Next
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 18 15 12 9 6"/></svg>
                        </button>
                        <button type="submit" id="submitBtn" class="btn-enroll btn-enroll-scarlet exam-nav-btn" style="display:none;" onclick="return confirm('Are you sure you want to submit the exam? You cannot change answers after submission.');">
                            Submit Exam
                        </button>
                    </div>
                </form>
            </div>

            <!-- Question Navigator Sidebar -->
            <aside class="exam-sidebar" aria-label="Question navigator">
                <h3>Question Navigator</h3>
                <div class="question-navigator" id="questionNav">
                    <?php foreach ($questions as $index => $question): ?>
                    <button type="button" class="qnav-btn<?= $index === 0 ? ' active' : '' ?>" data-q="<?= $index ?>" aria-label="Go to question <?= $index + 1 ?>">
                        <?= $index + 1 ?>
                    </button>
                    <?php endforeach; ?>
                </div>
                <div class="qnav-legend">
                    <span class="legend-item"><span class="legend-dot legend-visited"></span> Visited</span>
                    <span class="legend-item"><span class="legend-dot legend-answered"></span> Answered</span>
                    <span class="legend-item"><span class="legend-dot legend-current"></span> Current</span>
                </div>
            </aside>
        </div>
    </div>
</section>

<!-- Exam JavaScript -->
<script>
(function() {
    'use strict';

    // Timer configuration
    const durationMinutes = <?= $examDuration ?>;
    let totalSeconds = durationMinutes * 60;
    let timerInterval = null;

    // Question navigation state
    let currentQuestion = 0;
    const totalQuestions = <?= $totalQ ?>;
    const questions = document.querySelectorAll('.exam-question');
    const qnavBtns = document.querySelectorAll('.qnav-btn');
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');
    const submitBtn = document.getElementById('submitBtn');
    const examForm = document.getElementById('examForm');
    const timerDisplay = document.getElementById('timerDisplay');
    const progressBar = document.getElementById('examProgress');

    // Timer functionality
    function startTimer() {
        timerInterval = setInterval(function() {
            totalSeconds--;
            if (totalSeconds <= 0) {
                clearInterval(timerInterval);
                totalSeconds = 0;
                // Auto-submit when timer expires
                examForm.submit();
            }
            const mins = Math.floor(totalSeconds / 60);
            const secs = totalSeconds % 60;
            timerDisplay.textContent = String(mins).padStart(2, '0') + ':' + String(secs).padStart(2, '0');

            // Update timer colour when low
            const timerEl = document.getElementById('examTimer');
            if (totalSeconds <= 60) {
                timerEl.classList.add('timer-danger');
            } else if (totalSeconds <= 300) {
                timerEl.classList.add('timer-warning');
            }
        }, 1000);
    }

    // Show specific question
    function showQuestion(index) {
        questions.forEach(function(q) { q.classList.remove('active'); });
        qnavBtns.forEach(function(b) { b.classList.remove('active'); });

        if (questions[index]) {
            questions[index].classList.add('active');
        }
        if (qnavBtns[index]) {
            qnavBtns[index].classList.add('active');
            qnavBtns[index].classList.add('visited');
        }

        currentQuestion = index;

        // Update navigation buttons
        prevBtn.disabled = (index === 0);
        if (index === totalQuestions - 1) {
            nextBtn.style.display = 'none';
            submitBtn.style.display = 'inline-flex';
        } else {
            nextBtn.style.display = 'inline-flex';
            submitBtn.style.display = 'none';
        }

        // Update progress bar
        const progress = ((index + 1) / totalQuestions) * 100;
        progressBar.style.width = progress + '%';

        // Update answered indicators
        updateAnsweredState();
    }

    // Update answered state in navigator
    function updateAnsweredState() {
        questions.forEach(function(q, i) {
            const selected = q.querySelector('input[type="radio"]:checked');
            if (selected && qnavBtns[i]) {
                qnavBtns[i].classList.add('answered');
            }
        });
    }

    // Navigation event listeners
    prevBtn.addEventListener('click', function() {
        if (currentQuestion > 0) showQuestion(currentQuestion - 1);
    });

    nextBtn.addEventListener('click', function() {
        if (currentQuestion < totalQuestions - 1) showQuestion(currentQuestion + 1);
    });

    // Question navigator buttons
    qnavBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            const qIndex = parseInt(this.getAttribute('data-q'));
            showQuestion(qIndex);
        });
    });

    // Radio change handler
    document.querySelectorAll('.option-radio').forEach(function(radio) {
        radio.addEventListener('change', updateAnsweredState);
    });

    // Prevent back navigation during exam
    window.history.pushState(null, '', window.location.href);
    window.addEventListener('popstate', function() {
        window.history.pushState(null, '', window.location.href);
    });

    // Start the timer
    startTimer();
})();
</script>

<?php include __DIR__ . '/../layouts/footer.php'; ?>
