<?php
require_once '../includes/middleware.php';
require_once '../config/database.php';
$lms_config = require '../config/lms.php';
require_once '../includes/functions.php';

$db = getDB();

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

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

// Get parameters
$studentId = $_GET['student_id'] ?? 0;
$courseId = $_GET['course_id'] ?? 0;

if (!$studentId || !$courseId) {
    die('Invalid parameters');
}

// Verify course belongs to instructor
$stmt = $db->prepare("SELECT id, title, description, level FROM courses WHERE id = ? AND instructor_id = ?");
$stmt->execute([$courseId, $userId]);
$course = $stmt->fetch();

if (!$course) {
    die('Access denied');
}

// Get student info
$stmt = $db->prepare("
    SELECT u.username, u.email, up.first_name, up.last_name
    FROM users u
    LEFT JOIN user_profiles up ON u.id = up.user_id
    WHERE u.id = ?
");
$stmt->execute([$studentId]);
$student = $stmt->fetch();

if (!$student) {
    die('Student not found');
}

// Get enrollment info
$stmt = $db->prepare("
    SELECT ce.id as enrollment_id, ce.enrollment_date, ce.status, ce.progress_percentage
    FROM course_enrollments ce
    WHERE ce.course_id = ? AND ce.student_id = ?
");
$stmt->execute([$courseId, $studentId]);
$enrollment = $stmt->fetch();

if (!$enrollment) {
    die('Enrollment not found');
}

// Get lessons and progress
$stmt = $db->prepare("
    SELECT
        cl.id,
        cl.title,
        cl.description,
        cl.sort_order,
        clp.status as progress_status,
        clp.completed_at,
        clp.progress_percentage as score
    FROM course_lessons cl
    LEFT JOIN course_lesson_progress clp ON cl.id = clp.lesson_id AND clp.enrollment_id = ?
    WHERE cl.course_id = ?
    ORDER BY cl.sort_order
");
$stmt->execute([$enrollment['enrollment_id'], $courseId]);
$lessons = $stmt->fetchAll();

$page_title = 'Student Progress - ' . htmlspecialchars($student['first_name'] && $student['last_name'] ? $student['first_name'] . ' ' . $student['last_name'] : $student['username']) . ' - ' . $lms_config['lms']['site_name'];
$active_link = 'students';
?>
<!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($page_title); ?></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>
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <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;
        }

        /* Custom Styles for Dashboard Layout */
        .admin-sidebar {
            transition: transform 0.3s ease-in-out;
            min-width: 250px;
        }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0;
                transform: translateX(-100%);
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar {
                transform: translateX(0);
            }
            .admin-container.sidebar-open .sidebar-overlay {
                display: block;
            }
        }

        /* Sidebar Overlay for Mobile */
        .sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 40;
            display: none;
            transition: opacity 0.3s ease;
        }

        /* Progress bar styles */
        .progress-bar {
            height: 8px;
            background: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #007bff, #0056b3);
            transition: width 0.3s ease;
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

<!-- Sidebar Overlay (for closing sidebar on mobile tap outside) -->
<div id="sidebar-overlay" class="sidebar-overlay lg:hidden"></div>

<div class="flex">
    <?php include 'includes/sidebar.php'; ?>

    <!-- 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="Instructor Panel Logo" class="h-10 w-10">
                <div>
                    <h1 class="text-xl font-bold text-primary-blue"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></h1>
                    <p class="text-sm text-gray-600"><?php echo htmlspecialchars($page_title); ?></p>
                </div>
            </div>

            <div class="flex items-center space-x-4">
                <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username']); ?></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'] ?? 'I'), 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>
    </header>

    <!-- Main Content Area -->
    <main class="flex-1 overflow-y-auto pt-16">

        <?php include 'includes/mobile_menu.php'; ?>

        <!-- Page Header -->
        <div class="px-4 sm:px-6 lg:px-8 mb-8">
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div>
                    <h1 class="text-3xl font-bold text-gray-800">Student Progress</h1>
                    <p class="text-sm text-gray-600 mt-1">Track <?php echo htmlspecialchars($student['first_name'] && $student['last_name'] ? $student['first_name'] . ' ' . $student['last_name'] : $student['username']); ?>'s progress in <?php echo htmlspecialchars($course['title']); ?></p>
                </div>
                <a href="students.php" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200 inline-flex items-center justify-center">
                    <i class="fas fa-arrow-left mr-2"></i>Back to Students
                </a>
            </div>
        </div>

        <!-- Student and Course Info Cards -->
        <div class="px-4 sm:px-6 lg:px-8 grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <!-- Student Info Panel -->
            <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-xl font-bold text-gray-800">Student Information</h3>
                    <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-user text-blue-600 text-xl"></i>
                    </div>
                </div>
                <div class="space-y-3">
                    <div class="flex items-center">
                        <div class="w-12 h-12 bg-gray-100 rounded-full flex items-center justify-center flex-shrink-0 mr-4">
                            <i class="fas fa-user text-gray-500"></i>
                        </div>
                        <div>
                            <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($student['first_name'] && $student['last_name'] ? $student['first_name'] . ' ' . $student['last_name'] : $student['username']); ?></p>
                            <p class="text-sm text-gray-500"><?php echo htmlspecialchars($student['email']); ?></p>
                        </div>
                    </div>
                    <div class="pt-3 border-t border-gray-200">
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <p class="text-xs text-gray-500 uppercase tracking-wider">Enrolled</p>
                                <p class="text-sm font-medium text-gray-800"><?php echo date('M j, Y', strtotime($enrollment['enrollment_date'])); ?></p>
                            </div>
                            <div>
                                <p class="text-xs text-gray-500 uppercase tracking-wider">Status</p>
                                <span class="inline-block px-2.5 py-0.5 text-xs font-semibold rounded-full
                                    <?php
                                    switch($enrollment['status']) {
                                        case 'completed': echo 'bg-green-100 text-green-800'; break;
                                        case 'in_progress': echo 'bg-blue-100 text-blue-800'; break;
                                        case 'enrolled': echo 'bg-blue-100 text-blue-800'; break;
                                        case 'dropped': echo 'bg-red-100 text-red-800'; break;
                                        default: echo 'bg-gray-100 text-gray-800';
                                    }
                                    ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $enrollment['status'])); ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Course Info Panel -->
            <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-xl font-bold text-gray-800">Course Information</h3>
                    <div class="w-12 h-12 bg-purple-100 rounded-full flex items-center justify-center">
                        <i class="fas fa-book text-purple-600 text-xl"></i>
                    </div>
                </div>
                <div class="space-y-3">
                    <div>
                        <h4 class="font-semibold text-gray-900"><?php echo htmlspecialchars($course['title']); ?></h4>
                        <p class="text-sm text-gray-600 capitalize"><?php echo $course['level']; ?> level</p>
                    </div>
                    <div class="pt-3 border-t border-gray-200">
                        <p class="text-sm text-gray-600"><?php echo htmlspecialchars($course['description']); ?></p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Overall Progress Panel -->
        <div class="px-4 sm:px-6 lg:px-8 mb-8">
            <div class="bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-xl font-bold text-gray-800">Overall Progress</h3>
                    <div class="text-2xl font-extrabold text-primary-blue"><?php echo $enrollment['progress_percentage']; ?>%</div>
                </div>
                <div class="flex items-center">
                    <div class="flex-1 mr-4">
                        <div class="progress-bar h-3">
                            <div class="progress-fill" style="width: <?php echo $enrollment['progress_percentage']; ?>%"></div>
                        </div>
                    </div>
                </div>
                <div class="mt-4 flex items-center justify-between text-sm">
                    <span class="text-gray-500">Course Completion</span>
                    <span class="font-medium 
                        <?php 
                        if ($enrollment['progress_percentage'] >= 80) echo 'text-green-600';
                        elseif ($enrollment['progress_percentage'] >= 50) echo 'text-blue-600';
                        else echo 'text-yellow-600';
                        ?>">
                        <?php 
                        if ($enrollment['progress_percentage'] >= 80) echo 'Excellent';
                        elseif ($enrollment['progress_percentage'] >= 50) echo 'In Progress';
                        else echo 'Just Started';
                        ?>
                    </span>
                </div>
            </div>
        </div>

        <!-- Lesson Progress Panel -->
        <div class="px-4 sm:px-6 lg:px-8 mb-8">
            <div class="bg-white rounded-xl shadow-lg border border-accent-subtle overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
                    <h3 class="text-xl font-bold text-gray-800">Lesson Progress</h3>
                </div>
                <?php if (empty($lessons)): ?>
                    <div class="text-center py-12">
                        <i class="fas fa-book text-6xl text-gray-400 mb-4"></i>
                        <h4 class="text-xl font-semibold text-gray-800 mb-2">No lessons found</h4>
                        <p class="text-gray-500">This course doesn't have any lessons yet.</p>
                    </div>
                <?php else: ?>
                    <div class="divide-y divide-gray-200">
                        <?php foreach ($lessons as $lesson): ?>
                            <div class="px-6 py-4 hover:bg-gray-50 transition duration-150">
                                <div class="flex items-center justify-between">
                                    <div class="flex-1">
                                        <div class="flex items-center">
                                            <div class="w-8 h-8 rounded-full flex items-center justify-center mr-3 
                                                <?php
                                                switch($lesson['progress_status']) {
                                                    case 'completed': echo 'bg-green-100'; break;
                                                    case 'in_progress': echo 'bg-blue-100'; break;
                                                    default: echo 'bg-gray-100';
                                                }
                                                ?>">
                                                <?php
                                                switch($lesson['progress_status']) {
                                                    case 'completed': echo '<i class="fas fa-check text-green-600 text-sm"></i>'; break;
                                                    case 'in_progress': echo '<i class="fas fa-play text-blue-600 text-sm"></i>'; break;
                                                    default: echo '<i class="fas fa-circle text-gray-400 text-sm"></i>';
                                                }
                                                ?>
                                            </div>
                                            <div>
                                                <h4 class="text-lg font-medium text-gray-900"><?php echo htmlspecialchars($lesson['title']); ?></h4>
                                                <p class="text-sm text-gray-600 mt-0.5"><?php echo htmlspecialchars($lesson['description']); ?></p>
                                                <?php if ($lesson['progress_status'] === 'completed' && $lesson['completed_at']): ?>
                                                    <p class="text-xs text-green-600 mt-2">
                                                        <i class="fas fa-check-circle mr-1"></i>
                                                        Completed on <?php echo date('M j, Y H:i', strtotime($lesson['completed_at'])); ?>
                                                    </p>
                                                    <?php if ($lesson['score'] !== null): ?>
                                                        <p class="text-xs text-blue-600">
                                                            <i class="fas fa-star mr-1"></i>
                                                            Score: <?php echo $lesson['score']; ?>%
                                                        </p>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="ml-4">
                                        <span class="px-3 py-1 text-sm font-semibold rounded-full
                                            <?php
                                            switch($lesson['progress_status']) {
                                                case 'completed': echo 'bg-green-100 text-green-800'; break;
                                                case 'in_progress': echo 'bg-blue-100 text-blue-800'; break;
                                                default: echo 'bg-gray-100 text-gray-800';
                                            }
                                            ?>">
                                            <?php
                                            switch($lesson['progress_status']) {
                                                case 'completed': echo 'Completed'; break;
                                                case 'in_progress': echo 'In Progress'; break;
                                                default: echo 'Not Started';
                                            }
                                            ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

    </main>
</div>

<script>
    // Mobile menu toggle
    const mobileMenuButton = document.getElementById('mobileMenuButton');
    const sidebar = document.getElementById('admin-sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    const body = document.body;

    if (mobileMenuButton) {
        mobileMenuButton.addEventListener('click', () => {
            body.classList.toggle('sidebar-open');
        });
    }

    // Close sidebar when clicking the overlay on mobile
    if (overlay) {
        overlay.addEventListener('click', () => {
            body.classList.remove('sidebar-open');
        });
    }

    // Ensure sidebar is always visible on large screens
    window.addEventListener('resize', () => {
        if (window.innerWidth >= 1024) {
            body.classList.remove('sidebar-open');
        }
    });
</script>

</body>
</html>
