Path : /home/vishqocm/pcib.in/student/
File Upload :
Current File : /home/vishqocm//pcib.in/student/take_exam.php

<?php
// Start session
session_start();

// Include database configuration
require_once '../config/database.php';

// Check if user is logged in and has student role
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'student') {
    header('Location: ../login.php');
    exit;
}

$user_id = $_SESSION['user_id'];

// Process exam submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_answers'])) {
    // Get student exam ID
    $student_exam_id = isset($_POST['student_exam_id']) ? intval($_POST['student_exam_id']) : 0;
    
    if (!$student_exam_id) {
        $_SESSION['error_message'] = "Invalid exam session.";
        header('Location: exams.php');
        exit;
    }
    
    // Get exam details
    $exam_query = "SELECT se.*, es.passing_percentage, es.id as exam_id
                  FROM student_exams se
                  JOIN exam_schedules es ON se.exam_id = es.id
                  WHERE se.id = ? AND se.user_id = ?";
    $stmt = $conn->prepare($exam_query);
    $stmt->bind_param("ii", $student_exam_id, $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        $_SESSION['error_message'] = "Exam session not found or not authorized.";
        header('Location: exams.php');
        exit;
    }
    
    $exam_data = $result->fetch_assoc();
    $exam_id = $exam_data['exam_id'];
    
    // Store answers if provided
    $total_questions = 0;
    $correct_answers = 0;
    $total_possible_marks = 0;
    $earned_marks = 0;
    
    // Process multiple choice and true/false answers
    if (isset($_POST['answer']) && is_array($_POST['answer'])) {
        foreach ($_POST['answer'] as $question_id => $selected_option_id) {
            // Get question details
            $question_query = "SELECT * FROM questions WHERE id = ?";
            $stmt = $conn->prepare($question_query);
            $stmt->bind_param("i", $question_id);
            $stmt->execute();
            $question_result = $stmt->get_result();
            
            if ($question_result->num_rows > 0) {
                $question = $question_result->fetch_assoc();
                $total_questions++;
                $total_possible_marks += $question['marks'];
                
                // Check if the answer is correct
                $is_correct = 0;
                if ($question['question_type'] === 'multiple_choice' || $question['question_type'] === 'true_false') {
                    // Get the correct option ID
                    $option_query = "SELECT id FROM question_options WHERE question_id = ? AND is_correct = 1";
                    $stmt = $conn->prepare($option_query);
                    $stmt->bind_param("i", $question_id);
                    $stmt->execute();
                    $option_result = $stmt->get_result();
                    
                    if ($option_result->num_rows > 0) {
                        $correct_option = $option_result->fetch_assoc();
                        $is_correct = ($selected_option_id == $correct_option['id']) ? 1 : 0;
                        
                        if ($is_correct) {
                            $correct_answers++;
                            $earned_marks += $question['marks'];
                        }
                    }
                }
                
                // Save the answer
                $insert_answer = "INSERT INTO student_exam_answers 
                                 (student_exam_id, question_id, selected_option_id, is_correct) 
                                 VALUES (?, ?, ?, ?)";
                $stmt = $conn->prepare($insert_answer);
                $stmt->bind_param("iiis", $student_exam_id, $question_id, $selected_option_id, $is_correct);
                $stmt->execute();
            }
        }
    }
    
    // Process text answers (short answer and essay)
    if (isset($_POST['text_answer']) && is_array($_POST['text_answer'])) {
        foreach ($_POST['text_answer'] as $question_id => $answer_text) {
            if (!empty($answer_text)) {
                // Get question details
                $question_query = "SELECT * FROM questions WHERE id = ?";
                $stmt = $conn->prepare($question_query);
                $stmt->bind_param("i", $question_id);
                $stmt->execute();
                $question_result = $stmt->get_result();
                
                if ($question_result->num_rows > 0) {
                    $question = $question_result->fetch_assoc();
                    $total_questions++;
                    $total_possible_marks += $question['marks'];
                    
                    // Save the answer (marking these as pending until manual grading)
                    $is_correct = 'pending';
                    $insert_answer = "INSERT INTO student_exam_answers 
                                     (student_exam_id, question_id, answer_text, is_correct) 
                                     VALUES (?, ?, ?, ?)";
                    $stmt = $conn->prepare($insert_answer);
                    $stmt->bind_param("iiss", $student_exam_id, $question_id, $answer_text, $is_correct);
                    $stmt->execute();
                }
            }
        }
    }
    
    // Calculate percentage
    $percentage = 0;
    if ($total_possible_marks > 0) {
        $percentage = ($earned_marks / $total_possible_marks) * 100;
    }
    
    // Determine if passed based on passing percentage
    $status = ($percentage >= $exam_data['passing_percentage']) ? 'passed' : 'failed';
    
    // If there are pending answers (essays/short answers), mark as completed instead of pass/fail
    $has_pending_query = "SELECT COUNT(*) as pending_count FROM student_exam_answers 
                         WHERE student_exam_id = ? AND is_correct = 'pending'";
    $stmt = $conn->prepare($has_pending_query);
    $stmt->bind_param("i", $student_exam_id);
    $stmt->execute();
    $pending_result = $stmt->get_result()->fetch_assoc();
    
    if ($pending_result['pending_count'] > 0) {
        $status = 'completed'; // Will need manual grading
    }
    
    // Update the student exam record
    $update_exam = "UPDATE student_exams SET 
                   status = ?, 
                   end_time = NOW(), 
                   total_score = ?, 
                   percentage = ?
                   WHERE id = ?";
    $stmt = $conn->prepare($update_exam);
    $stmt->bind_param("sddi", $status, $earned_marks, $percentage, $student_exam_id);
    
    if ($stmt->execute()) {
        $_SESSION['success_message'] = "Exam submitted successfully.";
        header('Location: exam_results.php?id=' . $exam_id);
        exit;
    } else {
        $_SESSION['error_message'] = "Failed to submit exam: " . $conn->error;
    }
}

