<?php
// Student Page to Select and Take Quizzes

// Include the necessary files
require_once 'config.php';
require_once 'layouts.php';

// Check if the user is a student
if (get_user_role() !== 'student') {
    // If an admin is testing, allow access but remind them they are testing the student view
    if (get_user_role() === 'admin') {
        $test_mode_message = '
        <div class="fixed bottom-4 right-4 z-50 animate-bounce">
            <div class="bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4 shadow-lg rounded-r-lg" role="alert">
                <p class="font-bold"><i class="fa-solid fa-user-secret mr-2"></i>Admin View</p>
                <p>Testing as Student</p>
            </div>
        </div>';
    } else {
        die("Access Denied: Students only.");
    }
} else {
    $test_mode_message = '';
}

$message = '';
$quizId = $_GET['quiz_id'] ?? null;
$quiz = $quizId ? get_quiz_by_id((int)$quizId) : null;
$score = null;

// Helper function (same as in addquiz.php)
function format_time_display($seconds) {
    if ($seconds <= 0) return 'No Limit';
    $minutes = floor($seconds / 60);
    $remainingSeconds = $seconds % 60;
    $output = '';
    if ($minutes > 0) {
        $output .= $minutes . ' <span class="text-xs uppercase text-gray-400">min</span> ';
    }
    if ($remainingSeconds > 0) {
        $output .= $remainingSeconds . ' <span class="text-xs uppercase text-gray-400">sec</span>';
    }
    return trim($output);
}


// --- Handle Quiz Submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'submit_quiz') {
    $submittedQuizId = (int)$_POST['quiz_id'];
    $submittedQuiz = get_quiz_by_id($submittedQuizId);
    $questions = $submittedQuiz['questions'] ?? [];
    $correctCount = 0;

    if (!empty($questions)) {
        foreach ($questions as $qId => $questionData) {
            $submittedAnswer = $_POST['q' . $qId] ?? '';
            if ($submittedAnswer === $questionData['answer']) {
                $correctCount++;
            }
        }
    }

    // FIX: Define $score and $totalQuestions here
    $score = $correctCount;
    $totalQuestions = count($questions); // <-- This is the fix for lines 68 and 83

    $userId = $_SESSION['user_id'];   // or however you store logged user ID
    
    // Note: The original code called record_quiz_result before calculating $score/ $totalQuestions.
    // I am assuming the $score should be the $correctCount, and $totalQuestions should be passed.
    // However, since record_quiz_result only takes $score, I am leaving the logic as is,
    // but ensuring $score is set to $correctCount for the UI display below.
    record_quiz_result($userId, $submittedQuizId, $score); // Use $submittedQuizId, not $quizId which is null here

    
    // Percentage for visual display (Line 68)
    $percentage = ($totalQuestions > 0) ? round(($score / $totalQuestions) * 100) : 0;
    
    // Check if the submission was forced by the timer
    $submissionType = $_POST['submission_type'] ?? 'manual';
    
    if ($submissionType === 'timeout') {
        $message = '
        <div class="mb-8 bg-white rounded-2xl shadow-xl overflow-hidden border-t-8 border-red-500 transform transition-all hover:scale-[1.01]">
            <div class="p-8 text-center">
                <div class="inline-flex items-center justify-center w-20 h-20 rounded-full bg-red-100 mb-6 animate-pulse">
                    <i class="fa-solid fa-hourglass-end text-3xl text-red-600"></i>
                </div>
                <h3 class="text-3xl font-bold text-gray-800 mb-2">Time Expired!</h3>
                <p class="text-gray-500 mb-6">The quiz was automatically submitted.</p>
                <div class="flex justify-center items-center space-x-2 text-5xl font-extrabold text-gray-800">
                    <span class="text-red-600">'.$score.'</span><span class="text-gray-300 text-3xl">/</span><span>'.$totalQuestions.'</span>
                </div>
                <p class="text-sm text-gray-400 mt-2 font-medium uppercase tracking-wide">Final Score</p>
            </div>
        </div>';
    } else {
        $color = $percentage >= 70 ? 'green' : 'indigo';
        $icon = $percentage >= 70 ? 'fa-trophy' : 'fa-clipboard-check';
        
        $message = '
        <div class="mb-8 bg-white rounded-2xl shadow-xl overflow-hidden border-t-8 border-'.$color.'-500 transform transition-all hover:scale-[1.01]">
            <div class="p-8 text-center">
                <div class="inline-flex items-center justify-center w-20 h-20 rounded-full bg-'.$color.'-100 mb-6">
                    <i class="fa-solid '.$icon.' text-3xl text-'.$color.'-600"></i>
                </div>
                <h3 class="text-3xl font-bold text-gray-800 mb-2">Great Job!</h3>
                <p class="text-gray-500 mb-6">Your answers have been successfully recorded.</p>
                
                <div class="relative pt-1 px-10 max-w-md mx-auto">
                    <div class="flex mb-2 items-center justify-between">
                        <div>
                            <span class="text-xs font-semibold inline-block py-1 px-2 uppercase rounded-full text-'.$color.'-600 bg-'.$color.'-200">
                                Accuracy
                            </span>
                        </div>
                        <div class="text-right">
                            <span class="text-xs font-semibold inline-block text-'.$color.'-600">
                                '.$percentage.'%
                            </span>
                        </div>
                    </div>
                    <div class="overflow-hidden h-2 mb-4 text-xs flex rounded bg-'.$color.'-200">
                        <div style="width:'.$percentage.'%" class="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center bg-'.$color.'-500 transition-all duration-1000"></div>
                    </div>
                </div>

                <div class="mt-4 flex justify-center items-center space-x-2">
                     <span class="text-4xl font-extrabold text-gray-800">'.$score.'</span>
                     <span class="text-gray-400 text-2xl">/</span>
                     <span class="text-2xl text-gray-600">'.$totalQuestions.'</span>
                </div>
            </div>
             <div class="bg-gray-50 p-4 text-center border-t border-gray-100">
                <a href="student.php" class="text-'.$color.'-600 font-bold hover:text-'.$color.'-800 transition-colors">
                    <i class="fa-solid fa-arrow-left mr-2"></i> Back to Quiz List
                </a>
            </div>
        </div>';
    }

    // Clear the current quiz view after submission
    $quiz = null;
    $quizId = null;
}

