<?php
include '../config.php';

if (!isGuru()) {
    redirect('../login.php');
}

$guru_id = $_SESSION['user_id'];

// Get course ID from URL if specified
$course_id = isset($_GET['course_id']) ? intval($_GET['course_id']) : 0;
$filter_course = $course_id > 0 ? $course_id : null;

// Build query for lms_courses taught by this guru
$sql_lms_courses = "SELECT id, judul FROM lms_courses WHERE id_guru = ? ORDER BY judul";
$stmt_lms_courses = $conn->prepare($sql_lms_courses);
$stmt_lms_courses->bind_param('i', $guru_id);
$stmt_lms_courses->execute();
$lms_courses = $stmt_lms_courses->get_result();

// Build main query for student progress
$sql_progress = "SELECT 
    e.id as enrollment_id,
    e.id_siswa,
    e.id_course,
    e.progress,
    e.status,
    e.tanggal_enroll,
    e.tanggal_selesai,
    u.nama_lengkap as nama_siswa,
    u.email as email_siswa,
    u.foto_profil,
    c.judul as judul_course,
    cat.nama_kategori,
    c.level,
    (SELECT COUNT(*) FROM lms_lessons WHERE id_course = c.id) as total_lms_lessons,
    (SELECT COUNT(DISTINCT id_siswa) FROM lms_enrollments WHERE id_course = c.id) as total_students
    FROM lms_enrollments e
    LEFT JOIN lms_users u ON e.id_siswa = u.id
    LEFT JOIN lms_courses c ON e.id_course = c.id
    LEFT JOIN lms_categories cat ON c.id_kategori = cat.id
    WHERE c.id_guru = ?";

$params = [$guru_id];
$types = "i";

// Apply course filter if specified
if ($filter_course) {
    $sql_progress .= " AND e.id_course = ?";
    $params[] = $filter_course;
    $types .= "i";
}

$sql_progress .= " ORDER BY e.tanggal_enroll DESC";

$stmt_progress = $conn->prepare($sql_progress);
if (!empty($params)) {
    $stmt_progress->bind_param($types, ...$params);
}
$stmt_progress->execute();
$progress_data = $stmt_progress->get_result();

// Calculate overall statistics
$sql_stats = "SELECT 
    COUNT(DISTINCT e.id_siswa) as total_students,
    COUNT(DISTINCT e.id_course) as total_lms_courses,
    AVG(e.progress) as avg_progress,
    COUNT(CASE WHEN e.progress = 100 THEN 1 END) as completed_lms_courses,
    COUNT(CASE WHEN e.progress >= 50 AND e.progress < 100 THEN 1 END) as in_progress_lms_courses,
    COUNT(CASE WHEN e.progress < 50 THEN 1 END) as just_started_lms_courses
    FROM lms_enrollments e
    LEFT JOIN lms_courses c ON e.id_course = c.id
    WHERE c.id_guru = ?";

if ($filter_course) {
    $sql_stats .= " AND e.id_course = ?";
}

$stmt_stats = $conn->prepare($sql_stats);
if ($filter_course) {
    $stmt_stats->bind_param('ii', $guru_id, $filter_course);
} else {
    $stmt_stats->bind_param('i', $guru_id);
}
$stmt_stats->execute();
$stats = $stmt_stats->get_result()->fetch_assoc();

// Get recent activities
$sql_activities = "SELECT 
    qa.id_siswa,
    qa.id_quiz,
    qa.nilai,
    qa.waktu_selesai,
    u.nama_lengkap as nama_siswa,
    c.judul as judul_course,
    q.judul_quiz,
    q.passing_grade
    FROM lms_quiz_attempts qa
    LEFT JOIN lms_users u ON qa.id_siswa = u.id
    LEFT JOIN lms_quizzes q ON qa.id_quiz = q.id
    LEFT JOIN lms_lessons l ON q.id_lesson = l.id
    LEFT JOIN lms_courses c ON l.id_course = c.id
    WHERE c.id_guru = ? AND qa.status = 'completed'
    ORDER BY qa.waktu_selesai DESC 
    LIMIT 5";

