<?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
if (!hasAnyRole(['student'])) {
    header('Location: ../../login.php');
    exit;
}

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

$examId = $_GET['id'] ?? 0;
if (!$examId) {
    header('Location: ../dashboard.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: ../dashboard.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: ../dashboard.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: ../dashboard.php');
    exit;
}

if ($endDate && $currentTime > $endDate) {
    $_SESSION['error_message'] = 'This exam has ended.';
    header('Location: ../dashboard.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: ../dashboard.php');
    exit;
}

// Get exam questions
$stmt = $db->prepare("
    SELECT eq.*, q.title, q.content, q.question_type, q.points as default_points,
           q.explanation, q.hints, q.time_limit as question_time_limit
    FROM exam_questions eq
    JOIN questions q ON eq.question_id = q.id
    WHERE eq.exam_id = ?
    ORDER BY eq.sort_order
");
$stmt->execute([$examId]);
$examQuestions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Shuffle questions if required
if ($exam['shuffle_questions']) {
    shuffle($examQuestions);
}

// Get question options for multiple choice questions
$questionIds = array_column($examQuestions, 'question_id');
if (!empty($questionIds)) {
    $placeholders = str_repeat('?,', count($questionIds) - 1) . '?';
    $stmt = $db->prepare("
        SELECT * FROM question_options
        WHERE question_id IN ($placeholders)
        ORDER BY question_id, sort_order
    ");
    $stmt->execute($questionIds);
    $questionOptions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Group options by question_id
    $optionsByQuestion = [];
    foreach ($questionOptions as $option) {
        $optionsByQuestion[$option['question_id']][] = $option;
    }

    // Shuffle options if required
    if ($exam['shuffle_options']) {
        foreach ($optionsByQuestion as &$options) {
            shuffle($options);
        }
    }
}

// Check if there's an existing in-progress attempt
$existingAttempt = null;
if ($exam['has_attempted'] && $exam['last_attempt_status'] === 'in_progress') {
    $stmt = $db->prepare("
        SELECT * FROM exam_attempts
        WHERE exam_id = ? AND student_id = ? AND status = 'in_progress'
        ORDER BY started_at DESC LIMIT 1
    ");
    $stmt->execute([$examId, $userId]);
    $existingAttempt = $stmt->fetch(PDO::FETCH_ASSOC);
}

$page_title = htmlspecialchars($exam['title']) . ' - Mutalex Academy';
include '../../includes/header.php';
?>

<div class="exam-container">
    <!-- Exam Header -->
    <div class="exam-header bg-primary text-white p-3">
        <div class="container-fluid">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h4 class="mb-0"><?php echo htmlspecialchars($exam['title']); ?></h4>
                    <?php if ($exam['course_title']): ?>
                        <small><?php echo htmlspecialchars($exam['course_title']); ?></small>
                    <?php endif; ?>
                </div>
                <div class="col-md-6 text-end">
                    <div class="exam-info">
                        <span class="me-3">
                            <i class="fas fa-clock me-1"></i>
                            <span id="time-remaining">
                                <?php echo $exam['time_limit'] ? $exam['time_limit'] . ':00' : 'No limit'; ?>
                            </span>
                        </span>
                        <span class="me-3">
                            <i class="fas fa-list me-1"></i>
                            <?php echo count($examQuestions); ?> Questions
                        </span>
                        <span>
                            <i class="fas fa-trophy me-1"></i>
                            <?php echo $exam['total_points']; ?> Points
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container-fluid mt-3">
        <div class="row">
            <!-- Main Exam Content -->
            <div class="col-lg-9">
                <div class="exam-content">
                    <?php if ($existingAttempt): ?>
                        <!-- Resume Exam -->
                        <div class="alert alert-info">
                            <h5><i class="fas fa-play-circle me-2"></i>Resume Your Exam</h5>
                            <p>You have an unfinished attempt from <?php echo date('M j, Y g:i A', strtotime($existingAttempt['started_at'])); ?>.</p>
                            <button id="resume-exam" class="btn btn-primary">Resume Exam</button>
                            <button id="start-new" class="btn btn-outline-secondary ms-2">Start New Attempt</button>
                        </div>
                    <?php else: ?>
                        <!-- Start Exam -->
                        <div class="exam-start">
                            <div class="text-center py-5">
                                <i class="fas fa-clipboard-check fa-4x text-primary mb-4"></i>
                                <h3>Ready to Start Your Exam?</h3>
                                <p class="text-muted mb-4">Make sure you have a stable internet connection and sufficient time to complete the exam.</p>

                                <div class="exam-details card mb-4">
                                    <div class="card-body">
                                        <div class="row text-center">
                                            <div class="col-md-3">
                                                <div class="fw-bold fs-4"><?php echo count($examQuestions); ?></div>
                                                <small class="text-muted">Questions</small>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="fw-bold fs-4"><?php echo $exam['total_points']; ?></div>
                                                <small class="text-muted">Total Points</small>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="fw-bold fs-4">
                                                    <?php echo $exam['time_limit'] ? $exam['time_limit'] . ' min' : 'No limit'; ?>
                                                </div>
                                                <small class="text-muted">Time Limit</small>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="fw-bold fs-4"><?php echo $exam['passing_score']; ?>%</div>
                                                <small class="text-muted">Passing Score</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <?php if ($exam['instructions']): ?>
                                    <div class="exam-instructions card mb-4">
                                        <div class="card-header">
                                            <h5 class="mb-0">Exam Instructions</h5>
                                        </div>
                                        <div class="card-body">
                                            <?php echo nl2br(htmlspecialchars($exam['instructions'])); ?>
                                        </div>
                                    </div>
                                <?php endif; ?>

                                <button id="start-exam" class="btn btn-success btn-lg">
                                    <i class="fas fa-play me-2"></i>Start Exam
                                </button>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Exam Questions (hidden initially) -->
                    <div id="exam-questions" class="exam-questions" style="display: none;">
                        <form id="exam-form">
                            <?php foreach ($examQuestions as $index => $question): ?>
                                <div class="question-card card mb-4" id="question-<?php echo $index + 1; ?>" data-question-id="<?php echo $question['question_id']; ?>">
                                    <div class="card-header d-flex justify-content-between align-items-center">
                                        <h6 class="mb-0">
                                            Question <?php echo $index + 1; ?> of <?php echo count($examQuestions); ?>
                                            <span class="badge bg-primary ms-2"><?php echo $question['points']; ?> pts</span>
                                        </h6>
                                        <small class="text-muted">
                                            <?php echo ucfirst(str_replace('_', ' ', $question['question_type'])); ?>
                                        </small>
                                    </div>
                                    <div class="card-body">
                                        <div class="question-content mb-4">
                                            <h6><?php echo htmlspecialchars($question['title']); ?></h6>
                                            <div><?php echo $question['content']; ?></div>
                                        </div>

                                        <div class="question-answer">
                                            <?php
                                            $inputName = "answer[{$question['question_id']}]";
                                            $inputId = "answer-{$question['question_id']}";
                                            ?>

                                            <?php if ($question['question_type'] === 'mcq_single'): ?>
                                                <!-- Single Choice -->
                                                <div class="mcq-options">
                                                    <?php
                                                    $options = $optionsByQuestion[$question['question_id']] ?? [];
                                                    foreach ($options as $option):
                                                    ?>
                                                        <div class="form-check mb-2">
                                                            <input class="form-check-input" type="radio"
                                                                   name="<?php echo $inputName; ?>"
                                                                   id="option-<?php echo $option['id']; ?>"
                                                                   value="<?php echo $option['id']; ?>">
                                                            <label class="form-check-label" for="option-<?php echo $option['id']; ?>">
                                                                <?php echo htmlspecialchars($option['option_text']); ?>
                                                            </label>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>

                                            <?php elseif ($question['question_type'] === 'mcq_multiple'): ?>
                                                <!-- Multiple Choice -->
                                                <div class="mcq-options">
                                                    <?php
                                                    $options = $optionsByQuestion[$question['question_id']] ?? [];
                                                    foreach ($options as $option):
                                                    ?>
                                                        <div class="form-check mb-2">
                                                            <input class="form-check-input" type="checkbox"
                                                                   name="<?php echo $inputName; ?>[]"
                                                                   id="option-<?php echo $option['id']; ?>"
                                                                   value="<?php echo $option['id']; ?>">
                                                            <label class="form-check-label" for="option-<?php echo $option['id']; ?>">
                                                                <?php echo htmlspecialchars($option['option_text']); ?>
                                                            </label>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>

                                            <?php elseif ($question['question_type'] === 'true_false'): ?>
                                                <!-- True/False -->
                                                <div class="true-false-options">
                                                    <div class="form-check form-check-inline">
                                                        <input class="form-check-input" type="radio"
                                                               name="<?php echo $inputName; ?>"
                                                               id="true-<?php echo $question['question_id']; ?>"
                                                               value="true">
                                                        <label class="form-check-label" for="true-<?php echo $question['question_id']; ?>">
                                                            True
                                                        </label>
                                                    </div>
                                                    <div class="form-check form-check-inline">
                                                        <input class="form-check-input" type="radio"
                                                               name="<?php echo $inputName; ?>"
                                                               id="false-<?php echo $question['question_id']; ?>"
                                                               value="false">
                                                        <label class="form-check-label" for="false-<?php echo $question['question_id']; ?>">
                                                            False
                                                        </label>
                                                    </div>
                                                </div>

                                            <?php elseif ($question['question_type'] === 'essay' || $question['question_type'] === 'short_answer'): ?>
                                                <!-- Essay/Short Answer -->
                                                <textarea class="form-control"
                                                          name="<?php echo $inputName; ?>"
                                                          id="<?php echo $inputId; ?>"
                                                          rows="<?php echo $question['question_type'] === 'essay' ? '6' : '3'; ?>"
                                                          placeholder="Enter your answer here..."></textarea>

                                            <?php elseif ($question['question_type'] === 'code'): ?>
                                                <!-- Code Question -->
                                                <textarea class="form-control font-monospace"
                                                          name="<?php echo $inputName; ?>"
                                                          id="<?php echo $inputId; ?>"
                                                          rows="10"
                                                          placeholder="Write your code here..."></textarea>

                                            <?php elseif ($question['question_type'] === 'matching'): ?>
                                                <!-- Matching Question -->
                                                <div class="matching-container">
                                                    <?php
                                                    $options = $optionsByQuestion[$question['question_id']] ?? [];
                                                    $leftOptions = array_filter($options, fn($opt) => !empty($opt['match_value']));
                                                    $rightOptions = array_filter($options, fn($opt) => !empty($opt['match_value']));
                                                    ?>
                                                    <div class="row">
                                                        <div class="col-md-6">
                                                            <h6>Items to Match:</h6>
                                                            <?php foreach ($leftOptions as $option): ?>
                                                                <div class="mb-2">
                                                                    <strong><?php echo htmlspecialchars($option['option_text']); ?></strong>
                                                                </div>
                                                            <?php endforeach; ?>
                                                        </div>
                                                        <div class="col-md-6">
                                                            <h6>Matching Options:</h6>
                                                            <select class="form-select mb-2" name="<?php echo $inputName; ?>[<?php echo $option['id']; ?>]">
                                                                <option value="">Select match...</option>
                                                                <?php foreach ($rightOptions as $rightOption): ?>
                                                                    <option value="<?php echo $rightOption['id']; ?>">
                                                                        <?php echo htmlspecialchars($rightOption['match_value']); ?>
                                                                    </option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </div>
                                                    </div>
                                                </div>

                                            <?php elseif ($question['question_type'] === 'fill_blanks'): ?>
                                                <!-- Fill in the Blanks -->
                                                <div class="fill-blanks">
                                                    <?php echo $question['content']; // This would contain the text with [blank] placeholders ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Exam Sidebar -->
            <div class="col-lg-3">
                <div class="exam-sidebar">
                    <!-- Question Navigation -->
                    <div class="card mb-3">
                        <div class="card-header">
                            <h6 class="mb-0">Question Navigation</h6>
                        </div>
                        <div class="card-body">
                            <div class="question-nav-grid">
                                <?php for ($i = 1; $i <= count($examQuestions); $i++): ?>
                                    <button class="btn btn-outline-secondary btn-sm question-nav-btn <?php echo $i === 1 ? 'active' : ''; ?>"
                                            data-question="<?php echo $i; ?>">
                                        <?php echo $i; ?>
                                    </button>
                                <?php endfor; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Progress -->
                    <div class="card mb-3">
                        <div class="card-header">
                            <h6 class="mb-0">Progress</h6>
                        </div>
                        <div class="card-body">
                            <div class="progress mb-2">
                                <div class="progress-bar" id="progress-bar" role="progressbar" style="width: 0%"></div>
                            </div>
                            <small class="text-muted">
                                <span id="answered-count">0</span> of <?php echo count($examQuestions); ?> answered
                            </small>
                        </div>
                    </div>

                    <!-- Actions -->
                    <div class="card">
                        <div class="card-body">
                            <button id="save-progress" class="btn btn-outline-primary w-100 mb-2" disabled>
                                <i class="fas fa-save me-1"></i>Save Progress
                            </button>
                            <button id="submit-exam" class="btn btn-success w-100 mb-2" style="display: none;">
                                <i class="fas fa-paper-plane me-1"></i>Submit Exam
                            </button>
                            <button id="auto-submit" class="btn btn-warning w-100" style="display: none;">
                                <i class="fas fa-clock me-1"></i>Auto-Submit in <span id="auto-submit-timer"></span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Exam Security Warning -->
<div class="modal fade" id="securityModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title text-dark"><i class="fas fa-shield-alt me-2"></i>Exam Security</h5>
            </div>
            <div class="modal-body">
                <p><strong>Important:</strong> This exam has security measures in place. Please ensure:</p>
                <ul>
                    <li>You are in a quiet environment</li>
                    <li>You have a stable internet connection</li>
                    <li>You do not switch tabs or windows during the exam</li>
                    <li>You do not copy or paste content</li>
                </ul>
                <p class="text-danger"><strong>Violation of these rules may result in automatic submission or disqualification.</strong></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="acknowledge-security">I Understand</button>
            </div>
        </div>
    </div>
</div>

<script>
// Exam configuration
const examConfig = {
    examId: <?php echo $examId; ?>,
    timeLimit: <?php echo $exam['time_limit'] ?: 'null'; ?>,
    totalQuestions: <?php echo count($examQuestions); ?>,
    hasExistingAttempt: <?php echo $existingAttempt ? 'true' : 'false'; ?>,
    existingAnswers: <?php echo $existingAttempt ? json_encode(json_decode($existingAttempt['answers'], true)) : 'null'; ?>
};

let currentQuestion = 1;
let timeRemaining = examConfig.timeLimit ? examConfig.timeLimit * 60 : null; // in seconds
let timerInterval = null;
let examStarted = false;
let answers = examConfig.existingAnswers || {};

// Initialize exam
document.addEventListener('DOMContentLoaded', function() {
    initializeExam();
});

function initializeExam() {
    // Show security modal if proctored
    <?php if ($exam['is_proctored']): ?>
        const securityModal = new bootstrap.Modal(document.getElementById('securityModal'));
        securityModal.show();
    <?php endif; ?>

    // Load existing answers if resuming
    if (examConfig.hasExistingAttempt && examConfig.existingAnswers) {
        loadExistingAnswers();
    }

    // Setup event listeners
    setupEventListeners();
}

function setupEventListeners() {
    // Start exam button
    document.getElementById('start-exam').addEventListener('click', startExam);

    // Resume exam button
    document.getElementById('resume-exam').addEventListener('click', resumeExam);

    // Start new attempt button
    document.getElementById('start-new').addEventListener('click', startNewAttempt);

    // Question navigation
    document.querySelectorAll('.question-nav-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            navigateToQuestion(parseInt(this.dataset.question));
        });
    });

    // Save progress
    document.getElementById('save-progress').addEventListener('click', saveProgress);

    // Submit exam
    document.getElementById('submit-exam').addEventListener('click', submitExam);

    // Security acknowledgment
    document.getElementById('acknowledge-security').addEventListener('click', function() {
        bootstrap.Modal.getInstance(document.getElementById('securityModal')).hide();
    });

    // Answer change tracking
    document.getElementById('exam-form').addEventListener('change', function(e) {
        trackAnswer(e.target);
        updateProgress();
    });

    // Prevent copy/paste if security enabled
    <?php if ($exam['is_proctored']): ?>
        document.addEventListener('copy', preventCopyPaste);
        document.addEventListener('paste', preventCopyPaste);
        document.addEventListener('contextmenu', preventContextMenu);
        document.addEventListener('visibilitychange', handleVisibilityChange);
    <?php endif; ?>
}

