<?php
declare(strict_types=1);

session_start();

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

require_once __DIR__ . '/../config/database.php';
$pdo = getDbConnection();
$studentId = (int)$_SESSION['student_id'];

function esStudentLearningGate(PDO $pdo, int $studentId): array
{
    $studentStmt = $pdo->prepare(
        "SELECT grade, class_name, academic_year_id, self_selected_grade
         FROM students
         WHERE id = ?
         LIMIT 1"
    );
    $studentStmt->execute([$studentId]);
    $student = $studentStmt->fetch(PDO::FETCH_ASSOC) ?: [];

    $grade = max(0, (int)($student['grade'] ?? 0));
    $className = trim((string)($student['class_name'] ?? ''));
    $academicYearId = max(0, (int)($student['academic_year_id'] ?? 0));
    $selfSelectedGrade = max(0, (int)($student['self_selected_grade'] ?? 0));

    return [
        'grade' => $grade,
        'is_managed' => ($className !== '' && $academicYearId > 0),
        'self_selected_grade' => $selfSelectedGrade,
    ];
}


function esEnsureStudentBookStartLevelsTable(PDO $pdo): void
{
    $pdo->exec(
        "CREATE TABLE IF NOT EXISTS student_book_start_levels (
            student_id BIGINT UNSIGNED NOT NULL,
            book_id BIGINT UNSIGNED NOT NULL,
            level_id BIGINT UNSIGNED NOT NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (student_id, book_id),
            KEY idx_sbs_level (level_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
    );
}

function esBookStartLevelId(PDO $pdo, int $studentId, int $bookId): int
{
    esEnsureStudentBookStartLevelsTable($pdo);

    $stmt = $pdo->prepare(
        "SELECT level_id
         FROM student_book_start_levels
         WHERE student_id = ?
           AND book_id = ?
         LIMIT 1"
    );
    $stmt->execute([$studentId, $bookId]);

    return max(0, (int)$stmt->fetchColumn());
}

function esLevelIdsUpToStart(PDO $pdo, int $bookId, int $startLevelId): array
{
    $stmt = $pdo->prepare(
        "SELECT id
         FROM levels
         WHERE book_id = ?
           AND status = 'active'
         ORDER BY sort_order ASC, level_number ASC, id ASC"
    );
    $stmt->execute([$bookId]);

    $open = [];
    foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $id) {
        $id = (int)$id;
        $open[] = $id;

        if ($id === $startLevelId) {
            break;
        }
    }

    return $open;
}

function esLevelCompleted(PDO $pdo, int $studentId, int $levelId): bool
{
    $stmt = $pdo->prepare(
        "SELECT
            COUNT(*) AS total_lessons,
            SUM(CASE WHEN scp.status = 'completed' THEN 1 ELSE 0 END) AS completed_lessons
         FROM lessons l
         INNER JOIN units u ON u.id = l.unit_id
         LEFT JOIN student_content_progress scp
           ON scp.student_id = ?
          AND scp.content_type = 'lesson'
          AND scp.content_id = l.id
         WHERE u.level_id = ?
           AND u.status = 'active'
           AND l.status = 'active'"
    );
    $stmt->execute([$studentId, $levelId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

    $total = (int)($row['total_lessons'] ?? 0);
    $completed = (int)($row['completed_lessons'] ?? 0);

    return $total > 0 && $completed >= $total;
}

function esOpenLevelIdsForBook(PDO $pdo, int $studentId, int $bookId): array
{
    $stmt = $pdo->prepare(
        "SELECT id
         FROM levels
         WHERE book_id = ?
           AND status = 'active'
         ORDER BY sort_order ASC, level_number ASC, id ASC"
    );
    $stmt->execute([$bookId]);
    $ids = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));

    if ($ids === []) return [];

    $open = [$ids[0]];
    for ($i = 1, $count = count($ids); $i < $count; $i++) {
        if (esLevelCompleted($pdo, $studentId, $ids[$i - 1])) {
            $open[] = $ids[$i];
        } else {
            break;
        }
    }
    return $open;
}

