<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

// Check if user is student or higher
studentOrHigher();

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

// Get all enrolled exams with detailed information (from both course enrollments and direct exam access)
$stmt = $db->prepare("
    SELECT e.*, c.title as course_title, ce.enrollment_date, exa.access_granted_at as exam_access_date,
           ea.id as attempt_id, ea.status as attempt_status, ea.score, ea.completed_at,
           ea.started_at, e.passing_score,
           CASE
               WHEN ea.status IN ('submitted', 'graded', 'timed_out', 'completed') AND ea.score >= e.passing_score THEN 'passed'
               WHEN ea.status IN ('submitted', 'graded', 'timed_out', 'completed') AND ea.score < e.passing_score THEN 'failed'
               WHEN ea.status = 'in_progress' THEN 'in_progress'
               ELSE 'not_attempted'
           END as exam_result,
           CASE
               WHEN ce.id IS NOT NULL THEN 'course_enrollment'
               WHEN exa.id IS NOT NULL THEN 'direct_access'
               ELSE 'unknown'
           END as access_type
    FROM exams e
    LEFT JOIN courses c ON e.course_id = c.id
    LEFT JOIN course_enrollments ce ON c.id = ce.course_id AND ce.student_id = ?
    LEFT JOIN exam_access exa ON e.id = exa.exam_id AND exa.student_id = ?
    LEFT JOIN exam_attempts ea ON e.id = ea.exam_id AND ea.student_id = ? AND ea.id = (
        SELECT id FROM exam_attempts
        WHERE exam_id = e.id AND student_id = ?
        ORDER BY started_at DESC, id DESC
        LIMIT 1
    )
    WHERE e.status = 'published'
    AND (ce.id IS NOT NULL OR exa.id IS NOT NULL)
    ORDER BY e.end_date ASC, e.created_at DESC
");
$stmt->execute([$userId, $userId, $userId, $userId]);
$enrolledExams = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get exam statistics
$stmt = $db->prepare("
    SELECT
        COUNT(DISTINCT e.id) as total_exams,
        COUNT(DISTINCT CASE WHEN ea.status IN ('submitted', 'graded', 'timed_out', 'completed') AND ea.score >= e.passing_score THEN e.id END) as passed_exams,
        COUNT(DISTINCT CASE WHEN ea.status IN ('submitted', 'graded', 'timed_out', 'completed') AND ea.score < e.passing_score THEN e.id END) as failed_exams,
        COUNT(DISTINCT CASE WHEN ea.status = 'in_progress' THEN e.id END) as in_progress_exams,
        AVG(CASE WHEN ea.status IN ('submitted', 'graded', 'timed_out', 'completed') THEN ea.score END) as avg_score
    FROM exams e
    LEFT JOIN courses c ON e.course_id = c.id
    LEFT JOIN course_enrollments ce ON c.id = ce.course_id AND ce.student_id = ?
    LEFT JOIN exam_access exa ON e.id = exa.exam_id AND exa.student_id = ?
    LEFT JOIN exam_attempts ea ON e.id = ea.exam_id AND ea.student_id = ? AND ea.id = (
        SELECT id FROM exam_attempts
        WHERE exam_id = e.id AND student_id = ?
        ORDER BY started_at DESC, id DESC
        LIMIT 1
    )
    WHERE e.status = 'published'
    AND (ce.id IS NOT NULL OR exa.id IS NOT NULL)
");
$stmt->execute([$userId, $userId, $userId, $userId]);
$stats = $stmt->fetch(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($user['username'] ?? 'Student'); ?>'s Exams | Mutalex Academy</title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

    <!-- Main Application Container -->
    <div id="app" class="flex">

        <!-- Sidebar Navigation (Desktop View) -->
        <aside class="hidden lg:block w-64 bg-white border-r border-accent-subtle p-6 shadow-sm sticky top-16 h-screen">
            <div class="flex flex-col h-full">
                <!-- Logo/Title -->
                <div class="text-xl font-extrabold text-primary-blue mb-10 tracking-wider">
                    MUTALEX ACADEMY
                </div>

                <!-- Navigation Links -->
                <nav class="space-y-2 flex-grow">
                    <a href="dashboard.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Home -->
                        <span class="w-5 h-5">🏠</span>
                        <span>Dashboard</span>
                    </a>
                    <a href="available_courses.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Catalog -->
                        <span class="w-5 h-5">📖</span>
                        <span>View All Courses</span>
                    </a>
                    <a href="courses.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Book -->
                        <span class="w-5 h-5">📚</span>
                        <span>My Courses</span>
                    </a>
                    <a href="exams.php" class="flex items-center space-x-3 p-3 rounded-lg bg-primary-blue text-white font-semibold transition duration-150 shadow-md">
                        <!-- Icon Placeholder: Exam -->
                        <span class="w-5 h-5">📝</span>
                        <span>My Exam</span>
                    </a>
                    <a href="../exams/catalog.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: All Exams -->
                        <span class="w-5 h-5">📋</span>
                        <span>All Exam</span>
                    </a>
                    <a href="reports.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Checkmark -->
                        <span class="w-5 h-5">✅</span>
                        <span>Grades & Reports</span>
                    </a>
                    <a href="#" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Calendar -->
                        <span class="w-5 h-5">📅</span>
                        <span>Calendar</span>
                    </a>
                    <a href="../index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Globe -->
                        <span class="w-5 h-5">🌐</span>
                        <span>View Site</span>
                    </a>
                    <a href="../logout.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                        <!-- Icon Placeholder: Logout -->
                        <span class="w-5 h-5">🚪</span>
                        <span>Logout</span>
                    </a>
                </nav>

                <!-- Footer/User Info (Bottom of Sidebar) -->
                <div class="mt-8 pt-4 border-t border-accent-subtle">
                    <p class="text-xs text-gray-500 mb-2">Authenticated User:</p>
                    <p class="text-xs text-gray-700 truncate font-mono bg-accent-subtle p-1 rounded"><?php echo htmlspecialchars($user['username'] ?? 'User'); ?></p>
                </div>
            </div>
        </aside>
<!-- Main Content Area -->

<main class="flex-1 overflow-y-auto pt-16">

            <!-- Top Bar (Mobile/Desktop Header) -->
            <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10 border-b border-accent-subtle">
                <div class="px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
                    <div class="flex items-center space-x-3">
                        <img src="../assets/images/logo_1757657555.jpg" alt="Mutalex Academy Logo" class="h-10 w-10">
                        <div>
                            <h1 class="text-xl font-bold text-primary-blue">Mutalex Academy</h1>
                            <p class="text-sm text-gray-600">My Exams</p>
                        </div>
                    </div>

                    <div class="flex items-center space-x-4">
                        <!-- Cart Button -->
                        <button onclick="showDashboardCheckoutModal()" class="text-gray-600 hover:text-primary-blue p-2 rounded-full relative transition duration-150">
                            <!-- Shopping Cart Icon -->
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-shopping-cart">
                                <circle cx="8" cy="21" r="1"/>
                                <circle cx="19" cy="21" r="1"/>
                                <path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.15"/>
                            </svg>
                            <span id="dashboard-cart-count" class="absolute -top-1 -right-1 bg-red-500 text-white text-xs font-bold rounded-full h-5 w-5 flex items-center justify-center hidden">0</span>
                        </button>

                        <!-- User Profile -->
                        <div class="flex items-center space-x-2">
                            <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username'] ?? 'Student'); ?></span>
                            <img class="h-10 w-10 rounded-full border-2 border-primary-blue object-cover" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'S'), 0, 1); ?>" alt="User Avatar">
                            <!-- Mobile Menu Button (Hamburger) -->
                            <button class="lg:hidden p-2 rounded-lg text-text-dark hover:bg-accent-subtle ml-4" id="mobileMenuButton">
                                <span class="text-xl">☰</span>
                            </button>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Mobile Navigation Overlay (Hidden by default) -->
            <div id="mobileMenu" class="fixed inset-0 bg-white z-20 p-6 transform -translate-x-full transition-transform duration-300 lg:hidden">
                <div class="flex justify-between items-center mb-10">
                    <div class="text-xl font-extrabold text-primary-blue tracking-wider">MUTALEX ACADEMY</div>
                    <button id="closeMobileMenu" class="text-3xl text-text-dark">&times;</button>
                </div>
                <nav class="space-y-4">
                    <!-- Links repeated from sidebar -->
                    <a href="dashboard.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🏠 Dashboard</a>
                    <a href="available_courses.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📖 View All Courses</a>
                    <a href="courses.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle"> My Courses</a>
                    <a href="exams.php" class="block p-3 rounded-lg bg-primary-blue text-white font-semibold">📝 My Exam</a>
                    <a href="../exams/catalog.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📋 All Exam</a>
                    <a href="reports.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">✅ Grades & Reports</a>
                    <a href="#" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📅 Calendar</a>
                    <a href="../index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🌐 View Site</a>
                    <a href="../logout.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🚪 Logout</a>
                </nav>
            </div>

            <!-- Main Content -->
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

                <!-- Stats -->
                <div class="grid grid-cols-1 sm:grid-cols-5 gap-6 mb-8">
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <p class="text-sm text-gray-500">Total Exams</p>
                        <p class="text-3xl font-bold text-gray-900"><?php echo $stats['total_exams'] ?? 0; ?></p>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <p class="text-sm text-gray-500">Passed</p>
                        <p class="text-3xl font-bold text-green-600"><?php echo $stats['passed_exams'] ?? 0; ?></p>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <p class="text-sm text-gray-500">Failed</p>
                        <p class="text-3xl font-bold text-red-600"><?php echo $stats['failed_exams'] ?? 0; ?></p>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <p class="text-sm text-gray-500">In Progress</p>
                        <p class="text-3xl font-bold text-blue-600"><?php echo $stats['in_progress_exams'] ?? 0; ?></p>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <p class="text-sm text-gray-500">Avg Score</p>
                        <p class="text-3xl font-bold text-amber-600"><?php echo $stats['avg_score'] ? round($stats['avg_score']) : 0; ?>%</p>
                    </div>
                </div>

                <!-- Exams Grid -->
                <?php if (!empty($enrolledExams)): ?>
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                        <?php foreach ($enrolledExams as $exam): ?>
                            <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                                <div class="relative h-48 bg-gradient-to-br from-primary-blue to-indigo-600 flex items-center justify-center">
                                    <div class="text-white text-center">
                                        <i class="fas fa-file-alt w-16 h-16 mx-auto mb-2 opacity-75"></i>
                                        <p class="text-sm opacity-75"><?php echo ucfirst($exam['exam_type']); ?></p>
                                    </div>
                                    <div class="absolute top-4 right-4">
                                        <span class="px-2 py-1 text-xs font-medium rounded-full <?php
                                            echo $exam['exam_result'] === 'passed' ? 'bg-green-100 text-green-800' :
                                                 ($exam['exam_result'] === 'failed' ? 'bg-red-100 text-red-800' :
                                                  ($exam['exam_result'] === 'in_progress' ? 'bg-blue-100 text-blue-800' :
                                                   'bg-gray-100 text-gray-800'));
                                        ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', $exam['exam_result'])); ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="p-6">
                                    <h3 class="text-lg font-semibold text-gray-800 mb-2">
                                        <?php echo htmlspecialchars($exam['title']); ?>
                                    </h3>
                                    <p class="text-sm text-gray-600 mb-1">
                                        Course: <?php echo htmlspecialchars($exam['course_title']); ?>
                                    </p>
                                    <div class="flex items-center space-x-4 text-sm text-gray-600 mb-3">
                                        <div class="flex items-center">
                                            <i class="fas fa-clock mr-1"></i>
                                            <span><?php echo $exam['time_limit'] ? $exam['time_limit'] . ' min' : 'No limit'; ?></span>
                                        </div>
                                        <div class="flex items-center">
                                            <i class="fas fa-trophy mr-1"></i>
                                            <span><?php echo $exam['passing_score']; ?>%</span>
                                        </div>
                                    </div>

                                    <?php if ($exam['exam_result'] === 'passed'): ?>
                                        <div class="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg">
                                            <div class="flex items-center justify-between">
                                                <span class="text-sm font-medium text-green-800">Score: <?php echo round($exam['score']); ?>%</span>
                                                <span class="text-xs text-green-600">Passed</span>
                                            </div>
                                            <p class="text-xs text-green-600 mt-1">Completed: <?php echo date('M j, Y', strtotime($exam['completed_at'])); ?></p>
                                        </div>
                                    <?php elseif ($exam['exam_result'] === 'failed'): ?>
                                        <div class="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
                                            <div class="flex items-center justify-between">
                                                <span class="text-sm font-medium text-red-800">Score: <?php echo round($exam['score']); ?>%</span>
                                                <span class="text-xs text-red-600">Failed</span>
                                            </div>
                                            <p class="text-xs text-red-600 mt-1">Completed: <?php echo date('M j, Y', strtotime($exam['completed_at'])); ?></p>
                                        </div>
                                    <?php elseif ($exam['exam_result'] === 'in_progress'): ?>
                                        <div class="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                                            <p class="text-sm text-blue-800">Exam in progress</p>
                                            <p class="text-xs text-blue-600 mt-1">Started: <?php echo date('M j, Y H:i', strtotime($exam['started_at'])); ?></p>
                                        </div>
                                    <?php endif; ?>

                                    <div class="flex space-x-2">
                                        <?php if ($exam['exam_result'] === 'not_attempted' || $exam['exam_result'] === 'failed'): ?>
                                            <a href="/lms/student/exams/take.php?id=<?php echo $exam['id']; ?>" class="flex-1 block bg-primary-blue text-white text-center py-2 px-4 rounded-lg text-sm font-medium hover:bg-indigo-700">
                                                <?php echo $exam['exam_result'] === 'failed' ? 'Retake Exam' : 'Take Exam'; ?>
                                            </a>
                                        <?php elseif ($exam['exam_result'] === 'in_progress'): ?>
                                            <a href="/lms/student/exams/take.php?id=<?php echo $exam['id']; ?>" class="flex-1 block bg-blue-600 text-white text-center py-2 px-4 rounded-lg text-sm font-medium hover:bg-blue-700">
                                                Continue Exam
                                            </a>
                                        <?php else: ?>
                                            <a href="../exams/review.php?id=<?php echo $exam['attempt_id']; ?>" class="flex-1 block bg-green-600 text-white text-center py-2 px-4 rounded-lg text-sm font-medium hover:bg-green-700">
                                                Review Results
                                            </a>
                                        <?php endif; ?>
                                        <button class="bg-gray-100 text-gray-700 py-2 px-3 rounded-lg text-sm font-medium hover:bg-gray-200" onclick="showExamDetails(<?php echo $exam['id']; ?>)">
                                            <i class="fas fa-info-circle"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="bg-white p-12 rounded-xl shadow-lg text-center">
                        <i class="fas fa-file-alt text-gray-400 mx-auto h-16 w-16 mb-4"></i>
                        <h3 class="text-xl font-semibold text-gray-800 mb-2">No exams available</h3>
                        <p class="text-gray-600 mb-6">You don't have any exams in your enrolled courses yet.</p>
                        <a href="exams.php" class="bg-primary-blue text-white px-6 py-3 rounded-lg font-medium hover:bg-indigo-700">
                            View My Exams
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <!-- JavaScript for Mobile Menu Functionality -->
    <script>
        const mobileMenuButton = document.getElementById('mobileMenuButton');
        const closeMobileMenu = document.getElementById('closeMobileMenu');
        const mobileMenu = document.getElementById('mobileMenu');

        if (mobileMenuButton && closeMobileMenu && mobileMenu) {
            mobileMenuButton.addEventListener('click', () => {
                mobileMenu.classList.remove('-translate-x-full');
            });

            closeMobileMenu.addEventListener('click', () => {
                mobileMenu.classList.add('-translate-x-full');
            });

            // Close menu when a link is clicked
            mobileMenu.querySelectorAll('a').forEach(link => {
                link.addEventListener('click', () => {
                    mobileMenu.classList.add('-translate-x-full');
                });
            });
        }

        function showExamDetails(examId) {
            // Placeholder for exam details modal
            alert('Exam details for ID: ' + examId);
        }
    </script>
</body>
</html>