<?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 esSaveBookStartLevel(PDO $pdo, int $studentId, int $bookId, int $levelId): void
{
    esEnsureStudentBookStartLevelsTable($pdo);

    $stmt = $pdo->prepare(
        "INSERT INTO student_book_start_levels
            (student_id, book_id, level_id, created_at)
         VALUES (?, ?, ?, NOW())
         ON DUPLICATE KEY UPDATE
            level_id = level_id"
    );
    $stmt->execute([$studentId, $bookId, $levelId]);
}

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: chọn Level bắt đầu riêng cho từng Book.
    $bookStartLevelId = esBookStartLevelId($pdo, $studentId, $bookId);

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

    if (in_array(
        $levelId,
        esLevelIdsUpToStart($pdo, $bookId, $bookStartLevelId),
        true
    )) {
        return true;
    }

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

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

$bookSlug = trim((string)($_GET['book'] ?? ''));

if ($bookSlug === '') {
    header('Location: student-home.php');
    exit;
}

$bookStmt = $pdo->prepare(
    "SELECT id, name, slug
     FROM books
     WHERE slug = ?
       AND status = 'active'
     LIMIT 1"
);
$bookStmt->execute([$bookSlug]);
$book = $bookStmt->fetch(PDO::FETCH_ASSOC);

if (!$book) {
    http_response_code(404);
    exit('Không tìm thấy bộ sách.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selectedLevelId = (int)($_POST['level_id'] ?? 0);

    $selectedLevelStmt = $pdo->prepare(
        "SELECT id, book_id, level_number, name, slug
         FROM levels
         WHERE id = ?
           AND book_id = ?
           AND status = 'active'
         LIMIT 1"
    );
    $selectedLevelStmt->execute([
        $selectedLevelId,
        (int)$book['id'],
    ]);
    $selectedLevel = $selectedLevelStmt->fetch(PDO::FETCH_ASSOC);

    if (!$selectedLevel) {
        http_response_code(400);
        exit('Lớp không hợp lệ.');
    }

    // Học sinh tự do + Global Success + chưa chọn lớp bắt đầu:
    // lần bấm đầu tiên chính là lựa chọn lớp bắt đầu và được lưu vĩnh viễn.
    if (
        (string)$book['slug'] === 'global-success'
        && empty($learningGate['is_managed'])
        && (int)($learningGate['self_selected_grade'] ?? 0) <= 0
    ) {
        $chosenStartGrade = max(1, (int)($selectedLevel['level_number'] ?? 0));
        $saveStartStmt = $pdo->prepare(
            "UPDATE students
             SET self_selected_grade = ?
             WHERE id = ?
               AND (self_selected_grade IS NULL OR self_selected_grade = 0)"
        );
        $saveStartStmt->execute([$chosenStartGrade, $studentId]);
        $learningGate['self_selected_grade'] = $chosenStartGrade;
    }

    // Everybody Up / sách khác: lần bấm đầu tiên chính là Level bắt đầu của Book này.
    if ((string)$book['slug'] !== 'global-success') {
        $bookStartLevelId = esBookStartLevelId(
            $pdo,
            $studentId,
            (int)$book['id']
        );

        if ($bookStartLevelId <= 0) {
            esSaveBookStartLevel(
                $pdo,
                $studentId,
                (int)$book['id'],
                (int)$selectedLevel['id']
            );
        }
    }

    $canAccessSelectedLevel = esCanAccessLevel(
        $pdo,
        $studentId,
        (string)$book['slug'],
        (int)$book['id'],
        (int)$selectedLevel['id'],
        (int)($selectedLevel['level_number'] ?? 0),
        $learningGate
    );

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

    /*
     * Một Student + Book + Level chỉ có một learning path.
     * Nếu đã có thì chỉ mở lại và cập nhật thời điểm truy cập.
     */
    $savePathStmt = $pdo->prepare(
        "INSERT INTO student_learning_paths
            (student_id, book_id, level_id, is_active, started_at, last_accessed_at)
         VALUES
            (?, ?, ?, 1, NOW(), NOW())
         ON DUPLICATE KEY UPDATE
            is_active = 1,
            last_accessed_at = NOW()"
    );
    $savePathStmt->execute([
        $studentId,
        (int)$book['id'],
        (int)$selectedLevel['id'],
    ]);

    header(
        'Location: student-units.php?' . http_build_query([
            'book' => (string)$book['slug'],
            'level' => (string)$selectedLevel['slug'],
            'level_id' => (int)$selectedLevel['id'],
        ])
    );
    exit;
}

$levelStmt = $pdo->prepare(
    "SELECT
        id,
        book_id,
        level_number,
        name,
        slug,
        sort_order,
        status
     FROM levels
     WHERE book_id = ?
       AND status = 'active'
     ORDER BY sort_order ASC, level_number ASC, id ASC"
);
$levelStmt->execute([(int)$book['id']]);
$levels = $levelStmt->fetchAll(PDO::FETCH_ASSOC);

$isFreeGsFirstChoice = (
    (string)$book['slug'] === 'global-success'
    && empty($learningGate['is_managed'])
    && (int)($learningGate['self_selected_grade'] ?? 0) <= 0
);

$isOtherBookFirstChoice = (
    (string)$book['slug'] !== 'global-success'
    && esBookStartLevelId($pdo, $studentId, (int)$book['id']) <= 0
);

$isFirstLevelChoice = $isFreeGsFirstChoice || $isOtherBookFirstChoice;

foreach ($levels as &$levelRow) {
    $levelRow['is_unlocked'] = $isFirstLevelChoice
        ? true
        : esCanAccessLevel(
        $pdo,
        $studentId,
        (string)$book['slug'],
        (int)$book['id'],
        (int)$levelRow['id'],
        (int)($levelRow['level_number'] ?? 0),
        $learningGate
    );
}
unset($levelRow);

$pageTitle = (string)$book['name'];
$pageSubtitle = '';
$showBack = true;
$backUrl = 'student-home.php';
$activeStudentNav = 'learning';

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

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

* {
    box-sizing: border-box;
}

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

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

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

.level-section-title {
    margin: 2px 0 10px;
    color: var(--lv-text);
    font-size: 17px;
    font-weight: 850;
}

.level-list {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 11px;
}

.level-form {
    margin: 0;
}

.level-card {
    width: 100%;
    font: inherit;
    text-align: left;
    cursor: pointer;
    display: flex;
    min-height: 96px;
    align-items: center;
    gap: 12px;
    padding: 14px;
    border: 1px solid var(--lv-border);
    border-radius: 18px;
    background: var(--lv-surface);
    color: var(--lv-text);
    text-decoration: none;
    box-shadow: var(--lv-shadow);
    -webkit-tap-highlight-color: transparent;
}

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

.level-card.is-locked {
    cursor: not-allowed;
    opacity: .58;
    background: #f6f8fa;
    box-shadow: none;
}
.level-card.is-locked:active {
    transform: none;
}
.level-card__lock {
    margin-left: auto;
    color: #7b8899;
    font-size: 18px;
}

.level-card__number {
    flex: 0 0 48px;
    width: 48px;
    height: 48px;
    display: grid;
    place-items: center;
    border-radius: 15px;
    background: var(--lv-soft);
    color: var(--lv-primary);
    font-size: 20px;
    font-weight: 850;
}

.level-card__copy {
    min-width: 0;
    flex: 1;
}

.level-card__copy strong {
    display: block;
    font-size: 16px;
    line-height: 1.25;
}

.level-card__copy small {
    display: block;
    margin-top: 4px;
    color: var(--lv-muted);
    font-size: 11.5px;
}

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

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

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

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

    .level-list {
        grid-template-columns: 1fr;
    }

    .level-card {
        min-height: 78px;
        padding: 12px;
    }

    .level-card__number {
        flex-basis: 44px;
        width: 44px;
        height: 44px;
    }
}
</style>