function startExam() {
    examStarted = true;
    document.querySelector('.exam-start').style.display = 'none';
    document.getElementById('exam-questions').style.display = 'block';
    document.getElementById('save-progress').disabled = false;
    document.getElementById('submit-exam').style.display = 'block';

    // Create exam attempt
    createExamAttempt();

    // Start timer if time limit exists
    if (timeRemaining) {
        startTimer();
    }

    // Navigate to first question
    navigateToQuestion(1);
}

function resumeExam() {
    examStarted = true;
    document.querySelector('.exam-start').style.display = 'none';
    document.getElementById('exam-questions').style.display = 'block';
    document.getElementById('save-progress').disabled = false;
    document.getElementById('submit-exam').style.display = 'block';

    // Resume timer
    if (timeRemaining) {
        startTimer();
    }

    // Navigate to first question
    navigateToQuestion(1);
}

function startNewAttempt() {
    if (confirm('Are you sure you want to start a new attempt? Your previous progress will be lost.')) {
        // Reset answers
        answers = {};
        examConfig.existingAnswers = null;

        // Clear form
        document.getElementById('exam-form').reset();

        startExam();
    }
}

function createExamAttempt() {
    fetch('../../api/exams/attempts.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            exam_id: examConfig.examId,
            action: 'start'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (!data.success) {
            alert('Failed to start exam attempt: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to start exam attempt');
    });
}