function esCanAccessLevel(
    PDO $pdo,
    int $studentId,
    string $bookSlug,
    int $bookId,
    int $levelId,
    int $levelNumber,
    array $gate
): bool {
    if ($bookSlug === 'global-success') {
        if (!empty($gate['is_managed'])) {
            $grade = max(0, (int)($gate['grade'] ?? 0));
            return $grade > 0 && $levelNumber > 0 && $levelNumber <= $grade;
        }

        // Học sinh tự do: lần đầu được chọn lớp bắt đầu.
        // Sau khi đã chọn, các lớp thấp hơn luôn mở; lớp cao hơn mở tuần tự theo progress.
        $startGrade = max(0, (int)($gate['self_selected_grade'] ?? 0));
        if ($startGrade <= 0) {
            return false;
        }

        if ($levelNumber > 0 && $levelNumber <= $startGrade) {
            return true;
        }

        $openIds = esOpenLevelIdsForBook($pdo, $studentId, $bookId);
        return in_array($levelId, $openIds, true);
    }

    // Everybody Up / sách khác: dùng Level bắt đầu riêng theo Student + Book.
    $bookStartLevelId = esBookStartLevelId($pdo, $studentId, $bookId);

    if ($bookStartLevelId <= 0) {
        return false;
    }

    // Level đã chọn và tất cả Level thấp hơn luôn mở.
    if (in_array(
        $levelId,
        esLevelIdsUpToStart($pdo, $bookId, $bookStartLevelId),
        true
    )) {
        return true;
    }

    // Các Level cao hơn chỉ mở tuần tự theo progress.
    return in_array(
        $levelId,
        esOpenLevelIdsForBook($pdo, $studentId, $bookId),
        true
    );
}

$learningGate = esStudentLearningGate($pdo, $studentId);

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

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

$sql = "SELECT
            l.id,
            l.book_id,
            l.level_number,
            l.name,
            l.slug,
            b.name AS book_name,
            b.slug AS book_slug
        FROM levels l
        INNER JOIN books b
            ON b.id = l.book_id
        WHERE b.slug = ?
          AND b.status = 'active'
          AND l.status = 'active'";

$params = [$bookSlug];

if ($levelId > 0) {
    $sql .= " AND l.id = ?";
    $params[] = $levelId;
} else {
    $sql .= " AND l.slug = ?";
    $params[] = $levelSlug;
}

$sql .= " LIMIT 1";

$levelStmt = $pdo->prepare($sql);
$levelStmt->execute($params);
$level = $levelStmt->fetch(PDO::FETCH_ASSOC);

if (!$level) {
    http_response_code(404);
    exit('Không tìm thấy cấp độ.');
}

$canAccessLevel = esCanAccessLevel(
    $pdo,
    $studentId,
    (string)$level['book_slug'],
    (int)$level['book_id'],
    (int)$level['id'],
    (int)($level['level_number'] ?? 0),
    $learningGate
);

if (!$canAccessLevel) {
    http_response_code(403);
    exit('Cấp độ này chưa được mở.');
}

$unitStmt = $pdo->prepare(
    "SELECT
        id,
        book_id,
        level_id,
        unit_number,
        title,
        thumbnail,
        description,
        required_xp,
        sort_order,
        status
     FROM units
     WHERE level_id = ?
       AND status = 'active'
     ORDER BY sort_order ASC, id ASC"
);
$unitStmt->execute([(int)$level['id']]);
$units = $unitStmt->fetchAll(PDO::FETCH_ASSOC);

/*
 * UNIT UNLOCK STATES
 * Unit đầu tiên luôn mở.
 * Unit kế tiếp chỉ mở khi Lesson đầu của Unit đó thực sự đến ngày mở.
 * - sequential_daily: Lesson cuối Unit trước completed và đã sang ngày sau.
 * - scheduled_date: Lesson cuối Unit trước completed và đã đến unlock_date.
 * Không dựa vào XP/replay.
 */
$unitStates = [];
$today = new DateTimeImmutable('today');

$lastLessonStmt = $pdo->prepare(
    "SELECT l.id, scp.status, scp.completed_at
     FROM lessons l
     LEFT JOIN student_content_progress scp
       ON scp.student_id = ?
      AND scp.content_type = 'lesson'
      AND scp.content_id = l.id
     WHERE l.unit_id = ?
       AND l.status = 'active'
     ORDER BY l.sort_order DESC, l.id DESC
     LIMIT 1"
);

$firstLessonStmt = $pdo->prepare(
    "SELECT id, unlock_mode, unlock_date
     FROM lessons
     WHERE unit_id = ?
       AND status = 'active'
     ORDER BY sort_order ASC, id ASC
     LIMIT 1"
);

