<?php
include 'config.php';

// Handle filter dan pencarian
$category_filter = isset($_GET['category']) ? sanitize($_GET['category']) : '';
$level_filter = isset($_GET['level']) ? sanitize($_GET['level']) : '';
$price_filter = isset($_GET['price']) ? sanitize($_GET['price']) : '';
$search_query = isset($_GET['search']) ? sanitize($_GET['search']) : '';

// Build query untuk lms_courses
$sql_lms_courses = "SELECT c.*, u.nama_lengkap as nama_guru, cat.nama_kategori 
                FROM lms_courses c 
                JOIN lms_users u ON c.id_guru = u.id 
                JOIN lms_categories cat ON c.id_kategori = cat.id 
                WHERE 1=1";

$params = [];

// Apply filters
if (!empty($category_filter)) {
    $sql_lms_courses .= " AND c.id_kategori = ?";
    $params[] = $category_filter;
}

if (!empty($level_filter)) {
    $sql_lms_courses .= " AND c.level = ?";
    $params[] = $level_filter;
}

if (!empty($price_filter)) {
    if ($price_filter === 'free') {
        $sql_lms_courses .= " AND c.harga = 0";
    } elseif ($price_filter === 'paid') {
        $sql_lms_courses .= " AND c.harga > 0";
    }
}