// Check if exam ID is provided
if (!isset($_GET['id']) && !isset($_GET['exam_id'])) {
    $_SESSION['error_message'] = "No exam specified.";
    header('Location: scheduled-exams.php');
    exit;
}

// Get exam ID from either 'id' or 'exam_id' parameter
$exam_id = isset($_GET['id']) ? intval($_GET['id']) : intval($_GET['exam_id']);
$is_reattempt = isset($_GET['reattempt']) && $_GET['reattempt'] == 1;

// Check if the student has already completed this exam
$check_completion_query = "SELECT id, status, attempt_date FROM student_exams 
                          WHERE user_id = ? AND exam_id = ? 
                          ORDER BY attempt_date DESC LIMIT 1";
$stmt = $conn->prepare($check_completion_query);
$stmt->bind_param("ii", $user_id, $exam_id);
$stmt->execute();
$completion_result = $stmt->get_result();

if ($completion_result->num_rows > 0) {
    $completed_exam = $completion_result->fetch_assoc();
    
    // If this is a passed exam, redirect to results
    if ($completed_exam['status'] == 'passed' && !$is_reattempt) {
        $_SESSION['error_message'] = "You have already passed this exam. You cannot retake it.";
        header('Location: exam-results.php?id=' . $exam_id);
        exit;
    }
    
    // If this is a failed exam and not a reattempt request, check the timeframe
    if ($completed_exam['status'] == 'failed' && !$is_reattempt) {
        $attempt_date = new DateTime($completed_exam['attempt_date']);
        $current_date = new DateTime();
        $days_passed = $current_date->diff($attempt_date)->days;
        
        if ($days_passed < 7) {
            $_SESSION['error_message'] = "You must wait 7 days after a failed attempt before retaking the exam. " . 
                                        "You can retake this exam in " . (7 - $days_passed) . " days.";
            header('Location: exam-results.php?id=' . $exam_id);
    exit;
        }
        
        // Check if payment has been made for retake
        $payment_query = "SELECT * FROM payments 
                         WHERE user_id = ? AND exam_id = ? AND payment_type = 'reattempt_fee' 
                         AND status = 'completed' AND created_at > ?";
        
        $payment_stmt = $conn->prepare($payment_query);
        $one_week_ago = date('Y-m-d H:i:s', strtotime('-7 days'));
        $payment_stmt->bind_param("iis", $user_id, $exam_id, $one_week_ago);
        $payment_stmt->execute();
        $payment_result = $payment_stmt->get_result();
        
        if ($payment_result->num_rows == 0) {
            $_SESSION['error_message'] = "You need to pay the re-attempt fee before taking this exam again.";
            header('Location: exam-results.php?id=' . $exam_id);
            exit;
        }
    }
}

