<?php
include '../config.php';

if (!isSiswa()) {
    redirect('../login.php');
}

// Cek parameter
if (!isset($_GET['course_id']) || !isset($_GET['lesson_id'])) {
    $_SESSION['error'] = "Parameter tidak valid!";
    redirect('my_courses.php');
}

$course_id = sanitize($_GET['course_id']);
$lesson_id = sanitize($_GET['lesson_id']);
$user_id = $_SESSION['user_id'];

// Cek apakah siswa terdaftar di kursus ini
$sql_enrollment = "SELECT e.*, c.judul as course_title 
                   FROM lms_enrollments e 
                   JOIN lms_courses c ON e.id_course = c.id 
                   WHERE e.id_siswa = ? AND e.id_course = ? AND e.status = 'active'";
$stmt_enrollment = $conn->prepare($sql_enrollment);
$stmt_enrollment->bind_param('ii', $user_id, $course_id);
$stmt_enrollment->execute();
$result_enrollment = $stmt_enrollment->get_result();

if ($result_enrollment->num_rows == 0) {
    $_SESSION['error'] = "Anda belum terdaftar di kursus ini!";
    redirect('my_courses.php');
}

$enrollment = $result_enrollment->fetch_assoc();
$current_progress = $enrollment['progress'];

// Ambil data lesson
$sql_lesson = "SELECT l.*, c.judul as course_title, u.nama_lengkap as nama_guru,
               (SELECT COUNT(*) FROM lms_quizzes WHERE id_lesson = l.id) as has_quiz
               FROM lms_lessons l
               JOIN lms_courses c ON l.id_course = c.id
               JOIN lms_users u ON c.id_guru = u.id
               WHERE l.id = ? AND l.id_course = ?";
$stmt_lesson = $conn->prepare($sql_lesson);
$stmt_lesson->bind_param('ii', $lesson_id, $course_id);
$stmt_lesson->execute();
$result_lesson = $stmt_lesson->get_result();

if ($result_lesson->num_rows == 0) {
    $_SESSION['error'] = "Lesson tidak ditemukan!";
    redirect("course_learn.php?id=$course_id");
}

$lesson = $result_lesson->fetch_assoc();

// Ambil semua lms_lessons untuk navigasi - PERBAIKAN: tambahkan has_quiz di query
$sql_lms_lessons = "SELECT l.*, 
                (SELECT COUNT(*) FROM lms_quizzes WHERE id_lesson = l.id) as has_quiz
                FROM lms_lessons l 
                WHERE l.id_course = ? 
                ORDER BY l.urutan ASC";
$stmt_lms_lessons = $conn->prepare($sql_lms_lessons);
$stmt_lms_lessons->bind_param('i', $course_id);
$stmt_lms_lessons->execute();
$result_lms_lessons = $stmt_lms_lessons->get_result();

$lms_lessons_data = [];
while ($l = $result_lms_lessons->fetch_assoc()) {
    $lms_lessons_data[] = $l;
}

// Cari lesson sebelumnya dan selanjutnya
$current_index = null;
$prev_lesson = null;
$next_lesson = null;

foreach ($lms_lessons_data as $index => $l) {
    if ($l['id'] == $lesson_id) {
        $current_index = $index;
        $prev_lesson = $index > 0 ? $lms_lessons_data[$index - 1] : null;
        $next_lesson = $index < count($lms_lessons_data) - 1 ? $lms_lessons_data[$index + 1] : null;
        break;
    }
}

// Handle lesson completion
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['complete_lesson'])) {
    $lesson_urutan = $lesson['urutan'];
    
    // Update progress berdasarkan urutan lesson
    $new_progress = min(100, ($lesson_urutan * 10)); // Setiap lesson = 10% progress
    
    $sql_update = "UPDATE lms_enrollments SET progress = ? WHERE id_siswa = ? AND id_course = ?";
    $stmt_update = $conn->prepare($sql_update);
    $stmt_update->bind_param('iii', $new_progress, $user_id, $course_id);
    
    if ($stmt_update->execute()) {
        $_SESSION['success'] = "Lesson berhasil diselesaikan!";
        $current_progress = $new_progress;
        
        // Redirect ke lesson berikutnya jika ada
        if ($next_lesson) {
            redirect("lesson.php?course_id=$course_id&lesson_id=" . $next_lesson['id']);
        } else {
            redirect("course_learn.php?id=$course_id");
        }
    } else {
        $_SESSION['error'] = "Gagal update progress!";
    }
}