// --- Render Page ---
render_header('Student Portal');
render_topbar('Assessment Hub');
render_sidebar(get_user_role(), basename($_SERVER['PHP_SELF']));
?>

<!-- Custom Styles for Radio Button Cards -->
<style>
    .answer-radio:checked + .answer-card {
        border-color: #4F46E5; /* Indigo 600 */
        background-color: #EEF2FF; /* Indigo 50 */
        box-shadow: 0 4px 6px -1px rgba(79, 70, 229, 0.1), 0 2px 4px -1px rgba(79, 70, 229, 0.06);
    }
    .answer-radio:checked + .answer-card .check-circle {
        background-color: #4F46E5;
        border-color: #4F46E5;
        color: white;
    }
</style>

<div class="max-w-7xl mx-auto pb-12">
    <?= $test_mode_message ?>
    
    <!-- Dynamic Header -->
    <div class="mb-8 flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
            <h2 class="text-4xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-gray-900 to-gray-600">
                <?= $quiz ? 'Assessment in Progress' : 'Available Assessments' ?>
            </h2>
            <p class="text-gray-500 mt-2 font-medium">
                <?= $quiz ? 'Focus and do your best. Good luck!' : 'Select a quiz below to start testing your knowledge.' ?>
            </p>
        </div>
        <?php if (!$quiz): ?>
        <div class="hidden md:block">
             <div class="flex items-center bg-white rounded-full shadow-sm border border-gray-200 px-4 py-2">
                <i class="fa-solid fa-search text-gray-400 mr-2"></i>
                <input type="text" placeholder="Filter topics..." class="bg-transparent border-none focus:ring-0 text-sm w-48 text-gray-600">
             </div>
        </div>
        <?php endif; ?>
    </div>

    <?= $message ?>

    <?php if ($quiz && !empty($quiz['questions'])): ?>
        <?php 
            $timeLimitSeconds = $quiz['time_limit_seconds'] ?? 0;
            $hasTimeLimit = $timeLimitSeconds > 0;
            $quizTotalTime = $timeLimitSeconds;
        ?>
        
        <!-- QUIZ TAKING INTERFACE -->
        <div class="flex flex-col lg:flex-row gap-8 items-start">
            
            <!-- Sticky Sidebar: Timer & Info -->
            <div class="w-full lg:w-1/4 lg:sticky lg:top-6 z-10 order-1 lg:order-2">
                <div class="bg-white rounded-2xl shadow-xl overflow-hidden">
                    <div class="bg-indigo-600 p-6 text-white text-center relative overflow-hidden">
                        <div class="absolute top-0 left-0 w-full h-full opacity-10 bg-[url('https://www.transparenttextures.com/patterns/cubes.png')]"></div>
                        <h3 class="text-xl font-bold relative z-10"><?= htmlspecialchars($quiz['title']) ?></h3>
                        <p class="text-indigo-200 text-sm mt-1 relative z-10"><?= htmlspecialchars($quiz['topic']) ?></p>
                    </div>

                    <div class="p-6">
                        <!-- Timer Section -->
                        <?php if ($hasTimeLimit): ?>
                            <div class="text-center mb-6">
                                <p class="text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">Time Remaining</p>
                                <div id="timer-container" class="bg-gray-50 rounded-xl border-2 border-gray-100 p-4 transition-colors duration-300">
                                    <div id="quiz-timer" class="text-4xl font-black text-gray-700 tabular-nums tracking-tight">
                                        --:--
                                    </div>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="text-center mb-6 p-4 bg-green-50 rounded-xl border border-green-100">
                                <i class="fa-solid fa-infinity text-3xl text-green-500 mb-2"></i>
                                <p class="text-green-700 font-bold">No Time Limit</p>
                                <p class="text-xs text-green-600">Take your time</p>
                            </div>
                        <?php endif; ?>

                        <!-- Progress Info -->
                         <div class="space-y-4">
                            <div class="flex justify-between text-sm font-medium text-gray-600">
                                <span>Progress</span>
                                <span><?= count($quiz['questions']) ?> Questions</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-indigo-600 h-2 rounded-full" style="width: 0%" id="progressBar"></div>
                            </div>
                         </div>
                    </div>
                </div>
            </div>

            <!-- Questions Column -->
            <div class="w-full lg:w-3/4 order-2 lg:order-1">
                <form id="quizForm" method="POST" class="space-y-8">
                    <input type="hidden" name="action" value="submit_quiz">
                    <input type="hidden" name="quiz_id" value="<?= $quiz['id'] ?>">
                    <input type="hidden" name="submission_type" id="submission_type" value="manual">

                    <?php $qNum = 1; foreach ($quiz['questions'] as $qId => $questionData): ?>
                    
                    <!-- Question Card -->
                    <div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-md transition-shadow duration-300" id="question-card-<?= $qNum ?>">
                        <div class="p-8">
                            <div class="flex items-start gap-4 mb-6">
                                <div class="flex-shrink-0 w-10 h-10 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-700 font-bold text-lg shadow-sm">
                                    <?= $qNum ?>
                                </div>
                                <h3 class="text-lg font-semibold text-gray-800 leading-relaxed pt-1">
                                    <?= htmlspecialchars($questionData['question']) ?>
                                </h3>
                            </div>
                            
                            <!-- Answer Options Grid -->
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 ml-0 md:ml-14">
                                <?php foreach ($questionData['options'] as $idx => $option): ?>
                                <label class="relative group cursor-pointer">
                                    <input type="radio" 
                                           name="q<?= $qId ?>" 
                                           value="<?= htmlspecialchars($option) ?>" 
                                           required
                                           class="answer-radio absolute opacity-0 w-0 h-0"
                                           onclick="updateProgress()">
                                    
                                    <div class="answer-card h-full p-4 rounded-xl border-2 border-gray-100 bg-white hover:border-indigo-200 hover:bg-gray-50 transition-all duration-200 flex items-center gap-3">
                                        <div class="check-circle w-6 h-6 rounded-full border-2 border-gray-300 flex items-center justify-center transition-colors">
                                            <i class="fa-solid fa-check text-xs opacity-0 transition-opacity group-hover:opacity-50"></i>
                                        </div>
                                        <span class="text-gray-700 font-medium select-none"><?= htmlspecialchars($option) ?></span>
                                    </div>
                                </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                    <?php $qNum++; endforeach; ?>

                    <!-- Submit Button -->
                    <div class="pt-4 pb-12">
                        <button type="submit"
                                id="submitButton"
                                class="group w-full py-5 px-6 rounded-2xl shadow-lg shadow-green-500/30 text-white font-bold bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 focus:outline-none focus:ring-4 focus:ring-green-500/50 transition-all duration-300 transform hover:-translate-y-1 flex items-center justify-center text-xl">
                            <span>Submit Assessment</span>
                            <i class="fa-solid fa-paper-plane ml-3 group-hover:translate-x-1 transition-transform"></i>
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <?php if ($hasTimeLimit): ?>
        <script>
            // Timer & UI Logic
            const totalTimeInSeconds = <?= $quizTotalTime ?>;
            let timeRemaining = totalTimeInSeconds;
            const timerDisplay = document.getElementById('quiz-timer');
            const timerContainer = document.getElementById('timer-container');
            const form = document.getElementById('quizForm');
            const submitTypeField = document.getElementById('submission_type');
            const submitButton = document.getElementById('submitButton');
            let timerInterval;

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

            function updateTimer() {
                if (timeRemaining <= 0) {
                    clearInterval(timerInterval);
                    timerDisplay.textContent = "00:00";
                    submitButton.disabled = true;
                    submitButton.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-2"></i> Time Expired...';
                    submitTypeField.value = 'timeout';
                    form.submit();
                    return;
                }

                timerDisplay.textContent = formatTime(timeRemaining);

                // Visual urgency
                if (timeRemaining <= 60 && timeRemaining > 15) {
                    timerContainer.className = "bg-orange-50 rounded-xl border-2 border-orange-200 p-4 transition-colors duration-300";
                    timerDisplay.className = "text-4xl font-black text-orange-600 tabular-nums";
                } else if (timeRemaining <= 15) {
                    timerContainer.className = "bg-red-50 rounded-xl border-2 border-red-300 p-4 transition-colors duration-300 animate-pulse";
                    timerDisplay.className = "text-4xl font-black text-red-600 tabular-nums";
                }

                timeRemaining--;
            }

            form.addEventListener('submit', (e) => {
                if (timeRemaining <= 0 && submitTypeField.value === 'manual') {
                    e.preventDefault();
                    return;
                }
            });

            timerInterval = setInterval(updateTimer, 1000);
            updateTimer();
        </script>
        <?php endif; ?>

        <script>
            // Simple Progress Bar Update
            function updateProgress() {
                const totalQuestions = <?= count($quiz['questions']) ?>;
                const answered = document.querySelectorAll('input[type="radio"]:checked').length;
                const percentage = (answered / totalQuestions) * 100;
                document.getElementById('progressBar').style.width = percentage + '%';
                
                // Also uncheck others checked styling (handled by CSS peer/sibling selectors, 
                // but strictly for the icon visibility inside the circle if we wanted JS logic)
                const radios = document.querySelectorAll('.answer-radio');
                radios.forEach(r => {
                    const icon = r.nextElementSibling.querySelector('.fa-check');
                    if(r.checked) {
                        icon.style.opacity = '1';
                    } else {
                        icon.style.opacity = '0';
                    }
                });
            }
            // Initialize listener for icons
            document.querySelectorAll('.answer-radio').forEach(radio => {
                radio.addEventListener('change', updateProgress);
            });
        </script>

    <?php else: ?>
        <!-- DASHBOARD / QUIZ LIST VIEW -->
        
        <?php $allQuizzes = get_all_quizzes(); if (empty($allQuizzes)): ?>
            <div class="flex flex-col items-center justify-center p-16 bg-white rounded-3xl shadow-sm border border-gray-100 text-center">
                <div class="w-24 h-24 bg-gray-50 rounded-full flex items-center justify-center mb-6">
                    <i class="fa-solid fa-folder-open text-4xl text-gray-300"></i>
                </div>
                <h3 class="text-xl font-bold text-gray-800 mb-2">No Quizzes Available</h3>
                <p class="text-gray-500 max-w-md">There are currently no assessments assigned to your account. Please check back later.</p>
            </div>
        <?php else: ?>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                <?php foreach ($allQuizzes as $q): ?>
                    <?php 
                    $questionCount = count($q['questions']);
                    $lastScore = get_student_score($q['id']);
                    $hasTimeLimit = ($q['time_limit_seconds'] ?? 0) > 0;
                    
                    // Logic for card styling based on status
                    if ($lastScore !== null) {
                        $percentage = ($questionCount > 0) ? ($lastScore / $questionCount) * 100 : 0;
                        $statusColor = 'indigo';
                        $statusText = 'Completed';
                        $btnText = 'Retake Quiz';
                        $btnClass = 'bg-white text-indigo-600 border border-indigo-200 hover:bg-indigo-50';
                    } else {
                        $percentage = 0;
                        $statusColor = 'gray';
                        $statusText = 'Not Started';
                        $btnText = 'Start Quiz';
                        $btnClass = 'bg-indigo-600 text-white hover:bg-indigo-700 shadow-md shadow-indigo-500/20';
                    }
                    ?>

                    <div class="group bg-white rounded-2xl p-6 shadow-sm border border-gray-100 hover:shadow-xl hover:-translate-y-1 transition-all duration-300 flex flex-col h-full relative overflow-hidden">
                        <!-- Decorative top accent -->
                        <div class="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-indigo-500 to-purple-500 transform scale-x-0 group-hover:scale-x-100 transition-transform duration-500"></div>

                        <!-- Header -->
                        <div class="flex justify-between items-start mb-4">
                            <div class="p-3 bg-indigo-50 rounded-xl text-indigo-600 group-hover:bg-indigo-600 group-hover:text-white transition-colors duration-300">
                                <i class="fa-solid fa-shapes text-xl"></i>
                            </div>
                            <?php if($hasTimeLimit): ?>
                                <span class="text-xs font-bold px-2 py-1 bg-orange-100 text-orange-700 rounded-lg flex items-center">
                                    <i class="fa-solid fa-bolt mr-1"></i> Timed
                                </span>
                            <?php endif; ?>
                        </div>

                        <h4 class="text-xl font-bold text-gray-800 mb-2 group-hover:text-indigo-600 transition-colors"><?= htmlspecialchars($q['title']) ?></h4>
                        <p class="text-sm text-gray-500 mb-6 flex-grow"><?= htmlspecialchars($q['topic']) ?></p>

                        <!-- Stats Row -->
                        <div class="flex items-center space-x-4 text-sm text-gray-500 mb-6">
                            <div class="flex items-center">
                                <i class="fa-regular fa-circle-question mr-2 text-gray-400"></i>
                                <?= $questionCount ?> Qs
                            </div>
                            <div class="flex items-center">
                                <i class="fa-regular fa-clock mr-2 text-gray-400"></i>
                                <?= $hasTimeLimit ? format_time_display($q['time_limit_seconds']) : 'Unlimited' ?>
                            </div>
                        </div>

                        <!-- Footer / Progress -->
                        <div class="mt-auto">
                            <?php if ($lastScore !== null): ?>
                                <div class="mb-4">
                                    <div class="flex justify-between text-xs font-bold text-gray-600 mb-1">
                                        <span>Last Score</span>
                                        <span><?= $percentage ?>%</span>
                                    </div>
                                    <div class="w-full bg-gray-100 rounded-full h-1.5">
                                        <div class="bg-<?= $percentage > 70 ? 'green' : 'indigo' ?>-500 h-1.5 rounded-full" style="width: <?= $percentage ?>%"></div>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <a href="?quiz_id=<?= $q['id'] ?>" class="block w-full py-3 rounded-xl font-bold text-center transition-all duration-300 <?= $btnClass ?>">
                                <?= $btnText ?> <i class="fa-solid fa-arrow-right ml-2 text-xs"></i>
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<?php
render_main_content_end();
render_footer();
?>