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

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

$guru_id = $_SESSION['user_id'];

// Handle actions (delete)
if (isset($_GET['action']) && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $action = $_GET['action'];
    
    // Verify course ownership
    $check_ownership = $conn->query("SELECT id FROM lms_courses WHERE id = $id AND id_guru = $guru_id");
    
    if ($check_ownership->num_rows == 0) {
        $_SESSION['error'] = "Anda tidak memiliki akses untuk mengelola kursus ini!";
        header("Location: manage_courses.php");
        exit();
    }
    
    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 peserta!";
        } 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 guru's lms_courses with pagination
$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']) : '';
$status_filter = isset($_GET['status']) ? $conn->real_escape_string($_GET['status']) : '';

$where_conditions = ["c.id_guru = $guru_id"];
if (!empty($search)) {
    $where_conditions[] = "(c.judul LIKE '%$search%' OR c.deskripsi LIKE '%$search%')";
}
if (!empty($category_filter)) {
    $where_conditions[] = "c.id_kategori = $category_filter";
}
if (!empty($status_filter)) {
    if ($status_filter == 'published') {
        $where_conditions[] = "c.total_siswa > 0";
    } elseif ($status_filter == 'draft') {
        $where_conditions[] = "c.total_siswa = 0";
    }
}

$where_sql = implode(" AND ", $where_conditions);

// Get total count for pagination
$count_result = $conn->query("SELECT COUNT(*) as total 
                             FROM lms_courses c 
                             JOIN lms_categories cat ON c.id_kategori = cat.id 
                             WHERE $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.*, cat.nama_kategori,
               (SELECT COUNT(*) FROM lms_enrollments WHERE id_course = c.id) as total_lms_enrollments,
               (SELECT COUNT(*) FROM lms_lessons WHERE id_course = c.id) as total_lms_lessons
               FROM lms_courses c 
               JOIN lms_categories cat ON c.id_kategori = cat.id 
               WHERE $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");

// Get guru statistics
$sql_stats = "SELECT 
    (SELECT COUNT(*) FROM lms_courses WHERE id_guru = $guru_id) as total_lms_courses,
    (SELECT COUNT(*) FROM lms_enrollments e JOIN lms_courses c ON e.id_course = c.id WHERE c.id_guru = $guru_id) as total_lms_enrollments,
    (SELECT COUNT(*) FROM lms_courses WHERE id_guru = $guru_id AND total_siswa > 0) as published_lms_courses,
    (SELECT AVG(rating) FROM lms_courses WHERE id_guru = $guru_id AND rating > 0) as avg_rating";

$stats = $conn->query($sql_stats)->fetch_assoc();
?>

<!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;
        }
        .stat-card {
            border: none;
            border-radius: 10px;
            transition: transform 0.3s;
        }
        .stat-card:hover {
            transform: translateY(-5px);
        }
    </style>