// Cek apakah lesson ini sudah selesai
$is_lesson_completed = $lesson['urutan'] <= ($current_progress / 10);
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $lesson['judul_lesson']; ?> - SMANSAB LMS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-color: #3f51b5;
            --secondary-color: #f8f9fa;
        }
        
        body {
            background-color: #f5f7fb;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .learning-container {
            display: flex;
            min-height: 100vh;
        }
        
        /* Sidebar Styles */
        .sidebar-learning {
            width: 320px;
            background: white;
            border-right: 1px solid #e0e0e0;
            height: 100vh;
            position: fixed;
            left: 0;
            top: 0;
            overflow-y: auto;
            box-shadow: 2px 0 8px rgba(0,0,0,0.1);
        }
        
        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #e0e0e0;
            background: white;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        
        .sidebar-content {
            padding: 20px;
        }
        
        /* Main Content Styles */
        .content-learning {
            flex: 1;
            margin-left: 320px;
            background: #f5f7fb;
            min-height: 100vh;
        }
        
        .content-header {
            background: white;
            padding: 15px 30px;
            border-bottom: 1px solid #e0e0e0;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        .lesson-content-area {
            max-width: 900px;
            margin: 0 auto;
            padding: 30px;
        }
        
        /* Lesson List Styles */
        .lesson-item {
            padding: 12px 15px;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
        }
        
        .lesson-item:hover {
            border-color: var(--primary-color);
            background: #f8f9ff;
        }
        
        .lesson-item.active {
            border-color: var(--primary-color);
            background: #f0f4ff;
            box-shadow: 0 2px 8px rgba(63, 81, 181, 0.1);
        }
        
        .lesson-item.completed {
            border-left: 4px solid #28a745;
            background: #f8fff9;
        }
        
        .lesson-number {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            background: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 0.8rem;
            margin-right: 12px;
            flex-shrink: 0;
        }
        
        .lesson-item.active .lesson-number {
            background: var(--primary-color);
            color: white;
        }
        
        .lesson-item.completed .lesson-number {
            background: #28a745;
            color: white;
        }
        
        /* Progress Styles */
        .progress-container {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .progress-learning {
            height: 8px;
            border-radius: 4px;
            background: #e9ecef;
        }
        
        .progress-learning .progress-bar {
            border-radius: 4px;
            background: linear-gradient(45deg, #667eea, #764ba2);
        }
        
        /* Content Card Styles */
        .content-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            border: 1px solid #e9ecef;
            margin-bottom: 20px;
            overflow: hidden;
        }
        
        .content-card-header {
            padding: 25px 30px 0;
            border-bottom: none;
        }
        
        .content-card-body {
            padding: 25px 30px;
        }
        
        /* Lesson Content Styles */
        .lesson-html-content {
            line-height: 1.7;
            font-size: 1.05rem;
            color: #2d3748;
        }
        
        .lesson-html-content h1 {
            font-size: 2rem;
            font-weight: 700;
            color: #1a202c;
            margin-bottom: 1.5rem;
            border-bottom: 2px solid #e2e8f0;
            padding-bottom: 0.5rem;
        }
        
        .lesson-html-content h2 {
            font-size: 1.5rem;
            font-weight: 600;
            color: #2d3748;
            margin: 2rem 0 1rem 0;
        }
        
        .lesson-html-content h3 {
            font-size: 1.25rem;
            font-weight: 600;
            color: #4a5568;
            margin: 1.5rem 0 0.75rem 0;
        }
        
        .lesson-html-content p {
            margin-bottom: 1.25rem;
            color: #4a5568;
        }
        
        .lesson-html-content ul, 
        .lesson-html-content ol {
            margin-bottom: 1.25rem;
            padding-left: 2rem;
        }
        
        .lesson-html-content li {
            margin-bottom: 0.5rem;
            color: #4a5568;
        }
        
        .lesson-html-content blockquote {
            border-left: 4px solid var(--primary-color);
            padding: 1rem 1.5rem;
            margin: 1.5rem 0;
            background: #f7fafc;
            border-radius: 0 8px 8px 0;
            font-style: italic;
        }
        
        .lesson-html-content table {
            width: 100%;
            border-collapse: collapse;
            margin: 1.5rem 0;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .lesson-html-content table th,
        .lesson-html-content table td {
            border: 1px solid #e2e8f0;
            padding: 12px 15px;
            text-align: left;
        }
        
        .lesson-html-content table th {
            background: #f7fafc;
            font-weight: 600;
            color: #2d3748;
        }
        
        .lesson-html-content img {
            max-width: 100%;
            height: auto;
            border-radius: 8px;
            margin: 1.5rem 0;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        /* Video Container */
        .video-container {
            background: #000;
            border-radius: 12px;
            overflow: hidden;
            margin-bottom: 25px;
            position: relative;
        }
        
        .video-placeholder {
            height: 400px;
            background: linear-gradient(45deg, #1e3c72, #2a5298);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
        }
        
        .video-placeholder i {
            font-size: 4rem;
            opacity: 0.8;
        }
        
        /* Quiz Card Styles */
        .quiz-card {
            background: linear-gradient(135deg, #fff9e6, #fff3cd);
            border: 2px solid #ffeaa7;
            border-radius: 12px;
            padding: 25px;
            margin: 25px 0;
        }
        
        /* Navigation Buttons */
        .nav-buttons {
            background: white;
            padding: 20px 30px;
            border-top: 1px solid #e9ecef;
            position: sticky;
            bottom: 0;
            margin-top: 30px;
        }
        
        /* Completion Badge */
        .completion-badge {
            font-size: 0.75rem;
            padding: 4px 8px;
            border-radius: 12px;
        }
        
        /* Mobile Responsive */
        @media (max-width: 768px) {
            .learning-container {
                flex-direction: column;
            }
            
            .sidebar-learning {
                position: relative;
                width: 100%;
                height: auto;
            }
            
            .content-learning {
                margin-left: 0;
            }
            
            .lesson-content-area {
                padding: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="learning-container">
        <!-- Sidebar -->
        <div class="sidebar-learning">
            <div class="sidebar-header">
                <div class="d-flex align-items-center">
                    <a href="course_learn.php?id=<?php echo $course_id; ?>" class="btn btn-outline-primary btn-sm me-3">
                        <i class="bi bi-arrow-left"></i>
                    </a>
                    <div>
                        <h6 class="mb-1 fw-bold"><?php echo $lesson['course_title']; ?></h6>
                        <small class="text-muted">Oleh: <?php echo $lesson['nama_guru']; ?></small>
                    </div>
                </div>
            </div>
            
            <div class="sidebar-content">
                <!-- Progress Section -->
                <div class="progress-container">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted small">Progress Kursus</span>
                        <span class="text-muted small"><?php echo $current_progress; ?>%</span>
                    </div>
                    <div class="progress progress-learning">
                        <div class="progress-bar" style="width: <?php echo $current_progress; ?>%"></div>
                    </div>
                </div>
                
                <!-- lms_lessons List -->
                <h6 class="fw-bold mb-3">Daftar Materi</h6>
                <div class="lms_lessons-list">
                    <?php foreach ($lms_lessons_data as $l): 
                        $is_completed = $l['urutan'] <= ($current_progress / 10);
                        $is_active = $l['id'] == $lesson_id;
                        // PERBAIKAN: Gunakan $l['has_quiz'] yang sudah diambil dari query
                        $has_quiz = isset($l['has_quiz']) ? $l['has_quiz'] > 0 : false;
                    ?>
                        <div class="lesson-item <?php echo $is_active ? 'active' : ''; ?> <?php echo $is_completed ? 'completed' : ''; ?>"
                             onclick="window.location.href='lesson.php?course_id=<?php echo $course_id; ?>&lesson_id=<?php echo $l['id']; ?>'">
                            <div class="d-flex align-items-start">
                                <div class="lesson-number"><?php echo $l['urutan']; ?></div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-1 fw-semibold small"><?php echo $l['judul_lesson']; ?></h6>
                                    <div class="d-flex align-items-center text-muted small">
                                        <i class="bi bi-clock me-1"></i>
                                        <span><?php echo $l['durasi_menit']; ?> menit</span>
                                        <?php if ($has_quiz): ?>
                                            <i class="bi bi-pencil-square ms-2 me-1"></i>
                                            <span>Quiz</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="ms-2">
                                    <?php if ($is_completed): ?>
                                        <i class="bi bi-check-circle-fill text-success"></i>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="content-learning">
            <!-- Content Header -->
            <div class="content-header">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h4 class="fw-bold mb-1"><?php echo $lesson['judul_lesson']; ?></h4>
                        <p class="text-muted mb-0">
                            Pertemuan <?php echo $lesson['urutan']; ?> dari <?php echo count($lms_lessons_data); ?> • 
                            <?php echo $lesson['durasi_menit']; ?> menit
                        </p>
                    </div>
                    <div class="d-flex align-items-center">
                        <div class="me-3 text-end">
                            <small class="text-muted d-block">Progress Anda</small>
                            <span class="fw-bold text-primary"><?php echo $current_progress; ?>%</span>
                        </div>
                        <div class="dropdown">
                            <button class="btn btn-outline-primary dropdown-toggle" type="button" 
                                    data-bs-toggle="dropdown">
                                <i class="bi bi-person-circle me-2"></i>
                                <?php echo $_SESSION['nama_lengkap']; ?>
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="dashboard.php">
                                    <i class="bi bi-speedometer2 me-2"></i>Dashboard
                                </a></li>
                                <li><a class="dropdown-item" href="my_courses.php">
                                    <i class="bi bi-journal-bookmark me-2"></i>Kursus Saya
                                </a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item" href="../logout.php">
                                    <i class="bi bi-box-arrow-right me-2"></i>Logout
                                </a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Lesson Content Area -->
            <div class="lesson-content-area">
                <!-- Completion Status -->
                <div class="content-card">
                    <div class="content-card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h5 class="mb-1">Status Pembelajaran</h5>
                                <p class="text-muted mb-0">
                                    <?php if ($is_lesson_completed): ?>
                                        Anda telah menyelesaikan lesson ini
                                    <?php else: ?>
                                        Pelajari materi dengan seksama sebelum menyelesaikan lesson
                                    <?php endif; ?>
                                </p>
                            </div>
                            <div>
                                <?php if (!$is_lesson_completed): ?>
                                    <form method="POST" class="d-inline">
                                        <button type="submit" name="complete_lesson" 
                                                class="btn btn-success btn-lg"
                                                onclick="return confirm('Apakah Anda yakin telah menyelesaikan lesson ini?')">
                                            <i class="bi bi-check-circle me-2"></i>Tandai Selesai
                                        </button>
                                    </form>
                                <?php else: ?>
                                    <span class="badge bg-success fs-6 p-3">
                                        <i class="bi bi-check-circle me-2"></i>Sudah Selesai
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Video Content -->
                <?php if ($lesson['tipe_lesson'] == 'video' && !empty($lesson['video_url'])): ?>
                    <div class="content-card">
                        <div class="content-card-body">
                            <h5 class="mb-3">Video Pembelajaran</h5>
                            <div class="video-container">
                                <?php if (strpos($lesson['video_url'], 'youtube.com') !== false || strpos($lesson['video_url'], 'youtu.be') !== false): ?>
                                    <!-- Embed YouTube Video -->
                                    <iframe width="100%" height="400" 
                                            src="https://www.youtube.com/embed/<?php echo getYouTubeId($lesson['video_url']); ?>" 
                                            frameborder="0" 
                                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                                            allowfullscreen>
                                    </iframe>
                                <?php else: ?>
                                    <!-- HTML5 Video -->
                                    <video width="100%" height="400" controls>
                                        <source src="<?php echo $lesson['video_url']; ?>" type="video/mp4">
                                        Browser Anda tidak mendukung pemutar video.
                                    </video>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php elseif ($lesson['tipe_lesson'] == 'video'): ?>
                    <div class="content-card">
                        <div class="content-card-body">
                            <h5 class="mb-3">Video Pembelajaran</h5>
                            <div class="video-container">
                                <div class="video-placeholder">
                                    <i class="bi bi-play-btn"></i>
                                </div>
                            </div>
                            <div class="text-center mt-3">
                                <p class="text-muted mb-0">Video pembelajaran akan segera tersedia</p>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Lesson Content -->
                <div class="content-card">
                    <div class="content-card-body">
                        <h5 class="mb-4">Materi Pembelajaran</h5>
                        <?php if (!empty($lesson['konten'])): ?>
                            <div class="lesson-html-content">
                                <?php echo $lesson['konten']; ?>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <i class="bi bi-file-text text-muted" style="font-size: 4rem;"></i>
                                <h5 class="text-muted mt-3">Konten Belum Tersedia</h5>
                                <p class="text-muted">Materi pembelajaran untuk lesson ini sedang dalam persiapan.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Quiz Section -->
                <?php 
                // PERBAIKAN: Gunakan $lesson['has_quiz'] yang sudah diambil dari query utama
                $current_lesson_has_quiz = isset($lesson['has_quiz']) ? $lesson['has_quiz'] > 0 : false;
                ?>
                <?php if ($current_lesson_has_quiz): ?>
                    <div class="quiz-card">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div>
                                <h5 class="mb-1">
                                    <i class="bi bi-pencil-square text-warning me-2"></i>
                                    Quiz - <?php echo $lesson['judul_lesson']; ?>
                                </h5>
                                <p class="text-muted mb-0">
                                    Uji pemahaman Anda dengan mengerjakan quiz
                                </p>
                            </div>
                            <div>
                                <a href="take_quiz.php?lesson_id=<?php echo $lesson['id']; ?>" 
                                   class="btn btn-warning">
                                    <i class="bi bi-pencil me-2"></i>Kerjakan Quiz
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <!-- Navigation Buttons -->
                <div class="nav-buttons">
                    <div class="d-flex justify-content-between">
                        <div>
                            <?php if ($prev_lesson): ?>
                                <a href="lesson.php?course_id=<?php echo $course_id; ?>&lesson_id=<?php echo $prev_lesson['id']; ?>" 
                                   class="btn btn-outline-primary">
                                    <i class="bi bi-chevron-left me-2"></i>Materi Sebelumnya
                                </a>
                            <?php endif; ?>
                        </div>
                        
                        <div>
                            <?php if ($next_lesson): ?>
                                <a href="lesson.php?course_id=<?php echo $course_id; ?>&lesson_id=<?php echo $next_lesson['id']; ?>" 
                                   class="btn btn-primary">
                                    Materi Selanjutnya<i class="bi bi-chevron-right ms-2"></i>
                                </a>
                            <?php else: ?>
                                <a href="course_learn.php?id=<?php echo $course_id; ?>" 
                                   class="btn btn-success">
                                    Selesai Kursus<i class="bi bi-check-circle ms-2"></i>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Auto-scroll to current lesson in sidebar
            const activeLesson = document.querySelector('.lesson-item.active');
            if (activeLesson) {
                activeLesson.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }

            // Track time spent on lesson
            let startTime = new Date();
            
            window.addEventListener('beforeunload', function() {
                const endTime = new Date();
                const timeSpent = Math.round((endTime - startTime) / 1000); // in seconds
                
                // Send time spent to server (optional)
                console.log(`Waktu yang dihabiskan: ${timeSpent} detik`);
            });
        });

        // Helper function untuk mendapatkan YouTube ID
        function getYouTubeId(url) {
            const regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
            const match = url.match(regExp);
            return (match && match[7].length === 11) ? match[7] : false;
        }
    </script>
</body>
</html>

<?php
// Helper function untuk extract YouTube ID
function getYouTubeId($url) {
    $pattern = '/^(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&?\/\s]{11})/';
    preg_match($pattern, $url, $matches);
    return isset($matches[1]) ? $matches[1] : '';
}
?>