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

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

$user_id = $_SESSION['user_id'];

// Handle filter
$filter = isset($_GET['filter']) ? sanitize($_GET['filter']) : 'all';
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';

// Build query untuk kursus yang di-enroll
$sql_lms_courses = "SELECT c.*, e.progress, e.tanggal_enroll, e.status as enrollment_status,
                u.nama_lengkap as nama_guru, cat.nama_kategori,
                (SELECT COUNT(*) FROM lms_lessons l WHERE l.id_course = c.id) as total_lms_lessons,
                (SELECT COUNT(*) FROM lms_lessons l 
                 JOIN lms_enrollments e2 ON e2.id_course = c.id 
                 WHERE l.id_course = c.id AND e2.id_siswa = ?) as completed_lms_lessons
                FROM lms_enrollments e 
                JOIN lms_courses c ON e.id_course = c.id 
                JOIN lms_users u ON c.id_guru = u.id 
                JOIN lms_categories cat ON c.id_kategori = cat.id 
                WHERE e.id_siswa = ?";

$params = [$user_id, $user_id];
$types = "ii";

// Apply filter
if ($filter === 'active') {
    $sql_lms_courses .= " AND e.progress < 100 AND e.status = 'active'";
} elseif ($filter === 'completed') {
    $sql_lms_courses .= " AND e.progress = 100 AND e.status = 'active'";
} elseif ($filter === 'dropped') {
    $sql_lms_courses .= " AND e.status = 'dropped'";
}

// Apply search
if (!empty($search)) {
    $sql_lms_courses .= " AND (c.judul LIKE ? OR u.nama_lengkap LIKE ? OR cat.nama_kategori LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= "sss";
}

$sql_lms_courses .= " ORDER BY 
                CASE WHEN e.progress < 100 THEN 1 ELSE 2 END,
                e.tanggal_enroll DESC";

$stmt = $conn->prepare($sql_lms_courses);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result_lms_courses = $stmt->get_result();

// Hitung statistik filter
$sql_stats = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN progress < 100 AND status = 'active' THEN 1 ELSE 0 END) as active,
    SUM(CASE WHEN progress = 100 AND status = 'active' THEN 1 ELSE 0 END) as completed,
    SUM(CASE WHEN status = 'dropped' THEN 1 ELSE 0 END) as dropped
    FROM lms_enrollments 
    WHERE id_siswa = ?";