// Get exam details
$exam_query = "SELECT es.*, c.title as course_title,
              (SELECT COUNT(*) FROM exam_question_maps WHERE exam_id = es.id) as question_count
               FROM exam_schedules es 
               JOIN courses c ON es.course_id = c.id 
              WHERE es.id = ? AND es.is_active = 1";
$stmt = $conn->prepare($exam_query);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$exam_result = $stmt->get_result();

if ($exam_result->num_rows === 0) {
    $_SESSION['error_message'] = "Exam not found or not active.";
    header('Location: scheduled-exams.php');
    exit;
}

$exam = $exam_result->fetch_assoc();

// Check if user is enrolled in the course
$enrollment_query = "SELECT * FROM enrollments 
                    WHERE user_id = ? AND course_id = ? AND status = 'completed'";
$stmt = $conn->prepare($enrollment_query);
$stmt->bind_param("ii", $user_id, $exam['course_id']);
$stmt->execute();
$enrollment_result = $stmt->get_result();

if ($enrollment_result->num_rows === 0) {
    $_SESSION['error_message'] = "You cannot take this exam because you don't have a completed enrollment for this course.";
    header('Location: scheduled-exams.php');
    exit;
}

// Check if the student has any dues for this course
$dues_query = "SELECT has_dues FROM enrollments 
              WHERE user_id = ? AND course_id = ? AND status = 'completed'";
$stmt = $conn->prepare($dues_query);
$stmt->bind_param("ii", $user_id, $exam['course_id']);
$stmt->execute();
$dues_result = $stmt->get_result();
$enrollment_data = $dues_result->fetch_assoc();

if (isset($enrollment_data['has_dues']) && $enrollment_data['has_dues'] == 1) {
    $_SESSION['error_message'] = "You have pending dues for this course. Please clear your dues before taking the exam.";
    header('Location: scheduled-exams.php');
    exit;
}

// Check exam date and time - skip for reattempts
if (!$is_reattempt) {
$current_date = date('Y-m-d');
$current_time = date('H:i:s');

if ($exam['exam_date'] > $current_date) {
    $_SESSION['error_message'] = "This exam is scheduled for " . date('M d, Y', strtotime($exam['exam_date'])) . ". You cannot take it yet.";
        header('Location: scheduled-exams.php');
    exit;
}

if ($exam['exam_date'] == $current_date && $exam['start_time'] > $current_time) {
    $_SESSION['error_message'] = "This exam will start at " . date('h:i A', strtotime($exam['start_time'])) . ". Please wait until the scheduled time.";
        header('Location: scheduled-exams.php');
    exit;
}

if ($exam['exam_date'] < $current_date || ($exam['exam_date'] == $current_date && $exam['end_time'] < $current_time)) {
        if (!$is_reattempt) {
    $_SESSION['error_message'] = "This exam has ended. You can no longer take it.";
            header('Location: scheduled-exams.php');
    exit;
        }
    }
}

// Check if student has already started this exam
$student_exam_query = "SELECT * FROM student_exams WHERE user_id = ? AND exam_id = ? AND status = 'in_progress'";
$stmt = $conn->prepare($student_exam_query);
$stmt->bind_param("ii", $user_id, $exam_id);
$stmt->execute();
$student_exam_result = $stmt->get_result();
$student_exam = null;
$student_exam_id = null;

// If reattempt and there's an in-progress exam, clear it
if ($is_reattempt && $student_exam_result->num_rows > 0) {
    $in_progress = $student_exam_result->fetch_assoc();
    
    // Delete any existing answers
    $delete_answers = "DELETE FROM student_exam_answers WHERE student_exam_id = ?";
    $stmt = $conn->prepare($delete_answers);
    $stmt->bind_param("i", $in_progress['id']);
            $stmt->execute();
    
    // Delete the in-progress exam
    $delete_exam = "DELETE FROM student_exams WHERE id = ?";
    $stmt = $conn->prepare($delete_exam);
    $stmt->bind_param("i", $in_progress['id']);
    $stmt->execute();
    
    // Reset variables
    $student_exam_result = null;
}

