<?php 
// Debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('Asia/Dhaka');

require_once 'db_connect.php';
include 'includes/user_header.php'; 
if(file_exists('includes/sidebar.php')) { include 'includes/sidebar.php'; } 

$student_id = $_SESSION['student_id'] ?? null;
if (!$student_id) { echo "<script>window.location.href='login.php';</script>"; exit; }

$course_id = isset($_GET['course_id']) ? (int)$_GET['course_id'] : 0;
if (!$course_id) { echo "<script>window.location.href='my_courses.php';</script>"; exit; }

// 1. Check if student is actually enrolled in this course
$check_enroll = $pdo->prepare("SELECT id FROM enrollments WHERE student_id = ? AND course_id = ? AND status = 'active'");
$check_enroll->execute([$student_id, $course_id]);
if (!$check_enroll->fetch()) {
    die("<div class='p-5 text-center'><h3>Access Denied</h3><p>You are not enrolled in this course.</p><a href='my_courses.php'>Go Back</a></div>");
}

// 2. Fetch Course Details
$course_stmt = $pdo->prepare("SELECT title FROM courses WHERE id = ?");
$course_stmt->execute([$course_id]);
$course_title = $course_stmt->fetchColumn() ?: "Course Details";

// 3. Handle 'Mark as Complete' Request
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['mark_complete'])) {
    $complete_lesson_id = (int)$_POST['lesson_id'];
    
    // Insert into tracking if not already exists
    $track_check = $pdo->prepare("SELECT id FROM lesson_tracking WHERE student_id = ? AND lesson_id = ?");
    $track_check->execute([$student_id, $complete_lesson_id]);
    if (!$track_check->fetch()) {
        $track_ins = $pdo->prepare("INSERT INTO lesson_tracking (student_id, lesson_id, completed, completed_at) VALUES (?, ?, 1, NOW())");
        $track_ins->execute([$student_id, $complete_lesson_id]);
    }
    
    // Redirect to avoid form resubmission
    header("Location: watch_lesson.php?course_id=$course_id&lesson_id=$complete_lesson_id");
    exit;
}

