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

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

$guru_id = $_SESSION['user_id'];

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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;
    
    // Validasi
    $errors = [];
    
    if (empty($judul)) {
        $errors[] = "Judul kursus harus diisi";
    }
    
    if (empty($deskripsi)) {
        $errors[] = "Deskripsi kursus harus diisi";
    }
    
    if ($id_kategori <= 0) {
        $errors[] = "Kategori harus dipilih";
    }
    
    if (empty($errors)) {
        // Insert kursus baru
        $sql = "INSERT INTO lms_courses (judul, deskripsi, id_guru, id_kategori, level, durasi_jam, harga, created_at, updated_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ssiisid', $judul, $deskripsi, $guru_id, $id_kategori, $level, $durasi_jam, $harga);
        
        if ($stmt->execute()) {
            $course_id = $stmt->insert_id;
            $_SESSION['success'] = "Kursus berhasil dibuat!";
            header("Location: my_courses.php");
            exit();
        } else {
            $errors[] = "Gagal membuat kursus: " . $conn->error;
        }
        
        $stmt->close();
    }
    
    if (!empty($errors)) {
        $_SESSION['error'] = implode("<br>", $errors);
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Buat Kursus Baru - 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);
        }
        
        .form-container {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .preview-card {
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 20px;
            background: #f8f9fa;
        }
        
        .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">
                                <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">Buat Kursus Baru</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">
                    <div class="row justify-content-center">
                        <div class="col-lg-10">
                            <!-- Header -->
                            <div class="row mb-4">
                                <div class="col-12">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <h4 class="fw-bold">Buat Kursus Baru</h4>
                                            <p class="text-muted mb-0">Isi informasi dasar untuk memulai kursus baru Anda</p>
                                        </div>
                                        <a href="my_courses.php" class="btn btn-outline-secondary">
                                            <i class="bi bi-arrow-left me-2"></i>Kembali
                                        </a>
                                    </div>
                                </div>
                            </div>

                            <!-- Notifikasi -->
                            <?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; ?>

                            <?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; ?>

                            <!-- Form Buat Kursus -->
                            <div class="form-container">
                                <form method="POST" id="createCourseForm">
                                    <div class="row">
                                        <div class="col-md-8">
                                            <!-- Informasi Dasar -->
                                            <div class="mb-4">
                                                <h5 class="fw-bold mb-3">
                                                    <i class="bi bi-info-circle me-2"></i>Informasi Dasar
                                                </h5>
                                                
                                                <div class="mb-3">
                                                    <label for="judul" class="form-label fw-semibold">Judul Kursus</label>
                                                    <input type="text" class="form-control form-control-lg" 
                                                           id="judul" name="judul" 
                                                           placeholder="Contoh: Pemrograman Web Dasar dengan PHP"
                                                           value="<?php echo isset($_POST['judul']) ? htmlspecialchars($_POST['judul']) : ''; ?>" 
                                                           required>
                                                    <div class="form-text">Buat judul yang menarik dan deskriptif</div>
                                                </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" placeholder="Jelaskan apa yang akan dipelajari siswa dalam kursus ini..."
                                                              required><?php echo isset($_POST['deskripsi']) ? htmlspecialchars($_POST['deskripsi']) : ''; ?></textarea>
                                                    <div class="form-text">Deskripsi yang baik akan membantu siswa memahami isi kursus</div>
                                                </div>
                                            </div>

                                            <!-- Kategori & Level -->
                                            <div class="mb-4">
                                                <h5 class="fw-bold mb-3">
                                                    <i class="bi bi-tags me-2"></i>Kategori & Level
                                                </h5>
                                                
                                                <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 (isset($_POST['id_kategori']) && $_POST['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 Kesulitan</label>
                                                            <select class="form-select" id="level" name="level" required>
                                                                <option value="pemula" <?php echo (isset($_POST['level']) && $_POST['level'] == 'pemula') ? 'selected' : ''; ?>>Pemula</option>
                                                                <option value="menengah" <?php echo (isset($_POST['level']) && $_POST['level'] == 'menengah') ? 'selected' : ''; ?>>Menengah</option>
                                                                <option value="lanjutan" <?php echo (isset($_POST['level']) && $_POST['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">Perkiraan Durasi (Jam)</label>
                                                            <input type="number" class="form-control" 
                                                                   id="durasi_jam" name="durasi_jam" 
                                                                   min="1" max="100" 
                                                                   value="<?php echo isset($_POST['durasi_jam']) ? $_POST['durasi_jam'] : 1; ?>"
                                                                   required>
                                                            <div class="form-text">Perkiraan total waktu yang dibutuhkan untuk menyelesaikan kursus</div>
                                                        </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" 
                                                                   min="0" step="0.01"
                                                                   value="<?php echo isset($_POST['harga']) ? $_POST['harga'] : '0.00'; ?>">
                                                            <div class="form-text">Kosongkan atau isi 0 untuk kursus gratis</div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4">
                                            <!-- Preview & Panduan -->
                                            <div class="sticky-top" style="top: 100px;">
                                                <div class="preview-card mb-4">
                                                    <h6 class="fw-bold mb-3">
                                                        <i class="bi bi-eye me-2"></i>Preview
                                                    </h6>
                                                    <div id="previewTitle" class="fw-bold text-primary mb-2" style="min-height: 24px;">
                                                        Judul kursus akan muncul di sini
                                                    </div>
                                                    <div id="previewDescription" class="small text-muted" style="min-height: 60px;">
                                                        Deskripsi kursus akan muncul di sini
                                                    </div>
                                                    <div class="mt-2">
                                                        <span id="previewLevel" class="badge bg-secondary level-badge">Level</span>
                                                        <span id="previewDuration" class="badge bg-light text-dark small me-2">0h</span>
                                                        <span id="previewPrice" class="badge bg-success small">Gratis</span>
                                                    </div>
                                                </div>
                                                
                                                <div class="card border-0 bg-light">
                                                    <div class="card-body">
                                                        <h6 class="fw-bold">
                                                            <i class="bi bi-lightbulb me-2"></i>Tips
                                                        </h6>
                                                        <ul class="small mb-0 ps-3">
                                                            <li>Gunakan judul yang jelas dan menarik</li>
                                                            <li>Jelaskan manfaat yang akan didapat siswa</li>
                                                            <li>Sertakan prasyarat jika diperlukan</li>
                                                            <li>Pilih level yang sesuai dengan konten</li>
                                                            <li>Harga 0 untuk kursus gratis</li>
                                                        </ul>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Tombol Aksi -->
                                    <div class="row mt-4">
                                        <div class="col-12">
                                            <div class="d-flex justify-content-between">
                                                <a href="my_courses.php" class="btn btn-outline-secondary">
                                                    <i class="bi bi-x-circle me-2"></i>Batal
                                                </a>
                                                <button type="submit" class="btn btn-primary btn-lg">
                                                    <i class="bi bi-plus-circle me-2"></i>Buat Kursus
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Real-time preview
        document.addEventListener('DOMContentLoaded', function() {
            const judulInput = document.getElementById('judul');
            const deskripsiInput = document.getElementById('deskripsi');
            const levelSelect = document.getElementById('level');
            const durasiInput = document.getElementById('durasi_jam');
            const hargaInput = document.getElementById('harga');
            
            const previewTitle = document.getElementById('previewTitle');
            const previewDescription = document.getElementById('previewDescription');
            const previewLevel = document.getElementById('previewLevel');
            const previewDuration = document.getElementById('previewDuration');
            const previewPrice = document.getElementById('previewPrice');
            
            // Format currency
            function formatCurrency(amount) {
                return new Intl.NumberFormat('id-ID', {
                    style: 'currency',
                    currency: 'IDR',
                    minimumFractionDigits: 0
                }).format(amount);
            }
            
            // Update preview functions
            function updatePreview() {
                previewTitle.textContent = judulInput.value || 'Judul kursus akan muncul di sini';
                previewDescription.textContent = deskripsiInput.value || 'Deskripsi kursus akan muncul di sini';
                
                // Update level badge
                const level = levelSelect.value;
                const levelClasses = {
                    'pemula': 'bg-beginner',
                    'menengah': 'bg-intermediate', 
                    'lanjutan': 'bg-advanced'
                };
                previewLevel.textContent = level.charAt(0).toUpperCase() + level.slice(1);
                previewLevel.className = `badge ${levelClasses[level] || 'bg-secondary'} level-badge`;
                
                // Update duration
                previewDuration.textContent = durasiInput.value + 'h';
                
                // Update price
                const harga = parseFloat(hargaInput.value) || 0;
                if (harga > 0) {
                    previewPrice.textContent = formatCurrency(harga);
                    previewPrice.className = 'badge bg-success small';
                } else {
                    previewPrice.textContent = 'Gratis';
                    previewPrice.className = 'badge bg-info small';
                }
            }
            
            // Add event listeners
            judulInput.addEventListener('input', updatePreview);
            deskripsiInput.addEventListener('input', updatePreview);
            levelSelect.addEventListener('change', updatePreview);
            durasiInput.addEventListener('input', updatePreview);
            hargaInput.addEventListener('input', updatePreview);
            
            // Initial preview
            updatePreview();
            
            // Form validation
            const form = document.getElementById('createCourseForm');
            form.addEventListener('submit', function(e) {
                const judul = judulInput.value.trim();
                const deskripsi = deskripsiInput.value.trim();
                const harga = parseFloat(hargaInput.value);
                
                if (judul.length < 5) {
                    e.preventDefault();
                    alert('Judul kursus harus minimal 5 karakter');
                    judulInput.focus();
                    return;
                }
                
                if (deskripsi.length < 20) {
                    e.preventDefault();
                    alert('Deskripsi kursus harus minimal 20 karakter');
                    deskripsiInput.focus();
                    return;
                }
                
                if (harga < 0) {
                    e.preventDefault();
                    alert('Harga tidak boleh negatif');
                    hargaInput.focus();
                    return;
                }
            });
            
            // Auto-format harga input
            hargaInput.addEventListener('blur', function() {
                const value = parseFloat(this.value);
                if (!isNaN(value) && value >= 0) {
                    this.value = value.toFixed(2);
                }
            });
        });
    </script>
</body>
</html>
<?php
// Tutup koneksi database
if (isset($result_lms_categories)) {
    $result_lms_categories->free();
}
$conn->close();
?>