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

if (isset($_SESSION['user_id'])) {
    header('Location: dashboard.php'); exit;
}

// Ubah query untuk mengurutkan berdasarkan sort_order
$stmt = $pdo->query("SELECT courses.*, users.username as admin_name FROM courses JOIN users ON courses.admin_id = users.id ORDER BY courses.sort_order ASC");
$courses = $stmt->fetchAll();
?>

<main class="container mx-auto p-4 md:p-8">
    <div class="text-center py-12 md:py-20">
        <h1 class="text-4xl md:text-5xl font-extrabold text-gray-800">Platform Belajar Online Masa Kini</h1>
        <p class="mt-4 text-lg text-gray-600 max-w-2xl mx-auto">Tingkatkan keahlian Anda kapan saja dan di mana saja.</p>
        <div class="mt-8 flex justify-center gap-4">
            <a href="/auth/login.php" class="bg-blue-500 text-white font-semibold px-8 py-3 rounded-lg hover:bg-blue-600">Login</a>
            <a href="/auth/register.php" class="bg-gray-800 text-white font-semibold px-8 py-3 rounded-lg hover:bg-gray-900">Daftar Gratis</a>
        </div>
    </div>

    <div class="mt-12">
        <h2 class="text-3xl font-bold text-center text-gray-800 mb-8">Kursus Tersedia</h2>
        <?php if (empty($courses)): ?>
            <div class="text-center text-gray-500">
                <p>Belum ada kursus yang tersedia saat ini.</p>
            </div>
        <?php else: ?>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                <?php foreach ($courses as $course): ?>
                    <div class="bg-white rounded-xl shadow-lg overflow-hidden transform hover:-translate-y-2 transition-transform duration-300">
                        <div class="p-6">
                            <h3 class="text-xl font-bold text-gray-800 mb-2"><?= e($course['title']) ?></h3>
                            <p class="text-gray-600 text-sm mb-4 h-20 overflow-hidden"><?= e($course['description']) ?></p>
                            <div class="flex items-center text-xs text-gray-500 mb-6">
                                <span>Dibuat oleh: <?= e($course['admin_name']) ?></span>
                            </div>
                            <a href="/auth/login.php" class="block w-full text-center bg-gray-200 text-gray-800 font-semibold py-3 rounded-lg hover:bg-gray-300">
                                Lihat Kursus
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</main>

<?php require_once 'includes/footer.php'; ?>