// Continue with the rest of the file as it was
if ($student_exam_result && $student_exam_result->num_rows > 0) {
    $student_exam = $student_exam_result->fetch_assoc();
    $student_exam_id = $student_exam['id'];
} else {
    // Create a new student exam record
    $create_exam_query = "INSERT INTO student_exams (user_id, exam_id, status, start_time, created_at) 
                         VALUES (?, ?, 'in_progress', NOW(), NOW())";
    $stmt = $conn->prepare($create_exam_query);
    $stmt->bind_param("ii", $user_id, $exam_id);
    
    if ($stmt->execute()) {
        $student_exam_id = $conn->insert_id;
        
        // Fetch the created record
        $fetch_query = "SELECT * FROM student_exams WHERE id = ?";
        $stmt = $conn->prepare($fetch_query);
        $stmt->bind_param("i", $student_exam_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $student_exam = $result->fetch_assoc();
    } else {
        $_SESSION['error_message'] = "Failed to create exam session: " . $conn->error;
        header('Location: scheduled-exams.php');
        exit;
    }
}

// Get all questions for this exam
$questions_query = "SELECT q.*, eqm.id as map_id 
                   FROM questions q 
                   JOIN exam_question_maps eqm ON q.id = eqm.question_id 
                   WHERE eqm.exam_id = ? 
                   ORDER BY RAND()"; // Randomize question order
$stmt = $conn->prepare($questions_query);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$questions_result = $stmt->get_result();
$questions = [];

while ($question = $questions_result->fetch_assoc()) {
    $questions[] = $question;
}

// Get options for multiple choice questions
foreach ($questions as $key => $question) {
    if ($question['question_type'] === 'multiple_choice' || $question['question_type'] === 'true_false') {
        $options_query = "SELECT * FROM question_options WHERE question_id = ? ORDER BY RAND()"; // Randomize options
        $stmt = $conn->prepare($options_query);
        $stmt->bind_param("i", $question['id']);
        $stmt->execute();
        $options_result = $stmt->get_result();
        $questions[$key]['options'] = [];
        
        while ($option = $options_result->fetch_assoc()) {
            $questions[$key]['options'][] = $option;
        }
    }
}

// Calculate time remaining
$start_time = new DateTime($student_exam['start_time']);
$current_time = new DateTime();
$time_elapsed = $current_time->getTimestamp() - $start_time->getTimestamp();
$time_remaining = max(0, $exam['duration_minutes'] * 60 - $time_elapsed);

// Include header
include_once 'includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-lg-8">
            <!-- Exam Information -->
        <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary"><?php echo htmlspecialchars($exam['title']); ?></h6>
                    <div>
                        <span class="badge bg-warning text-dark" id="timer">Time remaining: --:--</span>
                    </div>
                </div>
                <div class="card-body">
                    <form id="examForm" method="POST" action="take_exam.php">
                        <input type="hidden" name="student_exam_id" value="<?php echo $student_exam['id']; ?>">
                        <input type="hidden" name="submit_answers" value="1">
                        
                        <?php if (empty($questions)): ?>
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle"></i> No questions have been added to this exam.
                            </div>
                        <?php else: ?>
                            <!-- Questions -->
                            <?php foreach ($questions as $index => $question): ?>
                                <div class="card mb-4 question-card" id="question-<?php echo $index; ?>">
                                    <div class="card-header bg-light">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h6 class="mb-0"><strong>Question <?php echo ($index + 1); ?></strong> 
                                                <span class="text-muted">(<?php echo ucfirst($question['question_type']); ?> - <?php echo $question['marks']; ?> marks)</span>
                                            </h6>
                                            <span class="badge bg-<?php echo $question['difficulty'] === 'easy' ? 'success' : ($question['difficulty'] === 'medium' ? 'primary' : 'danger'); ?>">
                                                <?php echo ucfirst($question['difficulty']); ?>
                                    </span>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <div class="question-text mb-3">
                                            <?php echo htmlspecialchars($question['question_text']); ?>
                                    </div>
                                    
                                        <?php if ($question['question_type'] === 'multiple_choice'): ?>
                                            <!-- Multiple Choice Question -->
                                            <div class="options-list">
                                                <?php foreach ($question['options'] as $option): ?>
                                                    <div class="form-check mb-2">
                                                        <input class="form-check-input" type="radio" 
                                                               name="answer[<?php echo $question['id']; ?>]" 
                                                               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 Question -->
                                            <div class="options-list">
                                                <?php foreach ($question['options'] as $option): ?>
                                                    <div class="form-check mb-2">
                                                        <input class="form-check-input" type="radio" 
                                                               name="answer[<?php echo $question['id']; ?>]" 
                                                               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'] === 'short_answer'): ?>
                                            <!-- Short Answer Question -->
                                            <div class="form-group">
                                                <input type="text" class="form-control" 
                                                       name="text_answer[<?php echo $question['id']; ?>]" 
                                                       placeholder="Your answer">
                                            </div>
                                        
                                        <?php elseif ($question['question_type'] === 'essay'): ?>
                                            <!-- Essay Question -->
                                            <div class="form-group">
                                                <textarea class="form-control" rows="5" 
                                                          name="text_answer[<?php echo $question['id']; ?>]" 
                                                          placeholder="Your answer"></textarea>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                            
                            <!-- Submit Button -->
                            <div class="d-flex justify-content-between align-items-center mt-4">
                                <button type="button" class="btn btn-secondary" id="prevBtn">Previous</button>
                                <div>
                                    <span id="questionCounter">Question 1 of <?php echo count($questions); ?></span>
                                </div>
                                <button type="button" class="btn btn-primary" id="nextBtn">Next</button>
                            </div>
                            
                            <div class="mt-4 text-center">
                                <button type="submit" name="submit_answers" class="btn btn-lg btn-success" id="submitBtn">
                                    <i class="fas fa-check-circle me-2"></i> Submit Exam
                                </button>
                            </div>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <!-- Exam Summary -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Exam Summary</h6>
                </div>
                <div class="card-body">
                    <p><strong>Course:</strong> <?php echo htmlspecialchars($exam['course_title']); ?></p>
                    <p><strong>Exam Date:</strong> <?php echo date('M d, Y', strtotime($exam['exam_date'])); ?></p>
                    <p><strong>Exam Time:</strong> <?php echo date('h:i A', strtotime($exam['start_time'])) . ' - ' . date('h:i A', strtotime($exam['end_time'])); ?></p>
                    <p><strong>Duration:</strong> <?php echo $exam['duration_minutes']; ?> minutes</p>
                    <p><strong>Total Questions:</strong> <?php echo count($questions); ?></p>
                    <p><strong>Passing Score:</strong> <?php echo $exam['passing_percentage']; ?>%</p>
                    
                    <hr>
                    
                    <!-- Question Navigation -->
                    <h6 class="font-weight-bold">Question Navigation</h6>
                    <div class="question-nav mt-3">
                        <?php foreach ($questions as $index => $question): ?>
                            <button type="button" 
                                    class="btn btn-outline-primary question-nav-btn mb-1" 
                                    data-question="<?php echo $index; ?>">
                                <?php echo ($index + 1); ?>
                            </button>
                        <?php endforeach; ?>
                    </div>
                    
                    <div class="mt-3">
                        <span class="badge bg-light text-dark me-1">◯</span> Not answered
                        <span class="badge bg-success text-white ms-3 me-1">◉</span> Answered
                    </div>
                </div>
            </div>
            
            <!-- Exam Instructions -->
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Instructions</h6>
                        </div>
                <div class="card-body">
                    <ul class="mb-0">
                        <li>Answer all questions to the best of your ability.</li>
                        <li>You have <?php echo $exam['duration_minutes']; ?> minutes to complete the exam.</li>
                        <li>The timer will continue if you refresh the page or leave.</li>
                        <li>Your answers are saved automatically when you navigate between questions.</li>
                        <li>Click "Submit Exam" once you have completed all questions.</li>
                        <li>Once submitted, you cannot return to the exam.</li>
                        <li><strong>Note:</strong> All exam times are shown in your local time zone for convenience, but are managed on the server in Indian Standard Time (IST/UTC+5:30).</li>
                    </ul>
                        </div>
                    </div>
                </div>
            </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Variables
    let currentQuestion = 0;
    const totalQuestions = <?php echo count($questions); ?>;
    const questionCards = document.querySelectorAll('.question-card');
    const navButtons = document.querySelectorAll('.question-nav-btn');
    
    // Initialize: show first question, hide others
    function showQuestion(index) {
        questionCards.forEach((card, i) => {
            card.style.display = i === index ? 'block' : 'none';
        });
        
        // Update the counter
        document.getElementById('questionCounter').textContent = `Question ${index + 1} of ${totalQuestions}`;
        
        // Update navigation buttons
        document.getElementById('prevBtn').disabled = index === 0;
        document.getElementById('nextBtn').textContent = index === totalQuestions - 1 ? 'Review' : 'Next';
        
        // Update the active navigation button
        navButtons.forEach((btn, i) => {
            btn.classList.toggle('active', i === index);
        });
        
        currentQuestion = index;
    }
    
    // Initialize: show first question, hide others
    showQuestion(0);
    
    // Navigation button event listeners
    document.getElementById('prevBtn').addEventListener('click', function() {
        if (currentQuestion > 0) {
            showQuestion(currentQuestion - 1);
        }
    });
    
    document.getElementById('nextBtn').addEventListener('click', function() {
        if (currentQuestion < totalQuestions - 1) {
            showQuestion(currentQuestion + 1);
                } else {
            // If on last question, scroll to submit button
            document.getElementById('submitBtn').scrollIntoView({ behavior: 'smooth' });
        }
    });
    
    // Question navigation buttons
    navButtons.forEach((btn, index) => {
        btn.addEventListener('click', function() {
            showQuestion(index);
        });
    });
    
    // Update the navigation buttons when answers are selected
    const radioInputs = document.querySelectorAll('input[type="radio"]');
    const textInputs = document.querySelectorAll('input[type="text"], textarea');
    
    function updateQuestionStatus() {
        questionCards.forEach((card, index) => {
            const questionId = card.id.split('-')[1];
            const radios = card.querySelectorAll('input[type="radio"]:checked');
            const textFields = card.querySelectorAll('input[type="text"], textarea');
            
            let isAnswered = false;
            
            if (radios.length > 0) {
                isAnswered = true;
                } else {
                for (let i = 0; i < textFields.length; i++) {
                    if (textFields[i].value.trim() !== '') {
                        isAnswered = true;
                        break;
                    }
                }
            }
            
            // Update the navigation button to reflect answered status
            if (isAnswered) {
                navButtons[index].classList.add('btn-success');
                navButtons[index].classList.remove('btn-outline-primary');
            } else {
                navButtons[index].classList.remove('btn-success');
                navButtons[index].classList.add('btn-outline-primary');
            }
        });
    }
    
    // Add event listeners to all input elements
    radioInputs.forEach(input => {
        input.addEventListener('change', updateQuestionStatus);
    });
    
    textInputs.forEach(input => {
        input.addEventListener('input', updateQuestionStatus);
    });
    
    // Confirm before submitting
    document.getElementById('examForm').addEventListener('submit', function(e) {
        const confirmed = confirm('Are you sure you want to submit your exam? You will not be able to make any changes after submission.');
        if (!confirmed) {
            e.preventDefault();
        }
    });
    
    // Check for unanswered questions before submitting
    document.getElementById('submitBtn').addEventListener('click', function(e) {
        const unansweredCount = document.querySelectorAll('.question-nav-btn.btn-outline-primary').length;
        
        if (unansweredCount > 0) {
            const confirmSubmit = confirm(`You have ${unansweredCount} unanswered question(s). Are you sure you want to submit your exam?`);
            
            if (!confirmSubmit) {
                e.preventDefault();
            }
        }
    });
    
    // Initialize question status
    updateQuestionStatus();
    
    // Set up timer
    const timeRemainingInSeconds = <?php echo $time_remaining; ?>;
    let timerSeconds = timeRemainingInSeconds;
    
    function updateTimer() {
        const hours = Math.floor(timerSeconds / 3600);
        const minutes = Math.floor((timerSeconds % 3600) / 60);
        const seconds = timerSeconds % 60;
        
        const formattedTime = 
            (hours > 0 ? hours + 'h ' : '') + 
            (minutes < 10 ? '0' : '') + minutes + 'm ' + 
            (seconds < 10 ? '0' : '') + seconds + 's';
        
        document.getElementById('timer').innerHTML = 'Time remaining: ' + formattedTime;
        
        if (timerSeconds <= 300) { // 5 minutes remaining
            document.getElementById('timer').classList.remove('bg-warning');
            document.getElementById('timer').classList.add('bg-danger');
        }
        
        if (timerSeconds <= 0) {
            clearInterval(timerInterval);
            alert('Time is up! Your exam will be submitted automatically.');
            document.getElementById('examForm').submit();
        }
        
        timerSeconds--;
    }
    
    // Initial timer update
    updateTimer();
    
    // Update timer every second
    const timerInterval = setInterval(updateTimer, 1000);
});
</script>

<?php
// Include footer
include_once 'includes/footer.php';
?>