$stmt_stats = $conn->prepare($sql_stats);
$stmt_stats->bind_param('i', $user_id);
$stmt_stats->execute();
$stats = $stmt_stats->get_result()->fetch_assoc();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kursus Saya - 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);
        }
        
        .course-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transition: transform 0.3s;
            margin-bottom: 20px;
        }
        
        .course-card:hover {
            transform: translateY(-5px);
        }
        
        .course-image {
            height: 120px;
            background: linear-gradient(45deg, #667eea, #764ba2);
            border-radius: 15px 15px 0 0;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 2.5rem;
        }
        
        .progress-course {
            height: 8px;
            border-radius: 4px;
        }
        
        .filter-btn {
            border: 1px solid #dee2e6;
            border-radius: 20px;
            padding: 8px 16px;
            margin: 0 5px 10px 0;
            transition: all 0.3s;
        }
        
        .filter-btn.active {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }
        
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }
        
        .empty-state i {
            font-size: 4rem;
            color: #6c757d;
            margin-bottom: 20px;
        }
        
        .status-badge {
            font-size: 0.7rem;
            padding: 4px 8px;
        }
        
        .course-actions .btn {
            margin: 2px;
        }
    </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">Siswa 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 active" href="my_courses.php">
                                <i class="bi bi-journal-bookmark"></i> Kursus Saya
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="progress.php">
                                <i class="bi bi-graph-up"></i> Progress Belajar
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="quizzes.php">
                                <i class="bi bi-pencil-square"></i> Kuis & Ujian
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="certificates.php">
                                <i class="bi bi-award"></i> Sertifikat
                            </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">Kursus Saya</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="../courses.php">
                                        <i class="bi bi-search me-2"></i>Jelajah Kursus
                                    </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">Kursus Saya</h4>
                                    <p class="text-muted mb-0">Kelola dan lanjutkan pembelajaran Anda</p>
                                </div>
                                <a href="../courses.php" class="btn btn-primary">
                                    <i class="bi bi-plus-circle me-2"></i>Tambah Kursus
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="flex-shrink-0">
                                        <div class="bg-primary rounded-circle p-3">
                                            <i class="bi bi-journal-bookmark text-white"></i>
                                        </div>
                                    </div>
                                    <div class="flex-grow-1 ms-3">
                                        <h4 class="fw-bold mb-0"><?php echo $stats['total']; ?></h4>
                                        <small class="text-muted">Total Kursus</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="flex-shrink-0">
                                        <div class="bg-warning rounded-circle p-3">
                                            <i class="bi bi-play-circle text-white"></i>
                                        </div>
                                    </div>
                                    <div class="flex-grow-1 ms-3">
                                        <h4 class="fw-bold mb-0"><?php echo $stats['active']; ?></h4>
                                        <small class="text-muted">Sedang Berjalan</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="flex-shrink-0">
                                        <div class="bg-success rounded-circle p-3">
                                            <i class="bi bi-check-circle text-white"></i>
                                        </div>
                                    </div>
                                    <div class="flex-grow-1 ms-3">
                                        <h4 class="fw-bold mb-0"><?php echo $stats['completed']; ?></h4>
                                        <small class="text-muted">Selesai</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="flex-shrink-0">
                                        <div class="bg-danger rounded-circle p-3">
                                            <i class="bi bi-x-circle text-white"></i>
                                        </div>
                                    </div>
                                    <div class="flex-grow-1 ms-3">
                                        <h4 class="fw-bold mb-0"><?php echo $stats['dropped']; ?></h4>
                                        <small class="text-muted">Dibatalkan</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter dan Search -->
                    <div class="card border-0 shadow-sm mb-4">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <h6 class="mb-3">Filter Status:</h6>
                                    <div class="d-flex flex-wrap">
                                        <a href="?filter=all<?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?>" 
                                           class="filter-btn <?php echo $filter === 'all' ? 'active' : ''; ?>">
                                            Semua (<?php echo $stats['total']; ?>)
                                        </a>
                                        <a href="?filter=active<?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?>" 
                                           class="filter-btn <?php echo $filter === 'active' ? 'active' : ''; ?>">
                                            Berjalan (<?php echo $stats['active']; ?>)
                                        </a>
                                        <a href="?filter=completed<?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?>" 
                                           class="filter-btn <?php echo $filter === 'completed' ? 'active' : ''; ?>">
                                            Selesai (<?php echo $stats['completed']; ?>)
                                        </a>
                                        <a href="?filter=dropped<?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?>" 
                                           class="filter-btn <?php echo $filter === 'dropped' ? 'active' : ''; ?>">
                                            Dibatalkan (<?php echo $stats['dropped']; ?>)
                                        </a>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <form method="GET" class="d-flex">
                                        <input type="text" name="search" class="form-control me-2" 
                                               placeholder="Cari kursus, guru, atau kategori..." 
                                               value="<?php echo htmlspecialchars($search); ?>">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="bi bi-search"></i>
                                        </button>
                                        <?php if (!empty($filter) && $filter !== 'all'): ?>
                                            <input type="hidden" name="filter" value="<?php echo $filter; ?>">
                                        <?php endif; ?>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- lms_courses Grid -->
                    <div class="row">
                        <?php if ($result_lms_courses->num_rows > 0): ?>
                            <?php while($course = $result_lms_courses->fetch_assoc()): 
                                $progress = $course['progress'];
                                $is_completed = $progress == 100;
                                $is_dropped = $course['enrollment_status'] === 'dropped';
                                $completed_lms_lessons = $course['completed_lms_lessons'] ?? 0;
                                $total_lms_lessons = $course['total_lms_lessons'] ?? 0;
                            ?>
                                <div class="col-xl-4 col-lg-6 mb-4">
                                    <div class="card course-card h-100">
                                        <div class="course-image">
                                            <i class="bi bi-laptop"></i>
                                            <?php if ($is_completed): ?>
                                                <div class="position-absolute top-0 end-0 m-3">
                                                    <span class="badge bg-success">
                                                        <i class="bi bi-check-circle me-1"></i>Selesai
                                                    </span>
                                                </div>
                                            <?php elseif ($is_dropped): ?>
                                                <div class="position-absolute top-0 end-0 m-3">
                                                    <span class="badge bg-danger">
                                                        <i class="bi bi-x-circle me-1"></i>Dibatalkan
                                                    </span>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="card-body">
                                            <div class="d-flex justify-content-between align-items-start mb-2">
                                                <span class="badge bg-light text-dark">
                                                    <?php echo $course['nama_kategori']; ?>
                                                </span>
                                                <div class="rating text-warning">
                                                    <i class="bi bi-star-fill"></i>
                                                    <small><?php echo $course['rating']; ?></small>
                                                </div>
                                            </div>
                                            
                                            <h6 class="card-title fw-bold"><?php echo $course['judul']; ?></h6>
                                            <p class="card-text small text-muted">
                                                <?php echo strlen($course['deskripsi']) > 100 ? 
                                                    substr($course['deskripsi'], 0, 100) . '...' : 
                                                    $course['deskripsi']; ?>
                                            </p>
                                            
                                            <div class="mb-3">
                                                <div class="d-flex justify-content-between mb-1">
                                                    <small class="text-muted">Progress</small>
                                                    <small class="text-muted"><?php echo $progress; ?>%</small>
                                                </div>
                                                <div class="progress progress-course">
                                                    <div class="progress-bar 
                                                        <?php echo $is_completed ? 'bg-success' : 'bg-primary'; ?>" 
                                                         style="width: <?php echo $progress; ?>%">
                                                    </div>
                                                </div>
                                                <small class="text-muted">
                                                    <?php echo $completed_lms_lessons; ?> dari <?php echo $total_lms_lessons; ?> materi selesai
                                                </small>
                                            </div>
                                            
                                            <div class="d-flex justify-content-between align-items-center mb-3">
                                                <small class="text-muted">
                                                    <i class="bi bi-person"></i> <?php echo $course['nama_guru']; ?>
                                                </small>
                                                <small class="text-muted">
                                                    <i class="bi bi-calendar"></i> 
                                                    <?php echo date('d M Y', strtotime($course['tanggal_enroll'])); ?>
                                                </small>
                                            </div>
                                            
                                            <div class="course-actions d-grid gap-2">
                                                <?php if (!$is_dropped && !$is_completed): ?>
                                                    <a href="course_detail.php?id=<?php echo $course['id']; ?>" 
                                                       class="btn btn-primary btn-sm">
                                                        <i class="bi bi-play-circle me-1"></i>Lanjutkan Belajar
                                                    </a>
                                                <?php elseif ($is_completed): ?>
                                                    <a href="certificates.php?course_id=<?php echo $course['id']; ?>" 
                                                       class="btn btn-success btn-sm">
                                                        <i class="bi bi-award me-1"></i>Lihat Sertifikat
                                                    </a>
                                                <?php endif; ?>
                                                
                                                <div class="btn-group w-100" role="group">
                                                    <a href="course_detail.php?id=<?php echo $course['id']; ?>" 
                                                       class="btn btn-outline-primary btn-sm">
                                                        <i class="bi bi-eye"></i>
                                                    </a>
                                                    <?php if (!$is_dropped && !$is_completed): ?>
                                                        <button type="button" class="btn btn-outline-danger btn-sm" 
                                                                data-bs-toggle="modal" 
                                                                data-bs-target="#dropCourseModal"
                                                                data-course-id="<?php echo $course['id']; ?>"
                                                                data-course-title="<?php echo htmlspecialchars($course['judul']); ?>">
                                                            <i class="bi bi-x-circle"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <div class="col-12">
                                <div class="empty-state">
                                    <i class="bi bi-journal-x"></i>
                                    <h4 class="text-muted">Tidak ada kursus yang ditemukan</h4>
                                    <p class="text-muted mb-4">
                                        <?php if (!empty($search) || $filter !== 'all'): ?>
                                            Coba ubah filter pencarian Anda
                                        <?php else: ?>
                                            Anda belum mendaftar di kursus manapun
                                        <?php endif; ?>
                                    </p>
                                    <a href="../courses.php" class="btn btn-primary btn-lg">
                                        <i class="bi bi-search me-2"></i>Jelajah Kursus
                                    </a>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Pagination (jika diperlukan) -->
                    <?php if ($result_lms_courses->num_rows > 12): ?>
                    <div class="row mt-4">
                        <div class="col-12">
                            <nav aria-label="Page navigation">
                                <ul class="pagination justify-content-center">
                                    <li class="page-item disabled">
                                        <a class="page-link" href="#" tabindex="-1">Previous</a>
                                    </li>
                                    <li class="page-item active"><a class="page-link" href="#">1</a></li>
                                    <li class="page-item"><a class="page-link" href="#">2</a></li>
                                    <li class="page-item"><a class="page-link" href="#">3</a></li>
                                    <li class="page-item">
                                        <a class="page-link" href="#">Next</a>
                                    </li>
                                </ul>
                            </nav>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Drop Course Modal -->
    <div class="modal fade" id="dropCourseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Batalkan Kursus</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Apakah Anda yakin ingin membatalkan kursus "<span id="courseTitle"></span>"?</p>
                    <p class="text-muted small">Progress belajar Anda akan hilang dan tidak dapat dikembalikan.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <form id="dropCourseForm" method="POST" action="drop_course.php">
                        <input type="hidden" name="course_id" id="dropCourseId">
                        <button type="submit" class="btn btn-danger">Ya, Batalkan Kursus</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Drop course modal handler
        document.addEventListener('DOMContentLoaded', function() {
            const dropCourseModal = document.getElementById('dropCourseModal');
            if (dropCourseModal) {
                dropCourseModal.addEventListener('show.bs.modal', function(event) {
                    const button = event.relatedTarget;
                    const courseId = button.getAttribute('data-course-id');
                    const courseTitle = button.getAttribute('data-course-title');
                    
                    document.getElementById('courseTitle').textContent = courseTitle;
                    document.getElementById('dropCourseId').value = courseId;
                });
            }
        });
    </script>
</body>
</html>