if (!empty($search_query)) {
    $sql_lms_courses .= " AND (c.judul LIKE ? OR c.deskripsi LIKE ? OR u.nama_lengkap LIKE ?)";
    $search_param = "%$search_query%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

$sql_lms_courses .= " ORDER BY c.rating DESC, c.total_siswa DESC";

// Prepare statement
$stmt = $conn->prepare($sql_lms_courses);
if (!empty($params)) {
    $types = str_repeat('s', count($params));
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result_lms_courses = $stmt->get_result();

// Ambil data kategori untuk filter
$sql_lms_categories = "SELECT * FROM lms_categories ORDER BY nama_kategori";
$result_lms_categories = $conn->query($sql_lms_categories);

// Ambil course yang sedang di-enroll oleh user (jika login sebagai siswa)
$enrolled_lms_courses = [];
if (isSiswa() && isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];
    $sql_enrolled = "SELECT id_course FROM lms_enrollments WHERE id_siswa = ?";
    $stmt_enrolled = $conn->prepare($sql_enrolled);
    $stmt_enrolled->bind_param('i', $user_id);
    $stmt_enrolled->execute();
    $result_enrolled = $stmt_enrolled->get_result();
    
    while ($row = $result_enrolled->fetch_assoc()) {
        $enrolled_lms_courses[] = $row['id_course'];
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kursus - 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;
        }
        
        .hero-lms_courses {
            background: linear-gradient(135deg, var(--primary-color), #7986cb);
            color: white;
            padding: 60px 0;
            margin-bottom: 40px;
        }
        
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s;
            height: 100%;
        }
        
        .card:hover {
            transform: translateY(-5px);
        }
        
        .course-card {
            position: relative;
        }
        
        .course-image {
            height: 160px;
            background: linear-gradient(45deg, #667eea, #764ba2);
            border-radius: 10px 10px 0 0;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 3rem;
        }
        
        .rating {
            color: #ffc107;
        }
        
        .enrolled-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            background: #28a745;
            color: white;
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 0.8rem;
        }
        
        .filter-section {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        .course-count {
            color: var(--primary-color);
            font-weight: bold;
        }
        
        .btn-enroll {
            background: var(--primary-color);
            color: white;
            border: none;
        }
        
        .btn-enroll:hover {
            background: #303f9f;
            color: white;
        }
        
        .btn-enrolled {
            background: #28a745;
            color: white;
            border: none;
        }
        
        .level-badge {
            font-size: 0.7rem;
            padding: 4px 8px;
        }
        
        .level-pemula { background: #d4edda; color: #155724; }
        .level-menengah { background: #fff3cd; color: #856404; }
        .level-lanjutan { background: #f8d7da; color: #721c24; }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
        <div class="container">
            <a class="navbar-brand fw-bold text-primary" href="index.php">
                <i class="bi bi-book-half"></i> SMANSAB LMS
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="index.php">Beranda</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="courses.php">Kursus</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="teachers.php">Guru</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="about.php">Tentang</a>
                    </li>
                </ul>
                <div class="d-flex">
                    <?php if (isLoggedIn()): ?>
                        <span class="navbar-text me-3">
                            <i class="bi bi-person-circle"></i> <?php echo $_SESSION['nama_lengkap']; ?>
                        </span>
                        <?php if (isAdmin()): ?>
                            <a href="admin/dashboard.php" class="btn btn-outline-primary me-2">Dashboard Admin</a>
                        <?php elseif (isGuru()): ?>
                            <a href="guru/dashboard.php" class="btn btn-outline-primary me-2">Dashboard Guru</a>
                        <?php elseif (isSiswa()): ?>
                            <a href="siswa/dashboard.php" class="btn btn-outline-primary me-2">Dashboard Siswa</a>
                        <?php endif; ?>
                        <a href="logout.php" class="btn btn-outline-secondary">Logout</a>
                    <?php else: ?>
                        <a href="login.php" class="btn btn-outline-primary me-2">Login</a>
                        <a href="register.php" class="btn btn-primary">Daftar</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </nav>

    <!-- Hero Section -->
    <section class="hero-lms_courses">
        <div class="container text-center">
            <h1 class="display-5 fw-bold mb-3">Temukan Kursus Terbaik untuk Anda</h1>
            <p class="lead mb-4">Jelajahi berbagai kursus berkualitas yang diajarkan oleh guru-guru terbaik kami</p>
            
            <!-- Search Form -->
            <form method="GET" class="row g-3 justify-content-center">
                <div class="col-md-6">
                    <div class="input-group">
                        <input type="text" name="search" class="form-control form-control-lg" 
                               placeholder="Cari kursus, guru, atau topik..." 
                               value="<?php echo htmlspecialchars($search_query); ?>">
                        <button class="btn btn-primary btn-lg" type="submit">
                            <i class="bi bi-search"></i> Cari
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </section>

    <div class="container">
        <!-- Filter Section -->
        <div class="filter-section">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h5 class="mb-0">
                        Menampilkan <span class="course-count"><?php echo $result_lms_courses->num_rows; ?></span> kursus
                        <?php if (!empty($search_query)): ?>
                            untuk "<em><?php echo htmlspecialchars($search_query); ?></em>"
                        <?php endif; ?>
                    </h5>
                </div>
                <div class="col-md-6">
                    <form method="GET" class="row g-2">
                        <div class="col-md-4">
                            <select name="category" class="form-select" onchange="this.form.submit()">
                                <option value="">Semua Kategori</option>
                                <?php while($category = $result_lms_categories->fetch_assoc()): ?>
                                    <option value="<?php echo $category['id']; ?>" 
                                        <?php echo $category_filter == $category['id'] ? 'selected' : ''; ?>>
                                        <?php echo $category['nama_kategori']; ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <select name="level" class="form-select" onchange="this.form.submit()">
                                <option value="">Semua Level</option>
                                <option value="pemula" <?php echo $level_filter == 'pemula' ? 'selected' : ''; ?>>Pemula</option>
                                <option value="menengah" <?php echo $level_filter == 'menengah' ? 'selected' : ''; ?>>Menengah</option>
                                <option value="lanjutan" <?php echo $level_filter == 'lanjutan' ? 'selected' : ''; ?>>Lanjutan</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <select name="price" class="form-select" onchange="this.form.submit()">
                                <option value="">Semua Harga</option>
                                <option value="free" <?php echo $price_filter == 'free' ? 'selected' : ''; ?>>Gratis</option>
                                <option value="paid" <?php echo $price_filter == 'paid' ? 'selected' : ''; ?>>Berbayar</option>
                            </select>
                        </div>
                        <?php if (!empty($search_query)): ?>
                            <input type="hidden" name="search" value="<?php echo htmlspecialchars($search_query); ?>">
                        <?php endif; ?>
                    </form>
                </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()): 
                    $is_enrolled = in_array($course['id'], $enrolled_lms_courses);
                ?>
                    <div class="col-lg-4 col-md-6 mb-4">
                        <div class="card course-card">
                            <?php if ($is_enrolled): ?>
                                <div class="enrolled-badge">
                                    <i class="bi bi-check-circle"></i> Terdaftar
                                </div>
                            <?php endif; ?>
                            
                            <div class="course-image">
                                <i class="bi bi-laptop"></i>
                            </div>
                            
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <span class="badge bg-<?php echo $course['harga'] == 0 ? 'success' : 'warning'; ?>">
                                        <?php echo $course['harga'] == 0 ? 'Gratis' : 'Rp ' . number_format($course['harga'], 0, ',', '.'); ?>
                                    </span>
                                    <span class="level-badge level-<?php echo $course['level']; ?>">
                                        <?php echo ucfirst($course['level']); ?>
                                    </span>
                                </div>
                                
                                <span class="badge bg-light text-dark mb-2"><?php echo $course['nama_kategori']; ?></span>
                                
                                <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="d-flex justify-content-between align-items-center mb-3">
                                    <div class="rating">
                                        <i class="bi bi-star-fill"></i>
                                        <span><?php echo $course['rating']; ?></span>
                                        <small class="text-muted">(<?php echo $course['total_siswa']; ?> siswa)</small>
                                    </div>
                                    <small class="text-muted">
                                        <i class="bi bi-clock"></i> <?php echo $course['durasi_jam']; ?> jam
                                    </small>
                                </div>
                                
                                <div class="d-flex justify-content-between align-items-center">
                                    <small class="text-muted">
                                        <i class="bi bi-person"></i> <?php echo $course['nama_guru']; ?>
                                    </small>
                                    
                                    <?php if (isSiswa()): ?>
                                        <?php if ($is_enrolled): ?>
                                            <a href="siswa/course_detail.php?id=<?php echo $course['id']; ?>" 
                                               class="btn btn-enrolled btn-sm">
                                                Lanjutkan Belajar
                                            </a>
                                        <?php else: ?>
                                            <form method="POST" action="enroll_course.php">
                                                <input type="hidden" name="course_id" value="<?php echo $course['id']; ?>">
                                                <button type="submit" class="btn btn-enroll btn-sm">
                                                    Daftar Kursus
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    <?php elseif (!isLoggedIn()): ?>
                                        <a href="login.php" class="btn btn-enroll btn-sm">
                                            Login untuk Daftar
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <div class="col-12 text-center py-5">
                    <i class="bi bi-search" style="font-size: 3rem; color: #6c757d;"></i>
                    <h4 class="mt-3">Tidak ada kursus yang ditemukan</h4>
                    <p class="text-muted">Coba ubah filter pencarian Anda atau jelajahi semua kursus</p>
                    <a href="courses.php" class="btn btn-primary">Lihat Semua Kursus</a>
                </div>
            <?php endif; ?>
        </div>

        <!-- Load More Button (jika ada banyak data) -->
        <?php if ($result_lms_courses->num_rows >= 12): ?>
            <div class="text-center mt-4">
                <button class="btn btn-outline-primary">Muat Lebih Banyak Kursus</button>
            </div>
        <?php endif; ?>
    </div>

    <!-- Footer -->
    <footer class="bg-dark text-white py-4 mt-5">
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <h5><i class="bi bi-book-half"></i> SMANSAB LMS</h5>
                    <p>Sistem Manajemen Pembelajaran untuk Sekolah Menengah Atas Negeri 1 Bogor</p>
                </div>
                <div class="col-md-3">
                    <h5>Tautan Cepat</h5>
                    <ul class="list-unstyled">
                        <li><a href="index.php" class="text-white">Beranda</a></li>
                        <li><a href="courses.php" class="text-white">Kursus</a></li>
                        <li><a href="teachers.php" class="text-white">Guru</a></li>
                    </ul>
                </div>
                <div class="col-md-3">
                    <h5>Kontak</h5>
                    <ul class="list-unstyled">
                        <li><i class="bi bi-geo-alt"></i> Jl. Merdeka No. 123, Bogor</li>
                        <li><i class="bi bi-telephone"></i> (0251) 123456</li>
                        <li><i class="bi bi-envelope"></i> info@smansab-lms.id</li>
                    </ul>
                </div>
            </div>
            <hr class="bg-light">
            <div class="text-center">
                <p>&copy; 2023 SMANSAB LMS. All rights reserved.</p>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>