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

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

$course_id = $_GET['course_id'] ?? null;
if (!$course_id) {
    header('Location: admin/manage_courses.php');
    exit;
}

// Ambil judul kursus untuk ditampilkan
$stmt_course = $pdo->prepare("SELECT title FROM courses WHERE id = ?");
$stmt_course->execute([$course_id]);
$course = $stmt_course->fetch();
if (!$course) {
    die("Kursus tidak ditemukan");
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf(); // Verifikasi token keamanan

    $action = $_POST['action'] ?? null;

    // Logika untuk menambah materi
    if ($action === 'add_lesson') {
        try {
            $title = $_POST['title'];
            $lesson_type = $_POST['lesson_type'];
            
            $order_stmt = $pdo->prepare("SELECT MAX(sort_order) as max_order FROM lessons WHERE course_id = ?");
            $order_stmt->execute([$course_id]);
            $new_order = ($order_stmt->fetchColumn() ?? 0) + 1;

            $content = null; $video_path = null; $external_url = null;

            switch ($lesson_type) {
                case 'text':
                    $content = $_POST['content'];
                    if(empty($content)) throw new Exception("Konten teks tidak boleh kosong.");
                    break;
                
                case 'video':
                case 'pdf':
                    $file_key = $lesson_type;
                    $upload_dir = '../uploads/' . $file_key . 's/';
                    $allowed_exts = ($file_key === 'video') ? ['mp4', 'webm'] : ['pdf'];

                    if (isset($_FILES[$file_key]) && $_FILES[$file_key]['error'] === UPLOAD_ERR_OK) {
                        $file_name = basename($_FILES[$file_key]['name']);
                        $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

                        if (in_array($file_extension, $allowed_exts)) {
                            if (!is_dir($upload_dir)) { mkdir($upload_dir, 0775, true); }
                            $unique_name = uniqid() . '-' . $file_name;
                            $dest_path = $upload_dir . $unique_name;
                            if(move_uploaded_file($_FILES[$file_key]['tmp_name'], $dest_path)) {
                                $video_path = 'uploads/' . $file_key . 's/' . $unique_name;
                            } else { throw new Exception("Gagal memindahkan file."); }
                        } else { throw new Exception("Tipe file tidak diizinkan."); }
                    } else { throw new Exception("Gagal mengunggah file atau tidak ada file yang dipilih."); }
                    break;

                case 'link':
                    $external_url = $_POST['external_url'];
                    if (!filter_var($external_url, FILTER_VALIDATE_URL)) {
                        throw new Exception("URL yang dimasukkan tidak valid.");
                    }
                    break;
            }

            $stmt_insert = $pdo->prepare("INSERT INTO lessons (course_id, title, lesson_type, content, video_path, external_url, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt_insert->execute([$course_id, $title, $lesson_type, $content, $video_path, $external_url, $new_order]);
            $message = "Materi berhasil ditambahkan.";

        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }

    // Logika untuk menghapus materi
    if ($action === 'delete_lesson') {
        $lesson_id_to_delete = $_POST['lesson_id'];
        $stmt_get_video = $pdo->prepare("SELECT video_path FROM lessons WHERE id = ?");
        $stmt_get_video->execute([$lesson_id_to_delete]);
        $video = $stmt_get_video->fetch();
        if ($video && !empty($video['video_path']) && file_exists('../' . $video['video_path'])) {
            unlink('../' . $video['video_path']);
        }

        $stmt_delete = $pdo->prepare("DELETE FROM lessons WHERE id = ?");
        $stmt_delete->execute([$lesson_id_to_delete]);
        $message = "Materi berhasil dihapus.";
    }
}

// Ambil daftar materi untuk ditampilkan
$lessons_stmt = $pdo->prepare("SELECT * FROM lessons WHERE course_id = ? ORDER BY sort_order ASC");
$lessons_stmt->execute([$course_id]);
$lessons = $lessons_stmt->fetchAll();
?>
<main class="container mx-auto p-4 md:p-8">
    <a href="manage_courses.php" class="text-blue-500 font-semibold hover:underline mb-6 inline-block">&larr; Kembali ke Daftar Kursus</a>
    <h1 class="text-3xl font-bold text-gray-800">Kelola Materi</h1>
    <p class="text-gray-600 mt-2 mb-8">Untuk kursus: <span class="font-semibold">"<?= e($course['title']) ?>"</span></p>
    
    <?php if ($message): ?><div class="bg-green-100 border-green-400 text-green-700 px-4 py-3 rounded-lg mb-6"><?= e($message) ?></div><?php endif; ?>
    <?php if ($error): ?><div class="bg-red-100 border-red-400 text-red-700 px-4 py-3 rounded-lg mb-6"><?= 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 Materi Baru</h2>
        <form action="manage_lessons.php?course_id=<?= $course_id ?>" method="POST" class="space-y-4" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?= e(generate_csrf_token()); ?>">
            <input type="hidden" name="action" value="add_lesson">
            <div>
                <label for="title" class="text-sm font-semibold text-gray-600 block">Judul Materi</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 class="text-sm font-semibold text-gray-600 block">Tipe Materi</label>
                <div class="mt-2 flex flex-wrap gap-4">
                    <label class="flex items-center"><input type="radio" name="lesson_type" value="text" checked onchange="toggleLessonInput(this.value)"> <span class="ml-2">Teks</span></label>
                    <label class="flex items-center"><input type="radio" name="lesson_type" value="video" onchange="toggleLessonInput(this.value)"> <span class="ml-2">Video</span></label>
                    <label class="flex items-center"><input type="radio" name="lesson_type" value="pdf" onchange="toggleLessonInput(this.value)"> <span class="ml-2">PDF</span></label>
                    <label class="flex items-center"><input type="radio" name="lesson_type" value="link" onchange="toggleLessonInput(this.value)"> <span class="ml-2">Link Eksternal</span></label>
                </div>
            </div>
            
            <div id="text-input">
                <label for="content" class="text-sm font-semibold text-gray-600 block">Konten Teks</label>
                <textarea name="content" rows="6" class="w-full px-4 py-2 mt-2 border border-gray-300 rounded-lg"></textarea>
            </div>
            
            <div id="video-input" class="hidden">
                <label for="video" class="text-sm font-semibold text-gray-600 block">Unggah File Video (MP4, WebM)</label>
                <input type="file" name="video" accept="video/mp4,video/webm" class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 mt-2">
            </div>

            <div id="pdf-input" class="hidden">
                <label for="pdf" class="text-sm font-semibold text-gray-600 block">Unggah File PDF</label>
                <input type="file" name="pdf" accept=".pdf" class="w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 mt-2">
            </div>

            <div id="link-input" class="hidden">
                <label for="external_url" class="text-sm font-semibold text-gray-600 block">URL Materi (Contoh: Google Doc)</label>
                <input type="url" name="external_url" placeholder="https://docs.google.com/..." class="w-full px-4 py-2 mt-2 border border-gray-300 rounded-lg">
            </div>

            <button type="submit" class="px-6 py-3 font-semibold text-white bg-blue-500 rounded-lg hover:bg-blue-600">Tambah Materi</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 scope="col" class="px-6 py-3 w-12"></th>
                    <th scope="col" class="px-6 py-3 w-24">Urutan</th>
                    <th scope="col" class="px-6 py-3">Judul Materi</th>
                    <th scope="col" class="px-6 py-3 text-right">Aksi</th>
                </tr>
            </thead>
            <tbody id="sortable-lessons">
                <?php if (empty($lessons)): ?>
                    <tr>
                        <td colspan="4" class="text-center py-6 text-gray-500">Belum ada materi untuk kursus ini. Silakan tambahkan materi baru di atas.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($lessons as $lesson): ?>
                    <tr class="bg-white border-b hover:bg-gray-50" data-id="<?= $lesson['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($lesson['sort_order']) ?></td>
                        <td class="px-6 py-4 font-semibold text-gray-900"><?= e($lesson['title']) ?></td>
                        <td class="px-6 py-4 text-right">
                            <div class="flex justify-end gap-4">
                                <a href="edit_lesson.php?id=<?= $lesson['id'] ?>" class="font-medium text-blue-600 hover:underline">Edit</a>
                                <form action="manage_lessons.php?course_id=<?= $course_id ?>" 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_lesson">
                                    <input type="hidden" name="lesson_id" value="<?= $lesson['id'] ?>">
                                    <button type="submit" class="font-medium text-red-600 hover:underline">Hapus</button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</main>
<script>
    function toggleLessonInput(type) {
        document.getElementById('text-input').classList.add('hidden');
        document.getElementById('video-input').classList.add('hidden');
        document.getElementById('pdf-input').classList.add('hidden');
        document.getElementById('link-input').classList.add('hidden');
        
        document.getElementById(type + '-input').classList.remove('hidden');
    }
    // Jalankan sekali saat halaman dimuat untuk menyetel kondisi awal
    toggleLessonInput('text');

    document.addEventListener('DOMContentLoaded', function() {
        const sortableLessons = document.getElementById('sortable-lessons');
        if(sortableLessons) {
            new Sortable(sortableLessons, {
                handle: '.drag-handle', animation: 150,
                onEnd: function (evt) {
                    const items = Array.from(sortableLessons.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: 'lessons', 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) => {
                                const orderCell = item.querySelector('td:nth-child(2)');
                                if (orderCell) { orderCell.textContent = index + 1; }
                            });
                        }
                    }).catch(error => console.error('Error:', error));
                }
            });
        }
    });
</script>
<?php require_once '../includes/footer.php'; ?>