<?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'];
?>

<!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 CDN -->
    <script src="https://cdn.tailwindcss.com"></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>
        /* Custom Tailwind Configuration */
        :root {
            --primary: #007bff;
            --secondary: #6c757d;
            --success: #28a745;
            --danger: #dc3545;
        }
        .text-primary { color: var(--primary); }
        .bg-primary { background-color: var(--primary); }
        .bg-success { background-color: var(--success); }
        .bg-secondary { background-color: var(--secondary); }

        /* Ensure smooth scrolling and font */
        body { font-family: 'Inter', sans-serif; background-color: #f8f9fa; }

        /* 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="antialiased">

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

<div class="admin-container flex min-h-screen">
    <!-- Sidebar -->
    <div id="admin-sidebar" class="admin-sidebar bg-gray-800 text-white shadow-xl lg:sticky lg:top-0 h-screen overflow-y-auto">
        <div class="p-6 border-b border-gray-700">
            <h2 class="text-2xl font-extrabold text-blue-400"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></h2>
            <p class="text-sm font-light text-gray-400 mt-1"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></p>
        </div>

        <nav class="p-4">
            <ul class="space-y-2">
                <li><a href="dashboard.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-chart-line w-5 h-5 mr-3"></i>Dashboard</a></li>
                <li><a href="courses/" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-graduation-cap w-5 h-5 mr-3"></i>My Courses</a></li>
                <li><a href="courses/new.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-plus-circle w-5 h-5 mr-3"></i>Create Course</a></li>
                <li><a href="/lms/instructor/questions/index.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-question-circle w-5 h-5 mr-3"></i>Question Bank</a></li>
                <li><a href="/lms/instructor/exams/index.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-clipboard-check w-5 h-5 mr-3"></i>Exams & Quizzes</a></li>
                <li><a href="students.php" class="flex items-center p-3 rounded-lg bg-gray-700 text-blue-300 font-semibold hover:bg-gray-700 transition duration-150"><i class="fas fa-users w-5 h-5 mr-3"></i>My Students</a></li>
                <li><a href="analytics.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-chart-bar w-5 h-5 mr-3"></i>Analytics</a></li>
                <li><a href="resources.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-book-open w-5 h-5 mr-3"></i>Resources</a></li>
                <li class="pt-4 border-t border-gray-700 mt-4">
                    <a href="../logout.php" class="flex items-center p-3 rounded-lg text-red-400 hover:bg-gray-700 transition duration-150">
                        <i class="fas fa-sign-out-alt w-5 h-5 mr-3"></i>Logout
                    </a>
                </li>
            </ul>
        </nav>
    </div>

    <!-- Main Content -->
    <div class="admin-content flex-1 p-4 sm:p-6 lg:p-8">
        <!-- Header (Mobile Menu Button and Page Title) -->
        <div class="admin-header flex justify-between items-center pb-6 border-b border-gray-200 mb-6">
            <div class="flex items-center">
                <!-- Hamburger Menu for Mobile -->
                <button id="sidebar-toggle" class="lg:hidden p-2 mr-4 text-gray-600 hover:text-gray-900 rounded-lg focus:outline-none">
                    <i class="fas fa-bars text-xl"></i>
                </button>
                <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>
            </div>
            <a href="students.php" class="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition duration-200">
                <i class="fas fa-arrow-left mr-2"></i>Back to Students
            </a>
        </div>

        <!-- Student and Course Info -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <!-- Student Info -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h3 class="text-xl font-semibold text-gray-800 mb-4">Student Information</h3>
                <div class="space-y-3">
                    <div class="flex items-center">
                        <div class="w-12 h-12 bg-gray-200 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-medium 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">
                        <p class="text-sm text-gray-600"><strong>Enrolled:</strong> <?php echo date('M j, Y', strtotime($enrollment['enrollment_date'])); ?></p>
                        <p class="text-sm text-gray-600"><strong>Status:</strong>
                            <span class="px-2 py-1 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>
                        </p>
                    </div>
                </div>
            </div>

            <!-- Course Info -->
            <div class="bg-white rounded-xl shadow-lg p-6">
                <h3 class="text-xl font-semibold text-gray-800 mb-4">Course Information</h3>
                <div class="space-y-3">
                    <div>
                        <h4 class="font-medium 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 -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
            <h3 class="text-xl font-semibold text-gray-800 mb-4">Overall Progress</h3>
            <div class="flex items-center">
                <div class="flex-1 mr-4">
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: <?php echo $enrollment['progress_percentage']; ?>%"></div>
                    </div>
                </div>
                <span class="text-lg font-semibold text-gray-700"><?php echo $enrollment['progress_percentage']; ?>%</span>
            </div>
        </div>

        <!-- Lesson Progress -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-xl font-semibold 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">
                            <div class="flex items-center justify-between">
                                <div class="flex-1">
                                    <h4 class="text-lg font-medium text-gray-900"><?php echo htmlspecialchars($lesson['title']); ?></h4>
                                    <p class="text-sm text-gray-600 mt-1"><?php echo htmlspecialchars($lesson['description']); ?></p>
                                    <?php if ($lesson['progress_status'] === 'completed' && $lesson['completed_at']): ?>
                                        <p class="text-xs text-green-600 mt-2">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">Score: <?php echo $lesson['score']; ?>%</p>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </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>
</div>

<script>
// Sidebar Toggle Logic
document.getElementById('sidebar-toggle').addEventListener('click', () => {
    document.querySelector('.admin-container').classList.toggle('sidebar-open');
});

// Close sidebar when clicking the overlay on mobile
document.getElementById('sidebar-overlay').addEventListener('click', () => {
    document.querySelector('.admin-container').classList.remove('sidebar-open');
});

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

</body>
</html>