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

// Handle POST requests for enroll/unenroll
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    // Course enrollment actions
    if ($action === 'enroll') {
        $courseId = $_POST['course_id'] ?? 0;
        $studentEmail = trim($_POST['student_email'] ?? '');
        if ($courseId && $studentEmail) {
            // Find student
            $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$studentEmail]);
            $student = $stmt->fetch();
            if ($student) {
                $result = enrollStudent($db, $courseId, $student['id'], $userId);
                $_SESSION['message'] = $result['message'];
                $_SESSION['message_type'] = $result['success'] ? 'success' : 'error';
            } else {
                $_SESSION['message'] = 'Student not found with that email.';
                $_SESSION['message_type'] = 'error';
            }
        } else {
            $_SESSION['message'] = 'Course and student email are required.';
            $_SESSION['message_type'] = 'error';
        }
    } elseif ($action === 'unenroll') {
        $enrollmentId = $_POST['enrollment_id'] ?? 0;
        if ($enrollmentId) {
            $result = unenrollStudent($db, $enrollmentId, $userId);
            $_SESSION['message'] = $result['message'];
            $_SESSION['message_type'] = $result['success'] ? 'success' : 'error';
        } else {
            $_SESSION['message'] = 'Enrollment ID required.';
            $_SESSION['message_type'] = 'error';
        }
    }
    
    // Exam enrollment actions
    elseif ($action === 'enroll_exam') {
        $examId = $_POST['exam_id'] ?? 0;
        $studentEmail = trim($_POST['student_email'] ?? '');
        if ($examId && $studentEmail) {
            // Find student
            $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$studentEmail]);
            $student = $stmt->fetch();
            if ($student) {
                $result = enrollExamStudent($db, $examId, $student['id'], $userId);
                $_SESSION['message'] = $result['message'];
                $_SESSION['message_type'] = $result['success'] ? 'success' : 'error';
            } else {
                $_SESSION['message'] = 'Student not found with that email.';
                $_SESSION['message_type'] = 'error';
            }
        } else {
            $_SESSION['message'] = 'Exam and student email are required.';
            $_SESSION['message_type'] = 'error';
        }
    } elseif ($action === 'unenroll_exam') {
        $examAccessId = $_POST['exam_access_id'] ?? 0;
        if ($examAccessId) {
            $result = unenrollExamStudent($db, $examAccessId, $userId);
            $_SESSION['message'] = $result['message'];
            $_SESSION['message_type'] = $result['success'] ? 'success' : 'error';
        } else {
            $_SESSION['message'] = 'Exam access ID required.';
            $_SESSION['message_type'] = 'error';
        }
    }
    
    // Redirect to avoid resubmission
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Get filter parameters
$courseFilter = $_GET['course'] ?? '';
$statusFilter = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';

// Get instructor's courses for filter dropdown
$stmt = $db->prepare("SELECT id, title FROM courses WHERE instructor_id = ? ORDER BY title");
$stmt->execute([$userId]);
$courses = $stmt->fetchAll();

// Build query for students
$query = "
    SELECT
        u.id as student_id,
        u.username,
        u.email,
        up.first_name,
        up.last_name,
        ce.id as enrollment_id,
        ce.enrollment_date,
        ce.status as enrollment_status,
        ce.progress_percentage,
        c.id as course_id,
        c.title as course_title,
        c.level as course_level,
        COUNT(DISTINCT cl.id) as total_lessons,
        COUNT(DISTINCT CASE WHEN clp.status = 'completed' THEN clp.lesson_id END) as completed_lessons
    FROM course_enrollments ce
    JOIN courses c ON ce.course_id = c.id
    JOIN users u ON ce.student_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
    WHERE c.instructor_id = ?
";

$params = [$userId];

if ($courseFilter) {
    $query .= " AND c.id = ?";
    $params[] = $courseFilter;
}

if ($statusFilter) {
    $query .= " AND ce.status = ?";
    $params[] = $statusFilter;
}

if ($search) {
    $query .= " AND (u.username LIKE ? OR u.email LIKE ? OR CONCAT(up.first_name, ' ', up.last_name) LIKE ?)";
    $searchParam = "%$search%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
}