function navigateToQuestion(questionNumber) {
    // Hide all questions
    document.querySelectorAll('.question-card').forEach(card => {
        card.style.display = 'none';
    });

    // Show selected question
    document.getElementById('question-' + questionNumber).style.display = 'block';

    // Update navigation
    document.querySelectorAll('.question-nav-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`[data-question="${questionNumber}"]`).classList.add('active');

    currentQuestion = questionNumber;
}

function trackAnswer(element) {
    const questionId = element.closest('.question-card').dataset.questionId;
    let value = null;

    if (element.type === 'radio' || element.type === 'checkbox') {
        if (element.type === 'checkbox') {
            // Handle multiple selections
            const checkboxes = document.querySelectorAll(`input[name="${element.name}"]:checked`);
            value = Array.from(checkboxes).map(cb => cb.value);
        } else {
            value = element.value;
        }
    } else if (element.tagName === 'TEXTAREA' || element.tagName === 'SELECT') {
        value = element.value;
    }

    if (value !== null) {
        answers[questionId] = value;
    }
}

function updateProgress() {
    const answeredCount = Object.keys(answers).length;
    const progressPercent = (answeredCount / examConfig.totalQuestions) * 100;

    document.getElementById('progress-bar').style.width = progressPercent + '%';
    document.getElementById('answered-count').textContent = answeredCount;

    // Update navigation button styles
    document.querySelectorAll('.question-nav-btn').forEach(btn => {
        const questionNum = parseInt(btn.dataset.question);
        const questionCard = document.getElementById('question-' + questionNum);
        const questionId = questionCard.dataset.questionId;

        btn.classList.remove('btn-success', 'btn-warning');
        if (answers[questionId]) {
            btn.classList.add('btn-success');
        } else {
            btn.classList.add('btn-warning');
        }
    });
}

function saveProgress() {
    fetch('../../api/exams/attempts.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            exam_id: examConfig.examId,
            action: 'save',
            answers: answers,
            time_spent: examConfig.timeLimit ? (examConfig.timeLimit * 60 - timeRemaining) : 0
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Progress saved successfully!');
        } else {
            alert('Failed to save progress: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to save progress');
    });
}

