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

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

$guru_id = $_SESSION['user_id'];

// Handle delete action
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_course'])) {
    $course_id = intval($_POST['course_id']);
    
    // Verify course ownership and check if course has students
    $check_course = $conn->prepare("SELECT id, total_siswa FROM lms_courses WHERE id = ? AND id_guru = ?");
    $check_course->bind_param('ii', $course_id, $guru_id);
    $check_course->execute();
    $course_data = $check_course->get_result()->fetch_assoc();
    
    if ($course_data) {
        if ($course_data['total_siswa'] > 0) {
            $_SESSION['error'] = "Tidak dapat menghapus kursus yang sudah memiliki siswa!";
        } else {
            // Start transaction
            $conn->begin_transaction();
            
            try {
                // Delete related lms_questions
                $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 = $course_id");
                
                // Delete related lms_quizzes
                $conn->query("DELETE qu FROM lms_quizzes qu 
                             JOIN lms_lessons l ON qu.id_lesson = l.id 
                             WHERE l.id_course = $course_id");
                
                // Delete related lms_lessons
                $conn->query("DELETE FROM lms_lessons WHERE id_course = $course_id");
                
                // Delete the course
                $conn->query("DELETE FROM lms_courses WHERE id = $course_id");
                
                // Commit transaction
                $conn->commit();
                
                $_SESSION['success'] = "Kursus berhasil dihapus!";
                header("Location: my_courses.php");
                exit();
                
            } catch (Exception $e) {
                // Rollback transaction if error
                $conn->rollback();
                $_SESSION['error'] = "Terjadi kesalahan saat menghapus kursus: " . $e->getMessage();
            }
        }
    } else {
        $_SESSION['error'] = "Kursus tidak ditemukan atau Anda tidak memiliki akses!";
    }
    
    header("Location: my_courses.php");
    exit();
}

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

// Build query untuk kursus yang diajar
$sql_lms_courses = "SELECT c.*, cat.nama_kategori,
                COUNT(e.id) as total_lms_enrollments,
                AVG(e.progress) as avg_progress,
                (SELECT COUNT(*) FROM lms_lessons WHERE id_course = c.id) as total_lms_lessons
                FROM lms_courses c 
                LEFT JOIN lms_categories cat ON c.id_kategori = cat.id 
                LEFT JOIN lms_enrollments e ON c.id = e.id_course 
                WHERE c.id_guru = ?";

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

// Apply filter
if ($filter === 'popular') {
    $sql_lms_courses .= " AND c.total_siswa >= 50";
} elseif ($filter === 'new') {
    $sql_lms_courses .= " AND c.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
} elseif ($filter === 'high_rating') {
    $sql_lms_courses .= " AND c.rating >= 4.0";
}

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

$sql_lms_courses .= " GROUP BY c.id 
                  ORDER BY c.created_at 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
$sql_stats = "SELECT 
    COUNT(*) as total_lms_courses,
    SUM(total_siswa) as total_students,
    AVG(rating) as avg_rating,
    SUM(durasi_jam) as total_hours
    FROM lms_courses 
    WHERE id_guru = ?";
