<?php
require_once '../includes/header.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: /dashboard.php'); exit;
}

$message = ''; $error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf();
    $action = $_POST['action'] ?? null;
    if ($action === 'add') {
        try {
            $order_stmt = $pdo->query("SELECT MAX(sort_order) as max_order FROM courses");
            $new_order = ($order_stmt->fetchColumn() ?? 0) + 1;
            $stmt = $pdo->prepare("INSERT INTO courses (title, description, admin_id, sort_order, price) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$_POST['title'], $_POST['description'], $_SESSION['user_id'], $new_order, $_POST['price']]);
            $message = 'Kursus berhasil ditambahkan.';
        } catch (PDOException $e) { $error = 'Gagal menambahkan kursus.'; error_log($e->getMessage()); }
    }
    if ($action === 'delete') {
        try {
            $stmt = $pdo->prepare("DELETE FROM courses WHERE id = ?");
            $stmt->execute([$_POST['course_id']]);
            $message = 'Kursus berhasil dihapus.';
        } catch (PDOException $e) { $error = 'Gagal menghapus kursus.'; error_log($e->getMessage()); }
    }
}

$courses = $pdo->query("SELECT courses.*, users.username FROM courses JOIN users ON courses.admin_id = users.id ORDER BY sort_order ASC")->fetchAll();
?>
<main class="container mx-auto p-4 md:p-8">
    <a href="index.php" class="text-blue-500 font-semibold hover:underline mb-6 inline-block">&larr; Kembali ke Admin Dashboard</a>
    <h1 class="text-3xl font-bold text-gray-800 mb-8">Kelola Kursus</h1>
    <?php if ($message): ?><div class="bg-green-100 p-4 rounded-lg mb-6 text-green-800"><?= e($message) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="bg-red-100 p-4 rounded-lg mb-6 text-red-800"><?= e($error) ?></div><?php endif; ?>
    <div id="save-indicator" class="fixed top-20 right-5 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg opacity-0 transition-opacity duration-300">Urutan disimpan!</div>
    
    <div class="bg-white p-8 rounded-xl shadow-lg mb-10">
        <h2 class="text-2xl font-bold text-gray-800 mb-6">Tambah Kursus Baru</h2>
        <form action="manage_courses.php" method="POST" class="space-y-4">
            <input type="hidden" name="csrf_token" value="<?= e(generate_csrf_token()); ?>">
            <input type="hidden" name="action" value="add">
            <div>
                <label for="title" class="text-sm font-semibold text-gray-600 block">Judul Kursus</label>
                <input type="text" name="title" id="title" class="w-full px-4 py-2 mt-2 border border-gray-300 rounded-lg" required>
            </div>
            <div>
                <label for="description" class="text-sm font-semibold text-gray-600 block">Deskripsi</label>
                <textarea name="description" id="description" rows="4" class="w-full px-4 py-2 mt-2 border border-gray-300 rounded-lg" required></textarea>
            </div>
            <div>
                <label for="price" class="text-sm font-semibold text-gray-600 block">Harga (Rp)</label>
                <input type="number" name="price" id="price" min="0" value="0" placeholder="Isi 0 untuk gratis" class="w-full px-4 py-2 mt-2 border border-gray-300 rounded-lg" required>
            </div>
            <button type="submit" class="px-6 py-3 font-semibold text-white bg-blue-500 rounded-lg hover:bg-blue-600">Tambah Kursus</button>
        </form>
    </div>

    <div class="bg-white rounded-xl shadow-lg overflow-x-auto">
        <table class="w-full text-sm text-left text-gray-600">
            <thead class="text-xs text-gray-700 uppercase bg-gray-50">
                <tr>
                    <th class="px-6 py-3 w-12"></th>
                    <th class="px-6 py-3 w-24">Urutan</th>
                    <th class="px-6 py-3">Judul</th>
                    <th class="px-6 py-3">Harga</th>
                    <th class="px-6 py-3 text-right">Aksi</th>
                </tr>
            </thead>
            <tbody id="sortable-courses">
                <?php foreach ($courses as $course): ?>
                <tr class="bg-white border-b hover:bg-gray-50" data-id="<?= $course['id'] ?>">
                    <td class="px-6 py-4 text-gray-400 drag-handle"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" viewBox="0 0 16 16"><path d="M7 2a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM7 5a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zM7 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm-3 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm-3 3a1 1 0 1 1-2 0 1 1 0 0 1 2 0zm3 0a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/></svg></td>
                    <td class="px-6 py-4 font-bold text-gray-800"><?= e($course['sort_order']) ?></td>
                    <td class="px-6 py-4 font-semibold text-gray-900"><?= e($course['title']) ?></td>
                    <td class="px-6 py-4"><?= $course['price'] > 0 ? 'Rp ' . number_format($course['price']) : 'Gratis' ?></td>
                    <td class="px-6 py-4 text-right">
                        <div class="flex justify-end gap-4">
                            <a href="manage_lessons.php?course_id=<?= $course['id'] ?>" class="font-medium text-green-600 hover:underline">Materi</a>
                            <a href="manage_quiz.php?course_id=<?= $course['id'] ?>" class="font-medium text-purple-600 hover:underline">Kuis</a>
                            <a href="edit_course.php?id=<?= $course['id'] ?>" class="font-medium text-blue-600 hover:underline">Edit</a>
                            <form action="manage_courses.php" method="POST" onsubmit="return confirm('Yakin hapus?');">
                                <input type="hidden" name="csrf_token" value="<?= e(generate_csrf_token()); ?>">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="course_id" value="<?= $course['id'] ?>">
                                <button type="submit" class="font-medium text-red-600 hover:underline">Hapus</button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</main>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const sortableCourses = document.getElementById('sortable-courses');
        if (sortableCourses) { new Sortable(sortableCourses, { handle: '.drag-handle', animation: 150, onEnd: function (evt) { 
            const items = Array.from(sortableCourses.children);
            const order = items.map(item => item.getAttribute('data-id'));
            fetch('/admin/update_order.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: 'courses', order: order })
            }).then(response => response.json()).then(data => {
                if(data.status === 'success') {
                    const indicator = document.getElementById('save-indicator');
                    indicator.classList.remove('opacity-0');
                    setTimeout(() => indicator.classList.add('opacity-0'), 2000);
                    items.forEach((item, index) => {
                        item.querySelector('td:nth-child(2)').textContent = index + 1;
                    });
                }
            }).catch(error => console.error('Error:', error));
         } }); }
    });
</script>
<?php require_once '../includes/footer.php'; ?>