foreach ($units as $index => $unitRow) {
    $currentUnitId = (int)$unitRow['id'];
    $isUnlocked = ($index === 0);
    $lockedMessage = '';
    $visibleUnlockDate = '';

    if ($index > 0) {
        $previousUnitId = (int)$units[$index - 1]['id'];

        $lastLessonStmt->execute([$studentId, $previousUnitId]);
        $previousLastLesson = $lastLessonStmt->fetch(PDO::FETCH_ASSOC) ?: [];

        $firstLessonStmt->execute([$currentUnitId]);
        $currentFirstLesson = $firstLessonStmt->fetch(PDO::FETCH_ASSOC) ?: [];

        $previousCompleted =
            (string)($previousLastLesson['status'] ?? '') === 'completed';
        $previousCompletedAt =
            trim((string)($previousLastLesson['completed_at'] ?? ''));

        $isUnlocked = false;

        if (!$previousCompleted || $previousCompletedAt === '') {
            $lockedMessage = 'Hoàn thành Unit trước để mở Unit này.';
        } elseif ($currentFirstLesson === []) {
            $lockedMessage = 'Unit này chưa có Lesson để mở.';
        } else {
            $mode = strtolower(trim(
                (string)($currentFirstLesson['unlock_mode'] ?? 'sequential_daily')
            ));
            $unlockDateRaw =
                trim((string)($currentFirstLesson['unlock_date'] ?? ''));

            if ($mode === 'scheduled_date') {
                if ($unlockDateRaw !== '') {
                    try {
                        $unlockDate =
                            (new DateTimeImmutable($unlockDateRaw))->setTime(0, 0);
                        $isUnlocked = $today >= $unlockDate;

                        if (!$isUnlocked) {
                            $lockedMessage =
                                'Unit này sẽ mở vào ngày ' . $unlockDate->format('d/m/Y') . '.';
                            // Chỉ scheduled_date mới hiện ngày trực tiếp trên thẻ Unit.
                            $visibleUnlockDate = $unlockDate->format('d/m/Y');
                        }
                    } catch (Throwable $e) {
                        $isUnlocked = false;
                        $lockedMessage = 'Unit này đang chờ ngày mở.';
                    }
                } else {
                    $lockedMessage = 'Unit này chưa được đặt ngày mở.';
                }
            } else {
                try {
                    $completedDate =
                        (new DateTimeImmutable($previousCompletedAt))->setTime(0, 0);
                    $openDate = $completedDate->modify('+1 day');
                    $isUnlocked = $today >= $openDate;

                    if (!$isUnlocked) {
                        $lockedMessage =
                            'Unit này sẽ mở vào ngày ' . $openDate->format('d/m/Y') . '.';
                    }
                } catch (Throwable $e) {
                    $isUnlocked = false;
                    $lockedMessage = 'Unit này chưa đến ngày mở.';
                }
            }
        }
    }

    $unitStates[$currentUnitId] = [
        'unlocked' => $isUnlocked,
        'locked_message' => $lockedMessage,
        'visible_unlock_date' => $visibleUnlockDate,
    ];
}

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

$pageTitle = (string)$level['name'];
$pageSubtitle = (string)$level['book_name'];
$showBack = true;
$backUrl = 'student-levels.php?book=' . urlencode((string)$level['book_slug']);
$activeStudentNav = 'learning';

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

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

* {
    box-sizing: border-box;
}

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

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

