<?php
// student/exam.php - Fixed Timezone Issues
require_once '../config/config.php';

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

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

// Get student exam - WITHOUT timezone manipulation in SQL
$stmt = $pdo->prepare("SELECT `id`, `student_id`, `exam_id`, DATE_ADD(start_time, INTERVAL 10 HOUR) as start_time, `end_time`, `time_taken`, `total_marks`, `obtained_marks`, `percentage`, `correct_answers`, `wrong_answers`, `unanswered`, `status`, `result`, `submitted_at` FROM `student_exams` WHERE student_id = ? AND exam_id = ?");
$stmt->execute([$student_id, $exam_id]);
$student_exam = $stmt->fetch();

// Debug: Uncomment to see what's happening
/*
echo "<pre>";
echo "Student Exam Status: " . ($student_exam->status ?? 'NO RECORD') . "\n";
echo "Start Time: " . ($student_exam->start_time ?? 'NULL') . "\n";
echo "Server Time: " . date('Y-m-d H:i:s') . "\n";
echo "PHP time(): " . time() . "\n";
exit;
*/

// Check if student_exam exists
if (!$student_exam) {
    // No exam record found - redirect to register
    redirect('student/register.php');
}

// Start exam if not started
if ($student_exam->status === 'not_started') {
    $stmt = $pdo->prepare("UPDATE student_exams SET status = 'in_progress', start_time = NOW() WHERE id = ?");
    $stmt->execute([$student_exam->id]);
    
    // Re-fetch the updated record
    $stmt = $pdo->prepare("SELECT `id`, `student_id`, `exam_id`, DATE_ADD(start_time, INTERVAL 10 HOUR) as start_time, `end_time`, `time_taken`, `total_marks`, `obtained_marks`, `percentage`, `correct_answers`, `wrong_answers`, `unanswered`, `status`, `result`, `submitted_at` FROM student_exams WHERE id = ?");
    $stmt->execute([$student_exam->id]);
    $student_exam = $stmt->fetch();
    
    // Initialize answers for all questions
    $stmt = $pdo->prepare("
        SELECT q.id FROM exam_questions eq 
        JOIN questions q ON eq.question_id = q.id 
        WHERE eq.exam_id = ? ORDER BY eq.question_order
    ");
    $stmt->execute([$exam_id]);
    $questions_to_init = $stmt->fetchAll();
    
    foreach ($questions_to_init as $q) {
        // Check if answer record already exists
        $check = $pdo->prepare("SELECT id FROM student_answers WHERE student_exam_id = ? AND question_id = ?");
        $check->execute([$student_exam->id, $q->id]);
        if (!$check->fetch()) {
            $stmt = $pdo->prepare("INSERT INTO student_answers (student_exam_id, question_id) VALUES (?, ?)");
            $stmt->execute([$student_exam->id, $q->id]);
        }
    }
}

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

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

if (!$exam) {
    redirect('student/register.php');
}

// Set correct timezone ONCE
date_default_timezone_set('Asia/Dubai'); // UAE

// Fetch start time normally
$stmt = $pdo->prepare("SELECT `id`, `student_id`, `exam_id`, DATE_ADD(start_time, INTERVAL 10 HOUR) as start_time, `end_time`, `time_taken`, `total_marks`, `obtained_marks`, `percentage`, `correct_answers`, `wrong_answers`, `unanswered`, `status`, `result`, `submitted_at` FROM student_exams WHERE id = ?");
$stmt->execute([$student_exam->id]);
$time_result = $stmt->fetch();

// Convert to timestamp using correct timezone
$start_timestamp = strtotime($time_result->start_time);

// Current timestamp (NO manual offset)
$current_timestamp = time();

$duration_seconds = $exam->duration * 60;
$elapsed = $current_timestamp - $start_timestamp;
$remaining = max(0, $duration_seconds - $elapsed);

// Debug: Uncomment to see time calculations

// echo "<pre>";
// echo "Server Time: " . date('Y-m-d H:i:s') . "\n";
// echo "Start Time: " . $time_result->start_time . "\n";
// echo "Elapsed (minutes): " . round($elapsed/60, 1) . "\n";
// echo "Remaining (minutes): " . round($remaining/60, 1) . "\n";
// exit;


if ($remaining <= 0) {
    redirect('student/submit_exam.php');
}

// Get questions with type info
$stmt = $pdo->prepare("
    SELECT q.*, eq.question_order, sa.selected_answer, sa.answer_text, sa.marked_for_review
    FROM exam_questions eq
    JOIN questions q ON eq.question_id = q.id
    LEFT JOIN student_answers sa ON q.id = sa.question_id AND sa.student_exam_id = ?
    WHERE eq.exam_id = ?
    ORDER BY eq.question_order
");
$stmt->execute([$student_exam->id, $exam_id]);
$questions = $stmt->fetchAll();

// Check if we have questions
if (empty($questions)) {
    echo "<div style='padding:20px;text-align:center;'>";
    echo "<h2>No questions assigned to this exam</h2>";
    echo "<p>Please contact the administrator.</p>";
    echo "</div>";
    exit;
}

// Question type icons and colors
$type_styles = [
    'mcq_4' => ['icon' => 'fa-list-ul', 'color' => 'blue', 'label' => 'Multiple Choice'],
    'mcq_3' => ['icon' => 'fa-list', 'color' => 'indigo', 'label' => 'Multiple Choice'],
    'mcq_2' => ['icon' => 'fa-toggle-on', 'color' => 'violet', 'label' => 'Multiple Choice'],
    'true_false' => ['icon' => 'fa-check-circle', 'color' => 'green', 'label' => 'True/False'],
    'fill_blank' => ['icon' => 'fa-pencil-alt', 'color' => 'yellow', 'label' => 'Fill in Blank'],
    'short_answer' => ['icon' => 'fa-align-left', 'color' => 'orange', 'label' => 'Short Answer'],
    'essay' => ['icon' => 'fa-file-alt', 'color' => 'red', 'label' => 'Essay'],
    'matching' => ['icon' => 'fa-random', 'color' => 'purple', 'label' => 'Matching']
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo escape($exam->title); ?> - Exam</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @keyframes slideDown {
            from { transform: translateY(-10px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        .question-container { animation: slideDown 0.3s ease-out; }
        .mobile-nav { max-height: 0; overflow: hidden; transition: max-height 0.3s ease-out; }
        .mobile-nav.open { max-height: 70vh; }
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }
        .timer-warning { animation: pulse 1s ease-in-out infinite; }
        .blank-input {
            border-bottom: 2px solid #3B82F6;
            background: transparent;
            min-width: 100px;
            text-align: center;
            font-weight: 600;
        }
        .blank-input:focus {
            outline: none;
            border-bottom-color: #8B5CF6;
            background: #EEF2FF;
        }
        .essay-textarea { min-height: 200px; resize: vertical; }
        .word-counter { font-size: 0.75rem; color: #6B7280; }
        .word-counter.warning { color: #F59E0B; }
        .word-counter.danger { color: #EF4444; }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Header -->
    <div class="bg-gradient-to-r from-blue-600 to-purple-600 text-white shadow-xl sticky top-0 z-50">
        <div class="w-full px-3 sm:px-4 lg:px-6 py-3 sm:py-4">
            <div class="hidden md:flex max-w-7xl mx-auto justify-between items-center">
                <div class="flex-1">
                    <h1 class="text-xl lg:text-2xl font-bold"><?php echo escape($exam->title); ?></h1>
                    <p class="text-sm text-blue-100 mt-1">
                        Question <span id="current-q">1</span> of <?php echo count($questions); ?>
                    </p>
                </div>
                <div class="text-center px-4">
                    <p class="text-xs sm:text-sm text-blue-100">Time Remaining</p>
                    <p class="text-2xl lg:text-3xl font-bold" id="timer">00:00:00</p>
                </div>
                <div class="flex-shrink-0">
                    <button onclick="toggleMobileNav()" class="px-4 py-2 bg-white/20 rounded-lg hover:bg-white/30 transition">
                        <i class="fas fa-grip mr-2"></i> Navigator
                    </button>
                </div>
            </div>
            
            <!-- Mobile Header -->
            <div class="md:hidden flex items-center justify-between gap-2">
                <div class="flex-1 min-w-0">
                    <h1 class="text-sm font-bold truncate"><?php echo escape($exam->title); ?></h1>
                    <p class="text-xs text-blue-100">Q <span id="current-q-mobile">1</span>/<?php echo count($questions); ?></p>
                </div>
                <div class="text-center px-2">
                    <p class="text-xs text-blue-100">Time</p>
                    <p class="text-base font-bold" id="timer-mobile">00:00:00</p>
                </div>
                <button onclick="toggleMobileNav()" class="p-2.5 bg-white/20 rounded-lg">
                    <i class="fas fa-bars"></i>
                </button>
            </div>
        </div>
    </div>
    
    <!-- Mobile Navigation Panel -->
    <div id="mobileNav" class="mobile-nav bg-white shadow-lg md:hidden border-b-4 border-blue-500 fixed left-0 right-0 z-40" style="top: 73px;">
        <div class="p-4 overflow-y-auto" style="max-height: calc(70vh - 73px);">
            <div class="flex justify-between items-center mb-3 pb-3 border-b">
                <h3 class="font-bold text-gray-800 text-sm">Question Navigator</h3>
                <button onclick="toggleMobileNav()" class="text-gray-500"><i class="fas fa-times"></i></button>
            </div>
            <div class="grid grid-cols-5 gap-2.5 mb-4">
                <?php foreach ($questions as $index => $q): 
                    $style = $type_styles[$q->question_type] ?? ['color' => 'gray'];
                    $nav_class = 'bg-gray-200 text-gray-700';
                    $has_answer = !empty($q->selected_answer) || !empty($q->answer_text);
                    if ($has_answer) $nav_class = 'bg-green-500 text-white';
                    if ($q->marked_for_review) $nav_class = 'bg-yellow-500 text-white';
                ?>
                <button onclick="goToQuestion(<?php echo $index; ?>); toggleMobileNav();" 
                        class="nav-btn-mobile w-full h-12 rounded-lg font-semibold text-sm transition shadow-sm <?php echo $nav_class; ?>"
                        data-nav-mobile="<?php echo $index; ?>"
                        data-question-id="<?php echo $q->id; ?>"
                        data-answered="<?php echo $has_answer ? '1' : '0'; ?>"
                        data-review="<?php echo $q->marked_for_review ? '1' : '0'; ?>">
                    <?php echo $index + 1; ?>
                </button>
                <?php endforeach; ?>
            </div>
            <div class="space-y-2 text-xs border-t pt-3">
                <div class="flex items-center gap-2"><div class="w-4 h-4 bg-green-500 rounded"></div><span>Answered</span></div>
                <div class="flex items-center gap-2"><div class="w-4 h-4 bg-yellow-500 rounded"></div><span>Marked for Review</span></div>
                <div class="flex items-center gap-2"><div class="w-4 h-4 bg-gray-200 rounded"></div><span>Not Answered</span></div>
            </div>
        </div>
    </div>
    
    <div id="navOverlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden" onclick="toggleMobileNav()"></div>
    
    <!-- Main Content -->
    <div class="max-w-7xl mx-auto px-3 sm:px-4 py-4 sm:py-6">
        <div class="grid grid-cols-1 lg:grid-cols-4 gap-4 sm:gap-6">
            <!-- Question Area -->
            <div class="lg:col-span-3">
                <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                    <?php foreach ($questions as $index => $q): 
                        $style = $type_styles[$q->question_type] ?? ['icon' => 'fa-question', 'color' => 'gray', 'label' => 'Question'];
                    ?>
                    <div class="question-container p-4 sm:p-6 <?php echo $index > 0 ? 'hidden' : ''; ?>" 
                         data-question="<?php echo $index; ?>" 
                         data-question-id="<?php echo $q->id; ?>"
                         data-question-type="<?php echo $q->question_type; ?>">
                        
                        <!-- Question Header -->
                        <div class="flex items-center justify-between mb-4 pb-3 border-b">
                            <div class="flex items-center gap-3">
                                <h2 class="text-lg sm:text-xl font-bold text-gray-800">Question <?php echo $index + 1; ?></h2>
                                <span class="inline-flex items-center px-2 py-1 text-xs font-semibold rounded-full bg-<?php echo $style['color']; ?>-100 text-<?php echo $style['color']; ?>-800">
                                    <i class="fas <?php echo $style['icon']; ?> mr-1"></i>
                                    <?php echo $style['label']; ?>
                                </span>
                            </div>
                            <span class="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-xs font-semibold">
                                <?php echo $q->marks; ?> Mark<?php echo $q->marks > 1 ? 's' : ''; ?>
                            </span>
                        </div>
                        
                        <!-- Question Text -->
                        <div class="mb-6 p-4 bg-gray-50 rounded-lg">
                            <p class="text-base sm:text-lg text-gray-800 leading-relaxed">
                                <?php 
                                if ($q->question_type === 'fill_blank') {
                                    $text = escape($q->question_text);
                                    $text = preg_replace('/_____/', '<input type="text" class="blank-input mx-1 px-2 py-1" data-blank="1" data-question-id="'.$q->id.'" placeholder="...">', $text);
                                    echo $text;
                                } else {
                                    echo escape($q->question_text);
                                }
                                ?>
                            </p>
                        </div>
                        
                        <!-- Answer Section Based on Question Type -->
                        <?php if (in_array($q->question_type, ['mcq_4', 'mcq_3', 'mcq_2'])): ?>
                            <div class="space-y-3">
                                <?php 
                                $options = ['a' => $q->option_a, 'b' => $q->option_b];
                                if ($q->question_type !== 'mcq_2') $options['c'] = $q->option_c;
                                if ($q->question_type === 'mcq_4') $options['d'] = $q->option_d;
                                
                                foreach ($options as $key => $value): 
                                    if (empty($value)) continue;
                                ?>
                                <label class="flex items-start p-3 sm:p-4 border-2 rounded-lg cursor-pointer hover:bg-blue-50 hover:border-blue-300 transition-all
                                    <?php echo strtolower($q->selected_answer) === $key ? 'border-blue-500 bg-blue-50 shadow-md' : 'border-gray-200'; ?>">
                                    <input type="radio" name="answer_<?php echo $q->id; ?>" value="<?php echo $key; ?>" 
                                           data-question-id="<?php echo $q->id; ?>"
                                           data-answer-type="mcq"
                                           <?php echo strtolower($q->selected_answer) === $key ? 'checked' : ''; ?>
                                           class="w-4 h-4 sm:w-5 sm:h-5 text-blue-600 mt-0.5 flex-shrink-0 answer-input">
                                    <span class="ml-2.5 sm:ml-3 text-sm sm:text-base text-gray-700 flex-1">
                                        <strong class="text-gray-900"><?php echo strtoupper($key); ?>.</strong> <?php echo escape($value); ?>
                                    </span>
                                </label>
                                <?php endforeach; ?>
                            </div>
                            
                        <?php elseif ($q->question_type === 'true_false'): ?>
                            <div class="flex gap-4 justify-center">
                                <label class="flex-1 max-w-xs cursor-pointer">
                                    <input type="radio" name="answer_<?php echo $q->id; ?>" value="true" 
                                           data-question-id="<?php echo $q->id; ?>"
                                           data-answer-type="tf"
                                           <?php echo strtolower($q->selected_answer) === 'true' ? 'checked' : ''; ?>
                                           class="sr-only peer answer-input">
                                    <div class="p-6 border-2 rounded-xl text-center transition-all
                                                peer-checked:border-green-500 peer-checked:bg-green-50
                                                hover:border-green-300 border-gray-200">
                                        <i class="fas fa-check-circle text-4xl text-green-500 mb-2"></i>
                                        <p class="text-xl font-bold text-gray-800">TRUE</p>
                                    </div>
                                </label>
                                <label class="flex-1 max-w-xs cursor-pointer">
                                    <input type="radio" name="answer_<?php echo $q->id; ?>" value="false" 
                                           data-question-id="<?php echo $q->id; ?>"
                                           data-answer-type="tf"
                                           <?php echo strtolower($q->selected_answer) === 'false' ? 'checked' : ''; ?>
                                           class="sr-only peer answer-input">
                                    <div class="p-6 border-2 rounded-xl text-center transition-all
                                                peer-checked:border-red-500 peer-checked:bg-red-50
                                                hover:border-red-300 border-gray-200">
                                        <i class="fas fa-times-circle text-4xl text-red-500 mb-2"></i>
                                        <p class="text-xl font-bold text-gray-800">FALSE</p>
                                    </div>
                                </label>
                            </div>
                            
                        <?php elseif ($q->question_type === 'fill_blank'): ?>
                            <div class="bg-yellow-50 rounded-lg p-4">
                                <label class="block text-gray-700 font-semibold mb-2">
                                    <i class="fas fa-pencil-alt text-yellow-600 mr-2"></i> Your Answer:
                                </label>
                                <input type="text" 
                                       name="answer_<?php echo $q->id; ?>"
                                       data-question-id="<?php echo $q->id; ?>"
                                       data-answer-type="fill"
                                       value="<?php echo escape($q->selected_answer ?? ''); ?>"
                                       placeholder="Type your answer here..."
                                       class="w-full px-4 py-3 border-2 border-yellow-300 rounded-lg focus:ring-2 focus:ring-yellow-500 focus:border-yellow-500 text-lg answer-input">
                            </div>
                            
                        <?php elseif ($q->question_type === 'short_answer'): ?>
                            <div class="bg-orange-50 rounded-lg p-4">
                                <label class="block text-gray-700 font-semibold mb-2">
                                    <i class="fas fa-align-left text-orange-600 mr-2"></i> Your Answer:
                                </label>
                                <textarea name="answer_<?php echo $q->id; ?>"
                                          data-question-id="<?php echo $q->id; ?>"
                                          data-answer-type="text"
                                          data-word-limit="<?php echo $q->word_limit ?? 0; ?>"
                                          placeholder="Write your answer here..."
                                          rows="4"
                                          class="w-full px-4 py-3 border-2 border-orange-300 rounded-lg focus:ring-2 focus:ring-orange-500 answer-input"><?php echo escape($q->answer_text ?? ''); ?></textarea>
                                <?php if ($q->word_limit): ?>
                                <p class="word-counter mt-2" data-limit="<?php echo $q->word_limit; ?>">
                                    <span class="current-words">0</span> / <?php echo $q->word_limit; ?> words
                                </p>
                                <?php endif; ?>
                            </div>
                            
                        <?php elseif ($q->question_type === 'essay'): ?>
                            <div class="bg-red-50 rounded-lg p-4">
                                <label class="block text-gray-700 font-semibold mb-2">
                                    <i class="fas fa-file-alt text-red-600 mr-2"></i> Write Your Essay:
                                </label>
                                <textarea name="answer_<?php echo $q->id; ?>"
                                          data-question-id="<?php echo $q->id; ?>"
                                          data-answer-type="text"
                                          data-word-limit="<?php echo $q->word_limit ?? 0; ?>"
                                          placeholder="Write your essay here..."
                                          class="w-full px-4 py-3 border-2 border-red-300 rounded-lg focus:ring-2 focus:ring-red-500 essay-textarea answer-input"><?php echo escape($q->answer_text ?? ''); ?></textarea>
                                <div class="flex justify-between mt-2">
                                    <p class="word-counter" data-limit="<?php echo $q->word_limit ?? 0; ?>">
                                        <span class="current-words">0</span><?php if ($q->word_limit): ?> / <?php echo $q->word_limit; ?><?php endif; ?> words
                                    </p>
                                    <p class="text-xs text-gray-500">
                                        <i class="fas fa-info-circle mr-1"></i> This question will be manually graded
                                    </p>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <!-- Navigation Buttons -->
                        <div class="flex flex-col sm:flex-row gap-2.5 sm:gap-3 mt-6 pt-6 border-t">
                            <button onclick="prevQuestion()" 
                                    class="flex-1 sm:flex-none px-4 sm:px-6 py-3 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition font-medium disabled:opacity-50"
                                    <?php echo $index === 0 ? 'disabled' : ''; ?>>
                                <i class="fas fa-arrow-left mr-2"></i> Previous
                            </button>
                            
                            <button onclick="markReview(<?php echo $q->id; ?>)" 
                                    class="flex-1 sm:flex-none px-4 sm:px-6 py-3 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition font-medium">
                                <i class="fas fa-bookmark mr-2"></i> Review
                            </button>
                            
                            <?php if ($index < count($questions) - 1): ?>
                            <button onclick="nextQuestion()" 
                                    class="flex-1 sm:flex-none px-4 sm:px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition font-medium sm:ml-auto">
                                Next <i class="fas fa-arrow-right ml-2"></i>
                            </button>
                            <?php else: ?>
                            <button onclick="submitExam()" 
                                    class="flex-1 sm:flex-none px-4 sm:px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition font-medium sm:ml-auto">
                                <i class="fas fa-check-circle mr-2"></i> Submit
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="mt-4 md:hidden">
                    <button onclick="submitExam()" class="w-full px-6 py-4 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-xl font-bold text-lg shadow-lg">
                        <i class="fas fa-paper-plane mr-2"></i> Submit Exam
                    </button>
                </div>
            </div>
            
            <!-- Desktop Navigator -->
            <div class="hidden lg:block lg:col-span-1">
                <div class="bg-white rounded-xl shadow-lg p-4 sticky top-24">
                    <h3 class="font-bold text-gray-800 mb-4 text-center">Navigator</h3>
                    <div class="grid grid-cols-5 gap-2 max-h-96 overflow-y-auto pr-2">
                        <?php foreach ($questions as $index => $q): 
                            $has_answer = !empty($q->selected_answer) || !empty($q->answer_text);
                            $nav_class = 'bg-gray-200 text-gray-700';
                            if ($has_answer) $nav_class = 'bg-green-500 text-white';
                            if ($q->marked_for_review) $nav_class = 'bg-yellow-500 text-white';
                        ?>
                        <button onclick="goToQuestion(<?php echo $index; ?>)" 
                                class="nav-btn w-10 h-10 rounded-lg font-semibold transition <?php echo $nav_class; ?>"
                                data-nav="<?php echo $index; ?>"
                                data-question-id="<?php echo $q->id; ?>"
                                data-answered="<?php echo $has_answer ? '1' : '0'; ?>"
                                data-review="<?php echo $q->marked_for_review ? '1' : '0'; ?>">
                            <?php echo $index + 1; ?>
                        </button>
                        <?php endforeach; ?>
                    </div>
                    
                    <div class="mt-4 text-xs space-y-2 border-t pt-4">
                        <div class="flex items-center"><div class="w-4 h-4 bg-green-500 rounded mr-2"></div><span>Answered</span></div>
                        <div class="flex items-center"><div class="w-4 h-4 bg-yellow-500 rounded mr-2"></div><span>Review</span></div>
                        <div class="flex items-center"><div class="w-4 h-4 bg-gray-200 rounded mr-2"></div><span>Not Answered</span></div>
                    </div>
                    
                    <button onclick="submitExam()" class="w-full mt-4 px-4 py-3 bg-gradient-to-r from-red-600 to-red-700 text-white rounded-lg font-semibold shadow-md">
                        <i class="fas fa-paper-plane mr-2"></i> Submit
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
    let currentQuestion = 0;
    let totalQuestions = <?php echo count($questions); ?>;
    let remainingTime = <?php echo $remaining; ?>;
    let studentExamId = <?php echo $student_exam->id; ?>;
    let warningShown = false;
    
    // Track answers in memory
    let answersState = {};
    <?php foreach ($questions as $idx => $q): ?>
    answersState[<?php echo $q->id; ?>] = {
        answered: <?php echo (!empty($q->selected_answer) || !empty($q->answer_text)) ? 'true' : 'false'; ?>,
        review: <?php echo $q->marked_for_review ? 'true' : 'false'; ?>
    };
    <?php endforeach; ?>

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

    function toggleMobileNav() {
        const nav = document.getElementById('mobileNav');
        const overlay = document.getElementById('navOverlay');
        nav.classList.toggle('open');
        overlay.classList.toggle('hidden');
        document.body.style.overflow = nav.classList.contains('open') ? 'hidden' : '';
    }

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

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

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

    function saveAnswer(questionId, answer, answerText = null, markForReview = 0) {
        const formData = new FormData();
        formData.append('student_exam_id', studentExamId);
        formData.append('question_id', questionId);
        if (answer !== null) formData.append('selected_answer', answer);
        if (answerText !== null) formData.append('answer_text', answerText);
        formData.append('marked_for_review', markForReview);
        
        return fetch('save_answer', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .catch(error => {
            console.error('Save error:', error);
            return { success: false };
        });
    }

    function updateNavStatus(questionId, answered, review = null) {
        if (answersState[questionId]) {
            if (answered !== null) answersState[questionId].answered = answered;
            if (review !== null) answersState[questionId].review = review;
        }
        
        let qIndex = Array.from(document.querySelectorAll('.question-container')).findIndex(
            q => q.dataset.questionId == questionId
        );
        
        document.querySelectorAll(`[data-nav="${qIndex}"], [data-nav-mobile="${qIndex}"]`).forEach(btn => {
            btn.dataset.answered = answered ? '1' : '0';
            if (review !== null) btn.dataset.review = review ? '1' : '0';
            
            btn.classList.remove('bg-gray-200', 'text-gray-700', 'bg-green-500', 'bg-yellow-500', 'text-white');
            
            if (review || btn.dataset.review === '1') {
                btn.classList.add('bg-yellow-500', 'text-white');
            } else if (answered) {
                btn.classList.add('bg-green-500', 'text-white');
            } else {
                btn.classList.add('bg-gray-200', 'text-gray-700');
            }
        });
    }

    document.querySelectorAll('.answer-input').forEach(input => {
        const eventType = input.tagName === 'TEXTAREA' ? 'blur' : 'change';
        
        input.addEventListener(eventType, function() {
            const questionId = this.dataset.questionId;
            const answerType = this.dataset.answerType;
            let answer = null;
            let answerText = null;
            
            if (answerType === 'text') {
                answerText = this.value;
                updateWordCount(this);
            } else if (answerType === 'fill') {
                answer = this.value;
            } else {
                answer = this.value;
            }
            
            saveAnswer(questionId, answer, answerText, 0).then(data => {
                if (data.success) {
                    const hasAnswer = (answer && answer.trim()) || (answerText && answerText.trim());
                    updateNavStatus(questionId, hasAnswer);
                }
            });
        });
        
        if (input.tagName === 'TEXTAREA') {
            input.addEventListener('input', function() {
                updateWordCount(this);
            });
            updateWordCount(input);
        }
    });

    function updateWordCount(textarea) {
        const container = textarea.closest('.bg-orange-50, .bg-red-50');
        if (!container) return;
        
        const counter = container.querySelector('.word-counter');
        if (!counter) return;
        
        const words = textarea.value.trim() ? textarea.value.trim().split(/\s+/).length : 0;
        const limit = parseInt(textarea.dataset.wordLimit) || 0;
        
        counter.querySelector('.current-words').textContent = words;
        
        if (limit > 0) {
            counter.classList.remove('warning', 'danger');
            if (words > limit) counter.classList.add('danger');
            else if (words > limit * 0.9) counter.classList.add('warning');
        }
    }

    function markReview(questionId) {
        saveAnswer(questionId, null, null, 1).then(data => {
            if (data.success) {
                updateNavStatus(questionId, null, true);
                alert('Question marked for review!');
            }
        });
    }

    function submitExam() {
        let answered = 0, unanswered = 0, review = 0;
        
        for (let qId in answersState) {
            if (answersState[qId].answered) answered++;
            else unanswered++;
            if (answersState[qId].review) review++;
        }
        
        let msg = `Summary:\n✓ Answered: ${answered}\n✗ Unanswered: ${unanswered}`;
        if (review > 0) msg += `\n⚠ Marked for review: ${review}`;
        msg += '\n\nAre you sure you want to submit?';
        
        if (confirm(msg)) {
            window.location.href = 'submit_exam';
        }
    }

    startTimer();
    updateNavButtons();
    
    window.addEventListener('beforeunload', function(e) {
        e.preventDefault();
        e.returnValue = '';
    });
    
    document.addEventListener('keydown', function(e) {
        if (e.key === 'ArrowRight') nextQuestion();
        if (e.key === 'ArrowLeft') prevQuestion();
    });
    </script>
</body>
</html>