// 4. Fetch Modules, Lessons, and Progress
$query = $pdo->prepare("
    SELECT m.id as module_id, m.title as module_title, 
           l.id as lesson_id, l.title as lesson_title, l.duration, l.video_url, l.notes, l.resource_url,
           IF(lt.completed = 1, 1, 0) as is_completed
    FROM modules m
    LEFT JOIN lessons l ON m.id = l.module_id
    LEFT JOIN lesson_tracking lt ON l.id = lt.lesson_id AND lt.student_id = ?
    WHERE m.course_id = ?
    ORDER BY m.order_num ASC, l.order_num ASC
");
$query->execute([$student_id, $course_id]);
$results = $query->fetchAll(PDO::FETCH_ASSOC);

$modules = [];
$first_lesson_id = null;
$total_lessons = 0;
$completed_lessons = 0;

foreach ($results as $row) {
    $m_id = $row['module_id'];
    if (!isset($modules[$m_id])) {
        $modules[$m_id] = [
            'title' => $row['module_title'],
            'lessons' => []
        ];
    }
    if ($row['lesson_id']) {
        $total_lessons++;
        if ($row['is_completed']) $completed_lessons++;
        if (!$first_lesson_id) $first_lesson_id = $row['lesson_id'];
        
        $modules[$m_id]['lessons'][] = [
            'id' => $row['lesson_id'],
            'title' => $row['lesson_title'],
            'duration' => $row['duration'],
            'completed' => $row['is_completed'],
            'video_url' => $row['video_url'],
            'notes' => $row['notes'],
            'resource_url' => $row['resource_url']
        ];
    }
}

// 5. Determine Active Lesson Data
$active_lesson_id = isset($_GET['lesson_id']) ? (int)$_GET['lesson_id'] : $first_lesson_id;

$current_lesson_title = "Select a lesson to start";
$current_video_url = "";
$teacher_notes = "No notes available for this lesson.";
$current_resource = null;
$is_current_completed = false;
$active_module_title = "General";

foreach ($modules as $m_id => $mod) {
    foreach ($mod['lessons'] as $les) {
        if ($les['id'] == $active_lesson_id) {
            $current_lesson_title = $les['title'];
            $current_video_url = $les['video_url'];
            $teacher_notes = $les['notes'];
            $current_resource = $les['resource_url'];
            $is_current_completed = $les['completed'];
            $active_module_title = $mod['title'];
            break 2;
        }
    }
}

// Convert normal YouTube links to embed format safely
if (strpos($current_video_url, 'watch?v=') !== false) {
    $current_video_url = str_replace('watch?v=', 'embed/', $current_video_url);
    $current_video_url = explode('&', $current_video_url)[0]; // Remove extra parameters
} elseif (strpos($current_video_url, 'youtu.be/') !== false) {
    $current_video_url = str_replace('youtu.be/', 'youtube.com/embed/', $current_video_url);
}

// Calculate Progress
$progress_percentage = $total_lessons > 0 ? round(($completed_lessons / $total_lessons) * 100) : 0;
?>

<style>
    :root { --primary: #064e3b; --primary-dark: #022c22; --accent: #d4af37; --bg-color: #f1f5f9; }
    .main-content { background-color: var(--bg-color); min-height: 100vh; padding: 20px; }
    
    .video-wrapper { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; border-radius: 16px; background: #000; box-shadow: 0 10px 30px rgba(0,0,0,0.1); }
    .video-wrapper iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0; }

    .content-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; padding: 25px; box-shadow: 0 5px 20px rgba(0,0,0,0.02); margin-top: 20px; }
    
    .playlist-card { background: #fff; border-radius: 16px; border: 1px solid #e2e8f0; box-shadow: 0 5px 20px rgba(0,0,0,0.02); height: calc(100vh - 100px); display: flex; flex-direction: column; overflow: hidden; position: sticky; top: 20px; }
    .playlist-header { padding: 20px; background: var(--primary-dark); color: white; border-bottom: 1px solid rgba(255,255,255,0.1); }
    .playlist-body { overflow-y: auto; flex-grow: 1; }
    
    .playlist-body::-webkit-scrollbar { width: 6px; }
    .playlist-body::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 10px; }

    .accordion-button { font-weight: 700; color: var(--primary-dark); background-color: #f8fafc; border-bottom: 1px solid #e2e8f0; padding: 15px 20px; }
    .accordion-button:not(.collapsed) { color: var(--primary); background-color: rgba(212, 175, 55, 0.1); box-shadow: none; }
    .accordion-button:focus { box-shadow: none; border-color: transparent; }
    
    .lesson-item { padding: 12px 20px; border-bottom: 1px solid #f1f5f9; cursor: pointer; transition: 0.2s; display: flex; align-items: center; text-decoration: none; color: #475569; }
    .lesson-item:hover { background: #f8fafc; color: var(--primary); padding-left: 25px; }
    .lesson-item.active { background: rgba(6, 78, 59, 0.05); border-left: 4px solid var(--primary); color: var(--primary); font-weight: 700; }
    
    .lesson-icon { width: 25px; height: 25px; border-radius: 50%; display: flex; justify-content: center; align-items: center; font-size: 10px; margin-right: 12px; }
    .icon-play { background: #e2e8f0; color: #64748b; }
    .icon-active { background: var(--primary); color: white; animation: pulse 2s infinite; }
    .icon-completed { background: #10b981; color: white; }

    @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(6, 78, 59, 0.4); } 70% { box-shadow: 0 0 0 10px rgba(6, 78, 59, 0); } 100% { box-shadow: 0 0 0 0 rgba(6, 78, 59, 0); } }

    .btn-complete { background: var(--primary); color: white; font-weight: 700; padding: 12px 25px; border-radius: 10px; border: none; transition: 0.3s; }
    .btn-complete:hover { background: #022c22; color: var(--accent); }
    .btn-completed { background: #10b981; color: white; font-weight: 700; padding: 12px 25px; border-radius: 10px; border: none; cursor: default; }
</style>

<div class="main-content">
    <div class="row g-4">
        
        <div class="col-lg-8">
            <nav aria-label="breadcrumb" class="mb-3">
                <ol class="breadcrumb mb-0 small fw-bold text-uppercase" style="font-size: 11px; letter-spacing: 0.5px;">
                    <li class="breadcrumb-item"><a href="my_courses.php" class="text-decoration-none text-muted">My Courses</a></li>
                    <li class="breadcrumb-item active" aria-current="page" style="color: var(--primary);"><?= htmlspecialchars($course_title) ?></li>
                </ol>
            </nav>

            <div class="video-wrapper mb-4">
                <?php if($current_video_url): ?>
                    <iframe src="<?= htmlspecialchars($current_video_url) ?>" title="Course Video Player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                <?php else: ?>
                    <div class="w-100 h-100 d-flex align-items-center justify-content-center text-white-50 flex-column" style="position: absolute;">
                        <i class="fas fa-video-slash fa-3x mb-3"></i>
                        <h5>No Video Available</h5>
                    </div>
                <?php endif; ?>
            </div>

            <div class="content-card">
                <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-4 gap-3">
                    <div>
                        <h4 class="fw-bold text-dark mb-1"><?= htmlspecialchars($current_lesson_title) ?></h4>
                        <span class="badge bg-light text-primary border"><i class="fas fa-folder-open me-1"></i> <?= htmlspecialchars($active_module_title) ?></span>
                    </div>
                    <div>
                        <?php if($active_lesson_id): ?>
                            <?php if($is_current_completed): ?>
                                <button class="btn-completed shadow-sm" disabled>
                                    Completed <i class="fas fa-check-double ms-2"></i>
                                </button>
                            <?php else: ?>
                                <form action="" method="POST" class="m-0">
                                    <input type="hidden" name="lesson_id" value="<?= $active_lesson_id ?>">
                                    <button type="submit" name="mark_complete" class="btn-complete shadow-sm">
                                        Mark as Complete <i class="fas fa-check-circle ms-2"></i>
                                    </button>
                                </form>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <hr class="opacity-10 mb-4">

                <ul class="nav nav-pills mb-3 gap-2" id="pills-tab" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active fw-bold rounded-pill px-4" id="pills-overview-tab" data-bs-toggle="pill" data-bs-target="#pills-overview" type="button" role="tab">Overview & Notes</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link fw-bold rounded-pill px-4" id="pills-resources-tab" data-bs-toggle="pill" data-bs-target="#pills-resources" type="button" role="tab">
                            Resources <?= $current_resource ? '<span class="badge bg-danger ms-1">1</span>' : '' ?>
                        </button>
                    </li>
                </ul>
                
                <div class="tab-content" id="pills-tabContent">
                    <div class="tab-pane fade show active text-muted" id="pills-overview" role="tabpanel" style="line-height: 1.8;">
                        <?= $teacher_notes ? nl2br(htmlspecialchars($teacher_notes)) : '<p>No specific notes for this lesson.</p>' ?>
                    </div>
                    <div class="tab-pane fade" id="pills-resources" role="tabpanel">
                        <?php if($current_resource): ?>
                            <a href="<?= htmlspecialchars($current_resource) ?>" target="_blank" class="d-flex align-items-center p-3 rounded-3 border text-decoration-none text-dark mb-2" style="background: #f8fafc; transition: 0.3s;" onmouseover="this.style.borderColor='var(--primary)'" onmouseout="this.style.borderColor='#e2e8f0'">
                                <div class="bg-danger text-white rounded p-2 me-3"><i class="fas fa-file-pdf fa-lg"></i></div>
                                <div>
                                    <h6 class="fw-bold mb-0">Lesson_Resource_File</h6>
                                    <small class="text-muted">Click to view/download</small>
                                </div>
                                <i class="fas fa-download ms-auto text-muted"></i>
                            </a>
                        <?php else: ?>
                            <p class="text-muted mt-2">No attachments provided for this lesson.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="playlist-card">
                <div class="playlist-header">
                    <h5 class="fw-bold mb-1 text-white">Course Content</h5>
                    <div class="progress mt-2" style="height: 6px; background: rgba(255,255,255,0.2);">
                        <div class="progress-bar" style="background: var(--accent); width: <?= $progress_percentage ?>%;"></div>
                    </div>
                    <small class="text-white-50 fw-bold mt-1 d-block" style="font-size: 11px;">
                        <?= $progress_percentage ?>% Completed (<?= $completed_lessons ?>/<?= $total_lessons ?> Lessons)
                    </small>
                </div>
                
                <div class="playlist-body">
                    <?php if(empty($modules)): ?>
                        <div class="text-center p-4 text-muted mt-5">
                            <i class="fas fa-folder-open fa-3x mb-3 opacity-25"></i>
                            <h6>Modules coming soon</h6>
                        </div>
                    <?php else: ?>
                        <div class="accordion accordion-flush" id="curriculumAccordion">
                            <?php foreach($modules as $m_index => $module): ?>
                            <div class="accordion-item border-0">
                                <h2 class="accordion-header" id="heading<?= $m_index ?>">
                                    <button class="accordion-button <?= $m_index == array_key_first($modules) ? '' : 'collapsed' ?>" type="button" data-bs-toggle="collapse" data-bs-target="#collapse<?= $m_index ?>">
                                        <?= htmlspecialchars($module['title']) ?>
                                    </button>
                                </h2>
                                <div id="collapse<?= $m_index ?>" class="accordion-collapse collapse <?= $m_index == array_key_first($modules) ? 'show' : '' ?>" data-bs-parent="#curriculumAccordion">
                                    <div class="accordion-body p-0">
                                        <?php foreach($module['lessons'] as $lesson): 
                                            $is_active = ($lesson['id'] == $active_lesson_id);
                                        ?>
                                            <a href="?course_id=<?= $course_id ?>&lesson_id=<?= $lesson['id'] ?>" class="lesson-item <?= $is_active ? 'active' : '' ?>">
                                                
                                                <?php if($is_active): ?>
                                                    <div class="lesson-icon icon-active"><i class="fas fa-play"></i></div>
                                                <?php elseif($lesson['completed']): ?>
                                                    <div class="lesson-icon icon-completed"><i class="fas fa-check"></i></div>
                                                <?php else: ?>
                                                    <div class="lesson-icon icon-play"><i class="fas fa-lock-open"></i></div>
                                                <?php endif; ?>

                                                <div class="w-100">
                                                    <div class="d-flex justify-content-between align-items-center">
                                                        <span class="mb-0 text-truncate" style="font-size: 14px; max-width: 180px;">
                                                            <?= htmlspecialchars($lesson['title']) ?>
                                                        </span>
                                                        <small class="text-muted fw-bold" style="font-size: 11px;">
                                                            <?= htmlspecialchars($lesson['duration']) ?>
                                                        </small>
                                                    </div>
                                                </div>
                                            </a>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<?php include 'includes/user_footer.php'; ?>