.student-app {
    width: min(100%, var(--un-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;
}

.unit-intro {
    display: grid;
    grid-template-columns: 58px minmax(0, 1fr);
    align-items: center;
    gap: 12px;
    margin-bottom: 14px;
    padding: 15px;
    border-radius: 20px;
    background: linear-gradient(135deg, #edf6ff, #e6f1ff);
    box-shadow: var(--un-shadow);
}

.unit-intro__icon {
    width: 54px;
    height: 58px;
    display: grid;
    place-items: center;
    border-radius: 15px;
    background: #fff;
    font-size: 32px;
}

.unit-intro strong {
    display: block;
    font-size: 18px;
}

.unit-intro span {
    display: block;
    margin-top: 4px;
    color: var(--un-muted);
    font-size: 13px;
}

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

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

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

.unit-card--locked {
    cursor: not-allowed;
    opacity: .58;
    filter: grayscale(.18);
}

.unit-card--locked:active {
    transform: none;
}

.unit-card--locked .unit-card__arrow {
    font-size: 19px;
}

.unit-card__icon {
    width: 54px;
    height: 54px;
    display: grid;
    place-items: center;
    overflow: hidden;
    border-radius: 16px;
    background: var(--un-soft);
    font-size: 27px;
}

.unit-card__icon img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

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

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

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

.unit-card__locked-message {
    display: block !important;
    margin-top: 5px !important;
    overflow: visible !important;
    color: #b56a00 !important;
    font-size: 11.5px !important;
    font-weight: 700 !important;
    line-height: 1.35 !important;
    white-space: normal !important;
    text-overflow: clip !important;
}

.unit-card__arrow {
    color: var(--un-primary);
    font-size: 27px;
    font-weight: 700;
    text-align: center;
}

.unit-empty {
    padding: 25px 18px;
    border: 1px dashed #bdd7e8;
    border-radius: 18px;
    background: rgba(255,255,255,.75);
    color: var(--un-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(--un-width)) !important;
    min-height: var(--un-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(--un-primary) !important;
}

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

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

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

    .unit-card {
        grid-template-columns: 48px minmax(0, 1fr) 28px;
        gap: 10px;
        min-height: 76px;
        padding: 11px;
    }

    .unit-card__icon {
        width: 48px;
        height: 48px;
        font-size: 24px;
    }
}
</style>

<section class="unit-intro">
    <div class="unit-intro__icon" aria-hidden="true">📚</div>
    <div>
        <strong><?= htmlspecialchars((string)$level['name'], ENT_QUOTES, 'UTF-8') ?></strong>
        <span><?= htmlspecialchars((string)$level['book_name'], ENT_QUOTES, 'UTF-8') ?></span>
    </div>
</section>

<section class="unit-list" aria-label="Danh sách Unit">
    <?php if ($units === []): ?>
        <div class="unit-empty">
            Cấp độ này chưa có Unit.
        </div>
    <?php endif; ?>

    <?php foreach ($units as $unit): ?>
        <?php
        $thumbnail = trim((string)($unit['thumbnail'] ?? ''));
        $query = http_build_query([
            'book' => (string)$level['book_slug'],
            'level' => (string)$level['slug'],
            'level_id' => (int)$level['id'],
            'unit_id' => (int)$unit['id'],
            'id' => (int)$unit['id'],
        ]);
        ?>
        <?php
        $unitState = $unitStates[(int)$unit['id']] ?? [
            'unlocked' => false,
            'locked_message' => 'Unit này chưa được mở.',
            'visible_unlock_date' => '',
        ];
        $isUnitUnlocked = (bool)$unitState['unlocked'];
        $unitLockedMessage = trim(
            (string)($unitState['locked_message'] ?? 'Unit này chưa được mở.')
        );
        $visibleUnlockDate = trim(
            (string)($unitState['visible_unlock_date'] ?? '')
        );
        ?>
        <?php if ($isUnitUnlocked): ?>
        <a
            class="unit-card"
            href="student-lessons.php?<?= htmlspecialchars($query, ENT_QUOTES, 'UTF-8') ?>"
        >
        <?php else: ?>
        <div
            class="unit-card unit-card--locked"
            aria-disabled="true"
            title="<?= htmlspecialchars($unitLockedMessage, ENT_QUOTES, 'UTF-8') ?>"
        >
        <?php endif; ?>
            <span class="unit-card__icon">
                <?php if ($thumbnail !== ''): ?>
                    <img
                        src="<?= htmlspecialchars('../' . ltrim($thumbnail, './'), ENT_QUOTES, 'UTF-8') ?>"
                        alt=""
                        loading="lazy"
                    >
                <?php else: ?>
                    📘
                <?php endif; ?>
            </span>

            <span class="unit-card__copy">
                <strong>
                    <?= htmlspecialchars((string)$unit['unit_number'], ENT_QUOTES, 'UTF-8') ?>
                </strong>
                <span>
                    <?= htmlspecialchars((string)$unit['title'], ENT_QUOTES, 'UTF-8') ?>
                </span>
                <?php if (!$isUnitUnlocked && $visibleUnlockDate !== ''): ?>
                    <span class="unit-card__locked-message">
                        🔒 Mở ngày <?= htmlspecialchars($visibleUnlockDate, ENT_QUOTES, 'UTF-8') ?>
                    </span>
                <?php endif; ?>
            </span>

            <span class="unit-card__arrow" aria-hidden="true">
                <?= $isUnitUnlocked ? '›' : '🔒' ?>
            </span>
        <?php if ($isUnitUnlocked): ?>
        </a>
        <?php else: ?>
        </div>
        <?php endif; ?>
    <?php endforeach; ?>
</section>

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