<?php
require_once '../config/database.php';
require_once '../includes/functions.php';

// 1. 權限檢查
check_login('student');
$student_id = $_SESSION['user_id'];

// 2. 獲取參數 (課程ID 與 Day/Index)
$course_id = isset($_GET['id']) ? (int)$_GET['id'] : 1;
$day_index = isset($_GET['day']) ? (int)$_GET['day'] : 0; // 0 = Lesson 1

try {
    // A. 獲取課程資訊
    $stmt = $pdo->prepare("SELECT * FROM courses WHERE id = ?");
    $stmt->execute([$course_id]);
    $course = $stmt->fetch();

    // B. 獲取該課程所有章節
    $stmt = $pdo->prepare("SELECT * FROM course_materials WHERE course_id = ? ORDER BY week_number ASC");
    $stmt->execute([$course_id]);
    $all_lessons = $stmt->fetchAll();

    if (!isset($all_lessons[$day_index])) {
        die("找不到該章節");
    }
    
    $current_lesson = $all_lessons[$day_index];
    $lesson_id = $current_lesson['id'];

    // C. 獲取本課影片
    $stmt = $pdo->prepare("SELECT * FROM lesson_videos WHERE lesson_id = ? ORDER BY video_order ASC");
    $stmt->execute([$lesson_id]);
    $videos = $stmt->fetchAll();
    
    // 預設播放影片邏輯
    $current_video = isset($_GET['vid']) ? 
        array_filter($videos, function($v) { return $v['id'] == $_GET['vid']; })[0] ?? ($videos[0] ?? null) 
        : ($videos[0] ?? null);

    // D. 獲取作業資訊
    $stmt = $pdo->prepare("SELECT * FROM assignments WHERE lesson_id = ?");
    $stmt->execute([$lesson_id]);
    $assignment = $stmt->fetch();

    // E. 檢查學生是否已提交作業 (解鎖關鍵)
    $is_assignment_submitted = false;
    if ($assignment) {
        // 檢查 student_assignments 表
        $stmt = $pdo->prepare("SELECT id FROM student_assignments WHERE user_id = ? AND assignment_id = ?");
        $stmt->execute([$student_id, $assignment['id']]);
        if ($stmt->rowCount() > 0) {
            $is_assignment_submitted = true;
        }
    } else {
        // 如果沒有作業，預設解鎖
        $is_assignment_submitted = true;
    }

    // F. 獲取測驗題目 (僅當解鎖時顯示)
    $quizzes = [];
    if ($is_assignment_submitted) {
        $stmt = $pdo->prepare("SELECT * FROM quizzes WHERE lesson_id = ?");
        $stmt->execute([$lesson_id]);
        $quizzes = $stmt->fetchAll();
    }

} catch (PDOException $e) {
    die("資料庫錯誤: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="zh-HK">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($current_lesson['title']) ?> - <?= htmlspecialchars($course['title']) ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@300;400;500;700&family=Noto+Serif+TC:wght@700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Noto Sans TC', sans-serif; }
        .font-serif { font-family: 'Noto Serif TC', serif; }
    </style>
</head>
<body class="bg-[#F3EDE9] min-h-screen flex flex-col">

    <!-- Navbar -->
    <nav class="bg-[#2C2C2C] text-white px-6 py-3 sticky top-0 z-50 shadow-md">
        <div class="container mx-auto max-w-7xl flex items-center justify-between">
            <a href="course_detail.php?id=<?= $course_id ?>" class="flex items-center gap-2 text-gray-300 hover:text-white transition">
                <i data-lucide="arrow-left" class="w-5 h-5"></i>
                <span class="text-sm">返回課程目錄</span>
            </a>
            <div class="text-center">
                <div class="text-xs text-gray-400 uppercase tracking-widest">LESSON <?= $day_index + 1 ?></div>
                <h1 class="font-serif text-lg font-bold text-[#E5D5C0]"><?= htmlspecialchars($current_lesson['title']) ?></h1>
            </div>
            <div class="w-24"></div>
        </div>
    </nav>

    <main class="container mx-auto max-w-7xl p-4 lg:p-6 flex-1">
        <div class="grid grid-cols-1 lg:grid-cols-12 gap-6 h-full">
            
            <!-- 左側：影片區 (8欄) -->
            <div class="lg:col-span-8 flex flex-col gap-6">
                <!-- 播放器 -->
                <div class="bg-black rounded-xl shadow-2xl overflow-hidden aspect-video relative">
                    <?php if ($current_video): ?>
                        <?php 
                            $embed_url = str_replace(["watch?v=", "youtu.be/"], ["embed/", "www.youtube.com/embed/"], $current_video['video_url']);
                        ?>
                        <iframe src="<?= $embed_url ?>" class="w-full h-full" frameborder="0" allowfullscreen></iframe>
                    <?php else: ?>
                        <div class="flex items-center justify-center h-full text-gray-500 flex-col">
                            <i data-lucide="video-off" class="w-12 h-12 mb-2 opacity-50"></i>
                            <p>本課暫無影片</p>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- 影片清單 (已移除高度限制) -->
                <div class="bg-white rounded-xl border border-[#E5E7EB] shadow-sm overflow-hidden">
                    <div class="p-4 border-b border-gray-100 bg-gray-50 flex justify-between items-center">
                        <h3 class="font-bold text-gray-700 flex items-center gap-2">
                            <i data-lucide="list-video" class="w-5 h-5"></i> 本課影片清單
                        </h3>
                        <span class="text-xs text-gray-500">共 <?= count($videos) ?> 個單元</span>
                    </div>
                    
                    <!-- ★ 關鍵修改：這裡移除了 max-h-60 和 overflow-y-auto，清單將會全展開 ★ -->
                    <div class="divide-y divide-gray-100">
                        <?php foreach ($videos as $idx => $v): 
                            $is_active = ($current_video && $v['id'] == $current_video['id']);
                        ?>
                        <a href="?id=<?= $course_id ?>&day=<?= $day_index ?>&vid=<?= $v['id'] ?>" 
                           class="flex items-center gap-4 p-4 hover:bg-gray-50 transition <?= $is_active ? 'bg-orange-50 border-l-4 border-orange-500' : '' ?>">
                            <div class="w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0 
                                <?= $is_active ? 'bg-orange-500 text-white' : 'bg-gray-200 text-gray-500' ?>">
                                <?= $idx + 1 ?>
                            </div>
                            <div class="text-sm font-medium truncate <?= $is_active ? 'text-orange-700' : 'text-gray-700' ?>">
                                <?= htmlspecialchars($v['title']) ?>
                            </div>
                        </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- 右側：作業與測驗 (4欄) -->
            <div class="lg:col-span-4 flex flex-col gap-6">
                
                <!-- 1. 作業區 -->
                <div class="bg-white rounded-xl border border-[#E5E7EB] shadow-sm p-6">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-lg font-bold text-gray-800">本週作業</h3>
                        <?php if ($is_assignment_submitted): ?>
                            <span class="bg-green-100 text-green-700 text-xs px-2 py-1 rounded-full font-bold flex items-center gap-1">
                                <i data-lucide="check-circle" class="w-3 h-3"></i> 已提交
                            </span>
                        <?php else: ?>
                            <span class="bg-red-100 text-red-700 text-xs px-2 py-1 rounded-full font-bold">未完成</span>
                        <?php endif; ?>
                    </div>

                    <?php if ($assignment): ?>
                        <div class="text-sm text-gray-600 mb-4 bg-gray-50 p-3 rounded border border-gray-100">
                            <?= nl2br(htmlspecialchars($assignment['description'])) ?>
                        </div>
                        
                        <?php if (!$is_assignment_submitted): ?>
                            <a href="upload_assignment.php?id=<?= $assignment['id'] ?>" class="block w-full py-3 bg-[#9B170C] hover:bg-[#7a1209] text-white text-center rounded-lg font-bold transition shadow-md flex items-center justify-center gap-2">
                                <i data-lucide="upload-cloud" class="w-4 h-4"></i> 立即交功課
                            </a>
                            <p class="text-xs text-center text-gray-400 mt-2">完成上傳後，下方測驗將自動解鎖。</p>
                        <?php else: ?>
                            <button disabled class="w-full py-3 bg-gray-100 text-gray-400 rounded-lg font-bold cursor-not-allowed border border-gray-200">
                                作業已提交
                            </button>
                        <?php endif; ?>
                    <?php else: ?>
                        <p class="text-sm text-gray-400 text-center">本課無作業</p>
                    <?php endif; ?>
                </div>

                <!-- 2. 測驗區 (含閱讀短文) -->
                <div class="bg-white rounded-xl border border-[#E5E7EB] shadow-sm p-6 relative overflow-hidden">
                    <div class="flex items-center gap-2 mb-4">
                        <i data-lucide="pen-tool" class="w-5 h-5 text-purple-600"></i>
                        <h3 class="text-lg font-bold text-gray-800">隨堂小測驗</h3>
                    </div>

                    <?php if ($is_assignment_submitted): ?>
                        
                        <!-- 測驗前閱讀短文 -->
                        <?php if (!empty($current_lesson['reading_material'])): ?>
                            <div class="mb-6 bg-orange-50 border border-orange-100 rounded-lg p-4">
                                <h4 class="text-sm font-bold text-orange-800 mb-2 flex items-center gap-2">
                                    <i data-lucide="book-open" class="w-4 h-4"></i> 測驗前閱讀
                                </h4>
                                <div class="text-sm text-gray-700 leading-relaxed whitespace-pre-line">
                                    <?= htmlspecialchars($current_lesson['reading_material']) ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if (count($quizzes) > 0): ?>
                            <form action="submit_quiz.php" method="POST" class="space-y-6">
                                <?php foreach ($quizzes as $idx => $q): ?>
                                    <div class="space-y-2">
                                        <p class="font-bold text-sm text-gray-800">Q<?= $idx+1 ?>. <?= htmlspecialchars($q['question']) ?></p>
                                        <div class="grid grid-cols-1 gap-2">
                                            <?php foreach (['A', 'B', 'C', 'D'] as $opt): ?>
                                                <label class="flex items-center gap-3 p-3 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer transition">
                                                    <input type="radio" name="quiz[<?= $q['id'] ?>]" value="<?= $opt ?>" class="text-purple-600 focus:ring-purple-500">
                                                    <span class="text-sm text-gray-600"><?= htmlspecialchars($q['option_' . strtolower($opt)]) ?></span>
                                                </label>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                                <button type="submit" class="w-full py-3 bg-purple-600 hover:bg-purple-700 text-white rounded-lg font-bold transition shadow-md">
                                    提交答案
                                </button>
                            </form>
                        <?php else: ?>
                            <div class="text-center py-8 text-gray-400 bg-gray-50 rounded-lg border border-dashed border-gray-200">
                                <p>本課暫無測驗題目</p>
                            </div>
                        <?php endif; ?>

                    <?php else: ?>
                        <!-- 鎖定畫面 -->
                        <div class="absolute inset-0 bg-white/80 backdrop-blur-[2px] z-10 flex flex-col items-center justify-center text-center p-6">
                            <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4 text-gray-400">
                                <i data-lucide="lock" class="w-8 h-8"></i>
                            </div>
                            <h4 class="font-bold text-gray-800 mb-2">測驗已鎖定</h4>
                            <p class="text-sm text-gray-500 max-w-[200px]">
                                請先完成上方「本週作業」上傳，系統將自動解鎖測驗與閱讀內容。
                            </p>
                        </div>
                        <!-- 模糊背景佔位 -->
                        <div class="opacity-20 filter blur-sm select-none">
                            <div class="h-24 bg-gray-200 rounded mb-4"></div>
                            <div class="h-8 bg-gray-200 rounded w-3/4 mb-2"></div>
                        </div>
                    <?php endif; ?>
                </div>

            </div>
        </div>
    </main>

    <script>lucide.createIcons();</script>
</body>
</html>
