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

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

// Handle actions (delete, toggle status)
if (isset($_GET['action']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $action = $_GET['action'];
    
    if ($action == 'delete') {
        // Check if course has lms_enrollments before deleting
        $check_lms_enrollments = $conn->query("SELECT COUNT(*) as total FROM lms_enrollments WHERE id_course = $id");
        $has_lms_enrollments = $check_lms_enrollments->fetch_assoc()['total'] > 0;
        
        if ($has_lms_enrollments) {
            $_SESSION['error'] = "Tidak dapat menghapus kursus yang sudah memiliki enrollment!";
        } else {
            // Delete related lms_lessons, lms_quizzes, lms_questions first
            $conn->query("DELETE q FROM lms_questions q 
                         JOIN lms_quizzes qu ON q.id_quiz = qu.id 
                         JOIN lms_lessons l ON qu.id_lesson = l.id 
                         WHERE l.id_course = $id");
            $conn->query("DELETE qu FROM lms_quizzes qu 
                         JOIN lms_lessons l ON qu.id_lesson = l.id 
                         WHERE l.id_course = $id");
            $conn->query("DELETE FROM lms_lessons WHERE id_course = $id");
            $conn->query("DELETE FROM lms_courses WHERE id = $id");
            $_SESSION['success'] = "Kursus berhasil dihapus!";
        }
    }
    
    header("Location: manage_courses.php");
    exit();
}

// Get all lms_courses with pagination and joins
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Search and filter functionality
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
$category_filter = isset($_GET['category']) ? intval($_GET['category']) : '';
$level_filter = isset($_GET['level']) ? $conn->real_escape_string($_GET['level']) : '';

$where_conditions = [];
if (!empty($search)) {
    $where_conditions[] = "(c.judul LIKE '%$search%' OR c.deskripsi LIKE '%$search%' OR u.nama_lengkap LIKE '%$search%')";
}
if (!empty($category_filter)) {
    $where_conditions[] = "c.id_kategori = $category_filter";
}
if (!empty($level_filter)) {
    $where_conditions[] = "c.level = '$level_filter'";
}

$where_sql = '';
if (!empty($where_conditions)) {
    $where_sql = "WHERE " . implode(" AND ", $where_conditions);
}

// Get total count for pagination
$count_result = $conn->query("SELECT COUNT(*) as total 
                             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_sql");
$total_lms_courses = $count_result->fetch_assoc()['total'];
$total_pages = ceil($total_lms_courses / $limit);

// Get lms_courses data with joins
$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_sql 
               ORDER BY c.created_at DESC 
               LIMIT $limit OFFSET $offset";
$result_lms_courses = $conn->query($sql_lms_courses);

// Get lms_categories for filter dropdown
$lms_categories_result = $conn->query("SELECT * FROM lms_categories ORDER BY nama_kategori");
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola 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>
        .table-actions {
            white-space: nowrap;
        }
        .badge-level-pemula { background-color: #28a745; }
        .badge-level-menengah { background-color: #ffc107; color: #000; }
        .badge-level-lanjutan { background-color: #dc3545; }
        .course-image {
            width: 60px;
            height: 40px;
            object-fit: cover;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <!-- Navbar Admin -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand fw-bold" href="dashboard.php">SMANSAB LMS - Admin</a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="manage_users.php">Kelola User</a>
                <a class="nav-link" href="manage_courses.php">Kelola Kursus</a>
                <a class="nav-link" href="../logout.php">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>Kelola Kursus</h2>
            <a href="add_course.php" class="btn btn-primary">
                <i class="bi bi-plus-circle"></i> Tambah Kursus
            </a>
        </div>

        <!-- Alert Messages -->
        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Search and Filter Form -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="GET" action="">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <input type="text" name="search" class="form-control" placeholder="Cari kursus..." 
                                   value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="col-md-3">
                            <select name="category" class="form-select">
                                <option value="">Semua Kategori</option>
                                <?php while($category = $lms_categories_result->fetch_assoc()): ?>
                                    <option value="<?php echo $category['id']; ?>" 
                                        <?php echo $category_filter == $category['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($category['nama_kategori']); ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select name="level" class="form-select">
                                <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-2">
                            <button type="submit" class="btn btn-primary w-100">Filter</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- lms_courses Table -->
        <div class="card">
            <div class="card-body">
                <?php if ($result_lms_courses->num_rows > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>Gambar</th>
                                    <th>Judul</th>
                                    <th>Guru</th>
                                    <th>Kategori</th>
                                    <th>Level</th>
                                    <th>Harga</th>
                                    <th>Rating</th>
                                    <th>Siswa</th>
                                    <th>Tanggal</th>
                                    <th>Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while($course = $result_lms_courses->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <?php if (!empty($course['gambar_course'])): ?>
                                            <img src="../<?php echo htmlspecialchars($course['gambar_course']); ?>" 
                                                 alt="Course Image" class="course-image">
                                        <?php else: ?>
                                            <div class="course-image bg-light d-flex align-items-center justify-content-center">
                                                <i class="bi bi-image text-muted"></i>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($course['judul']); ?></strong>
                                        <br>
                                        <small class="text-muted">
                                            <?php echo strlen($course['deskripsi']) > 50 ? 
                                                substr($course['deskripsi'], 0, 50) . '...' : 
                                                $course['deskripsi']; ?>
                                        </small>
                                    </td>
                                    <td><?php echo htmlspecialchars($course['nama_guru']); ?></td>
                                    <td>
                                        <span class="badge bg-info"><?php echo htmlspecialchars($course['nama_kategori']); ?></span>
                                    </td>
                                    <td>
                                        <span class="badge badge-level-<?php echo $course['level']; ?>">
                                            <?php echo ucfirst($course['level']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?php echo $course['harga'] == 0 ? 'success' : 'warning'; ?>">
                                            <?php echo $course['harga'] == 0 ? 'Gratis' : 'Rp ' . number_format($course['harga'], 0, ',', '.'); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <i class="bi bi-star-fill text-warning me-1"></i>
                                            <span><?php echo number_format($course['rating'], 1); ?></span>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge bg-secondary">
                                            <i class="bi bi-people"></i> <?php echo $course['total_siswa']; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <small><?php echo date('d/m/Y', strtotime($course['created_at'])); ?></small>
                                    </td>
                                    <td class="table-actions">
                                        <a href="course_detail.php?id=<?php echo $course['id']; ?>" 
                                           class="btn btn-sm btn-outline-info" title="Lihat Detail" target="_blank">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                        <a href="?action=delete&id=<?php echo $course['id']; ?>" 
                                           class="btn btn-sm btn-outline-danger" title="Hapus"
                                           onclick="return confirm('Yakin ingin menghapus kursus ini? Semua materi dan quiz akan ikut terhapus.')">
                                            <i class="bi bi-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-center">
                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo $category_filter; ?>&level=<?php echo urlencode($level_filter); ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>

                <?php else: ?>
                    <div class="text-center py-4">
                        <i class="bi bi-book display-1 text-muted"></i>
                        <h4 class="text-muted mt-3">Tidak ada kursus ditemukan</h4>
                        <p class="text-muted">Silakan ubah kriteria pencarian atau tambah kursus baru.</p>
                        <a href="add_course.php" class="btn btn-primary">
                            <i class="bi bi-plus-circle"></i> Tambah Kursus Pertama
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Summary -->
        <div class="row mt-4">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body text-center">
                        <h5>Total Kursus</h5>
                        <h3><?php echo $total_lms_courses; ?></h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body text-center">
                        <h5>Kursus Gratis</h5>
                        <h3>
                            <?php 
                            $free_count = $conn->query("SELECT COUNT(*) as total FROM lms_courses WHERE harga = 0")->fetch_assoc()['total'];
                            echo $free_count;
                            ?>
                        </h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-dark">
                    <div class="card-body text-center">
                        <h5>Kursus Berbayar</h5>
                        <h3>
                            <?php 
                            $paid_count = $conn->query("SELECT COUNT(*) as total FROM lms_courses WHERE harga > 0")->fetch_assoc()['total'];
                            echo $paid_count;
                            ?>
                        </h3>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body text-center">
                        <h5>Total Enrollment</h5>
                        <h3>
                            <?php 
                            $enrollment_count = $conn->query("SELECT COUNT(*) as total FROM lms_enrollments")->fetch_assoc()['total'];
                            echo $enrollment_count;
                            ?>
                        </h3>
                    </div>
                </div>
            </div>
        </div>
    </div>

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