$stmt_stats = $conn->prepare($sql_stats);
$stmt_stats->bind_param('i', $guru_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;
        }
        
        .level-badge {
            font-size: 0.7rem;
            padding: 4px 8px;
        }
        
        .course-actions .btn {
            margin: 2px;
        }
        
        .bg-lms_courses {
            background: linear-gradient(45deg, #667eea, #764ba2);
        }
        
        .bg-students {
            background: linear-gradient(45deg, #f093fb, #f5576c);
        }
        
        .bg-rating {
            background: linear-gradient(45deg, #4facfe, #00f2fe);
        }
        
        .bg-hours {
            background: linear-gradient(45deg, #43e97b, #38f9d7);
        }
        
        .btn-delete-disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
    </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 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="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" 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">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="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">
                    <!-- Notifikasi -->
                    <?php if (isset($_SESSION['success'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        <?php unset($_SESSION['success']); ?>
                    <?php endif; ?>

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

                    <!-- 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 pantau semua kursus yang Anda ajarkan</p>
                                </div>
                                <a href="create_course.php" class="btn btn-primary">
                                    <i class="bi bi-plus-circle me-2"></i>Buat Kursus Baru
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card stat-card border-0 text-white bg-lms_courses">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-8">
                                            <h6 class="card-title mb-2">Total Kursus</h6>
                                            <h2 class="fw-bold"><?php echo $stats['total_lms_courses']; ?></h2>
                                            <small>Kursus dibuat</small>
                                        </div>
                                        <div class="col-4 text-end">
                                            <i class="bi bi-journal-bookmark" style="font-size: 2.5rem;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card stat-card border-0 text-white bg-students">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-8">
                                            <h6 class="card-title mb-2">Total Siswa</h6>
                                            <h2 class="fw-bold"><?php echo $stats['total_students']; ?></h2>
                                            <small>Siswa terdaftar</small>
                                        </div>
                                        <div class="col-4 text-end">
                                            <i class="bi bi-people" style="font-size: 2.5rem;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card stat-card border-0 text-white bg-rating">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-8">
                                            <h6 class="card-title mb-2">Rating Rata-rata</h6>
                                            <h2 class="fw-bold"><?php echo number_format($stats['avg_rating'] ?? 0, 1); ?></h2>
                                            <small>Penilaian kursus</small>
                                        </div>
                                        <div class="col-4 text-end">
                                            <i class="bi bi-star" style="font-size: 2.5rem;"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card stat-card border-0 text-white bg-hours">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-8">
                                            <h6 class="card-title mb-2">Total Jam</h6>
                                            <h2 class="fw-bold"><?php echo $stats['total_hours']; ?>h</h2>
                                            <small>Durasi pembelajaran</small>
                                        </div>
                                        <div class="col-4 text-end">
                                            <i class="bi bi-clock" style="font-size: 2.5rem;"></i>
                                        </div>
                                    </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 Kursus:</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 Kursus
                                        </a>
                                        <a href="?filter=popular<?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?>" 
                                           class="filter-btn <?php echo $filter === 'popular' ? 'active' : ''; ?>">
                                            Populer
                                        </a>
                                        <a href="?filter=new<?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?>" 
                                           class="filter-btn <?php echo $filter === 'new' ? 'active' : ''; ?>">
                                            Terbaru
                                        </a>
                                        <a href="?filter=high_rating<?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?>" 
                                           class="filter-btn <?php echo $filter === 'high_rating' ? 'active' : ''; ?>">
                                            Rating Tinggi
                                        </a>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <h6 class="mb-3">Cari Kursus:</h6>
                                    <form method="GET" class="d-flex">
                                        <input type="text" name="search" class="form-control me-2" 
                                               placeholder="Cari judul, kategori, atau deskripsi..." 
                                               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()): 
                                $avg_progress = $course['avg_progress'] ?? 0;
                                $level_class = [
                                    'pemula' => 'bg-success',
                                    'menengah' => 'bg-warning',
                                    'lanjutan' => 'bg-danger'
                                ];
                                $can_delete = $course['total_siswa'] == 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 ($course['total_siswa'] >= 100): ?>
                                                <div class="position-absolute top-0 end-0 m-3">
                                                    <span class="badge bg-warning">
                                                        <i class="bi bi-star me-1"></i>Populer
                                                    </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>
                                                <span class="badge <?php echo $level_class[$course['level']] ?? 'bg-secondary'; ?> level-badge">
                                                    <?php echo ucfirst($course['level']); ?>
                                                </span>
                                            </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 Rata-rata</small>
                                                    <small class="text-muted"><?php echo number_format($avg_progress, 1); ?>%</small>
                                                </div>
                                                <div class="progress progress-course">
                                                    <div class="progress-bar 
                                                        <?php echo $avg_progress >= 80 ? 'bg-success' : 
                                                              ($avg_progress >= 50 ? 'bg-warning' : 'bg-primary'); ?>" 
                                                         style="width: <?php echo $avg_progress; ?>%">
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="row text-center mb-3">
                                                <div class="col-4">
                                                    <small class="text-muted">Siswa</small>
                                                    <h6 class="fw-bold mb-0"><?php echo $course['total_siswa']; ?></h6>
                                                </div>
                                                <div class="col-4">
                                                    <small class="text-muted">Materi</small>
                                                    <h6 class="fw-bold mb-0"><?php echo $course['total_lms_lessons']; ?></h6>
                                                </div>
                                                <div class="col-4">
                                                    <small class="text-muted">Rating</small>
                                                    <h6 class="fw-bold mb-0"><?php echo $course['rating']; ?></h6>
                                                </div>
                                            </div>
                                            
                                            <div class="course-actions d-grid gap-2">
                                                <a href="course_management.php?id=<?php echo $course['id']; ?>" 
                                                   class="btn btn-primary btn-sm">
                                                    <i class="bi bi-gear me-1"></i>Kelola Kursus
                                                </a>
                                                
                                                <div class="btn-group w-100" role="group">
                                                    <button type="button" class="btn btn-outline-warning btn-sm" 
                                                            data-bs-toggle="modal" 
                                                            data-bs-target="#editCourseModal"
                                                            data-course-id="<?php echo $course['id']; ?>"
                                                            data-course-title="<?php echo htmlspecialchars($course['judul']); ?>"
                                                            data-course-description="<?php echo htmlspecialchars($course['deskripsi']); ?>">
                                                        <i class="bi bi-pencil"></i>
                                                    </button>
                                                    <a href="course_detail.php?id=<?php echo $course['id']; ?>" 
                                                       class="btn btn-outline-primary btn-sm">
                                                        <i class="bi bi-eye"></i>
                                                    </a>
                                                    <a href="manage_lessons.php?course_id=<?php echo $course['id']; ?>" 
                                                       class="btn btn-outline-success btn-sm">
                                                        <i class="bi bi-collection-play"></i>
                                                    </a>
                                                    <a href="students_progress.php?course_id=<?php echo $course['id']; ?>" 
                                                       class="btn btn-outline-info btn-sm">
                                                        <i class="bi bi-graph-up"></i>
                                                    </a>
                                                    
                                                    <!-- Delete Button dengan pengecekan -->
                                                    <?php if ($can_delete): ?>
                                                        <button type="button" class="btn btn-outline-danger btn-sm" 
                                                                data-bs-toggle="modal" 
                                                                data-bs-target="#deleteCourseModal"
                                                                data-course-id="<?php echo $course['id']; ?>"
                                                                data-course-title="<?php echo htmlspecialchars($course['judul']); ?>">
                                                            <i class="bi bi-trash"></i>
                                                        </button>
                                                    <?php else: ?>
                                                        <button type="button" class="btn btn-outline-secondary btn-sm btn-delete-disabled" 
                                                                title="Tidak dapat menghapus kursus yang sudah memiliki siswa" disabled>
                                                            <i class="bi bi-trash"></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-plus"></i>
                                    <h4 class="text-muted">Belum ada kursus</h4>
                                    <p class="text-muted mb-4">
                                        <?php if (!empty($search) || $filter !== 'all'): ?>
                                            Tidak ada kursus yang sesuai dengan pencarian Anda
                                        <?php else: ?>
                                            Mulai dengan membuat kursus pertama Anda
                                        <?php endif; ?>
                                    </p>
                                    <a href="create_course.php" class="btn btn-primary btn-lg">
                                        <i class="bi bi-plus-circle me-2"></i>Buat Kursus Pertama
                                    </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>

    <!-- Edit Course Name Modal -->
    <div class="modal fade" id="editCourseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Nama Kursus</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="editCourseForm" method="POST" action="edit_course.php">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="editCourseTitle" class="form-label">Nama Kursus</label>
                            <input type="text" class="form-control" id="editCourseTitle" name="judul" required>
                        </div>
                        <div class="mb-3">
                            <label for="editCourseDescription" class="form-label">Deskripsi</label>
                            <textarea class="form-control" id="editCourseDescription" name="deskripsi" rows="3"></textarea>
                        </div>
                        <input type="hidden" name="course_id" id="editCourseId">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Delete Course Modal -->
    <div class="modal fade" id="deleteCourseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Hapus Kursus</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" action="">
                    <div class="modal-body">
                        <p>Apakah Anda yakin ingin menghapus kursus "<span id="courseTitle"></span>"?</p>
                        <p class="text-danger small">
                            <i class="bi bi-exclamation-triangle"></i> 
                            Tindakan ini tidak dapat dibatalkan. Semua data kursus, materi, dan progress siswa akan dihapus.
                        </p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                        <input type="hidden" name="course_id" id="deleteCourseId">
                        <button type="submit" name="delete_course" class="btn btn-danger">Ya, Hapus Kursus</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

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

            // Delete course modal handler
            const deleteCourseModal = document.getElementById('deleteCourseModal');
            if (deleteCourseModal) {
                deleteCourseModal.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('deleteCourseId').value = courseId;
                });
            }

            // Confirm before deleting course
            const deleteForm = document.querySelector('#deleteCourseModal form');
            if (deleteForm) {
                deleteForm.addEventListener('submit', function(e) {
                    if (!confirm('Apakah Anda yakin ingin menghapus kursus ini? Tindakan ini tidak dapat dibatalkan!')) {
                        e.preventDefault();
                    }
                });
            }

            // Form validation for edit course
            const editForm = document.getElementById('editCourseForm');
            if (editForm) {
                editForm.addEventListener('submit', function(e) {
                    const title = document.getElementById('editCourseTitle').value.trim();
                    const description = document.getElementById('editCourseDescription').value.trim();
                    
                    if (title.length < 3) {
                        e.preventDefault();
                        alert('Judul kursus harus minimal 3 karakter');
                        return;
                    }
                    
                    if (description.length < 10) {
                        e.preventDefault();
                        alert('Deskripsi kursus harus minimal 10 karakter');
                        return;
                    }
                });
            }
        });
    </script>
</body>
</html>
<?php
// Tutup koneksi database
if (isset($result_lms_courses)) {
    $result_lms_courses->free();
}
if (isset($stmt)) {
    $stmt->close();
}
if (isset($stmt_stats)) {
    $stmt_stats->close();
}
$conn->close();
?>