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

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

$guru_id = $_SESSION['user_id'];

// Get course ID from URL
$course_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($course_id <= 0) {
    $_SESSION['error'] = "Kursus tidak valid";
    redirect('my_courses.php');
}

// Check if course belongs to logged in guru
$sql_course = "SELECT c.*, cat.nama_kategori, u.nama_lengkap as nama_guru 
               FROM lms_courses c 
               LEFT JOIN lms_categories cat ON c.id_kategori = cat.id 
               LEFT JOIN lms_users u ON c.id_guru = u.id 
               WHERE c.id = ? AND c.id_guru = ?";
$stmt_course = $conn->prepare($sql_course);
$stmt_course->bind_param('ii', $course_id, $guru_id);
$stmt_course->execute();
$course = $stmt_course->get_result()->fetch_assoc();

if (!$course) {
    $_SESSION['error'] = "Kursus tidak ditemukan atau Anda tidak memiliki akses";
    redirect('my_courses.php');
}

// Get course statistics
$sql_stats = "SELECT 
    COUNT(DISTINCT e.id_siswa) as total_students,
    AVG(e.progress) as avg_progress,
    COUNT(DISTINCT l.id) as total_lms_lessons,
    COUNT(DISTINCT q.id) as total_lms_quizzes
    FROM lms_courses c
    LEFT JOIN lms_enrollments e ON c.id = e.id_course
    LEFT JOIN lms_lessons l ON c.id = l.id_course
    LEFT JOIN lms_quizzes q ON l.id = q.id_lesson
    WHERE c.id = ?";
$stmt_stats = $conn->prepare($sql_stats);
$stmt_stats->bind_param('i', $course_id);
$stmt_stats->execute();
$stats = $stmt_stats->get_result()->fetch_assoc();

// Get recent lms_enrollments
$sql_lms_enrollments = "SELECT e.*, u.nama_lengkap, u.email 
                   FROM lms_enrollments e 
                   LEFT JOIN lms_users u ON e.id_siswa = u.id 
                   WHERE e.id_course = ? 
                   ORDER BY e.tanggal_enroll DESC 
                   LIMIT 5";
$stmt_lms_enrollments = $conn->prepare($sql_lms_enrollments);
$stmt_lms_enrollments->bind_param('i', $course_id);
$stmt_lms_enrollments->execute();
$recent_lms_enrollments = $stmt_lms_enrollments->get_result();

// Get lms_lessons count by type
$sql_lesson_types = "SELECT tipe_lesson, COUNT(*) as count 
                    FROM lms_lessons 
                    WHERE id_course = ? 
                    GROUP BY tipe_lesson";
$stmt_lesson_types = $conn->prepare($sql_lesson_types);
$stmt_lesson_types->bind_param('i', $course_id);
$stmt_lesson_types->execute();
$lesson_types = $stmt_lesson_types->get_result();

// Handle course update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? sanitize($_POST['action']) : '';
    
    if ($action === 'update_course') {
        $judul = isset($_POST['judul']) ? sanitize($_POST['judul']) : '';
        $deskripsi = isset($_POST['deskripsi']) ? sanitize($_POST['deskripsi']) : '';
        $id_kategori = isset($_POST['id_kategori']) ? intval($_POST['id_kategori']) : 0;
        $level = isset($_POST['level']) ? sanitize($_POST['level']) : 'pemula';
        $durasi_jam = isset($_POST['durasi_jam']) ? intval($_POST['durasi_jam']) : 0;
        $harga = isset($_POST['harga']) ? floatval($_POST['harga']) : 0.00;
        
        // Validate
        if (empty($judul) || empty($deskripsi) || $id_kategori <= 0) {
            $_SESSION['error'] = "Semua field wajib diisi";
        } else {
            $update_sql = "UPDATE lms_courses SET 
                          judul = ?, deskripsi = ?, id_kategori = ?, 
                          level = ?, durasi_jam = ?, harga = ?, updated_at = NOW() 
                          WHERE id = ? AND id_guru = ?";
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param('ssisidii', $judul, $deskripsi, $id_kategori, $level, $durasi_jam, $harga, $course_id, $guru_id);
            
            if ($update_stmt->execute()) {
                $_SESSION['success'] = "Kursus berhasil diperbarui";
                // Refresh course data
                $stmt_course->execute();
                $course = $stmt_course->get_result()->fetch_assoc();
                header("Location: my_courses.php");
                exit(); // penting! hentikan eksekusi script agar redirect langsung berjalan
            } else {
                $_SESSION['error'] = "Gagal memperbarui kursus: " . $conn->error;
            }
            $update_stmt->close();
        }
    }
}