$query .= " GROUP BY ce.id ORDER BY ce.enrollment_date DESC";

$stmt = $db->prepare($query);
$stmt->execute($params);
$students = $stmt->fetchAll();

// Get summary statistics
$stmt = $db->prepare("
    SELECT
        COUNT(DISTINCT ce.student_id) as total_students,
        COUNT(ce.id) as total_enrollments,
        COUNT(CASE WHEN ce.status = 'completed' THEN 1 END) as completed_enrollments,
        AVG(ce.progress_percentage) as avg_progress
    FROM course_enrollments ce
    JOIN courses c ON ce.course_id = c.id
    WHERE c.instructor_id = ?
");
$stmt->execute([$userId]);
$stats = $stmt->fetch();

// Get instructor's exams for filter dropdown and enrollment form
$stmt = $db->prepare("SELECT id, title FROM exams WHERE instructor_id = ? ORDER BY title");
$stmt->execute([$userId]);
$exams = $stmt->fetchAll();

// Get filter parameters for exams
$examFilter = $_GET['exam'] ?? '';
$examStatusFilter = $_GET['exam_status'] ?? '';
$examSearch = $_GET['exam_search'] ?? '';

// Build query for exam enrollments
$examQuery = "
    SELECT
        u.id as student_id,
        u.username,
        u.email,
        up.first_name,
        up.last_name,
        ea.id as exam_access_id,
        ea.access_granted_at,
        ea.payment_status,
        e.id as exam_id,
        e.title as exam_title,
        e.time_limit,
        e.passing_score,
        COUNT(DISTINCT eat.id) as attempt_count,
        MAX(eat.score) as best_score,
        MAX(eat.completed_at) as last_attempt_at
    FROM exam_access ea
    JOIN exams e ON ea.exam_id = e.id
    JOIN users u ON ea.student_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    LEFT JOIN exam_attempts eat ON e.id = eat.exam_id AND eat.student_id = u.id
    WHERE e.instructor_id = ?
";

$examParams = [$userId];

if ($examFilter) {
    $examQuery .= " AND e.id = ?";
    $examParams[] = $examFilter;
}

if ($examSearch) {
    $examQuery .= " AND (u.username LIKE ? OR u.email LIKE ? OR CONCAT(up.first_name, ' ', up.last_name) LIKE ?)";
    $searchParam = "%$examSearch%";
    $examParams[] = $searchParam;
    $examParams[] = $searchParam;
    $examParams[] = $searchParam;
}

if ($examStatusFilter) {
    if ($examStatusFilter === 'completed') {
        $examQuery .= " AND ea.payment_status = 'paid'";
    } elseif ($examStatusFilter === 'free') {
        $examQuery .= " AND ea.payment_status = 'free'";
    } elseif ($examStatusFilter === 'has_access') {
        $examQuery .= " AND (ea.payment_status = 'free' OR ea.payment_status = 'paid')";
    }
}

$examQuery .= " GROUP BY ea.id ORDER BY ea.access_granted_at DESC";

$stmt = $db->prepare($examQuery);
$stmt->execute($examParams);
$examEnrollments = $stmt->fetchAll();

// Get exam summary statistics
$stmt = $db->prepare("
    SELECT
        COUNT(DISTINCT ea.student_id) as total_students,
        COUNT(ea.id) as total_enrollments,
        COUNT(CASE WHEN ea.payment_status = 'paid' THEN 1 END) as purchased_access,
        COUNT(CASE WHEN ea.payment_status = 'free' THEN 1 END) as free_access,
        COUNT(DISTINCT eat.id) as total_attempts
    FROM exam_access ea
    JOIN exams e ON ea.exam_id = e.id
    LEFT JOIN exam_attempts eat ON e.id = eat.exam_id AND eat.student_id = ea.student_id
    WHERE e.instructor_id = ?
");
$stmt->execute([$userId]);
$examStats = $stmt->fetch();

// Functions for enroll/unenroll
function enrollStudent($db, $courseId, $studentId, $instructorId) {
    try {
        // Check if course belongs to instructor
        $stmt = $db->prepare("SELECT id FROM courses WHERE id = ? AND instructor_id = ?");
        $stmt->execute([$courseId, $instructorId]);
        if (!$stmt->fetch()) {
            return ['success' => false, 'message' => 'You do not own this course.'];
        }
        // Check if already enrolled
        $stmt = $db->prepare("SELECT id FROM course_enrollments WHERE course_id = ? AND student_id = ? AND status != 'dropped'");
        $stmt->execute([$courseId, $studentId]);
        if ($stmt->fetch()) {
            return ['success' => false, 'message' => 'Student is already enrolled in this course.'];
        }
        // Enroll
        $stmt = $db->prepare("INSERT INTO course_enrollments (course_id, student_id, status, enrollment_date) VALUES (?, ?, 'enrolled', NOW())");
        if ($stmt->execute([$courseId, $studentId])) {
            return ['success' => true, 'message' => 'Student enrolled successfully.'];
        } else {
            return ['success' => false, 'message' => 'Failed to enroll student.'];
        }
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

function unenrollStudent($db, $enrollmentId, $instructorId) {
    try {
        // Check if enrollment belongs to instructor's course
        $stmt = $db->prepare("SELECT ce.id FROM course_enrollments ce JOIN courses c ON ce.course_id = c.id WHERE ce.id = ? AND c.instructor_id = ?");
        $stmt->execute([$enrollmentId, $instructorId]);
        if (!$stmt->fetch()) {
            return ['success' => false, 'message' => 'Enrollment not found or access denied.'];
        }
        // Unenroll
        $stmt = $db->prepare("UPDATE course_enrollments SET status = 'dropped', updated_at = NOW() WHERE id = ?");
        if ($stmt->execute([$enrollmentId])) {
            return ['success' => true, 'message' => 'Student unenrolled successfully.'];
        } else {
            return ['success' => false, 'message' => 'Failed to unenroll student.'];
        }
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

// Exam enrollment functions
function enrollExamStudent($db, $examId, $studentId, $instructorId) {
    try {
        // Check if exam belongs to instructor
        $stmt = $db->prepare("SELECT id FROM exams WHERE id = ? AND instructor_id = ?");
        $stmt->execute([$examId, $instructorId]);
        if (!$stmt->fetch()) {
            return ['success' => false, 'message' => 'You do not own this exam.'];
        }
        // Check if already has access
        $stmt = $db->prepare("SELECT id FROM exam_access WHERE exam_id = ? AND student_id = ?");
        $stmt->execute([$examId, $studentId]);
        if ($stmt->fetch()) {
            return ['success' => false, 'message' => 'Student already has access to this exam.'];
        }
        // Grant exam access
        $stmt = $db->prepare("INSERT INTO exam_access (exam_id, student_id, payment_status, access_granted_at) VALUES (?, ?, 'free', NOW())");
        if ($stmt->execute([$examId, $studentId])) {
            return ['success' => true, 'message' => 'Student granted exam access successfully.'];
        } else {
            return ['success' => false, 'message' => 'Failed to grant exam access.'];
        }
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

function unenrollExamStudent($db, $examAccessId, $instructorId) {
    try {
        // Check if exam access belongs to instructor's exam
        $stmt = $db->prepare("SELECT ea.id FROM exam_access ea JOIN exams e ON ea.exam_id = e.id WHERE ea.id = ? AND e.instructor_id = ?");
        $stmt->execute([$examAccessId, $instructorId]);
        if (!$stmt->fetch()) {
            return ['success' => false, 'message' => 'Exam access not found or access denied.'];
        }
        // Remove exam access
        $stmt = $db->prepare("DELETE FROM exam_access WHERE id = ?");
        if ($stmt->execute([$examAccessId])) {
            return ['success' => true, 'message' => 'Student exam access removed successfully.'];
        } else {
            return ['success' => false, 'message' => 'Failed to remove exam access.'];
        }
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

$page_title = 'My Students - ' . $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;
            /* Using min-h-screen utility class */
        }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0; /* Always positioned at 0, use transform to hide */
                transform: translateX(-100%); /* Hidden by default on mobile */
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar {
                transform: translateX(0); /* Show on mobile */
            }
            .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;
        }

        /* Toast Notification Styles */
        #toast-container {
            position: fixed;
            top: 1.5rem;
            right: 1.5rem;
            z-index: 100;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            max-width: 350px;
        }

        .toast {
            padding: 1rem 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            color: white;
            opacity: 0;
            transform: translateX(100%);
            transition: opacity 0.3s ease-out, transform 0.3s ease-out;
        }

        .toast.show {
            opacity: 1;
            transform: translateX(0);
        }

        .toast-success { background-color: #10b981; }
        .toast-error { background-color: #ef4444; }

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

<!-- Toast Notification Container -->
<div id="toast-container"></div>

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

        <!-- Messages -->
        <?php if (isset($_SESSION['message'])): ?>
        <div class="bg-<?php echo $_SESSION['message_type'] === 'success' ? 'green' : 'red'; ?>-100 border border-<?php echo $_SESSION['message_type'] === 'success' ? 'green' : 'red'; ?>-400 text-<?php echo $_SESSION['message_type'] === 'success' ? 'green' : 'red'; ?>-700 px-4 py-3 rounded mb-6" role="alert">
            <?php echo htmlspecialchars($_SESSION['message']); ?>
        </div>
        <?php unset($_SESSION['message'], $_SESSION['message_type']); ?>
        <?php endif; ?>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                <h3 class="text-3xl font-bold text-blue-600"><?php echo $stats['total_students']; ?></h3>
                <p class="text-gray-500 mt-2">Total Students</p>
            </div>
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                <h3 class="text-3xl font-bold text-green-600"><?php echo $stats['total_enrollments']; ?></h3>
                <p class="text-gray-500 mt-2">Total Enrollments</p>
            </div>
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                <h3 class="text-3xl font-bold text-purple-600"><?php echo $stats['completed_enrollments']; ?></h3>
                <p class="text-gray-500 mt-2">Completed Courses</p>
            </div>
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                <h3 class="text-3xl font-bold text-yellow-600"><?php echo round($stats['avg_progress'] ?? 0); ?>%</h3>
                <p class="text-gray-500 mt-2">Average Progress</p>
            </div>
        </div>

        <!-- Filters and Search -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
            <form method="GET" class="flex flex-col lg:flex-row gap-4">
                <div class="flex-1">
                    <label for="search" class="block text-sm font-medium text-gray-700 mb-2">Search Students</label>
                    <input type="text" id="search" name="search" value="<?php echo htmlspecialchars($search); ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                           placeholder="Search by name, username, or email...">
                </div>
                <div>
                    <label for="course" class="block text-sm font-medium text-gray-700 mb-2">Filter by Course</label>
                    <select id="course" name="course" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <option value="">All Courses</option>
                        <?php foreach ($courses as $course): ?>
                            <option value="<?php echo $course['id']; ?>" <?php echo $courseFilter == $course['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($course['title']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="status" class="block text-sm font-medium text-gray-700 mb-2">Enrollment Status</label>
                    <select id="status" name="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <option value="">All Statuses</option>
                        <option value="enrolled" <?php echo $statusFilter === 'enrolled' ? 'selected' : ''; ?>>Enrolled</option>
                        <option value="in_progress" <?php echo $statusFilter === 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
                        <option value="completed" <?php echo $statusFilter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                        <option value="dropped" <?php echo $statusFilter === 'dropped' ? 'selected' : ''; ?>>Dropped</option>
                    </select>
                </div>
                <div class="flex items-end">
                    <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200">
                        <i class="fas fa-search mr-2"></i>Filter
                    </button>
                </div>
            </form>
        </div>

        <!-- Enroll Student Section -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">Enroll a Student</h3>
            <form method="POST" class="flex flex-col lg:flex-row gap-4">
                <input type="hidden" name="action" value="enroll">
                <div class="flex-1">
                    <label for="enroll_course" class="block text-sm font-medium text-gray-700 mb-2">Select Course</label>
                    <select id="enroll_course" name="course_id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                        <option value="">Choose a course</option>
                        <?php foreach ($courses as $course): ?>
                            <option value="<?php echo $course['id']; ?>"><?php echo htmlspecialchars($course['title']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="flex-1">
                    <label for="student_email" class="block text-sm font-medium text-gray-700 mb-2">Student Email</label>
                    <input type="email" id="student_email" name="student_email" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="student@example.com" required>
                </div>
                <div class="flex items-end">
                    <button type="submit" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition duration-200">
                        <i class="fas fa-user-plus mr-2"></i>Enroll Student
                    </button>
                </div>
            </form>
        </div>

        <!-- Students Table -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <?php if (empty($students)): ?>
                <div class="text-center py-12">
                    <i class="fas fa-users text-6xl text-gray-400 mb-4"></i>
                    <h4 class="text-xl font-semibold text-gray-800 mb-2">No students found</h4>
                    <p class="text-gray-500">No students are currently enrolled in your courses.</p>
                </div>
            <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Student</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Course</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Progress</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Enrolled</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($students as $student): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center flex-shrink-0">
                                                <i class="fas fa-user text-gray-500"></i>
                                            </div>
                                            <div class="ml-4">
                                                <div class="text-sm font-medium text-gray-900">
                                                    <?php echo htmlspecialchars($student['first_name'] && $student['last_name'] ? $student['first_name'] . ' ' . $student['last_name'] : $student['username']); ?>
                                                </div>
                                                <div class="text-sm text-gray-500"><?php echo htmlspecialchars($student['email']); ?></div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm text-gray-900"><?php echo htmlspecialchars($student['course_title']); ?></div>
                                        <div class="text-sm text-gray-500 capitalize"><?php echo $student['course_level']; ?> level</div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="flex-1 mr-4">
                                                <div class="progress-bar">
                                                    <div class="progress-fill" style="width: <?php echo $student['progress_percentage']; ?>%"></div>
                                                </div>
                                            </div>
                                            <span class="text-sm text-gray-500"><?php echo $student['progress_percentage']; ?>%</span>
                                        </div>
                                        <div class="text-xs text-gray-400 mt-1">
                                            <?php echo $student['completed_lessons']; ?>/<?php echo $student['total_lessons']; ?> lessons
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full
                                            <?php
                                            switch($student['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('_', ' ', $student['enrollment_status'])); ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                        <?php echo date('M j, Y', strtotime($student['enrollment_date'])); ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                        <div class="flex space-x-2">
                                            <button onclick="viewStudentProgress(<?php echo $student['student_id']; ?>, <?php echo $student['course_id']; ?>)"
                                                    class="text-blue-600 hover:text-blue-900" title="View Progress">
                                                <i class="fas fa-chart-line"></i>
                                            </button>
                                            <button onclick="contactStudent(<?php echo $student['student_id']; ?>)"
                                                    class="text-green-600 hover:text-green-900" title="Contact Student">
                                                <i class="fas fa-envelope"></i>
                                            </button>
                                            <form method="POST" style="display:inline;" onsubmit="return confirm('Are you sure you want to unenroll this student?')">
                                                <input type="hidden" name="action" value="unenroll">
                                                <input type="hidden" name="enrollment_id" value="<?php echo $student['enrollment_id']; ?>">
                                                <button type="submit" class="text-red-600 hover:text-red-900" title="Unenroll Student">
                                                    <i class="fas fa-user-times"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- Exam Enrollments Section -->
        <div class="mb-8">
            <!-- Tab Navigation -->
            <div class="flex border-b border-gray-200 mb-6">
                <button id="tab-courses" class="px-6 py-3 text-sm font-medium text-blue-600 border-b-2 border-blue-600" onclick="switchTab('courses')">
                    <i class="fas fa-book mr-2"></i>Course Enrollments
                </button>
                <button id="tab-exams" class="px-6 py-3 text-sm font-medium text-gray-500 hover:text-gray-700" onclick="switchTab('exams')">
                    <i class="fas fa-file-alt mr-2"></i>Exam Enrollments
                </button>
            </div>

            <!-- Exam Statistics Cards -->
            <div id="exam-stats" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                    <h3 class="text-3xl font-bold text-blue-600"><?php echo $examStats['total_students']; ?></h3>
                    <p class="text-gray-500 mt-2">Total Exam Students</p>
                </div>
                <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                    <h3 class="text-3xl font-bold text-green-600"><?php echo $examStats['total_enrollments']; ?></h3>
                    <p class="text-gray-500 mt-2">Total Exam Access</p>
                </div>
                <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                    <h3 class="text-3xl font-bold text-purple-600"><?php echo $examStats['purchased_access']; ?></h3>
                    <p class="text-gray-500 mt-2">Purchased Access</p>
                </div>
                <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                    <h3 class="text-3xl font-bold text-yellow-600"><?php echo $examStats['total_attempts']; ?></h3>
                    <p class="text-gray-500 mt-2">Total Attempts</p>
                </div>
            </div>

            <!-- Exam Filters and Search -->
            <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
                <form method="GET" class="flex flex-col lg:flex-row gap-4">
                    <div class="flex-1">
                        <label for="exam_search" class="block text-sm font-medium text-gray-700 mb-2">Search Students</label>
                        <input type="text" id="exam_search" name="exam_search" value="<?php echo htmlspecialchars($_GET['exam_search'] ?? ''); ?>"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                               placeholder="Search by name, username, or email...">
                    </div>
                    <div>
                        <label for="exam" class="block text-sm font-medium text-gray-700 mb-2">Filter by Exam</label>
                        <select id="exam" name="exam" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <option value="">All Exams</option>
                            <?php foreach ($exams as $exam): ?>
                                <option value="<?php echo $exam['id']; ?>" <?php echo $examFilter == $exam['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($exam['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="exam_status" class="block text-sm font-medium text-gray-700 mb-2">Access Type</label>
                        <select id="exam_status" name="exam_status" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <option value="">All Types</option>
                            <option value="free" <?php echo $examStatusFilter === 'free' ? 'selected' : ''; ?>>Free Access</option>
                            <option value="completed" <?php echo $examStatusFilter === 'completed' ? 'selected' : ''; ?>>Purchased</option>
                            <option value="has_access" <?php echo $examStatusFilter === 'has_access' ? 'selected' : ''; ?>>Has Access</option>
                        </select>
                    </div>
                    <div class="flex items-end">
                        <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200">
                            <i class="fas fa-search mr-2"></i>Filter
                        </button>
                    </div>
                </form>
            </div>

            <!-- Enroll Student for Exam Section -->
            <?php if (!empty($exams)): ?>
            <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">Grant Exam Access</h3>
                <form method="POST" class="flex flex-col lg:flex-row gap-4">
                    <input type="hidden" name="action" value="enroll_exam">
                    <div class="flex-1">
                        <label for="enroll_exam" class="block text-sm font-medium text-gray-700 mb-2">Select Exam</label>
                        <select id="enroll_exam" name="exam_id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                            <option value="">Choose an exam</option>
                            <?php foreach ($exams as $exam): ?>
                                <option value="<?php echo $exam['id']; ?>"><?php echo htmlspecialchars($exam['title']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="flex-1">
                        <label for="exam_student_email" class="block text-sm font-medium text-gray-700 mb-2">Student Email</label>
                        <input type="email" id="exam_student_email" name="student_email" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="student@example.com" required>
                    </div>
                    <div class="flex items-end">
                        <button type="submit" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition duration-200">
                            <i class="fas fa-user-plus mr-2"></i>Grant Access
                        </button>
                    </div>
                </form>
            </div>
            <?php endif; ?>

            <!-- Exam Enrollments Table -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                <?php if (empty($examEnrollments)): ?>
                    <div class="text-center py-12">
                        <i class="fas fa-file-alt text-6xl text-gray-400 mb-4"></i>
                        <h4 class="text-xl font-semibold text-gray-800 mb-2">No exam enrollments found</h4>
                        <p class="text-gray-500">No students have been granted access to your exams yet.</p>
                    </div>
                <?php else: ?>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Student</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Exam</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Access Type</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Attempts</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Best Score</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Access Granted</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php foreach ($examEnrollments as $examEnrollment): ?>
                                    <tr class="hover:bg-gray-50">
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="flex items-center">
                                                <div class="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center flex-shrink-0">
                                                    <i class="fas fa-user text-gray-500"></i>
                                                </div>
                                                <div class="ml-4">
                                                    <div class="text-sm font-medium text-gray-900">
                                                        <?php echo htmlspecialchars($examEnrollment['first_name'] && $examEnrollment['last_name'] ? $examEnrollment['first_name'] . ' ' . $examEnrollment['last_name'] : $examEnrollment['username']); ?>
                                                    </div>
                                                    <div class="text-sm text-gray-500"><?php echo htmlspecialchars($examEnrollment['email']); ?></div>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <div class="text-sm text-gray-900"><?php echo htmlspecialchars($examEnrollment['exam_title']); ?></div>
                                            <div class="text-sm text-gray-500">
                                                <?php echo $examEnrollment['time_limit']; ?> min | Pass: <?php echo $examEnrollment['passing_score']; ?>%
                                            </div>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full
                                                <?php
                                                switch($examEnrollment['payment_status']) {
                                                    case 'paid': echo 'bg-green-100 text-green-800'; break;
                                                    case 'free': echo 'bg-blue-100 text-blue-800'; break;
                                                    case 'pending': echo 'bg-yellow-100 text-yellow-800'; break;
                                                    default: echo 'bg-gray-100 text-gray-800';
                                                }
                                                ?>">
                                                <?php echo ucfirst($examEnrollment['payment_status']); ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            <?php echo $examEnrollment['attempt_count']; ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            <?php echo $examEnrollment['best_score'] ? $examEnrollment['best_score'] . '%' : '-'; ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            <?php echo date('M j, Y', strtotime($examEnrollment['access_granted_at'])); ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                            <div class="flex space-x-2">
                                                <a href="exams/attempts.php?exam_id=<?php echo $examEnrollment['exam_id']; ?>&student_id=<?php echo $examEnrollment['student_id']; ?>"
                                                   class="text-blue-600 hover:text-blue-900" title="View Attempts">
                                                    <i class="fas fa-list-alt"></i>
                                                </a>
                                                <form method="POST" style="display:inline;" onsubmit="return confirm('Are you sure you want to remove this student\'s exam access?')">
                                                    <input type="hidden" name="action" value="unenroll_exam">
                                                    <input type="hidden" name="exam_access_id" value="<?php echo $examEnrollment['exam_access_id']; ?>">
                                                    <button type="submit" class="text-red-600 hover:text-red-900" title="Remove Access">
                                                        <i class="fas fa-user-times"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>

<!-- Custom Confirmation Modal (Hidden by default) -->
<div id="confirmation-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white p-6 rounded-lg shadow-2xl max-w-sm w-full transform transition-all">
        <h3 class="text-xl font-bold text-gray-800 mb-4" id="modal-title">Confirm Action</h3>
        <p class="text-gray-600 mb-6" id="modal-message">Are you sure you want to perform this action?</p>
        <div class="flex justify-end space-x-3">
            <button id="modal-cancel" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition">Cancel</button>
            <button id="modal-confirm" class="px-4 py-2 text-white rounded-md transition"></button>
        </div>
    </div>
</div>


<script>
    // --- UI/Utility Functions ---

    // Tab switching functionality
    function switchTab(tab) {
        const coursesTab = document.getElementById('tab-courses');
        const examsTab = document.getElementById('tab-exams');
        
        if (tab === 'courses') {
            coursesTab.className = 'px-6 py-3 text-sm font-medium text-blue-600 border-b-2 border-blue-600';
            examsTab.className = 'px-6 py-3 text-sm font-medium text-gray-500 hover:text-gray-700';
            // Show course elements, hide exam elements
            document.querySelectorAll('.bg-white.rounded-xl.shadow-lg').forEach((el, index) => {
                if (index < 4) el.style.display = ''; // Course sections
            });
            document.getElementById('exam-stats').style.display = 'none';
            // Hide exam enrollments section (last .bg-white element after stats)
            const examEnrollmentsDiv = document.querySelector('#exam-stats').nextElementSibling;
            while (examEnrollmentsDiv && !examEnrollmentsDiv.classList.contains('bg-white')) {
                examEnrollmentsDiv = examEnrollmentsDiv.nextElementSibling;
            }
            if (examEnrollmentsDiv) examEnrollmentsDiv.style.display = 'none';
        } else {
            examsTab.className = 'px-6 py-3 text-sm font-medium text-blue-600 border-b-2 border-blue-600';
            coursesTab.className = 'px-6 py-3 text-sm font-medium text-gray-500 hover:text-gray-700';
            // Show exam elements, hide course elements
            document.querySelectorAll('.bg-white.rounded-xl.shadow-lg').forEach((el, index) => {
                if (index >= 4) el.style.display = ''; // Exam sections
            });
            document.getElementById('exam-stats').style.display = '';
            // Show exam enrollments section
            const examEnrollmentsDiv = document.querySelector('#exam-stats').nextElementSibling;
            while (examEnrollmentsDiv && !examEnrollmentsDiv.classList.contains('bg-white')) {
                examEnrollmentsDiv = examEnrollmentsDiv.nextElementSibling;
            }
            if (examEnrollmentsDiv) examEnrollmentsDiv.style.display = '';
        }
    }

    // Function to show a dismissible toast notification
    function showToast(message, type = 'success') {
        const container = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`; // Note: 'show' added below
        toast.innerHTML = `<i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} mr-2"></i>${message}`;
        container.appendChild(toast);

        // Force repaint to start transition
        setTimeout(() => toast.classList.add('show'), 10);

        // Auto-dismiss after 4 seconds
        setTimeout(() => {
            toast.classList.remove('show');
            // Remove from DOM after transition finishes
            setTimeout(() => toast.remove(), 300);
        }, 4000);
    }

    // Function to handle the custom confirmation modal (replacing window.confirm)
    function showConfirmationModal(action, reviewId) {
        const modal = document.getElementById('confirmation-modal');
        const title = document.getElementById('modal-title');
        const message = document.getElementById('modal-message');
        const confirmButton = document.getElementById('modal-confirm');
        const cancelButton = document.getElementById('modal-cancel');

        const isApprove = action === 'approve';
        const actionText = isApprove ? 'Approve' : 'Reject';

        // Placeholder function to simulate the PHP action
        const performAction = () => {
            // In a real application, this would be an AJAX call:
            // fetch('api/review_action.php', { method: 'POST', body: JSON.stringify({ action: action, review_id: reviewId }) })
            // .then(response => response.json()).then(data => { ... })
            fetch('../api/reviews.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: action,
                    review_id: reviewId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(`Review ${actionText.toLowerCase()}d successfully.`, 'success');
                    modal.classList.add('hidden');
                    modal.classList.remove('flex');
                    // Reload or remove the review item from the UI
                    location.reload();
                } else {
                    showToast('Error: ' + data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            });
        };

        // Set modal content
        title.textContent = `Confirm ${actionText}`;
        message.textContent = `Are you sure you want to ${actionText.toLowerCase()} this review? This action cannot be undone. (Review ID: ${reviewId})`;
        confirmButton.textContent = actionText;
        confirmButton.className = `px-4 py-2 text-white rounded-md transition ${isApprove ? 'bg-green-500 hover:bg-green-600' : 'bg-red-500 hover:bg-red-600'}`;

        // Show modal
        modal.classList.remove('hidden');
        modal.classList.add('flex');

        // Set listeners
        confirmButton.onclick = performAction;
        cancelButton.onclick = () => {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        };

        // Allow clicking the overlay to close
        document.getElementById('sidebar-overlay').onclick = () => {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        };
    }

    // Mobile Menu Functionality
    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');
            });
        });
    }

    // Student actions
    function viewStudentProgress(studentId, courseId) {
        // Redirect to student progress page (to be implemented)
        window.location.href = `student_progress.php?student_id=${studentId}&course_id=${courseId}`;
    }

    function contactStudent(studentId) {
        // Open contact modal or redirect to messaging system
        alert('Contact functionality will be implemented. Student ID: ' + studentId);
    }
</script>

</body>
</html>