function submitExam() {
    if (!confirm('Are you sure you want to submit your exam? This action cannot be undone.')) {
        return;
    }

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

    fetch('../../api/exams/attempts.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            exam_id: examConfig.examId,
            action: 'submit',
            answers: answers,
            time_spent: examConfig.timeLimit ? (examConfig.timeLimit * 60 - timeRemaining) : 0
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.href = 'review.php?id=' + examConfig.examId;
        } else {
            alert('Failed to submit exam: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to submit exam');
    });
}

function startTimer() {
    timerInterval = setInterval(function() {
        timeRemaining--;

        if (timeRemaining <= 0) {
            clearInterval(timerInterval);
            autoSubmitExam();
            return;
        }

        updateTimerDisplay();

        // Show auto-submit warning in last 5 minutes
        if (timeRemaining <= 300) {
            document.getElementById('auto-submit').style.display = 'block';
            document.getElementById('auto-submit-timer').textContent = formatTime(timeRemaining);
        }
    }, 1000);
}

function updateTimerDisplay() {
    const minutes = Math.floor(timeRemaining / 60);
    const seconds = timeRemaining % 60;
    document.getElementById('time-remaining').textContent =
        minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0');
}

function formatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return minutes + ':' + secs.toString().padStart(2, '0');
}

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

