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

if (!isset($_SESSION['user_id'])) {
    header('Location: /auth/login.php');
    exit;
}
$user_id = $_SESSION['user_id'];

// 1. Ambil semua kursus
$courses_stmt = $pdo->query("SELECT c.*, u.username as admin_name FROM courses c JOIN users u ON c.admin_id = u.id ORDER BY c.sort_order ASC");
$courses = $courses_stmt->fetchAll();

// 2. Ambil ID kursus yang sudah dibeli/diselesaikan oleh pengguna
$orders_stmt = $pdo->prepare("SELECT course_id FROM orders WHERE user_id = ? AND status = 'completed'");
$orders_stmt->execute([$user_id]);
$enrolled_course_ids = array_column($orders_stmt->fetchAll(), 'course_id');

// 3. Ambil data rating
$ratings_stmt = $pdo->query("SELECT course_id, AVG(rating) as avg_rating, COUNT(id) as review_count FROM reviews GROUP BY course_id");
$ratings = array_column($ratings_stmt->fetchAll(), null, 'course_id');

// 4. Ambil data progres
$lesson_counts_stmt = $pdo->query("SELECT course_id, COUNT(id) AS total_lessons FROM lessons GROUP BY course_id");
$total_lessons_per_course = array_column($lesson_counts_stmt->fetchAll(), 'total_lessons', 'course_id');
$completed_stmt = $pdo->prepare("SELECT l.course_id, COUNT(up.id) AS completed_lessons FROM user_progress up JOIN lessons l ON up.lesson_id = l.id WHERE up.user_id = ? GROUP BY l.course_id");
$completed_stmt->execute([$user_id]);
$completed_lessons_per_course = array_column($completed_stmt->fetchAll(), 'completed_lessons', 'course_id');
?>
<main class="container mx-auto p-4 md:p-8">
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-800">Selamat Datang, <?= e($_SESSION['username']) ?>!</h1>
        <p class="text-gray-600 mt-2">Silakan pilih kursus di bawah ini untuk memulai perjalanan belajar Anda.</p>
    </div>

    <?php if (empty($courses)): ?>
        <div class="bg-blue-100 border border-blue-400 text-blue-700 px-4 py-3 rounded-lg" role="alert">
            <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): ?>
                <?php
                    $course_id = $course['id'];
                    $total_lessons = $total_lessons_per_course[$course_id] ?? 0;
                    $completed_lessons = $completed_lessons_per_course[$course_id] ?? 0;
                    $is_course_completed = (in_array($course_id, $enrolled_course_ids) && $total_lessons > 0 && $total_lessons == $completed_lessons);
                    
                    $avg_rating = $ratings[$course_id]['avg_rating'] ?? 0;
                    $review_count = $ratings[$course_id]['review_count'] ?? 0;
                ?>
                <div class="bg-white rounded-xl shadow-lg overflow-hidden transform hover:-translate-y-2 transition-transform duration-300">
                    <div class="p-6 flex flex-col h-full">
                        <div class="flex-grow">
                            <div class="flex justify-between items-start">
                                <h3 class="text-xl font-bold text-gray-800 mb-2 <?= $is_course_completed ? 'line-through text-gray-400' : '' ?>"><?= e($course['title']) ?></h3>
                                <?php if ($is_course_completed): ?>
                                    <span class="text-xs font-semibold text-green-700 bg-green-100 px-2 py-1 rounded-full">Selesai</span>
                                <?php endif; ?>
                            </div>
                            
                            <div class="flex items-center mb-4">
                                <span class="text-yellow-500 font-bold mr-1"><?= number_format($avg_rating, 1) ?></span>
                                <?php for ($i = 1; $i <= 5; $i++): ?><svg class="w-4 h-4 <?= $i <= round($avg_rating) ? 'text-yellow-400' : 'text-gray-300' ?>" fill="currentColor" viewBox="0 0 20 20"><path d="M10 15l-5.878 3.09 1.123-6.545L.489 6.91l6.572-.955L10 0l2.939 5.955 6.572.955-4.756 4.635 1.123 6.545z"/></svg><?php endfor; ?>
                                <span class="text-xs text-gray-500 ml-2">(<?= $review_count ?> ulasan)</span>
                            </div>

                            <p class="text-gray-600 text-sm mb-4 line-clamp-3"><?= e($course['description']) ?></p>
                        </div>
                        <div class="mt-auto">
                            <div class="flex items-center text-xs text-gray-500 mb-6"><span>Dibuat oleh: <?= e($course['admin_name']) ?></span></div>
                            <?php if (in_array($course['id'], $enrolled_course_ids)): ?>
                                <a href="/course/view.php?id=<?= $course['id'] ?>" class="block w-full text-center bg-green-500 text-white font-semibold py-3 rounded-lg hover:bg-green-600">Masuk Kelas</a>
                            <?php elseif ($course['price'] > 0): ?>
                                <form action="/course/order.php" method="POST">
                                    <input type="hidden" name="csrf_token" value="<?= e(generate_csrf_token()); ?>">
                                    <input type="hidden" name="course_id" value="<?= $course['id'] ?>">
                                    <button type="submit" class="block w-full text-center bg-blue-500 text-white font-semibold py-3 rounded-lg hover:bg-blue-600">Beli Kursus (Rp <?= number_format($course['price']) ?>)</button>
                                </form>
                            <?php else: // Gratis ?>
                                <form action="/course/order.php" method="POST">
                                    <input type="hidden" name="csrf_token" value="<?= e(generate_csrf_token()); ?>">
                                    <input type="hidden" name="course_id" value="<?= $course['id'] ?>">
                                    <button type="submit" class="block w-full text-center bg-gray-800 text-white font-semibold py-3 rounded-lg hover:bg-gray-900">Daftar Gratis</button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</main>
<?php require_once 'includes/footer.php'; ?>