$stmt_activities = $conn->prepare($sql_activities);
$stmt_activities->bind_param('i', $guru_id);
$stmt_activities->execute();
$recent_activities = $stmt_activities->get_result();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Progress Siswa - SMANSAB LMS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #3f51b5;
            --secondary-color: #f5f5f5;
        }
        
        .sidebar {
            background: var(--primary-color);
            color: white;
            min-height: 100vh;
            padding: 0;
        }
        
        .sidebar-sticky {
            position: sticky;
            top: 0;
            height: 100vh;
            padding-top: 20px;
            overflow-y: auto;
        }
        
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            margin: 2px 0;
            border-radius: 0;
            transition: all 0.3s;
        }
        
        .sidebar .nav-link:hover {
            color: white;
            background: rgba(255, 255, 255, 0.1);
        }
        
        .sidebar .nav-link.active {
            color: white;
            background: rgba(255, 255, 255, 0.2);
            border-left: 4px solid #fff;
        }
        
        .sidebar .nav-link i {
            width: 20px;
            margin-right: 10px;
        }
        
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        
        .navbar-custom {
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border: none;
        }
        
        .progress-course {
            height: 8px;
            border-radius: 4px;
        }
        
        .student-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
        }
        
        .avatar-placeholder {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }
        
        .level-badge {
            font-size: 0.7rem;
            padding: 4px 8px;
        }
        
        .bg-beginner { background: #28a745 !important; }
        .bg-intermediate { background: #ffc107 !important; color: #000 !important; }
        .bg-advanced { background: #dc3545 !important; }
        
        .progress-table tbody tr {
            transition: all 0.3s;
        }
        
        .progress-table tbody tr:hover {
            background-color: #f8f9fa;
        }
        
        .activity-card {
            border-left: 4px solid var(--primary-color);
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .filter-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .export-btn {
            background: linear-gradient(45deg, #28a745, #20c997);
            border: none;
            color: white;
        }
        
        .progress-indicator {
            width: 80px;
        }
        
        .status-badge {
            font-size: 0.75rem;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }
        
        .empty-state i {
            font-size: 4rem;
            color: #6c757d;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 sidebar">
                <div class="sidebar-sticky">
                    <div class="text-center mb-4">
                        <h4 class="fw-bold">
                            <i class="bi bi-book-half"></i><br>
                            SMANSAB LMS
                        </h4>
                        <small class="text-white-50">Guru Dashboard</small>
                    </div>
                    
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="bi bi-speedometer2"></i> Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="my_courses.php">
                                <i class="bi bi-journal-bookmark"></i> Kursus Saya
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="manage_lessons.php">
                                <i class="bi bi-collection-play"></i> Kelola Materi
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="manage_quizzes.php">
                                <i class="bi bi-pencil-square"></i> Kelola Kuis
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="students_progress.php">
                                <i class="bi bi-graph-up"></i> Progress Siswa
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="profile.php">
                                <i class="bi bi-person"></i> Profil Saya
                            </a>
                        </li>
                        <li class="nav-item mt-4">
                            <a class="nav-link" href="../logout.php">
                                <i class="bi bi-box-arrow-right"></i> Logout
                            </a>
                        </li>
                    </ul>
                    
                    <div class="mt-5 px-3">
                        <small class="text-white-50">
                            <i class="bi bi-info-circle"></i> Butuh bantuan?
                            <a href="#" class="text-white">Hubungi Admin</a>
                        </small>
                    </div>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 main-content">
                <!-- Top Navbar -->
                <nav class="navbar navbar-custom">
                    <div class="container-fluid">
                        <div class="d-flex align-items-center">
                            <button class="btn btn-outline-primary me-3 d-md-none" type="button">
                                <i class="bi bi-list"></i>
                            </button>
                            <h5 class="mb-0">Progress Siswa</h5>
                        </div>
                        <div class="d-flex align-items-center">
                            <div class="dropdown">
                                <button class="btn btn-outline-primary dropdown-toggle" type="button" 
                                        data-bs-toggle="dropdown">
                                    <i class="bi bi-person-circle me-2"></i>
                                    <?php echo $_SESSION['nama_lengkap']; ?>
                                </button>
                                <ul class="dropdown-menu">
                                    <li><a class="dropdown-item" href="profile.php">
                                        <i class="bi bi-person me-2"></i>Profil
                                    </a></li>
                                    <li><a class="dropdown-item" href="my_courses.php">
                                        <i class="bi bi-journal-bookmark me-2"></i>Kursus Saya
                                    </a></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item" href="../logout.php">
                                        <i class="bi bi-box-arrow-right me-2"></i>Logout
                                    </a></li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </nav>

                <div class="container-fluid mt-4">
                    <!-- Header Section -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h4 class="fw-bold">Progress Siswa</h4>
                                    <p class="text-muted mb-0">Pantau perkembangan dan pencapaian siswa Anda</p>
                                </div>
                                <div class="dropdown">
                                    <button class="btn export-btn dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                        <i class="bi bi-download me-2"></i>Ekspor Data
                                    </button>
                                    <ul class="dropdown-menu">
                                        <li><a class="dropdown-item" href="#">
                                            <i class="bi bi-file-earmark-excel me-2"></i>Excel
                                        </a></li>
                                        <li><a class="dropdown-item" href="#">
                                            <i class="bi bi-file-earmark-pdf me-2"></i>PDF
                                        </a></li>
                                        <li><a class="dropdown-item" href="#">
                                            <i class="bi bi-file-earmark-text me-2"></i>CSV
                                        </a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-people display-6 text-primary mb-3"></i>
                                <h3 class="fw-bold"><?php echo $stats['total_students'] ?? 0; ?></h3>
                                <p class="text-muted mb-0">Total Siswa</p>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-journal-bookmark display-6 text-success mb-3"></i>
                                <h3 class="fw-bold"><?php echo $stats['total_lms_courses'] ?? 0; ?></h3>
                                <p class="text-muted mb-0">Total Kursus</p>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-graph-up display-6 text-warning mb-3"></i>
                                <h3 class="fw-bold"><?php echo number_format($stats['avg_progress'] ?? 0, 1); ?>%</h3>
                                <p class="text-muted mb-0">Progress Rata-rata</p>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-check-circle display-6 text-info mb-3"></i>
                                <h3 class="fw-bold"><?php echo $stats['completed_lms_courses'] ?? 0; ?></h3>
                                <p class="text-muted mb-0">Selesai</p>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-arrow-right-circle display-6 text-primary mb-3"></i>
                                <h3 class="fw-bold"><?php echo $stats['in_progress_lms_courses'] ?? 0; ?></h3>
                                <p class="text-muted mb-0">Sedang Berjalan</p>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-play-circle display-6 text-secondary mb-3"></i>
                                <h3 class="fw-bold"><?php echo $stats['just_started_lms_courses'] ?? 0; ?></h3>
                                <p class="text-muted mb-0">Baru Mulai</p>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="filter-card">
                        <div class="row">
                            <div class="col-md-6">
                                <h6 class="fw-bold mb-3">Filter berdasarkan Kursus:</h6>
                                <form method="GET" class="d-flex">
                                    <select class="form-select me-2" name="course_id" onchange="this.form.submit()">
                                        <option value="">Semua Kursus</option>
                                        <?php while($course = $lms_courses->fetch_assoc()): ?>
                                            <option value="<?php echo $course['id']; ?>" 
                                                <?php echo $filter_course == $course['id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($course['judul']); ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                    <?php if ($filter_course): ?>
                                        <a href="students_progress.php" class="btn btn-outline-secondary">
                                            <i class="bi bi-x-circle"></i>
                                        </a>
                                    <?php endif; ?>
                                </form>
                            </div>
                            <div class="col-md-6">
                                <h6 class="fw-bold mb-3">Cari Siswa:</h6>
                                <div class="input-group">
                                    <input type="text" class="form-control" placeholder="Nama siswa atau email...">
                                    <button class="btn btn-primary" type="button">
                                        <i class="bi bi-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Main Progress Table -->
                        <div class="col-lg-8">
                            <div class="stats-card">
                                <div class="d-flex justify-content-between align-items-center mb-4">
                                    <h5 class="fw-bold mb-0">
                                        Daftar Progress Siswa
                                        <?php if ($filter_course): ?>
                                            <small class="text-muted">(Filtered)</small>
                                        <?php endif; ?>
                                    </h5>
                                    <span class="badge bg-primary">
                                        <?php echo $progress_data->num_rows; ?> Data
                                    </span>
                                </div>

                                <?php if ($progress_data->num_rows > 0): ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover progress-table">
                                            <thead>
                                                <tr>
                                                    <th>Siswa</th>
                                                    <th>Kursus</th>
                                                    <th>Progress</th>
                                                    <th>Status</th>
                                                    <th>Tanggal Daftar</th>
                                                    <th>Aksi</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while($progress = $progress_data->fetch_assoc()): ?>
                                                    <tr>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <?php if (!empty($progress['foto_profil'])): ?>
                                                                    <img src="../<?php echo $progress['foto_profil']; ?>" 
                                                                         alt="<?php echo htmlspecialchars($progress['nama_siswa']); ?>" 
                                                                         class="student-avatar me-3">
                                                                <?php else: ?>
                                                                    <div class="avatar-placeholder me-3">
                                                                        <?php echo strtoupper(substr($progress['nama_siswa'], 0, 1)); ?>
                                                                    </div>
                                                                <?php endif; ?>
                                                                <div>
                                                                    <div class="fw-semibold"><?php echo htmlspecialchars($progress['nama_siswa']); ?></div>
                                                                    <small class="text-muted"><?php echo $progress['email_siswa']; ?></small>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <div>
                                                                <div class="fw-semibold"><?php echo htmlspecialchars($progress['judul_course']); ?></div>
                                                                <div class="d-flex gap-1 mt-1">
                                                                    <span class="badge bg-light text-dark small">
                                                                        <?php echo $progress['nama_kategori']; ?>
                                                                    </span>
                                                                    <span class="badge <?php echo 'bg-' . ($progress['level'] === 'pemula' ? 'beginner' : ($progress['level'] === 'menengah' ? 'intermediate' : 'advanced')); ?> level-badge">
                                                                        <?php echo ucfirst($progress['level']); ?>
                                                                    </span>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <div class="progress-indicator">
                                                                <div class="d-flex justify-content-between mb-1">
                                                                    <small class="text-muted"><?php echo $progress['progress']; ?>%</small>
                                                                </div>
                                                                <div class="progress progress-course">
                                                                    <div class="progress-bar 
                                                                        <?php echo $progress['progress'] >= 80 ? 'bg-success' : 
                                                                              ($progress['progress'] >= 50 ? 'bg-warning' : 'bg-primary'); ?>" 
                                                                         style="width: <?php echo $progress['progress']; ?>%">
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <?php 
                                                            $status_class = [
                                                                'active' => 'bg-primary',
                                                                'completed' => 'bg-success',
                                                                'dropped' => 'bg-danger'
                                                            ];
                                                            $status_text = [
                                                                'active' => 'Aktif',
                                                                'completed' => 'Selesai',
                                                                'dropped' => 'Berhenti'
                                                            ];
                                                            ?>
                                                            <span class="badge <?php echo $status_class[$progress['status']] ?? 'bg-secondary'; ?> status-badge">
                                                                <?php echo $status_text[$progress['status']] ?? $progress['status']; ?>
                                                            </span>
                                                            <!-- PERBAIKAN: Cek apakah tanggal_selesai tidak NULL -->
                                                            <?php if ($progress['progress'] == 100 && $progress['status'] == 'completed' && !empty($progress['tanggal_selesai'])): ?>
                                                                <br>
                                                                <small class="text-muted">
                                                                    <?php echo date('d M Y', strtotime($progress['tanggal_selesai'])); ?>
                                                                </small>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <small class="text-muted">
                                                                <?php echo date('d M Y', strtotime($progress['tanggal_enroll'])); ?>
                                                            </small>
                                                        </td>
                                                        <td>
                                                            <div class="dropdown">
                                                                <button class="btn btn-sm btn-outline-primary dropdown-toggle" 
                                                                        type="button" data-bs-toggle="dropdown">
                                                                    <i class="bi bi-three-dots"></i>
                                                                </button>
                                                                <ul class="dropdown-menu">
                                                                    <li>
                                                                        <a class="dropdown-item" href="#" data-bs-toggle="modal" 
                                                                           data-bs-target="#studentDetailModal" 
                                                                           data-student-name="<?php echo htmlspecialchars($progress['nama_siswa']); ?>"
                                                                           data-course-name="<?php echo htmlspecialchars($progress['judul_course']); ?>"
                                                                           data-progress="<?php echo $progress['progress']; ?>">
                                                                            <i class="bi bi-eye me-2"></i>Detail
                                                                        </a>
                                                                    </li>
                                                                    <li>
                                                                        <a class="dropdown-item" href="#">
                                                                            <i class="bi bi-envelope me-2"></i>Kirim Pesan
                                                                        </a>
                                                                    </li>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    <li>
                                                                        <a class="dropdown-item text-warning" href="#">
                                                                            <i class="bi bi-exclamation-triangle me-2"></i>Tandai
                                                                        </a>
                                                                    </li>
                                                                </ul>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php else: ?>
                                    <div class="empty-state">
                                        <i class="bi bi-people display-1 text-muted"></i>
                                        <h4 class="text-muted mt-3">Belum ada data progress</h4>
                                        <p class="text-muted">
                                            <?php if ($filter_course): ?>
                                                Tidak ada siswa yang terdaftar di kursus ini
                                            <?php else: ?>
                                                Belum ada siswa yang mendaftar ke kursus Anda
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Sidebar - Recent Activities & Quick Stats -->
                        <div class="col-lg-4">
                            <!-- Recent Activities -->
                            <div class="stats-card">
                                <h5 class="fw-bold mb-4">
                                    <i class="bi bi-clock-history me-2"></i>Aktivitas Terbaru
                                </h5>
                                
                                <?php if ($recent_activities->num_rows > 0): ?>
                                    <div class="activities-list">
                                        <?php while($activity = $recent_activities->fetch_assoc()): ?>
                                            <div class="activity-card">
                                                <div class="d-flex justify-content-between align-items-start mb-2">
                                                    <h6 class="fw-bold mb-0"><?php echo htmlspecialchars($activity['nama_siswa']); ?></h6>
                                                    <span class="badge <?php echo $activity['nilai'] >= $activity['passing_grade'] ? 'bg-success' : 'bg-danger'; ?>">
                                                        <?php echo $activity['nilai']; ?>
                                                    </span>
                                                </div>
                                                <p class="small text-muted mb-2">Menyelesaikan kuis: <?php echo htmlspecialchars($activity['judul_quiz']); ?></p>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <small class="text-muted"><?php echo htmlspecialchars($activity['judul_course']); ?></small>
                                                    <small class="text-muted">
                                                        <?php echo date('H:i', strtotime($activity['waktu_selesai'])); ?>
                                                    </small>
                                                </div>
                                            </div>
                                        <?php endwhile; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="text-center py-3">
                                        <i class="bi bi-inbox display-4 text-muted"></i>
                                        <p class="text-muted mt-2 mb-0">Belum ada aktivitas terbaru</p>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Progress Distribution -->
                            <div class="stats-card">
                                <h5 class="fw-bold mb-4">Distribusi Progress</h5>
                                <div class="distribution-chart">
                                    <?php
                                    $total_lms_enrollments = $progress_data->num_rows;
                                    $completed_percent = $total_lms_enrollments > 0 ? ($stats['completed_lms_courses'] / $total_lms_enrollments) * 100 : 0;
                                    $in_progress_percent = $total_lms_enrollments > 0 ? ($stats['in_progress_lms_courses'] / $total_lms_enrollments) * 100 : 0;
                                    $just_started_percent = $total_lms_enrollments > 0 ? ($stats['just_started_lms_courses'] / $total_lms_enrollments) * 100 : 0;
                                    ?>
                                    <div class="mb-3">
                                        <div class="d-flex justify-content-between mb-1">
                                            <small>Selesai (100%)</small>
                                            <small><?php echo $stats['completed_lms_courses'] ?? 0; ?></small>
                                        </div>
                                        <div class="progress progress-course">
                                            <div class="progress-bar bg-success" 
                                                 style="width: <?php echo $completed_percent; ?>%">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="d-flex justify-content-between mb-1">
                                            <small>Sedang Berjalan (50-99%)</small>
                                            <small><?php echo $stats['in_progress_lms_courses'] ?? 0; ?></small>
                                        </div>
                                        <div class="progress progress-course">
                                            <div class="progress-bar bg-warning" 
                                                 style="width: <?php echo $in_progress_percent; ?>%">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="d-flex justify-content-between mb-1">
                                            <small>Baru Mulai (0-49%)</small>
                                            <small><?php echo $stats['just_started_lms_courses'] ?? 0; ?></small>
                                        </div>
                                        <div class="progress progress-course">
                                            <div class="progress-bar bg-primary" 
                                                 style="width: <?php echo $just_started_percent; ?>%">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Quick Actions -->
                            <div class="stats-card">
                                <h5 class="fw-bold mb-4">Aksi Cepat</h5>
                                <div class="d-grid gap-2">
                                    <button class="btn btn-outline-primary btn-sm">
                                        <i class="bi bi-download me-2"></i>Unduh Laporan
                                    </button>
                                    <button class="btn btn-outline-success btn-sm">
                                        <i class="bi bi-envelope me-2"></i>Kirim Pengumuman
                                    </button>
                                    <button class="btn btn-outline-warning btn-sm">
                                        <i class="bi bi-graph-up me-2"></i>Lihat Analytics
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Student Detail Modal -->
    <div class="modal fade" id="studentDetailModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Detail Progress Siswa</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="studentDetailContent">
                        <!-- Content will be loaded via JavaScript -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                    <button type="button" class="btn btn-primary">
                        <i class="bi bi-envelope me-2"></i>Kirim Pesan
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Student detail modal handler
            const studentDetailModal = document.getElementById('studentDetailModal');
            if (studentDetailModal) {
                studentDetailModal.addEventListener('show.bs.modal', function(event) {
                    const button = event.relatedTarget;
                    const studentName = button.getAttribute('data-student-name');
                    const courseName = button.getAttribute('data-course-name');
                    const progress = button.getAttribute('data-progress');
                    
                    const modalContent = document.getElementById('studentDetailContent');
                    modalContent.innerHTML = `
                        <div class="row">
                            <div class="col-md-4 text-center">
                                <div class="avatar-placeholder mx-auto mb-3" style="width: 80px; height: 80px;">
                                    ${studentName.charAt(0).toUpperCase()}
                                </div>
                                <h5>${studentName}</h5>
                                <p class="text-muted">Siswa</p>
                            </div>
                            <div class="col-md-8">
                                <h6 class="fw-bold">Progress di Kursus: ${courseName}</h6>
                                <div class="progress progress-course mb-3">
                                    <div class="progress-bar 
                                        ${progress >= 80 ? 'bg-success' : 
                                          progress >= 50 ? 'bg-warning' : 'bg-primary'}" 
                                         style="width: ${progress}%">
                                    </div>
                                </div>
                                <div class="text-center">
                                    <h3 class="fw-bold text-primary">${progress}%</h3>
                                    <p class="text-muted">Telah menyelesaikan</p>
                                </div>
                                
                                <div class="mt-4">
                                    <h6 class="fw-bold mb-3">Aktivitas Terbaru:</h6>
                                    <ul class="list-unstyled">
                                        <li class="mb-2">
                                            <i class="bi bi-check-circle-fill text-success me-2"></i>
                                            Menyelesaikan modul pengenalan
                                        </li>
                                        <li class="mb-2">
                                            <i class="bi bi-check-circle-fill text-success me-2"></i>
                                            Mengumpulkan tugas praktikum
                                        </li>
                                        <li class="mb-2">
                                            <i class="bi bi-star-fill text-warning me-2"></i>
                                            Nilai kuis: 85/100
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    `;
                });
            }

            // Search functionality
            const searchInput = document.querySelector('input[type="text"]');
            const searchButton = document.querySelector('.btn-primary[type="button"]');
            
            if (searchInput && searchButton) {
                searchButton.addEventListener('click', function() {
                    const searchTerm = searchInput.value.trim();
                    if (searchTerm) {
                        // Implement search logic here
                        console.log('Searching for:', searchTerm);
                        alert('Fitur pencarian akan diimplementasikan');
                    }
                });
                
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        searchButton.click();
                    }
                });
            }

            // Export functionality
            document.querySelectorAll('.dropdown-item').forEach(item => {
                item.addEventListener('click', function(e) {
                    if (this.textContent.includes('Excel') || 
                        this.textContent.includes('PDF') || 
                        this.textContent.includes('CSV')) {
                        e.preventDefault();
                        const format = this.textContent.trim();
                        alert(`Mengekspor data dalam format ${format}`);
                    }
                });
            });
        });
    </script>
</body>
</html>
<?php
// Tutup koneksi database
if (isset($stmt_lms_courses)) $stmt_lms_courses->close();
if (isset($stmt_progress)) $stmt_progress->close();
if (isset($stmt_stats)) $stmt_stats->close();
if (isset($stmt_activities)) $stmt_activities->close();
$conn->close();
?>