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

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

if (!$course_id) {
    header('Location: /dashboard.php');
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM courses WHERE id = ?");
$stmt->execute([$course_id]);
$course = $stmt->fetch();

if (!$course) {
    echo "<main class='container mx-auto p-8'><div class='bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg' role='alert'><strong>Error:</strong> Kursus tidak ditemukan atau telah dihapus.</div></main>";
    require_once '../includes/footer.php';
    exit;
}

// --- LOGIKA HAK AKSES ---
$access_stmt = $pdo->prepare("SELECT id FROM orders WHERE user_id = ? AND course_id = ? AND status = 'completed'");
$access_stmt->execute([$user_id, $course_id]);
if (!$access_stmt->fetch()) {
    echo "<main class='container mx-auto p-8 text-center'><div class='bg-yellow-100 border-yellow-400 text-yellow-700 p-6 rounded-lg shadow-lg'>";
    echo "<h2 class='text-2xl font-bold mb-4'>Akses Ditolak</h2>";
    echo "<p>Anda harus terdaftar di kursus ini untuk melihat materinya.</p>";
    echo "<a href='/dashboard.php' class='inline-block mt-6 bg-blue-500 text-white font-semibold px-6 py-2 rounded-lg'>Kembali ke Dashboard</a>";
    echo "</div></main>";
    require_once '../includes/footer.php';
    exit;
}
// --- AKHIR LOGIKA HAK AKSES ---

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'submit_review') {
    check_csrf();
    $rating = $_POST['rating'];
    $comment = $_POST['comment'];
    try {
        if (empty($rating) || $rating < 1 || $rating > 5) { throw new Exception("Rating wajib diisi."); }
        $stmt_check = $pdo->prepare("SELECT id FROM reviews WHERE user_id = ? AND course_id = ?");
        $stmt_check->execute([$user_id, $course_id]);
        if ($stmt_check->fetch()) { throw new Exception("Anda sudah memberikan ulasan untuk kursus ini."); }
        $stmt_insert = $pdo->prepare("INSERT INTO reviews (course_id, user_id, rating, comment) VALUES (?, ?, ?, ?)");
        $stmt_insert->execute([$course_id, $user_id, $rating, $comment]);
        $message = "Terima kasih atas ulasan Anda!";
    } catch (Exception $e) { $error = $e->getMessage(); }
}

$lessons_stmt = $pdo->prepare("SELECT * FROM lessons WHERE course_id = ? ORDER BY sort_order ASC");
$lessons_stmt->execute([$course_id]);
$lessons = $lessons_stmt->fetchAll();

$total_lessons = count($lessons);
$completed_lessons_stmt = $pdo->prepare("SELECT COUNT(id) FROM user_progress WHERE user_id = ? AND lesson_id IN (SELECT id FROM lessons WHERE course_id = ?)");
$completed_lessons_stmt->execute([$user_id, $course_id]);
$completed_lessons = $completed_lessons_stmt->fetchColumn();
$is_course_completed = ($total_lessons > 0 && $total_lessons == $completed_lessons);

$user_review_stmt = $pdo->prepare("SELECT * FROM reviews WHERE user_id = ? AND course_id = ?");
$user_review_stmt->execute([$user_id, $course_id]);
$user_review = $user_review_stmt->fetch();
$all_reviews_stmt = $pdo->prepare("SELECT r.*, u.username FROM reviews r JOIN users u ON r.user_id = u.id WHERE r.course_id = ? ORDER BY r.created_at DESC");
$all_reviews_stmt->execute([$course_id]);
$all_reviews = $all_reviews_stmt->fetchAll();

$completed_lessons_ids_stmt = $pdo->prepare("SELECT lesson_id FROM user_progress WHERE user_id = ?");
$completed_lessons_ids_stmt->execute([$user_id]);
$completed_lessons_ids = array_column($completed_lessons_ids_stmt->fetchAll(), 'lesson_id');