function loadExistingAnswers() {
    // Load answers into form
    Object.keys(answers).forEach(questionId => {
        const value = answers[questionId];
        const questionCard = document.querySelector(`[data-question-id="${questionId}"]`);

        if (questionCard) {
            if (Array.isArray(value)) {
                // Multiple choice
                value.forEach(optionId => {
                    const input = questionCard.querySelector(`input[value="${optionId}"]`);
                    if (input) input.checked = true;
                });
            } else {
                // Single choice or text
                const input = questionCard.querySelector(`input[name*="${questionId}"][value="${value}"]`) ||
                             questionCard.querySelector(`textarea[name*="${questionId}"]`) ||
                             questionCard.querySelector(`select[name*="${questionId}"]`);
                if (input) {
                    if (input.type === 'radio' || input.type === 'checkbox') {
                        input.checked = true;
                    } else {
                        input.value = value;
                    }
                }
            }
        }
    });
}

// Security functions
function preventCopyPaste(e) {
    e.preventDefault();
    alert('Copy/paste is not allowed during this exam.');
}

function preventContextMenu(e) {
    e.preventDefault();
    alert('Right-click is disabled during this exam.');
}

function handleVisibilityChange() {
    if (document.hidden) {
        alert('Warning: You switched away from the exam window. This may be recorded.');
    }
}
</script>

<style>
.exam-container {
    min-height: 100vh;
    background-color: #f8f9fa;
}

.exam-header {
    position: sticky;
    top: 0;
    z-index: 1000;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.exam-info {
    font-size: 0.9rem;
}

.question-card {
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.question-nav-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(40px, 1fr));
    gap: 5px;
}

.question-nav-btn {
    width: 40px;
    height: 40px;
    padding: 0;
    border-radius: 50%;
}

.question-nav-btn.active {
    background-color: #007bff;
    color: white;
}

.mcq-options .form-check-label {
    cursor: pointer;
}

.true-false-options .form-check-label {
    cursor: pointer;
}

.exam-sidebar {
    position: sticky;
    top: 100px;
}

@media (max-width: 991.98px) {
    .exam-sidebar {
        position: static;
        margin-top: 20px;
    }
}
</style>

<?php include '../../includes/footer.php'; ?>