<h2 class="level-section-title">
    <?= $isFirstLevelChoice
        ? 'Chọn cấp độ bắt đầu'
        : ($bookSlug === 'global-success' ? 'Chọn lớp' : 'Chọn cấp độ') ?>
</h2>
<?php if ($isFreeGsFirstChoice): ?>
    <div class="level-empty" style="margin-bottom:12px;padding:14px 16px;">
        Em đang học lớp mấy? Hãy chọn lớp để bắt đầu. Các lớp thấp hơn cũng sẽ được mở để em ôn lại.
    </div>
<?php elseif ($isOtherBookFirstChoice): ?>
    <div class="level-empty" style="margin-bottom:12px;padding:14px 16px;">
        Em muốn bắt đầu từ cấp độ nào? Hãy chọn cấp độ phù hợp. Các cấp độ thấp hơn cũng sẽ được mở để em tham khảo và ôn lại.
    </div>
<?php endif; ?>

<section class="level-list" aria-label="<?= $bookSlug === 'global-success' ? 'Danh sách lớp' : 'Danh sách cấp độ' ?>">
    <?php if ($levels === []): ?>
        <div class="level-empty">
            Chưa có cấp độ cho bộ sách này.
        </div>
    <?php endif; ?>

    <?php foreach ($levels as $level): ?>
        <?php
        $iconText = $bookSlug === 'global-success'
            ? (string)$level['level_number']
            : (
                $level['slug'] === 'starter'
                    ? 'S'
                    : (string)$level['level_number']
            );
        ?>
        <?php $isUnlocked = !empty($level['is_unlocked']); ?>
        <form method="post" class="level-form">
            <input
                type="hidden"
                name="level_id"
                value="<?= (int)$level['id'] ?>"
            >
            <button
                type="submit"
                class="level-card<?= $isUnlocked ? '' : ' is-locked' ?>"
                <?= $isUnlocked ? '' : 'disabled' ?>
            >

            <span class="level-card__number">
                <?= htmlspecialchars($iconText, ENT_QUOTES, 'UTF-8') ?>
            </span>

            <span class="level-card__copy">
                <strong>
                    <?= htmlspecialchars(
                        $bookSlug === 'global-success'
                            ? (
                                preg_match('/\d+/', (string)$level['name'])
                                    ? (string)$level['name']
                                    : 'Lớp ' . (string)$level['level_number']
                            )
                            : (string)$level['name'],
                        ENT_QUOTES,
                        'UTF-8'
                    ) ?>
                </strong>
                <small>
                    <?php if ($isUnlocked): ?>
                        Chọn để xem Unit
                    <?php elseif ($bookSlug === 'global-success' && !empty($learningGate['is_managed'])): ?>
                        Giáo viên sẽ mở khi em lên lớp
                    <?php else: ?>
                        Hoàn thành cấp độ trước để mở
                    <?php endif; ?>
                </small>
            </span>

            <?php if (!$isUnlocked): ?>
                <span class="level-card__lock" aria-hidden="true">🔒</span>
            <?php endif; ?>
            </button>
        </form>
    <?php endforeach; ?>
</section>

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