// Get lms_categories for dropdown
$sql_lms_categories = "SELECT id, nama_kategori FROM lms_categories ORDER BY nama_kategori";
$result_lms_categories = $conn->query($sql_lms_categories);
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Kursus - <?php echo htmlspecialchars($course['judul']); ?> - 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-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
        }
        
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border: none;
        }
        
        .nav-tabs-custom .nav-link {
            border: none;
            padding: 15px 25px;
            font-weight: 500;
            color: #6c757d;
            border-bottom: 3px solid transparent;
        }
        
        .nav-tabs-custom .nav-link.active {
            color: var(--primary-color);
            border-bottom: 3px solid var(--primary-color);
            background: transparent;
        }
        
        .tab-content {
            background: white;
            border-radius: 0 0 15px 15px;
            padding: 30px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .quick-action-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
            transition: transform 0.3s;
            border: none;
        }
        
        .quick-action-card:hover {
            transform: translateY(-5px);
        }
        
        .progress-course {
            height: 8px;
            border-radius: 4px;
        }
        
        .student-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }
        
        .level-badge {
            font-size: 0.7rem;
            padding: 4px 8px;
        }
        
        .bg-beginner { background: #28a745 !important; }
        .bg-intermediate { background: #ffc107 !important; color: #000 !important; }
        .bg-advanced { background: #dc3545 !important; }
    </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" 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?course_id=<?php echo $course_id; ?>">
                                <i class="bi bi-collection-play"></i> Kelola Materi
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="manage_quizzes.php?course_id=<?php echo $course_id; ?>">
                                <i class="bi bi-pencil-square"></i> Kelola Kuis
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="students_progress.php?course_id=<?php echo $course_id; ?>">
                                <i class="bi bi-graph-up"></i> Progress Siswa
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="course_management.php?id=<?php echo $course_id; ?>">
                                <i class="bi bi-gear"></i> Kelola Kursus
                            </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">Kelola Kursus</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; ?>

                    <!-- Course Header -->
                    <div class="course-header">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <nav aria-label="breadcrumb">
                                    <ol class="breadcrumb breadcrumb-dark">
                                        <li class="breadcrumb-item"><a href="my_courses.php" class="text-white-50">Kursus Saya</a></li>
                                        <li class="breadcrumb-item active text-white"><?php echo htmlspecialchars($course['judul']); ?></li>
                                    </ol>
                                </nav>
                                <h1 class="fw-bold mb-2"><?php echo htmlspecialchars($course['judul']); ?></h1>
                                <p class="mb-3 opacity-75"><?php echo htmlspecialchars($course['deskripsi']); ?></p>
                                <div class="d-flex flex-wrap gap-2">
                                    <span class="badge bg-light text-dark">
                                        <i class="bi bi-tag me-1"></i><?php echo $course['nama_kategori']; ?>
                                    </span>
                                    <span class="badge <?php echo 'bg-' . ($course['level'] === 'pemula' ? 'beginner' : ($course['level'] === 'menengah' ? 'intermediate' : 'advanced')); ?> level-badge">
                                        <i class="bi bi-bar-chart me-1"></i><?php echo ucfirst($course['level']); ?>
                                    </span>
                                    <span class="badge bg-light text-dark">
                                        <i class="bi bi-clock me-1"></i><?php echo $course['durasi_jam']; ?> jam
                                    </span>
                                    <span class="badge bg-light text-dark">
                                        <i class="bi bi-star me-1"></i>Rating: <?php echo $course['rating']; ?>
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-4 text-end">
                                <div class="btn-group">
                                    <a href="course_detail.php?id=<?php echo $course_id; ?>" class="btn btn-outline-light">
                                        <i class="bi bi-eye me-1"></i>Preview
                                    </a>
                                    <a href="my_courses.php" class="btn btn-light">
                                        <i class="bi bi-arrow-left me-1"></i>Kembali
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Stats -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-people display-6 text-primary mb-3"></i>
                                <h3 class="fw-bold"><?php echo $stats['total_students'] ?? 0; ?></h3>
                                <p class="text-muted mb-0">Siswa Terdaftar</p>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-graph-up display-6 text-success mb-3"></i>
                                <h3 class="fw-bold"><?php echo number_format($stats['avg_progress'] ?? 0, 1); ?>%</h3>
                                <p class="text-muted mb-0">Progress Rata-rata</p>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-collection-play display-6 text-warning mb-3"></i>
                                <h3 class="fw-bold"><?php echo $stats['total_lms_lessons'] ?? 0; ?></h3>
                                <p class="text-muted mb-0">Total Materi</p>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stats-card text-center">
                                <i class="bi bi-pencil-square display-6 text-info mb-3"></i>
                                <h3 class="fw-bold"><?php echo $stats['total_lms_quizzes'] ?? 0; ?></h3>
                                <p class="text-muted mb-0">Total Kuis</p>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <h5 class="fw-bold mb-3">Aksi Cepat</h5>
                            <div class="row">
                                <div class="col-xl-2 col-md-4 col-6 mb-3">
                                    <a href="manage_lessons.php?course_id=<?php echo $course_id; ?>" class="text-decoration-none">
                                        <div class="quick-action-card">
                                            <i class="bi bi-plus-circle display-6 text-primary mb-3"></i>
                                            <h6 class="fw-bold">Tambah Materi</h6>
                                        </div>
                                    </a>
                                </div>
                                <div class="col-xl-2 col-md-4 col-6 mb-3">
                                    <a href="manage_quizzes.php?course_id=<?php echo $course_id; ?>" class="text-decoration-none">
                                        <div class="quick-action-card">
                                            <i class="bi bi-plus-circle display-6 text-success mb-3"></i>
                                            <h6 class="fw-bold">Buat Kuis</h6>
                                        </div>
                                    </a>
                                </div>
                                <div class="col-xl-2 col-md-4 col-6 mb-3">
                                    <a href="students_progress.php?course_id=<?php echo $course_id; ?>" class="text-decoration-none">
                                        <div class="quick-action-card">
                                            <i class="bi bi-graph-up display-6 text-warning mb-3"></i>
                                            <h6 class="fw-bold">Lihat Progress</h6>
                                        </div>
                                    </a>
                                </div>
                                <div class="col-xl-2 col-md-4 col-6 mb-3">
                                    <a href="course_detail.php?id=<?php echo $course_id; ?>" class="text-decoration-none">
                                        <div class="quick-action-card">
                                            <i class="bi bi-eye display-6 text-info mb-3"></i>
                                            <h6 class="fw-bold">Preview Kursus</h6>
                                        </div>
                                    </a>
                                </div>
                                <div class="col-xl-2 col-md-4 col-6 mb-3">
                                    <button type="button" class="btn btn-link text-decoration-none p-0 w-100" data-bs-toggle="modal" data-bs-target="#shareCourseModal">
                                        <div class="quick-action-card">
                                            <i class="bi bi-share display-6 text-secondary mb-3"></i>
                                            <h6 class="fw-bold">Bagikan</h6>
                                        </div>
                                    </button>
                                </div>
                                <div class="col-xl-2 col-md-4 col-6 mb-3">
                                    <button type="button" class="btn btn-link text-decoration-none p-0 w-100" data-bs-toggle="modal" data-bs-target="#analyticsModal">
                                        <div class="quick-action-card">
                                            <i class="bi bi-bar-chart display-6 text-danger mb-3"></i>
                                            <h6 class="fw-bold">Analytics</h6>
                                        </div>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Main Content Tabs -->
                    <div class="row">
                        <div class="col-12">
                            <ul class="nav nav-tabs nav-tabs-custom" id="courseTabs" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" id="edit-tab" data-bs-toggle="tab" data-bs-target="#edit" type="button" role="tab">
                                        <i class="bi bi-pencil me-2"></i>Edit Kursus
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="students-tab" data-bs-toggle="tab" data-bs-target="#students" type="button" role="tab">
                                        <i class="bi bi-people me-2"></i>Siswa (<?php echo $stats['total_students'] ?? 0; ?>)
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="content-tab" data-bs-toggle="tab" data-bs-target="#content" type="button" role="tab">
                                        <i class="bi bi-collection-play me-2"></i>Konten
                                    </button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="settings-tab" data-bs-toggle="tab" data-bs-target="#settings" type="button" role="tab">
                                        <i class="bi bi-gear me-2"></i>Pengaturan
                                    </button>
                                </li>
                            </ul>
                            
                            <div class="tab-content" id="courseTabsContent">
                                <!-- Tab 1: Edit Course -->
                                <div class="tab-pane fade show active" id="edit" role="tabpanel">
                                    <form method="POST">
                                        <input type="hidden" name="action" value="update_course">
                                        <div class="row">
                                            <div class="col-md-8">
                                                <div class="mb-3">
                                                    <label for="judul" class="form-label fw-semibold">Judul Kursus</label>
                                                    <input type="text" class="form-control" id="judul" name="judul" 
                                                           value="<?php echo htmlspecialchars($course['judul']); ?>" required>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="deskripsi" class="form-label fw-semibold">Deskripsi Kursus</label>
                                                    <textarea class="form-control" id="deskripsi" name="deskripsi" rows="5" required><?php echo htmlspecialchars($course['deskripsi']); ?></textarea>
                                                </div>
                                                
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label for="id_kategori" class="form-label fw-semibold">Kategori</label>
                                                            <select class="form-select" id="id_kategori" name="id_kategori" required>
                                                                <option value="">Pilih Kategori</option>
                                                                <?php while($category = $result_lms_categories->fetch_assoc()): ?>
                                                                    <option value="<?php echo $category['id']; ?>" 
                                                                        <?php echo $course['id_kategori'] == $category['id'] ? 'selected' : ''; ?>>
                                                                        <?php echo htmlspecialchars($category['nama_kategori']); ?>
                                                                    </option>
                                                                <?php endwhile; ?>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label for="level" class="form-label fw-semibold">Level</label>
                                                            <select class="form-select" id="level" name="level" required>
                                                                <option value="pemula" <?php echo $course['level'] == 'pemula' ? 'selected' : ''; ?>>Pemula</option>
                                                                <option value="menengah" <?php echo $course['level'] == 'menengah' ? 'selected' : ''; ?>>Menengah</option>
                                                                <option value="lanjutan" <?php echo $course['level'] == 'lanjutan' ? 'selected' : ''; ?>>Lanjutan</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label for="durasi_jam" class="form-label fw-semibold">Durasi (Jam)</label>
                                                            <input type="number" class="form-control" id="durasi_jam" name="durasi_jam" 
                                                                   value="<?php echo $course['durasi_jam']; ?>" min="1" max="100" required>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="mb-3">
                                                            <label for="harga" class="form-label fw-semibold">Harga (Rp)</label>
                                                            <input type="number" class="form-control" id="harga" name="harga" 
                                                                   value="<?php echo $course['harga']; ?>" min="0" step="0.01">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <div class="card border-0 bg-light">
                                                    <div class="card-body">
                                                        <h6 class="fw-bold mb-3">
                                                            <i class="bi bi-info-circle me-2"></i>Informasi Kursus
                                                        </h6>
                                                        <div class="mb-2">
                                                            <small class="text-muted">Dibuat pada:</small>
                                                            <div class="fw-semibold"><?php echo date('d M Y', strtotime($course['created_at'])); ?></div>
                                                        </div>
                                                        <div class="mb-2">
                                                            <small class="text-muted">Diupdate pada:</small>
                                                            <div class="fw-semibold"><?php echo date('d M Y', strtotime($course['updated_at'])); ?></div>
                                                        </div>
                                                        <div class="mb-2">
                                                            <small class="text-muted">Total Siswa:</small>
                                                            <div class="fw-semibold"><?php echo $stats['total_students'] ?? 0; ?> siswa</div>
                                                        </div>
                                                        <div class="mb-2">
                                                            <small class="text-muted">Rating:</small>
                                                            <div class="fw-semibold">
                                                                <?php echo $course['rating']; ?> 
                                                                <i class="bi bi-star-fill text-warning"></i>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="mt-4">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="bi bi-check-circle me-2"></i>Simpan Perubahan
                                            </button>
                                            <a href="my_courses.php" class="btn btn-outline-secondary">Batal</a>
                                        </div>
                                    </form>
                                </div>
                                
                                <!-- Tab 2: Students -->
                                <div class="tab-pane fade" id="students" role="tabpanel">
                                    <div class="d-flex justify-content-between align-items-center mb-4">
                                        <h5 class="fw-bold mb-0">Daftar Siswa</h5>
                                        <a href="students_progress.php?course_id=<?php echo $course_id; ?>" class="btn btn-primary">
                                            <i class="bi bi-graph-up me-2"></i>Lihat Progress Detail
                                        </a>
                                    </div>
                                    
                                    <?php if ($recent_lms_enrollments->num_rows > 0): ?>
                                        <div class="table-responsive">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Siswa</th>
                                                        <th>Email</th>
                                                        <th>Tanggal Daftar</th>
                                                        <th>Progress</th>
                                                        <th>Status</th>
                                                        <th>Aksi</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while($enrollment = $recent_lms_enrollments->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <div class="d-flex align-items-center">
                                                                    <div class="student-avatar me-3">
                                                                        <?php echo strtoupper(substr($enrollment['nama_lengkap'], 0, 1)); ?>
                                                                    </div>
                                                                    <div>
                                                                        <div class="fw-semibold"><?php echo htmlspecialchars($enrollment['nama_lengkap']); ?></div>
                                                                    </div>
                                                                </div>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($enrollment['email']); ?></td>
                                                            <td><?php echo date('d M Y', strtotime($enrollment['tanggal_enroll'])); ?></td>
                                                            <td>
                                                                <div class="d-flex align-items-center">
                                                                    <div class="progress progress-course flex-grow-1 me-2" style="width: 100px;">
                                                                        <div class="progress-bar 
                                                                            <?php echo $enrollment['progress'] >= 80 ? 'bg-success' : 
                                                                                  ($enrollment['progress'] >= 50 ? 'bg-warning' : 'bg-primary'); ?>" 
                                                                             style="width: <?php echo $enrollment['progress']; ?>%">
                                                                        </div>
                                                                    </div>
                                                                    <small><?php echo $enrollment['progress']; ?>%</small>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge 
                                                                    <?php echo $enrollment['status'] === 'completed' ? 'bg-success' : 
                                                                          ($enrollment['status'] === 'active' ? 'bg-primary' : 'bg-secondary'); ?>">
                                                                    <?php echo ucfirst($enrollment['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <button class="btn btn-sm btn-outline-primary">
                                                                    <i class="bi bi-envelope"></i>
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                        
                                        <div class="text-center mt-3">
                                            <a href="students_progress.php?course_id=<?php echo $course_id; ?>" class="btn btn-outline-primary">
                                                Lihat Semua Siswa
                                            </a>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-center py-5">
                                            <i class="bi bi-people display-1 text-muted"></i>
                                            <h5 class="text-muted mt-3">Belum ada siswa yang mendaftar</h5>
                                            <p class="text-muted">Siswa akan muncul di sini setelah mendaftar ke kursus Anda</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                
                                <!-- Tab 3: Content -->
                                <div class="tab-pane fade" id="content" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <h5 class="fw-bold mb-4">Ringkasan Konten</h5>
                                            
                                            <div class="row mb-4">
                                                <div class="col-md-6">
                                                    <div class="card border-0 bg-primary text-white">
                                                        <div class="card-body">
                                                            <div class="d-flex justify-content-between align-items-center">
                                                                <div>
                                                                    <h3 class="fw-bold"><?php echo $stats['total_lms_lessons'] ?? 0; ?></h3>
                                                                    <p class="mb-0">Total Materi</p>
                                                                </div>
                                                                <i class="bi bi-collection-play display-4 opacity-50"></i>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="card border-0 bg-success text-white">
                                                        <div class="card-body">
                                                            <div class="d-flex justify-content-between align-items-center">
                                                                <div>
                                                                    <h3 class="fw-bold"><?php echo $stats['total_lms_quizzes'] ?? 0; ?></h3>
                                                                    <p class="mb-0">Total Kuis</p>
                                                                </div>
                                                                <i class="bi bi-pencil-square display-4 opacity-50"></i>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <?php if ($lesson_types->num_rows > 0): ?>
                                                <h6 class="fw-bold mb-3">Jenis Materi</h6>
                                                <div class="row">
                                                    <?php while($lesson_type = $lesson_types->fetch_assoc()): ?>
                                                        <div class="col-md-4 mb-3">
                                                            <div class="card border-0 bg-light">
                                                                <div class="card-body text-center">
                                                                    <i class="bi 
                                                                        <?php echo $lesson_type['tipe_lesson'] === 'video' ? 'bi-camera-video' : 
                                                                              ($lesson_type['tipe_lesson'] === 'quiz' ? 'bi-pencil-square' : 
                                                                              ($lesson_type['tipe_lesson'] === 'tugas' ? 'bi-file-earmark-text' : 'bi-file-text')); ?> 
                                                                        display-6 text-primary mb-2"></i>
                                                                    <h5 class="fw-bold"><?php echo $lesson_type['count']; ?></h5>
                                                                    <small class="text-muted text-uppercase"><?php echo $lesson_type['tipe_lesson']; ?></small>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    <?php endwhile; ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="col-md-4">
                                            <div class="card border-0 bg-light">
                                                <div class="card-body">
                                                    <h6 class="fw-bold mb-3">Manajemen Konten</h6>
                                                    <div class="d-grid gap-2">
                                                        <a href="manage_lessons.php?course_id=<?php echo $course_id; ?>" class="btn btn-primary">
                                                            <i class="bi bi-plus-circle me-2"></i>Tambah Materi Baru
                                                        </a>
                                                        <a href="manage_quizzes.php?course_id=<?php echo $course_id; ?>" class="btn btn-success">
                                                            <i class="bi bi-plus-circle me-2"></i>Buat Kuis Baru
                                                        </a>
                                                        <a href="course_content.php?id=<?php echo $course_id; ?>" class="btn btn-outline-primary">
                                                            <i class="bi bi-list-ul me-2"></i>Lihat Urutan Materi
                                                        </a>
                                                    </div>
                                                    
                                                    <hr class="my-4">
                                                    
                                                    <h6 class="fw-bold mb-3">Tips</h6>
                                                    <ul class="small text-muted">
                                                        <li>Urutkan materi dari mudah ke sulit</li>
                                                        <li>Sertakan kuis untuk evaluasi</li>
                                                        <li>Gunakan berbagai jenis konten</li>
                                                        <li>Update materi secara berkala</li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Tab 4: Settings -->
                                <div class="tab-pane fade" id="settings" role="tabpanel">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <h5 class="fw-bold mb-4">Pengaturan Kursus</h5>
                                            
                                            <div class="card border-0 bg-light mb-4">
                                                <div class="card-body">
                                                    <h6 class="fw-bold mb-3">
                                                        <i class="bi bi-shield-lock me-2"></i>Visibilitas Kursus
                                                    </h6>
                                                    <div class="form-check form-switch mb-2">
                                                        <input class="form-check-input" type="checkbox" id="visibilitySwitch" checked>
                                                        <label class="form-check-label" for="visibilitySwitch">
                                                            Tampilkan kursus di katalog
                                                        </label>
                                                    </div>
                                                    <small class="text-muted">Jika dinonaktifkan, kursus hanya dapat diakses melalui link langsung</small>
                                                </div>
                                            </div>
                                            
                                            <div class="card border-0 bg-light mb-4">
                                                <div class="card-body">
                                                    <h6 class="fw-bold mb-3">
                                                        <i class="bi bi-people me-2"></i>Pendaftaran Siswa
                                                    </h6>
                                                    <div class="form-check mb-2">
                                                        <input class="form-check-input" type="radio" name="enrollmentType" id="enrollmentAuto" checked>
                                                        <label class="form-check-label" for="enrollmentAuto">
                                                            Otomatis - Siswa dapat langsung mendaftar
                                                        </label>
                                                    </div>
                                                    <div class="form-check">
                                                        <input class="form-check-input" type="radio" name="enrollmentType" id="enrollmentManual">
                                                        <label class="form-check-label" for="enrollmentManual">
                                                            Manual - Butuh persetujuan guru
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="card border-0 bg-warning bg-opacity-10 mb-4">
                                                <div class="card-body">
                                                    <h6 class="fw-bold mb-3 text-warning">
                                                        <i class="bi bi-exclamation-triangle me-2"></i>Zona Berbahaya
                                                    </h6>
                                                    <p class="text-muted mb-3">Tindakan ini tidak dapat dibatalkan. Semua data kursus akan dihapus permanen.</p>
                                                    <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteCourseModal">
                                                        <i class="bi bi-trash me-2"></i>Hapus Kursus
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4">
                                            <div class="card border-0 bg-light">
                                                <div class="card-body">
                                                    <h6 class="fw-bold mb-3">Status Kursus</h6>
                                                    <div class="mb-3">
                                                        <div class="d-flex justify-content-between align-items-center mb-1">
                                                            <small class="text-muted">Ketersediaan</small>
                                                            <span class="badge bg-success">Aktif</span>
                                                        </div>
                                                        <div class="d-flex justify-content-between align-items-center mb-1">
                                                            <small class="text-muted">Pendaftaran</small>
                                                            <span class="badge bg-success">Dibuka</span>
                                                        </div>
                                                        <div class="d-flex justify-content-between align-items-center mb-1">
                                                            <small class="text-muted">Terakhir Diupdate</small>
                                                            <small class="text-muted"><?php echo date('d M Y', strtotime($course['updated_at'])); ?></small>
                                                        </div>
                                                    </div>
                                                    
                                                    <hr>
                                                    
                                                    <h6 class="fw-bold mb-3">Ekspor Data</h6>
                                                    <div class="d-grid gap-2">
                                                        <button type="button" class="btn btn-outline-primary btn-sm">
                                                            <i class="bi bi-download me-2"></i>Ekspor Daftar Siswa
                                                        </button>
                                                        <button type="button" class="btn btn-outline-success btn-sm">
                                                            <i class="bi bi-download me-2"></i>Ekspor Progress
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Share Course Modal -->
    <div class="modal fade" id="shareCourseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Bagikan Kursus</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Bagikan link kursus ini dengan siswa:</p>
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" value="<?php echo "https://smansab-lms.id/course_detail.php?id=" . $course_id; ?>" readonly>
                        <button class="btn btn-outline-secondary" type="button" id="copyLinkBtn">
                            <i class="bi bi-clipboard"></i>
                        </button>
                    </div>
                    <div class="alert alert-success d-none" id="copySuccessAlert">
                        Link berhasil disalin ke clipboard!
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Analytics Modal -->
    <div class="modal fade" id="analyticsModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Analytics Kursus</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row text-center">
                        <div class="col-md-4 mb-3">
                            <div class="card border-0 bg-light">
                                <div class="card-body">
                                    <h3 class="fw-bold text-primary"><?php echo $stats['total_students'] ?? 0; ?></h3>
                                    <small class="text-muted">Total Siswa</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="card border-0 bg-light">
                                <div class="card-body">
                                    <h3 class="fw-bold text-success"><?php echo number_format($stats['avg_progress'] ?? 0, 1); ?>%</h3>
                                    <small class="text-muted">Progress Rata-rata</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="card border-0 bg-light">
                                <div class="card-body">
                                    <h3 class="fw-bold text-warning"><?php echo $course['rating']; ?></h3>
                                    <small class="text-muted">Rating</small>
                                </div>
                            </div>
                        </div>
                    </div>
                    <p class="text-muted text-center">Analytics lengkap tersedia di halaman Progress Siswa</p>
                </div>
                <div class="modal-footer">
                    <a href="students_progress.php?course_id=<?php echo $course_id; ?>" class="btn btn-primary">
                        Lihat Analytics Lengkap
                    </a>
                </div>
            </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>
                <div class="modal-body">
                    <p>Apakah Anda yakin ingin menghapus kursus "<strong><?php echo htmlspecialchars($course['judul']); ?></strong>"?</p>
                    <p class="text-danger small">
                        <i class="bi bi-exclamation-triangle"></i> 
                        Tindakan ini tidak dapat dibatalkan. Semua data kursus, materi, kuis, dan progress siswa akan dihapus permanen.
                    </p>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="confirmDelete">
                        <label class="form-check-label text-danger" for="confirmDelete">
                            Saya memahami konsekuensi dari penghapusan ini
                        </label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <form method="POST" action="delete_course.php">
                        <input type="hidden" name="course_id" value="<?php echo $course_id; ?>">
                        <button type="submit" class="btn btn-danger" id="deleteConfirmBtn" disabled>
                            Ya, Hapus Kursus
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Copy link functionality
            const copyLinkBtn = document.getElementById('copyLinkBtn');
            const copySuccessAlert = document.getElementById('copySuccessAlert');
            
            if (copyLinkBtn) {
                copyLinkBtn.addEventListener('click', function() {
                    const linkInput = this.closest('.input-group').querySelector('input');
                    linkInput.select();
                    document.execCommand('copy');
                    
                    copySuccessAlert.classList.remove('d-none');
                    setTimeout(() => {
                        copySuccessAlert.classList.add('d-none');
                    }, 3000);
                });
            }
            
            // Delete course confirmation
            const confirmDeleteCheckbox = document.getElementById('confirmDelete');
            const deleteConfirmBtn = document.getElementById('deleteConfirmBtn');
            
            if (confirmDeleteCheckbox && deleteConfirmBtn) {
                confirmDeleteCheckbox.addEventListener('change', function() {
                    deleteConfirmBtn.disabled = !this.checked;
                });
            }
            
            // Auto-save draft (simulated)
            const form = document.querySelector('form');
            if (form) {
                let saveTimeout;
                
                form.addEventListener('input', function() {
                    clearTimeout(saveTimeout);
                    saveTimeout = setTimeout(() => {
                        // Simulate auto-save
                        console.log('Auto-saving...');
                    }, 2000);
                });
            }
        });
    </script>
</body>
</html>
<?php
// Tutup koneksi database
if (isset($stmt_course)) $stmt_course->close();
if (isset($stmt_stats)) $stmt_stats->close();
if (isset($stmt_lms_enrollments)) $stmt_lms_enrollments->close();
if (isset($stmt_lesson_types)) $stmt_lesson_types->close();
if (isset($result_lms_categories)) $result_lms_categories->free();
$conn->close();
?>