</head>
<body>
    <!-- Navbar Guru -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand fw-bold" href="dashboard.php">SMANSAB LMS - Guru</a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link active" 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><i class="bi bi-journals"></i> Kelola Kursus Saya</h2>
            <a href="add_course.php" class="btn btn-primary">
                <i class="bi bi-plus-circle"></i> Buat Kursus Baru
            </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; ?>

        <!-- Guru Statistics -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="stat-card card bg-primary text-white">
                    <div class="card-body text-center py-3">
                        <i class="bi bi-journals display-6"></i>
                        <h4><?php echo $stats['total_lms_courses']; ?></h4>
                        <p class="mb-0">Total Kursus</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card card bg-success text-white">
                    <div class="card-body text-center py-3">
                        <i class="bi bi-people display-6"></i>
                        <h4><?php echo $stats['total_lms_enrollments']; ?></h4>
                        <p class="mb-0">Total Siswa</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card card bg-warning text-dark">
                    <div class="card-body text-center py-3">
                        <i class="bi bi-eye display-6"></i>
                        <h4><?php echo $stats['published_lms_courses']; ?></h4>
                        <p class="mb-0">Kursus Aktif</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card card bg-info text-white">
                    <div class="card-body text-center py-3">
                        <i class="bi bi-star display-6"></i>
                        <h4><?php echo number_format($stats['avg_rating'] ?? 0, 1); ?></h4>
                        <p class="mb-0">Rating Rata-rata</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 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="status" class="form-select">
                                <option value="">Semua Status</option>
                                <option value="published" <?php echo $status_filter == 'published' ? 'selected' : ''; ?>>Published</option>
                                <option value="draft" <?php echo $status_filter == 'draft' ? 'selected' : ''; ?>>Draft</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="bi bi-filter"></i> 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 Kursus</th>
                                    <th>Kategori</th>
                                    <th>Level</th>
                                    <th>Harga</th>
                                    <th>Materi</th>
                                    <th>Siswa</th>
                                    <th>Rating</th>
                                    <th>Status</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>
                                        <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>
                                        <span class="badge bg-secondary">
                                            <i class="bi bi-journals"></i> <?php echo $course['total_lms_lessons']; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge bg-primary">
                                            <i class="bi bi-people"></i> <?php echo $course['total_lms_enrollments']; ?>
                                        </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>
                                        <?php if ($course['total_lms_enrollments'] > 0): ?>
                                            <span class="badge bg-success">Published</span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">Draft</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="table-actions">
                                        <a href="edit_course.php?id=<?php echo $course['id']; ?>" 
                                           class="btn btn-sm btn-outline-primary" title="Edit">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                        <a href="manage_lessons.php?course_id=<?php echo $course['id']; ?>" 
                                           class="btn btn-sm btn-outline-success" title="Kelola Materi">
                                            <i class="bi bi-journals"></i>
                                        </a>
                                        <a href="course_detail.php?id=<?php echo $course['id']; ?>" 
                                           class="btn btn-sm btn-outline-info" title="Lihat Detail">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                        <?php if ($course['total_lms_enrollments'] == 0): ?>
                                            <a href="delete_course.php?id=<?php echo $course['id']; ?>" 
                                               class="btn btn-sm btn-outline-danger" title="Hapus">
                                                <i class="bi bi-trash"></i>
                                            </a>
                                        <?php else: ?>
                                            <button class="btn btn-sm btn-outline-secondary" 
                                                    title="Tidak dapat menghapus kursus yang sudah memiliki peserta" disabled>
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination - PERBAIKAN: Mengganti endwhile dengan endfor -->
                    <?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; ?>&status=<?php echo urlencode($status_filter); ?>">
                                        <?php echo $i; ?>
                                    </a>
                                </li>
                            <?php endfor; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>

                <?php else: ?>
                    <div class="text-center py-4">
                        <i class="bi bi-journals display-1 text-muted"></i>
                        <h4 class="text-muted mt-3">Belum ada kursus</h4>
                        <p class="text-muted">Mulai buat kursus pertama Anda dan bagikan pengetahuan Anda.</p>
                        <a href="add_course.php" class="btn btn-primary">
                            <i class="bi bi-plus-circle"></i> Buat Kursus Pertama
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Quick Tips -->
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="card-title mb-0"><i class="bi bi-lightbulb"></i> Tips Mengelola Kursus</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6><i class="bi bi-check-circle text-success"></i> Yang harus dilakukan:</h6>
                        <ul>
                            <li>Buat deskripsi kursus yang menarik dan informatif</li>
                            <li>Unggah gambar cover yang relevan</li>
                            <li>Susun materi pembelajaran secara bertahap</li>
                            <li>Berikan kuis untuk mengukur pemahaman siswa</li>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <h6><i class="bi bi-x-circle text-danger"></i> Yang harus dihindari:</h6>
                        <ul>
                            <li>Jangan hapus kursus yang sudah memiliki peserta</li>
                            <li>Jangan ubah struktur materi setelah kursus berjalan</li>
                            <li>Hindari konten yang tidak relevan dengan judul</li>
                            <li>Jangan gunakan gambar yang tidak jelas hak ciptanya</li>
                        </ul>
                    </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>