<?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 courses with detailed information
$stmt = $db->prepare("
    SELECT c.*, ce.enrollment_date, ce.progress_percentage, ce.status as enrollment_status,
           ce.completion_date, cat.name as category_name, cat.color as category_color,
           u.username as instructor_name, up.first_name, up.last_name,
           COUNT(DISTINCT cl.id) as total_lessons,
           COUNT(DISTINCT clp.id) as completed_lessons
    FROM course_enrollments ce
    JOIN courses c ON ce.course_id = c.id
    LEFT JOIN course_categories cat ON c.category_id = cat.id
    JOIN users u ON c.instructor_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    LEFT JOIN course_lessons cl ON c.id = cl.course_id
    LEFT JOIN course_lesson_progress clp ON cl.id = clp.lesson_id AND clp.enrollment_id = ce.id AND clp.status = 'completed'
    WHERE ce.student_id = ?
    GROUP BY ce.id, c.id
    ORDER BY ce.enrollment_date DESC
");
$stmt->execute([$userId]);
$enrolledCourses = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get enrollment statistics
$stmt = $db->prepare("
    SELECT
        COUNT(*) as total_courses,
        COUNT(CASE WHEN status = 'completed' THEN 1 END) as completed_courses,
        COUNT(CASE WHEN status = 'in_progress' THEN 1 END) as in_progress_courses,
        AVG(progress_percentage) as avg_progress
    FROM course_enrollments
    WHERE student_id = ?
");
$stmt->execute([$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>My Courses | <?php echo htmlspecialchars($user['username'] ?? 'Student'); ?> - 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-0 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="courses.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: Book -->
                        <span class="w-5 h-5">📚</span>
                        <span>My Courses</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>
                </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">

            <!-- Top Bar (Mobile/Desktop Header) -->
            <header class="bg-white shadow-sm sticky top-0 z-10 border-b border-accent-subtle">
                <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
                    <h1 class="text-2xl font-bold text-text-dark">My Courses</h1>

                    <div class="flex items-center space-x-4">
                        <!-- User Profile Dropdown (Mock) -->
                        <div class="relative group">
                            <button class="flex items-center space-x-2 p-2 rounded-full hover:bg-accent-subtle transition duration-150">
                                <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">
                            </button>
                            <!-- 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="courses.php" class="block p-3 rounded-lg bg-primary-blue text-white font-semibold">📚 My Courses</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>
                </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-4 gap-6 mb-8">

                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <p class="text-sm text-gray-500">Total Courses</p>
                        <p class="text-3xl font-bold text-gray-900"><?php echo $stats['total_courses'] ?? 0; ?></p>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <p class="text-sm text-gray-500">Completed</p>
                        <p class="text-3xl font-bold text-green-600"><?php echo $stats['completed_courses'] ?? 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_courses'] ?? 0; ?></p>
                    </div>
                    <div class="bg-white p-6 rounded-xl shadow-md">
                        <p class="text-sm text-gray-500">Avg Progress</p>
                        <p class="text-3xl font-bold text-amber-600"><?php echo round($stats['avg_progress'] ?? 0); ?>%</p>
                    </div>
                </div>

                <!-- Courses Grid -->
                <?php if (!empty($enrolledCourses)): ?>
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php foreach ($enrolledCourses as $course): ?>
                            <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-graduation-cap w-16 h-16 mx-auto mb-2 opacity-75"></i>
                                        <p class="text-sm opacity-75"><?php echo htmlspecialchars($course['category_name'] ?? 'Course'); ?></p>
                                    </div>
                                    <div class="absolute top-4 right-4">
                                        <span class="px-2 py-1 text-xs font-medium rounded-full <?php
                                            echo $course['enrollment_status'] === 'completed' ? 'bg-green-100 text-green-800' :
                                                 'bg-blue-100 text-blue-800';
                                        ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', $course['enrollment_status'])); ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="p-6">
                                    <h3 class="text-lg font-semibold text-gray-800 mb-2">
                                        <?php echo htmlspecialchars($course['title']); ?>
                                    </h3>
                                    <p class="text-sm text-gray-600 mb-3">
                                        by <?php echo htmlspecialchars($course['first_name'] && $course['last_name'] ? $course['first_name'] . ' ' . $course['last_name'] : $course['instructor_name']); ?>
                                    </p>
                                    <div class="mb-4">
                                        <div class="flex justify-between text-sm text-gray-600 mb-1">
                                            <span>Progress</span>
                                            <span><?php echo round($course['progress_percentage']); ?>%</span>
                                        </div>
                                        <div class="w-full bg-gray-200 rounded-full h-2">
                                            <div class="bg-primary-blue h-2 rounded-full" style="width: <?php echo $course['progress_percentage']; ?>%"></div>
                                        </div>
                                    </div>
                                    <div class="flex space-x-2">
                                        <a href="../courses/learn.php?id=<?php echo $course['id']; ?>" class="flex-1 bg-primary-blue text-white text-center py-2 px-4 rounded-lg text-sm font-medium hover:bg-indigo-700">
                                            <?php echo $course['enrollment_status'] === 'completed' ? 'Review' : 'Continue'; ?>
                                        </a>
                                        <a href="../courses/detail.php?id=<?php echo $course['id']; ?>" class="bg-gray-100 text-gray-700 py-2 px-3 rounded-lg text-sm font-medium hover:bg-gray-200">
                                            <i class="fas fa-info-circle"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="bg-white p-12 rounded-xl shadow-lg text-center">
                        <i class="fas fa-graduation-cap text-gray-400 mx-auto h-16 w-16 mb-4"></i>
                        <h3 class="text-xl font-semibold text-gray-800 mb-2">No courses enrolled</h3>
                        <p class="text-gray-600 mb-6">Start your learning journey by enrolling in courses.</p>
                        <a href="../courses/catalog.php" class="bg-primary-blue text-white px-6 py-3 rounded-lg font-medium hover:bg-indigo-700">
                            Browse Courses
                        </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');
                });
            });
        }
    </script>
</body>
</html>