<?php
declare(strict_types=1);

session_start();

if (!isset($_SESSION['student_id'])) {
    header('Location: student-login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/lesson_progress_engine.php';
$pdo = getDbConnection();

$bookSlug = trim((string)($_GET['book'] ?? ''));
$levelSlug = trim((string)($_GET['level'] ?? ''));
$levelId = max(0, (int)($_GET['level_id'] ?? 0));
$unitId = max(0, (int)($_GET['unit_id'] ?? 0));
$lessonId = max(0, (int)($_GET['lesson_id'] ?? 0));

if (
    $bookSlug === ''
    || $levelId <= 0
    || $unitId <= 0
    || $lessonId <= 0
) {
    header('Location: student-learning.php');
    exit;
}

/*
|--------------------------------------------------------------------------
| Xác nhận toàn bộ chuỗi Book → Level → Unit → Lesson
|--------------------------------------------------------------------------
*/
$contextStmt = $pdo->prepare(
    "SELECT
        b.id AS book_id,
        b.name AS book_name,
        b.slug AS book_slug,

        l.id AS level_id,
        l.name AS level_name,
        l.slug AS level_slug,

        u.id AS unit_id,
        u.unit_number,
        u.title AS unit_title,

        le.id AS lesson_id,
        le.lesson_number,
        le.title AS lesson_title,
        le.unlock_mode,
        le.unlock_date
     FROM lessons le
     INNER JOIN units u
        ON u.id = le.unit_id
     INNER JOIN levels l
        ON l.id = u.level_id
     INNER JOIN books b
        ON b.id = l.book_id
     WHERE le.id = ?
       AND u.id = ?
       AND l.id = ?
       AND b.slug = ?
       AND le.status = 'active'
       AND u.status = 'active'
       AND l.status = 'active'
       AND b.status = 'active'
     LIMIT 1"
);
$contextStmt->execute([
    $lessonId,
    $unitId,
    $levelId,
    $bookSlug,
]);
$context = $contextStmt->fetch(PDO::FETCH_ASSOC);

if (!$context) {
    http_response_code(404);
    exit('Không tìm thấy bài học trong cấp độ đã chọn.');
}

/*
|--------------------------------------------------------------------------
| LESSON DATE GATE
|--------------------------------------------------------------------------
| Chặn cả trường hợp học sinh gõ URL trực tiếp.
| Giữ nguyên XP/progress; chỉ kiểm tra quyền mở Lesson.
*/
$studentId = (int)$_SESSION['student_id'];
$lessonUnlocked = false;

// Lesson đã bắt đầu hoặc hoàn thành thì luôn được mở lại để ôn tập.
$currentProgressStmt = $pdo->prepare(
    "SELECT status
     FROM student_content_progress
     WHERE student_id = ?
       AND content_type = 'lesson'
       AND content_id = ?
     LIMIT 1"
);
$currentProgressStmt->execute([$studentId, $lessonId]);
$currentLessonStatus = strtolower(
    trim((string)($currentProgressStmt->fetchColumn() ?: 'not_started'))
);

if (in_array($currentLessonStatus, ['in_progress', 'completed'], true)) {
    $lessonUnlocked = true;
} else {
    $lessonOrderStmt = $pdo->prepare(
        "SELECT id, unlock_mode, unlock_date
         FROM lessons
         WHERE unit_id = ?
           AND status = 'active'
         ORDER BY sort_order ASC, id ASC"
    );
    $lessonOrderStmt->execute([$unitId]);
    $orderedLessons = $lessonOrderStmt->fetchAll(PDO::FETCH_ASSOC);

    $currentIndex = null;
    foreach ($orderedLessons as $index => $orderedLesson) {
        if ((int)$orderedLesson['id'] === $lessonId) {
            $currentIndex = $index;
            break;
        }
    }

    if ($currentIndex !== null) {
        $unlockMode = strtolower(
            trim((string)($context['unlock_mode'] ?? 'sequential_daily'))
        );
        $unlockDateRaw = trim((string)($context['unlock_date'] ?? ''));
        $today = new DateTimeImmutable('today');

        if ($unlockMode === 'scheduled_date') {
            if ($unlockDateRaw !== '') {
                try {
                    $unlockDate = new DateTimeImmutable($unlockDateRaw);
                    $lessonUnlocked = $today >= $unlockDate->setTime(0, 0);
                } catch (Throwable $e) {
                    $lessonUnlocked = false;
                }
            }
        } elseif ($currentIndex === 0) {
            // Lesson đầu tiên không có lịch riêng thì mở ngay.
            $lessonUnlocked = true;
        } else {
            $previousLessonId = (int)$orderedLessons[$currentIndex - 1]['id'];

            $previousProgressStmt = $pdo->prepare(
                "SELECT status, completed_at
                 FROM student_content_progress
                 WHERE student_id = ?
                   AND content_type = 'lesson'
                   AND content_id = ?
                 LIMIT 1"
            );
            $previousProgressStmt->execute([$studentId, $previousLessonId]);
            $previousProgress = $previousProgressStmt->fetch(PDO::FETCH_ASSOC) ?: [];

            $previousCompleted =
                strtolower(trim((string)($previousProgress['status'] ?? '')))
                === 'completed';

            $previousCompletedAt =
                trim((string)($previousProgress['completed_at'] ?? ''));

            if ($previousCompleted && $previousCompletedAt !== '') {
                try {
                    $previousCompletedDate =
                        new DateTimeImmutable($previousCompletedAt);

                    $lessonUnlocked =
                        $today > $previousCompletedDate->setTime(0, 0);
                } catch (Throwable $e) {
                    $lessonUnlocked = false;
                }
            }
        }
    }
}

if (!$lessonUnlocked) {
    $lockedReturnUrl = 'student-lessons.php?' . http_build_query([
        'book' => (string)$context['book_slug'],
        'level' => (string)$context['level_slug'],
        'level_id' => (int)$context['level_id'],
        'unit_id' => (int)$context['unit_id'],
        'locked' => 1,
    ]);

    header('Location: ' . $lockedReturnUrl);
    exit;
}

/*
|--------------------------------------------------------------------------
| Chỉ lấy hoạt động giáo viên đã thêm vào Lesson
|--------------------------------------------------------------------------
*/
$activityStmt = $pdo->prepare(
    "SELECT
        id,
        lesson_id,
        flashcard_set_id,
        title,
        activity_type,
        instructions,
        required_xp,
        xp_reward,
        passing_score,
        sort_order,
        status
     FROM activities
     WHERE lesson_id = ?
       AND status = 'active'
     ORDER BY sort_order ASC, id ASC"
);
$activityStmt->execute([$lessonId]);
$activities = $activityStmt->fetchAll(PDO::FETCH_ASSOC);

$rawLessonNumber = trim((string)$context['lesson_number']);
$lessonNumberForUrl = preg_match('/(\d+)/', $rawLessonNumber, $lessonMatch)
    ? (int)$lessonMatch[1]
    : $rawLessonNumber;

$_SESSION['last_learning_url'] = (string)($_SERVER['REQUEST_URI'] ?? '');

$pageTitle = (string)$context['unit_number'];
$pageSubtitle = (string)$context['unit_title'];
$showBack = true;
$backUrl = 'student-lessons.php?' . http_build_query([
    'book' => (string)$context['book_slug'],
    'level' => (string)$context['level_slug'],
    'level_id' => (int)$context['level_id'],
    'unit_id' => (int)$context['unit_id'],
]);
$activeStudentNav = 'learning';

function activityIcon(string $type): string
{
    return match (strtolower(trim($type))) {
        'vocabulary', 'word_list', 'word-list' => '🔤',
        'flashcards', 'flashcard' => '🃏',
        'listen_repeat', 'listen-repeat', 'listening' => '🎧',
        'memory' => '🧠',
        'matching', 'match' => '🧩',
        'quiz' => '❓',
        'speaking', 'sentence_speaking' => '🎤',
        'practice' => '📝',
        default => '🎮',
    };
}

function activityDescription(string $type): string
{
    return match (strtolower(trim($type))) {
        'vocabulary', 'word_list', 'word-list' => 'Xem từ, hình ảnh và nghe phát âm.',
        'flashcards', 'flashcard' => 'Học từ bằng thẻ hình và âm thanh.',
        'listen_repeat', 'listen-repeat', 'listening' => 'Nghe và luyện nói từng từ.',
        'memory' => 'Lật thẻ và tìm các cặp giống nhau.',
        'matching', 'match' => 'Ghép từ với hình ảnh phù hợp.',
        'quiz' => 'Trả lời câu hỏi của bài học.',
        'speaking', 'sentence_speaking' => 'Luyện nói câu theo mẫu.',
        'practice' => 'Luyện tập nội dung vừa học.',
        default => 'Bắt đầu hoạt động.',
    };
}

function activityFile(string $type): string
{
    return match (strtolower(trim($type))) {
        'vocabulary', 'word_list', 'word-list' => 'student-word-list.php',
        'flashcards', 'flashcard' => 'student-flashcards.php',
        'listen_repeat', 'listen-repeat', 'listening' => 'student-listen-repeat.php',
        'memory' => 'student-memory.php',
        'matching', 'match' => 'student-matching.php',
        'quiz' => 'student-quiz.php',
        'speaking', 'sentence_speaking' => 'student-speaking.php',
        'practice' => 'student-practice.php',
        default => 'student-practice.php',
    };
}

include __DIR__ . '/../includes/student-layout-start.php';
?>

<style>
:root {
    --ac-bg: #eef7ff;
    --ac-surface: #ffffff;
    --ac-text: #17324d;
    --ac-muted: #6f8799;
    --ac-primary: #197fc4;
    --ac-primary-dark: #0b67ac;
    --ac-soft: #e7f4ff;
    --ac-border: #dbe9f3;
    --ac-shadow: 0 7px 22px rgba(29, 80, 116, .09);
    --ac-width: 520px;
    --ac-nav-height: 78px;
}

* {
    box-sizing: border-box;
}

html,
body {
    margin: 0 !important;
    min-height: 100%;
    background: var(--ac-bg) !important;
    color: var(--ac-text) !important;
    font-family: "Segoe UI", Tahoma, Arial, sans-serif !important;
}

body {
    padding-bottom: calc(var(--ac-nav-height) + env(safe-area-inset-bottom) + 16px) !important;
}

.student-app {
    width: min(100%, var(--ac-width)) !important;
    min-height: 100vh !important;
    margin: 0 auto !important;
    background: #f7fbff !important;
    box-shadow: 0 0 28px rgba(27, 73, 108, .08) !important;
}

.student-header {
    position: sticky !important;
    top: 0 !important;
    z-index: 40 !important;
    display: grid !important;
    grid-template-columns: 46px minmax(0, 1fr) 46px !important;
    align-items: center !important;
    gap: 9px !important;
    min-height: 76px !important;
    padding: 12px 14px !important;
    background: linear-gradient(135deg, #3488ef, #17b8e4) !important;
    color: #fff !important;
    box-shadow: 0 5px 15px rgba(31, 135, 210, .22) !important;
}

.student-back {
    width: 44px !important;
    height: 44px !important;
    display: grid !important;
    place-items: center !important;
    border-radius: 50% !important;
    background: rgba(255,255,255,.15) !important;
    color: #fff !important;
    text-decoration: none !important;
    font-size: 27px !important;
    font-weight: 800 !important;
    box-shadow: none !important;
}

.student-header__text {
    min-width: 0 !important;
    text-align: center !important;
}

.student-header__text h1 {
    margin: 0 !important;
    color: #fff !important;
    font-size: 23px !important;
    font-weight: 850 !important;
    line-height: 1.15 !important;
}

.student-header__text p {
    margin: 4px 0 0 !important;
    overflow: hidden !important;
    color: rgba(255,255,255,.92) !important;
    font-size: 12.5px !important;
    white-space: nowrap !important;
    text-overflow: ellipsis !important;
}

.student-header__spacer {
    width: 44px !important;
    height: 44px !important;
}

.student-content {
    width: 100% !important;
    padding: 16px 14px 26px !important;
}

.lesson-card {
    display: grid;
    grid-template-columns: 52px minmax(0, 1fr);
    align-items: center;
    gap: 11px;
    min-height: 72px;
    margin-bottom: 13px;
    padding: 12px 14px;
    border-radius: 20px;
    background: linear-gradient(135deg, #edf6ff, #e6f1ff);
    box-shadow: var(--ac-shadow);
}

.lesson-card__icon {
    width: 48px;
    height: 48px;
    display: grid;
    place-items: center;
    border-radius: 14px;
    background: #fff;
    font-size: 29px;
}

.lesson-card strong {
    display: block;
    color: #123e62;
    font-size: 18px;
}

.lesson-card span {
    display: block;
    margin-top: 3px;
    overflow: hidden;
    color: var(--ac-muted);
    font-size: 12.5px;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.activity-list {
    display: grid;
    gap: 11px;
}

.activity-card {
    display: grid;
    grid-template-columns: 50px minmax(0, 1fr) 70px;
    align-items: center;
    gap: 11px;
    min-height: 82px;
    padding: 13px;
    border: 1px solid var(--ac-border);
    border-radius: 18px;
    background: var(--ac-surface);
    color: var(--ac-text);
    text-decoration: none;
    box-shadow: var(--ac-shadow);
    -webkit-tap-highlight-color: transparent;
}

.activity-card:active {
    transform: scale(.985);
}

.activity-card__icon {
    width: 50px;
    height: 50px;
    display: grid;
    place-items: center;
    border-radius: 15px;
    background: var(--ac-soft);
    font-size: 25px;
}

.activity-card__copy {
    min-width: 0;
}

.activity-card__copy strong {
    display: block;
    color: var(--ac-primary-dark);
    font-size: 16px;
    line-height: 1.3;
}

.activity-card__copy span {
    display: block;
    margin-top: 4px;
    overflow: hidden;
    color: var(--ac-muted);
    font-size: 12.5px;
    line-height: 1.4;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.activity-card__button {
    min-width: 70px;
    padding: 9px 8px;
    border-radius: 12px;
    background: var(--ac-primary);
    color: #fff;
    font-size: 10.5px;
    font-weight: 850;
    text-align: center;
}

.activity-empty {
    padding: 25px 18px;
    border: 1px dashed #bdd7e8;
    border-radius: 18px;
    background: rgba(255,255,255,.75);
    color: var(--ac-muted);
    text-align: center;
    line-height: 1.5;
}

.student-nav {
    position: fixed !important;
    z-index: 9999 !important;
    left: 50% !important;
    bottom: 0 !important;
    width: min(100%, var(--ac-width)) !important;
    min-height: var(--ac-nav-height) !important;
    display: grid !important;
    grid-template-columns: repeat(4, minmax(0, 1fr)) !important;
    padding: 7px 8px calc(7px + env(safe-area-inset-bottom)) !important;
    border-top: 1px solid #dce5ed !important;
    background: rgba(255,255,255,.98) !important;
    box-shadow: 0 -6px 18px rgba(32, 65, 93, .11) !important;
    transform: translateX(-50%) !important;
    backdrop-filter: blur(14px);
}

.student-nav__item {
    position: relative !important;
    display: flex !important;
    min-width: 0 !important;
    flex-direction: column !important;
    align-items: center !important;
    justify-content: center !important;
    gap: 2px !important;
    color: #586879 !important;
    text-decoration: none !important;
}

.student-nav__icon {
    width: 42px !important;
    height: 34px !important;
    display: grid !important;
    place-items: center !important;
    border-radius: 12px !important;
    font-size: 23px !important;
}

.student-nav__label {
    overflow: hidden !important;
    max-width: 100% !important;
    color: inherit !important;
    font-size: 11.5px !important;
    font-weight: 750 !important;
    white-space: nowrap !important;
    text-overflow: ellipsis !important;
}

.student-nav__item.is-active {
    color: var(--ac-primary) !important;
}

.student-nav__item.is-active .student-nav__icon {
    background: var(--ac-soft) !important;
}

.student-nav__item.is-active::after {
    content: "";
    position: absolute;
    top: -7px;
    width: 52px;
    height: 3px;
    border-radius: 999px;
    background: var(--ac-primary);
}

@media (max-width: 390px) {
    .student-content {
        padding-left: 11px !important;
        padding-right: 11px !important;
    }

    .activity-card {
        grid-template-columns: 46px minmax(0, 1fr) 62px;
        gap: 9px;
        min-height: 76px;
        padding: 11px;
    }

    .activity-card__icon {
        width: 46px;
        height: 46px;
        font-size: 23px;
    }

    .activity-card__button {
        min-width: 62px;
        padding: 8px 6px;
        font-size: 9.5px;
    }
}
</style>

<section class="lesson-card">
    <div class="lesson-card__icon" aria-hidden="true">📘</div>
    <div>
        <strong><?= htmlspecialchars((string)$context['lesson_title'], ENT_QUOTES, 'UTF-8') ?></strong>
        <span><?= htmlspecialchars((string)$context['level_name'], ENT_QUOTES, 'UTF-8') ?></span>
    </div>
</section>

<section class="activity-list" aria-label="Hoạt động trong bài học">
    <?php if ($activities === []): ?>
        <div class="activity-empty">
            Bài học này chưa có hoạt động.
        </div>
    <?php endif; ?>

    <?php foreach ($activities as $activity): ?>
        <?php
        $activityType = (string)$activity['activity_type'];

        $query = http_build_query([
            'book' => (string)$context['book_slug'],
            'level' => (string)$context['level_slug'],
            'level_id' => (int)$context['level_id'],
            'unit_id' => (int)$context['unit_id'],
            'id' => (int)$context['unit_id'],
            'lesson_id' => (int)$context['lesson_id'],
            'lesson' => $lessonNumberForUrl,
            'activity_id' => (int)$activity['id'],
            'activity' => (int)$activity['id'],
        ]);

        // Mỗi thẻ phải mở đúng activity hiện tại.
        // Truyền đầy đủ context để runtime/game không bị rơi sang activity kế tiếp.
        $url = 'student-runtime/index.php?' . $query;
        ?>
        <a
            class="activity-card"
            href="<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>"
        >
            <span class="activity-card__icon" aria-hidden="true">
                <?= activityIcon($activityType) ?>
            </span>

            <span class="activity-card__copy">
                <strong>
                    <?= htmlspecialchars((string)$activity['title'], ENT_QUOTES, 'UTF-8') ?>
                </strong>
                <span>
                    <?= htmlspecialchars(activityDescription($activityType), ENT_QUOTES, 'UTF-8') ?>
                </span>
            </span>

            <span class="activity-card__button">Bắt đầu</span>
        </a>
    <?php endforeach; ?>
</section>

<?php include __DIR__ . '/../includes/student-layout-end.php'; ?>