$last_completed_index = -1;
foreach ($lessons as $index => $lesson) {
    if (in_array($lesson['id'], $completed_lessons_ids)) {
        $last_completed_index = $index;
    }
}
$next_lesson_index = $last_completed_index + 1;
?>
<main class="container mx-auto p-4 md:p-8">
    <div class="bg-white rounded-xl shadow-lg p-6 md:p-8">
        <h2 class="text-2xl font-bold text-gray-800 mb-6"><?= e($course['title']) ?></h2>
        <div class="space-y-2">
            <?php if (empty($lessons)): ?>
                <p class="text-gray-500">Belum ada materi yang ditambahkan untuk kursus ini.</p>
            <?php else: ?>
                <?php foreach ($lessons as $index => $lesson): ?>
                    <?php
                        $is_completed = in_array($lesson['id'], $completed_lessons_ids);
                        $is_in_progress = ($index === $next_lesson_index);
                    ?>
                    <div class="border rounded-lg overflow-hidden">
                        <div class="lesson-toggle flex items-center p-4 cursor-pointer hover:bg-gray-50 <?= $is_completed ? 'bg-green-50' : '' ?>">
                            <div class="flex-shrink-0">
                                <?php if ($is_completed): ?><div class="flex items-center justify-center w-8 h-8 rounded-full bg-green-500 text-white"><svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg></div>
                                <?php else: ?><div class="flex items-center justify-center w-8 h-8 rounded-full bg-gray-200 text-gray-600 font-bold"><?= e($lesson['sort_order']) ?></div><?php endif; ?>
                            </div>
                            <div class="flex-grow mx-4">
                                <div class="flex items-center space-x-3">
                                    <p class="font-semibold text-gray-700 <?= $is_completed ? 'line-through text-gray-400' : '' ?>"><?= e($lesson['title']) ?></p>
                                    <?php if ($is_completed): ?><span class="text-xs font-semibold text-green-700 bg-green-100 px-2 py-1 rounded-full">Selesai</span>
                                    <?php elseif ($is_in_progress): ?><span class="text-xs font-semibold text-yellow-700 bg-yellow-100 px-2 py-1 rounded-full">Proses</span><?php endif; ?>
                                </div>
                            </div>
                            <div class="flex-shrink-0 text-gray-400"><svg class="w-6 h-6 transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg></div>
                        </div>
                        <div class="lesson-content hidden p-6 border-t border-gray-200 bg-gray-50">
                            <?php if ($lesson['lesson_type'] === 'video' && !empty($lesson['video_path'])): ?><video class="w-full rounded-lg" controls oncontextmenu="return false;"><source src="/stream.php?lesson_id=<?= e($lesson['id']) ?>" type="video/mp4">Browser Anda tidak mendukung tag video.</video>
                            <?php elseif ($lesson['lesson_type'] === 'pdf' && !empty($lesson['video_path'])): ?><div class="text-center"><p class="mb-4">Materi ini berupa file PDF.</p><a href="/<?= e($lesson['video_path']) ?>" target="_blank" class="inline-block bg-red-500 text-white font-semibold px-6 py-3 rounded-lg hover:bg-red-600">Buka PDF</a></div>
                            <?php elseif ($lesson['lesson_type'] === 'link' && !empty($lesson['external_url'])): ?><div class="text-center"><p class="mb-4">Materi ini berupa tautan.</p><a href="<?= e($lesson['external_url']) ?>" target="_blank" class="inline-block bg-gray-600 text-white font-semibold px-6 py-3 rounded-lg hover:bg-gray-700">Buka Tautan</a></div>
                            <?php else: ?><div class="prose max-w-none"><?= nl2br(e($lesson['content'])) ?></div><?php endif; ?>
                            <?php if (!$is_completed): ?><div class="mt-6"><a href="mark_complete.php?lesson_id=<?= $lesson['id'] ?>&course_id=<?= $course['id'] ?>" class="bg-blue-500 text-white font-semibold px-6 py-2 rounded-lg hover:bg-blue-600 text-sm">Tandai Selesai</a></div><?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <div class="bg-white rounded-xl shadow-lg p-6 md:p-8 mt-8">
        <h3 class="text-2xl font-bold text-gray-800 mb-6">Ulasan Kursus</h3>
        <?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; ?>
        <?php if ($is_course_completed && !$user_review): ?>
        <div class="border rounded-lg p-6 mb-8">
            <h4 class="text-lg font-semibold mb-4">Tulis Ulasan Anda</h4>
            <form action="view.php?id=<?= $course_id ?>" method="POST">
                <input type="hidden" name="csrf_token" value="<?= e(generate_csrf_token()); ?>"><input type="hidden" name="action" value="submit_review">
                <div class="mb-4">
                    <label class="block text-gray-700 mb-2">Rating Anda:</label>
                    <div class="flex flex-row-reverse justify-end items-center rating">
                        <input type="radio" name="rating" id="star5" value="5" class="hidden"><label for="star5" class="text-3xl cursor-pointer text-gray-300 hover:text-yellow-400">★</label>
                        <input type="radio" name="rating" id="star4" value="4" class="hidden"><label for="star4" class="text-3xl cursor-pointer text-gray-300 hover:text-yellow-400">★</label>
                        <input type="radio" name="rating" id="star3" value="3" class="hidden"><label for="star3" class="text-3xl cursor-pointer text-gray-300 hover:text-yellow-400">★</label>
                        <input type="radio" name="rating" id="star2" value="2" class="hidden"><label for="star2" class="text-3xl cursor-pointer text-gray-300 hover:text-yellow-400">★</label>
                        <input type="radio" name="rating" id="star1" value="1" class="hidden" required><label for="star1" class="text-3xl cursor-pointer text-gray-300 hover:text-yellow-400">★</label>
                    </div>
                </div>
                <div class="mb-4"><label for="comment" class="block text-gray-700 mb-2">Ulasan (opsional):</label><textarea name="comment" id="comment" rows="4" class="w-full p-2 border rounded-lg"></textarea></div>
                <button type="submit" class="px-6 py-3 font-semibold text-white bg-blue-500 rounded-lg hover:bg-blue-600">Kirim Ulasan</button>
            </form>
        </div>
        <style>.rating:not(:hover) input:checked ~ label, .rating:hover input:hover ~ label { color: #f59e0b; }</style>
        <?php elseif ($user_review): ?><p class="mb-6 bg-gray-100 p-4 rounded-lg">Anda sudah memberikan ulasan untuk kursus ini. Terima kasih!</p><?php endif; ?>
        <div class="space-y-6">
            <?php if (empty($all_reviews)): ?><p class="text-gray-500">Belum ada ulasan untuk kursus ini.</p>
            <?php else: ?>
                <?php foreach ($all_reviews as $review): ?>
                <div class="border-b pb-6 last:border-b-0"><div class="flex items-center mb-2"><strong class="mr-2"><?= e($review['username']) ?></strong><div class="flex items-center"><?php for ($i = 1; $i <= 5; $i++): ?><svg class="w-4 h-4 <?= $i <= $review['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; ?></div></div><p class="text-gray-600"><?= nl2br(e($review['comment'])) ?></p></div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
    <?php if ($is_course_completed): ?>
    <div class="text-center mt-8 border-t pt-8">
        <h3 class="text-xl font-semibold mb-4">Anda Telah Menyelesaikan Semua Materi!</h3>
        <p class="text-gray-600 mb-6">Sekarang, ambil kuis akhir untuk menyelesaikan kursus ini sepenuhnya.</p>
        <a href="quiz.php?course_id=<?= $course_id ?>" class="px-8 py-4 font-semibold text-white bg-green-500 rounded-lg hover:bg-green-600">Mulai Kuis Akhir</a>
    </div>
    <?php endif; ?>
    <div class="text-center mt-8">
         <a href="/dashboard.php" class="bg-gray-800 text-white font-semibold px-6 py-3 rounded-lg hover:bg-gray-900">Kembali ke Dashboard</a>
    </div>
</main>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const toggles = document.querySelectorAll('.lesson-toggle');
    toggles.forEach(toggle => {
        toggle.addEventListener('click', () => {
            const content = toggle.nextElementSibling;
            const arrow = toggle.querySelector('svg');
            if (content.classList.contains('hidden')) {
                content.classList.remove('hidden');
                arrow.style.transform = 'rotate(180deg)';
            } else {
                content.classList.add('hidden');
                arrow.style.transform = 'rotate(0deg)';
            }
        });
    });
});
</script>
<?php require_once '../includes/footer.php'; ?>