<?php
declare(strict_types=1);
require __DIR__ . '/../partials/auth.php';

$pageTitle = 'Content Library';
$pageSubtitle = 'Manage books, units, lessons and activities';
$activeTeacherNav = 'content';

// ─── Database ─────────────────────────────────
require_once __DIR__ . '/../../config/database.php';
$pdo = getDbConnection();

$currentUserRole = strtolower(trim((string)($_SESSION['user_role'] ?? $_SESSION['role'] ?? 'teacher')));
$currentUserId = (int)($_SESSION['user_id'] ?? 0);
$isAdmin = ($currentUserRole === 'admin');


// ─── Teacher-specific Lesson schedule ─────────────────────────────
// Lesson content remains shared/owned by its creator.
// A Teacher may still schedule a shared Lesson for the classes they teach.
$pdo->exec("
    CREATE TABLE IF NOT EXISTS teacher_lesson_schedules (
        id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        teacher_id BIGINT UNSIGNED NOT NULL,
        lesson_id BIGINT UNSIGNED NOT NULL,
        school_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
        academic_year_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
        grade INT NULL,
        class_name VARCHAR(100) NOT NULL,
        unlock_mode VARCHAR(40) NOT NULL DEFAULT 'sequential_daily',
        unlock_date DATE NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_teacher_lesson_schedule
            (teacher_id, lesson_id, school_id, academic_year_id, class_name),
        KEY idx_tls_lookup
            (teacher_id, school_id, academic_year_id, class_name, lesson_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

$teacherScheduleSchoolId = 0;
$teacherScheduleClasses = [];
$teacherScheduleYears = [];

if (!$isAdmin && $currentUserId > 0) {
    try {
        $scopeStmt = $pdo->prepare(
            "SELECT school_id
             FROM teacher_profiles
             WHERE user_id = ?
             LIMIT 1"
        );
        $scopeStmt->execute([$currentUserId]);
        $teacherScheduleSchoolId = max(0, (int)$scopeStmt->fetchColumn());

        // Chỉ dùng danh sách này để gợi ý khi Teacher chọn lớp.
        // Ownership lớp sẽ được nối chặt bằng teacher_class_assignments ở bước quản lý lớp.
        if ($teacherScheduleSchoolId > 0) {
            $studentCols = array_column(
                $pdo->query("SHOW COLUMNS FROM students")->fetchAll(PDO::FETCH_ASSOC),
                null,
                'Field'
            );

            if (isset($studentCols['class_name'], $studentCols['school_id'])) {
                $sql = "SELECT DISTINCT class_name
                        FROM students
                        WHERE school_id = ?
                          AND class_name IS NOT NULL
                          AND TRIM(class_name) <> ''";
                if (isset($studentCols['status'])) {
                    $sql .= " AND status = 'active'";
                }
                $sql .= " ORDER BY class_name ASC";

                $stmt = $pdo->prepare($sql);
                $stmt->execute([$teacherScheduleSchoolId]);
                $teacherScheduleClasses = array_values(array_filter(array_map(
                    static fn($v): string => trim((string)$v),
                    $stmt->fetchAll(PDO::FETCH_COLUMN)
                )));
            }
        }

        $yearExists = $pdo->query(
            "SELECT COUNT(*)
             FROM information_schema.tables
             WHERE table_schema = DATABASE()
               AND table_name = 'academic_years'"
        )->fetchColumn();

        if ((int)$yearExists > 0) {
            $yearCols = array_column(
                $pdo->query("SHOW COLUMNS FROM academic_years")->fetchAll(PDO::FETCH_ASSOC),
                null,
                'Field'
            );
            $labelCol = null;
            foreach (['name', 'year_name', 'label', 'title', 'school_year'] as $candidate) {
                if (isset($yearCols[$candidate])) {
                    $labelCol = $candidate;
                    break;
                }
            }

            if ($labelCol !== null) {
                $teacherScheduleYears = $pdo->query(
                    "SELECT id, `" . $labelCol . "` AS year_label
                     FROM academic_years
                     ORDER BY id DESC"
                )->fetchAll(PDO::FETCH_ASSOC);
            }
        }
    } catch (Throwable $scheduleContextError) {
        error_log('[EnglishSpeak teacher schedule context] ' . $scheduleContextError->getMessage());
    }
}

/*
 * Đồng bộ Content Library với "Sách đang làm việc" trên Topbar.
 * Khi vừa đổi sách từ Topbar, ưu tiên teacher_book_id và reset Level/Unit.
 * Các click Book/Level/Unit bên trong Content Library vẫn tiếp tục dùng query string như cũ.
 */
$bookChangedFromTopbar = !empty($_SESSION['teacher_book_changed']);

if ($bookChangedFromTopbar) {
    $selectedBookId = max(0, (int)($_SESSION['teacher_book_id'] ?? 0));
    $selectedLevelId = 0;
    $selectedUnitId = 0;
    unset($_SESSION['teacher_book_changed']);
} else {
    $selectedBookId = isset($_GET['book_id'])
        ? (int)$_GET['book_id']
        : (int)($_POST['book_id'] ?? ($_SESSION['teacher_book_id'] ?? 0));
    $selectedLevelId = isset($_GET['level_id']) ? (int)$_GET['level_id'] : (int)($_POST['level_id'] ?? 0);
    $selectedUnitId = isset($_GET['unit_id']) ? (int)$_GET['unit_id'] : (int)($_POST['unit_id'] ?? 0);
}


function clTableColumns(PDO $pdo, string $table): array {
    $rows = $pdo->query("SHOW COLUMNS FROM `{$table}`")->fetchAll(PDO::FETCH_ASSOC);
    return array_column($rows, null, 'Field');
}

function clSlug(string $value): string {
    $slug = strtolower(trim((string)preg_replace('/[^a-zA-Z0-9]+/', '-', $value), '-'));
    return $slug !== '' ? $slug : 'lesson-' . time();
}

function clUniqueSlug(PDO $pdo, string $table, string $baseSlug): string {
    $baseSlug = clSlug($baseSlug);
    $slug = $baseSlug;
    $suffix = 2;

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM `{$table}` WHERE slug = ?");

    while (true) {
        $stmt->execute([$slug]);

        if ((int)$stmt->fetchColumn() === 0) {
            return $slug;
        }

        $slug = $baseSlug . '-' . $suffix;
        $suffix++;
    }
}


function clNormalizeActiveLessonNumbers(PDO $pdo, int $unitId): void {
    if ($unitId <= 0) {
        return;
    }

    $columns = clTableColumns($pdo, 'lessons');
    if (!isset($columns['lesson_number'], $columns['unit_id'])) {
        return;
    }

    $orderParts = [];
    if (isset($columns['sort_order'])) {
        $orderParts[] = 'sort_order';
    }
    $orderParts[] = 'id';

    $where = 'unit_id = ?';
    if (isset($columns['status'])) {
        $where .= " AND status = 'active'";
    }

    $stmt = $pdo->prepare(
        'SELECT id, lesson_number
         FROM lessons
         WHERE ' . $where . '
         ORDER BY ' . implode(', ', $orderParts)
    );
    $stmt->execute([$unitId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($rows === []) {
        return;
    }

    $checkStmt = $pdo->prepare(
        'SELECT id
         FROM lessons
         WHERE unit_id = ?
           AND lesson_number = ?
           AND id <> ?
         LIMIT 1'
    );

    $updateStmt = $pdo->prepare(
        'UPDATE lessons
         SET lesson_number = ?' .
         (isset($columns['updated_at']) ? ', updated_at = NOW()' : '') .
        ' WHERE id = ? AND unit_id = ?'
    );

    foreach ($rows as $index => $row) {
        $desiredNumber = $index + 1;
        $currentNumber = (int)preg_replace('/\D+/', '', (string)($row['lesson_number'] ?? ''));

        if ($currentNumber === $desiredNumber) {
            continue;
        }

        /*
         * Chỉ sửa khi số mong muốn chưa bị một record khác chiếm.
         * Như vậy an toàn cả với database cũ có UNIQUE(unit_id, lesson_number).
         */
        $checkStmt->execute([$unitId, $desiredNumber, (int)$row['id']]);
        if ($checkStmt->fetchColumn()) {
            continue;
        }

        $updateStmt->execute([
            $desiredNumber,
            (int)$row['id'],
            $unitId,
        ]);
    }
}

function clInsertDynamic(PDO $pdo, string $table, array $data): int {
    $columns = clTableColumns($pdo, $table);
    $fields = [];
    $values = [];
    $params = [];

    foreach ($data as $field => $value) {
        if (!isset($columns[$field])) {
            continue;
        }

        $fields[] = "`{$field}`";

        if ($value === '__NOW__') {
            $values[] = 'NOW()';
        } else {
            $values[] = '?';
            $params[] = $value;
        }
    }

    if ($fields === []) {
        throw new RuntimeException("Table {$table} has no supported columns.");
    }

    $sql = "INSERT INTO `{$table}` (" . implode(', ', $fields) . ")
            VALUES (" . implode(', ', $values) . ")";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    return (int)$pdo->lastInsertId();
}

function clBookLevelTemplates(string $template, string $customText): array {
    if ($template === 'global-success') {
        return [
            ['number' => 1, 'name' => 'Lớp 1', 'slug' => 'grade-1'],
            ['number' => 2, 'name' => 'Lớp 2', 'slug' => 'grade-2'],
            ['number' => 3, 'name' => 'Lớp 3', 'slug' => 'grade-3'],
            ['number' => 4, 'name' => 'Lớp 4', 'slug' => 'grade-4'],
            ['number' => 5, 'name' => 'Lớp 5', 'slug' => 'grade-5'],
        ];
    }

    if ($template === 'everybody-up') {
        return [
            ['number' => 1, 'name' => 'Starter', 'slug' => 'starter'],
            ['number' => 1, 'name' => 'Up 1', 'slug' => 'up-1'],
            ['number' => 2, 'name' => 'Up 2', 'slug' => 'up-2'],
            ['number' => 3, 'name' => 'Up 3', 'slug' => 'up-3'],
            ['number' => 4, 'name' => 'Up 4', 'slug' => 'up-4'],
            ['number' => 5, 'name' => 'Up 5', 'slug' => 'up-5'],
            ['number' => 6, 'name' => 'Up 6', 'slug' => 'up-6'],
        ];
    }

    $lines = preg_split('/\R+/', trim($customText)) ?: [];
    $levels = [];
    $sort = 1;

    foreach ($lines as $line) {
        $name = trim((string)$line);

        if ($name === '') {
            continue;
        }

        $number = preg_match('/\d+/', $name, $match)
            ? (int)$match[0]
            : $sort;

        $levels[] = [
            'number' => $number,
            'name' => $name,
            'slug' => clSlug($name),
        ];

        $sort++;
    }

    return $levels;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');

    if (!$isAdmin && in_array($action, [
        'create_book', 'update_book', 'delete_book',
        'create_level', 'update_level', 'delete_level',
        'create_unit', 'update_unit', 'duplicate_unit', 'move_unit', 'delete_unit'
    ], true)) {
        http_response_code(403);
        exit('Bạn không có quyền thay đổi cấu trúc Sách / Lớp / Unit.');
    }


    if ($action === 'delete_lesson_schedule') {
        if ($isAdmin || $currentUserId <= 0) {
            http_response_code(403);
            exit('Chỉ Teacher mới có thể xóa lịch mở của lớp mình.');
        }

        $scheduleId = max(0, (int)($_POST['schedule_id'] ?? 0));
        $bookId = max(0, (int)($_POST['book_id'] ?? 0));
        $levelId = max(0, (int)($_POST['level_id'] ?? 0));
        $unitId = max(0, (int)($_POST['unit_id'] ?? 0));

        try {
            if ($scheduleId <= 0) {
                throw new RuntimeException('Lịch mở không hợp lệ.');
            }

            // Chỉ xóa đúng lịch thuộc Teacher đang đăng nhập.
            // Không ảnh hưởng Lesson gốc, lớp/năm học khác hoặc Teacher khác.
            $deleteStmt = $pdo->prepare(
                "DELETE FROM teacher_lesson_schedules
                 WHERE id = ?
                   AND teacher_id = ?"
            );
            $deleteStmt->execute([$scheduleId, $currentUserId]);

            if ($deleteStmt->rowCount() < 1) {
                throw new RuntimeException('Không tìm thấy lịch mở hoặc bạn không có quyền xóa lịch này.');
            }

            $_SESSION['cl_message'] = 'Đã xóa lịch mở Lesson.';
            $_SESSION['cl_message_type'] = 'success';
        } catch (Throwable $e) {
            error_log('[EnglishSpeak delete_lesson_schedule] ' . $e->getMessage());
            $_SESSION['cl_message'] = $e instanceof RuntimeException
                ? $e->getMessage()
                : 'Không thể xóa lịch mở Lesson.';
            $_SESSION['cl_message_type'] = 'error';
        }

        header(
            'Location: index.php?book_id=' . $bookId .
            '&level_id=' . $levelId .
            '&unit_id=' . $unitId
        );
        exit;
    }

    if ($action === 'save_lesson_schedule') {
        if ($isAdmin || $currentUserId <= 0) {
            http_response_code(403);
            exit('Chỉ Teacher mới sử dụng lịch mở riêng cho lớp.');
        }

        $lessonId = max(0, (int)($_POST['lesson_id'] ?? 0));
        $bookId = max(0, (int)($_POST['book_id'] ?? 0));
        $levelId = max(0, (int)($_POST['level_id'] ?? 0));
        $unitId = max(0, (int)($_POST['unit_id'] ?? 0));
        $academicYearId = max(0, (int)($_POST['academic_year_id'] ?? 0));
        $gradeRaw = trim((string)($_POST['grade'] ?? ''));
        $grade = $gradeRaw !== '' ? max(1, min(5, (int)$gradeRaw)) : null;
        $className = trim((string)($_POST['class_name'] ?? ''));
        $unlockMode = trim((string)($_POST['schedule_unlock_mode'] ?? 'sequential_daily'));
        $unlockDate = trim((string)($_POST['schedule_unlock_date'] ?? ''));

        if (!in_array($unlockMode, ['sequential_daily', 'scheduled_date'], true)) {
            $unlockMode = 'sequential_daily';
        }
        if ($unlockMode !== 'scheduled_date') {
            $unlockDate = '';
        }

        try {
            if ($lessonId <= 0 || $unitId <= 0) {
                throw new RuntimeException('Lesson không hợp lệ.');
            }
            if ($className === '') {
                throw new RuntimeException('Vui lòng chọn hoặc nhập lớp áp dụng.');
            }
            if ($academicYearId <= 0) {
                throw new RuntimeException('Vui lòng chọn năm học.');
            }
            if ($unlockMode === 'scheduled_date') {
                $date = DateTimeImmutable::createFromFormat('!Y-m-d', $unlockDate);
                if (!$date || $date->format('Y-m-d') !== $unlockDate) {
                    throw new RuntimeException('Ngày mở Lesson không hợp lệ.');
                }
            }

            // Teacher phải được Admin gán Book này.
            $bookGuard = $pdo->prepare(
                "SELECT COUNT(*)
                 FROM teacher_books
                 WHERE teacher_id = ?
                   AND book_id = ?"
            );
            $bookGuard->execute([$currentUserId, $bookId]);
            if ((int)$bookGuard->fetchColumn() < 1) {
                throw new RuntimeException('Bạn không được phép sử dụng Book này.');
            }

            // Lesson phải thật sự thuộc Unit đang mở.
            $lessonGuard = $pdo->prepare(
                "SELECT COUNT(*)
                 FROM lessons
                 WHERE id = ?
                   AND unit_id = ?
                   AND status = 'active'"
            );
            $lessonGuard->execute([$lessonId, $unitId]);
            if ((int)$lessonGuard->fetchColumn() < 1) {
                throw new RuntimeException('Không tìm thấy Lesson cần đặt lịch.');
            }

            $scopeStmt = $pdo->prepare(
                "SELECT school_id
                 FROM teacher_profiles
                 WHERE user_id = ?
                 LIMIT 1"
            );
            $scopeStmt->execute([$currentUserId]);
            $schoolId = max(0, (int)$scopeStmt->fetchColumn());
            if ($schoolId <= 0) {
                throw new RuntimeException('Tài khoản Teacher chưa có Trường hợp lệ.');
            }

            $stmt = $pdo->prepare(
                "INSERT INTO teacher_lesson_schedules
                    (teacher_id, lesson_id, school_id, academic_year_id, grade,
                     class_name, unlock_mode, unlock_date, created_at, updated_at)
                 VALUES
                    (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                 ON DUPLICATE KEY UPDATE
                    grade = VALUES(grade),
                    unlock_mode = VALUES(unlock_mode),
                    unlock_date = VALUES(unlock_date),
                    updated_at = NOW()"
            );
            $stmt->execute([
                $currentUserId,
                $lessonId,
                $schoolId,
                $academicYearId,
                $grade,
                $className,
                $unlockMode,
                $unlockDate !== '' ? $unlockDate : null,
            ]);

            $_SESSION['cl_message'] = 'Đã lưu lịch mở Lesson cho lớp ' . $className . '.';
            $_SESSION['cl_message_type'] = 'success';
        } catch (Throwable $e) {
            error_log('[EnglishSpeak save_lesson_schedule] ' . $e->getMessage());
            $_SESSION['cl_message'] = $e instanceof RuntimeException
                ? $e->getMessage()
                : 'Không thể lưu lịch mở Lesson.';
            $_SESSION['cl_message_type'] = 'error';
        }

        header(
            'Location: index.php?book_id=' . $bookId .
            '&level_id=' . $levelId .
            '&unit_id=' . $unitId
        );
        exit;
    }

    if ($action === 'create_book') {
        $bookName = trim((string)($_POST['book_name'] ?? ''));
        $requestedSlug = trim((string)($_POST['book_slug'] ?? ''));
        $description = trim((string)($_POST['book_description'] ?? ''));
        $coverImage = trim((string)($_POST['cover_image'] ?? ''));
        $levelTemplate = trim((string)($_POST['level_template'] ?? 'custom'));
        $customLevels = trim((string)($_POST['custom_levels'] ?? ''));

        if ($bookName === '') {
            $_SESSION['cl_message'] = 'Please enter a Book name.';
            $_SESSION['cl_message_type'] = 'error';
            header('Location: index.php');
            exit;
        }

        $levelsToCreate = clBookLevelTemplates($levelTemplate, $customLevels);

        if ($levelsToCreate === []) {
            $_SESSION['cl_message'] = 'Please add at least one Level.';
            $_SESSION['cl_message_type'] = 'error';
            header('Location: index.php');
            exit;
        }

        try {
            $pdo->beginTransaction();

            $bookSlug = clUniqueSlug(
                $pdo,
                'books',
                $requestedSlug !== '' ? $requestedSlug : $bookName
            );

            $bookSortOrder = (int)$pdo->query(
                "SELECT COALESCE(MAX(sort_order), 0) + 1 FROM books"
            )->fetchColumn();

            $newBookId = clInsertDynamic($pdo, 'books', [
                'name' => $bookName,
                'slug' => $bookSlug,
                'description' => $description,
                'cover_image' => $coverImage,
                'sort_order' => $bookSortOrder,
                'status' => 'active',
                'created_at' => '__NOW__',
                'updated_at' => '__NOW__',
            ]);

            $firstLevelId = 0;
            $levelSortOrder = 1;

            foreach ($levelsToCreate as $levelData) {
                $levelId = clInsertDynamic($pdo, 'levels', [
                    'book_id' => $newBookId,
                    'level_number' => (int)$levelData['number'],
                    'name' => (string)$levelData['name'],
                    'slug' => (string)$levelData['slug'],
                    'sort_order' => $levelSortOrder,
                    'status' => 'active',
                    'created_at' => '__NOW__',
                    'updated_at' => '__NOW__',
                ]);

                if ($firstLevelId === 0) {
                    $firstLevelId = $levelId;
                }

                $levelSortOrder++;
            }

            $pdo->commit();

            $_SESSION['cl_message'] = 'Book and Levels created successfully.';
            $_SESSION['cl_message_type'] = 'success';

            header(
                'Location: index.php?book_id=' . $newBookId .
                '&level_id=' . $firstLevelId .
                '&unit_id=0'
            );
            exit;
        } catch (Throwable $e) {
            error_log('[create_level] '.$e->getMessage());
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            $_SESSION['cl_message'] = 'Could not create the Book.';
            $_SESSION['cl_message_type'] = 'error';
            header('Location: index.php');
            exit;
        }
    }



    if ($action === 'update_book') {
        $bookId = (int)($_POST['book_id'] ?? 0);
        $name = trim((string)($_POST['book_name'] ?? ''));
        $slugInput = trim((string)($_POST['book_slug'] ?? ''));
        $description = trim((string)($_POST['book_description'] ?? ''));
        $coverImage = trim((string)($_POST['cover_image'] ?? ''));

        if ($bookId <= 0 || $name === '') {
            $_SESSION['cl_message'] = 'Please enter a valid Book name.';
            $_SESSION['cl_message_type'] = 'error';
            header('Location: index.php');
            exit;
        }

        try {
            $slug = clSlug($slugInput !== '' ? $slugInput : $name);
            $slugCheck = $pdo->prepare(
                'SELECT COUNT(*) FROM books WHERE slug = ? AND id <> ?'
            );
            $slugCheck->execute([$slug, $bookId]);

            if ((int)$slugCheck->fetchColumn() > 0) {
                $slug = clUniqueSlug($pdo, 'books', $slug);
            }

            $cols = clTableColumns($pdo, 'books');
            $sets = [];
            $params = [];

            foreach ([
                'name' => $name,
                'slug' => $slug,
                'description' => $description,
                'cover_image' => $coverImage,
            ] as $field => $value) {
                if (isset($cols[$field])) {
                    $sets[] = "`{$field}` = ?";
                    $params[] = $value;
                }
            }

            if (isset($cols['updated_at'])) {
                $sets[] = '`updated_at` = NOW()';
            }

            $params[] = $bookId;
            $stmt = $pdo->prepare(
                'UPDATE books SET ' . implode(', ', $sets) . ' WHERE id = ?'
            );
            $stmt->execute($params);

            $_SESSION['cl_message'] = 'Book updated successfully.';
            $_SESSION['cl_message_type'] = 'success';
        } catch (Throwable $e) {
            $_SESSION['cl_message'] = 'Could not update the Book.';
            $_SESSION['cl_message_type'] = 'error';
        }

        header('Location: index.php?book_id=' . $bookId);
        exit;
    }

    if ($action === 'delete_book') {
        $bookId = (int)($_POST['book_id'] ?? 0);

        if ($bookId > 0) {
            try {
                $countStmt = $pdo->prepare(
                    'SELECT
                        (SELECT COUNT(*) FROM levels WHERE book_id = ?) AS level_count,
                        (SELECT COUNT(*) FROM units WHERE book_id = ?) AS unit_count'
                );
                $countStmt->execute([$bookId, $bookId]);
                $counts = $countStmt->fetch(PDO::FETCH_ASSOC) ?: [];

                $hasContent =
                    (int)($counts['level_count'] ?? 0) > 0
                    || (int)($counts['unit_count'] ?? 0) > 0;

                if ($hasContent) {
                    $cols = clTableColumns($pdo, 'books');

                    if (isset($cols['status'])) {
                        $sql = "UPDATE books SET status = 'inactive'";
                        if (isset($cols['updated_at'])) {
                            $sql .= ', updated_at = NOW()';
                        }
                        $sql .= ' WHERE id = ?';

                        $stmt = $pdo->prepare($sql);
                        $stmt->execute([$bookId]);

                        $_SESSION['cl_message'] = 'Book has content, so it was archived instead of deleted.';
                        $_SESSION['cl_message_type'] = 'success';
                    } else {
                        throw new RuntimeException('Books table has no status column.');
                    }
                } else {
                    $stmt = $pdo->prepare('DELETE FROM books WHERE id = ?');
                    $stmt->execute([$bookId]);

                    $_SESSION['cl_message'] = 'Empty Book deleted.';
                    $_SESSION['cl_message_type'] = 'success';
                }
            } catch (Throwable $e) {
                $_SESSION['cl_message'] = 'Could not delete or archive the Book.';
                $_SESSION['cl_message_type'] = 'error';
            }
        }

        header('Location: index.php');
        exit;
    }

    if ($action === 'create_level') {
        $bookId = (int)($_POST['book_id'] ?? 0);
        $name = trim((string)($_POST['level_name'] ?? ''));
        $number = (int)($_POST['level_number'] ?? 0);
        $slugInput = trim((string)($_POST['level_slug'] ?? ''));

        if ($bookId <= 0 || $name === '') {
            $_SESSION['cl_message'] = 'Please enter a Level name.';
            $_SESSION['cl_message_type'] = 'error';
            header('Location: index.php?book_id=' . $bookId);
            exit;
        }

        try {
            /*
             * Bảo đảm Book tồn tại.
             */
            $bookStmt = $pdo->prepare(
                "SELECT id
                 FROM books
                 WHERE id = ?
                 LIMIT 1"
            );
            $bookStmt->execute([$bookId]);

            if (!$bookStmt->fetchColumn()) {
                throw new RuntimeException('Book not found.');
            }

            /*
             * Nếu giáo viên không nhập Level Number,
             * tự lấy số lớn nhất trong Book + 1.
             */
            if ($number <= 0) {
                $numberStmt = $pdo->prepare(
                    "SELECT COALESCE(MAX(level_number), 0) + 1
                     FROM levels
                     WHERE book_id = ?"
                );
                $numberStmt->execute([$bookId]);
                $number = max(1, (int)$numberStmt->fetchColumn());
            }

            /*
             * Không cho trùng tên Level trong cùng Book.
             */
            $nameStmt = $pdo->prepare(
                "SELECT id
                 FROM levels
                 WHERE book_id = ?
                   AND LOWER(TRIM(name)) = LOWER(TRIM(?))
                 LIMIT 1"
            );
            $nameStmt->execute([$bookId, $name]);

            if ($nameStmt->fetchColumn()) {
                throw new RuntimeException(
                    'This Level name already exists in the selected Book.'
                );
            }

            /*
             * Bảng levels có UNIQUE(book_id, level_number).
             */
            $numberCheckStmt = $pdo->prepare(
                "SELECT id
                 FROM levels
                 WHERE book_id = ?
                   AND level_number = ?
                 LIMIT 1"
            );
            $numberCheckStmt->execute([$bookId, $number]);

            if ($numberCheckStmt->fetchColumn()) {
                throw new RuntimeException(
                    'This Level Number already exists in the selected Book.'
                );
            }

            /*
             * Tạo slug duy nhất trong cùng Book,
             * đúng UNIQUE(book_id, slug).
             */
            $baseSlug = clSlug(
                $slugInput !== '' ? $slugInput : $name
            );
            $slug = $baseSlug;
            $suffix = 2;

            $slugStmt = $pdo->prepare(
                "SELECT id
                 FROM levels
                 WHERE book_id = ?
                   AND slug = ?
                 LIMIT 1"
            );

            while (true) {
                $slugStmt->execute([$bookId, $slug]);

                if (!$slugStmt->fetchColumn()) {
                    break;
                }

                $slug = $baseSlug . '-' . $suffix;
                $suffix++;
            }

            $sortStmt = $pdo->prepare(
                "SELECT COALESCE(MAX(sort_order), 0) + 1
                 FROM levels
                 WHERE book_id = ?"
            );
            $sortStmt->execute([$bookId]);
            $sortOrder = max(1, (int)$sortStmt->fetchColumn());

            /*
             * INSERT đúng theo cấu trúc thật của bảng levels:
             * book_id, level_number, name, slug,
             * sort_order, status, created_at, updated_at.
             */
            $stmt = $pdo->prepare(
                "INSERT INTO levels (
                    book_id,
                    level_number,
                    name,
                    slug,
                    sort_order,
                    status,
                    created_at,
                    updated_at
                ) VALUES (
                    ?,
                    ?,
                    ?,
                    ?,
                    ?,
                    'active',
                    NOW(),
                    NOW()
                )"
            );

            $stmt->execute([
                $bookId,
                $number,
                $name,
                $slug,
                $sortOrder,
            ]);

            $levelId = (int)$pdo->lastInsertId();

            if ($levelId <= 0) {
                throw new RuntimeException(
                    'Level insert returned no ID.'
                );
            }

            $_SESSION['cl_message'] = 'Level created successfully.';
            $_SESSION['cl_message_type'] = 'success';

            header(
                'Location: index.php?book_id=' . $bookId .
                '&level_id=' . $levelId .
                '&unit_id=0'
            );
            exit;
        } catch (Throwable $e) {
            error_log(
                '[EnglishSpeak create_level] ' .
                $e->getMessage()
            );

            $_SESSION['cl_message'] =
                'Could not create the Level. Please check the Level Number and try again.';
            $_SESSION['cl_message_type'] = 'error';

            header('Location: index.php?book_id=' . $bookId);
            exit;
        }
    }

    if ($action === 'update_level') {
        $bookId = (int)($_POST['book_id'] ?? 0);
        $levelId = (int)($_POST['level_id'] ?? 0);
        $name = trim((string)($_POST['level_name'] ?? ''));
        $number = (int)($_POST['level_number'] ?? 0);
        $slugInput = trim((string)($_POST['level_slug'] ?? ''));

        if ($bookId <= 0 || $levelId <= 0 || $name === '') {
            $_SESSION['cl_message'] = 'Please enter valid Level information.';
            $_SESSION['cl_message_type'] = 'error';
            header('Location: index.php?book_id=' . $bookId);
            exit;
        }

        try {
            $cols = clTableColumns($pdo, 'levels');
            $sets = [];
            $params = [];

            foreach ([
                'name' => $name,
                'level_number' => $number,
                'slug' => clSlug($slugInput !== '' ? $slugInput : $name),
            ] as $field => $value) {
                if (isset($cols[$field])) {
                    $sets[] = "`{$field}` = ?";
                    $params[] = $value;
                }
            }

            if (isset($cols['updated_at'])) {
                $sets[] = '`updated_at` = NOW()';
            }

            $params[] = $levelId;
            $params[] = $bookId;

            $stmt = $pdo->prepare(
                'UPDATE levels SET ' . implode(', ', $sets) .
                ' WHERE id = ? AND book_id = ?'
            );
            $stmt->execute($params);

            $_SESSION['cl_message'] = 'Level updated successfully.';
            $_SESSION['cl_message_type'] = 'success';
        } catch (Throwable $e) {
            $_SESSION['cl_message'] = 'Could not update the Level.';
            $_SESSION['cl_message_type'] = 'error';
        }

        header(
            'Location: index.php?book_id=' . $bookId .
            '&level_id=' . $levelId .
            '&unit_id=0'
        );
        exit;
    }

    if ($action === 'delete_level') {
        $bookId = (int)($_POST['book_id'] ?? 0);
        $levelId = (int)($_POST['level_id'] ?? 0);

        if ($bookId > 0 && $levelId > 0) {
            try {
                $unitCountStmt = $pdo->prepare(
                    'SELECT COUNT(*) FROM units WHERE level_id = ?'
                );
                $unitCountStmt->execute([$levelId]);
                $unitCount = (int)$unitCountStmt->fetchColumn();

                if ($unitCount > 0) {
                    $cols = clTableColumns($pdo, 'levels');

                    if (isset($cols['status'])) {
                        $sql = "UPDATE levels SET status = 'inactive'";
                        if (isset($cols['updated_at'])) {
                            $sql .= ', updated_at = NOW()';
                        }
                        $sql .= ' WHERE id = ? AND book_id = ?';

                        $stmt = $pdo->prepare($sql);
                        $stmt->execute([$levelId, $bookId]);

                        $_SESSION['cl_message'] = 'Level has Units, so it was archived instead of deleted.';
                        $_SESSION['cl_message_type'] = 'success';
                    } else {
                        throw new RuntimeException('Levels table has no status column.');
                    }
                } else {
                    $stmt = $pdo->prepare(
                        'DELETE FROM levels WHERE id = ? AND book_id = ?'
                    );
                    $stmt->execute([$levelId, $bookId]);

                    $_SESSION['cl_message'] = 'Empty Level deleted.';
                    $_SESSION['cl_message_type'] = 'success';
                }
            } catch (Throwable $e) {
                $_SESSION['cl_message'] = 'Could not delete or archive the Level.';
                $_SESSION['cl_message_type'] = 'error';
            }
        }

        header('Location: index.php?book_id=' . $bookId);
        exit;
    }


    if ($action === 'create_unit') {
        $bookId = (int)($_POST['book_id'] ?? 0);
        $levelId = (int)($_POST['level_id'] ?? 0);
        $unitNumber = trim((string)($_POST['unit_number'] ?? ''));
        $title = trim((string)($_POST['title'] ?? ''));
        $description = trim((string)($_POST['description'] ?? ''));

        $returnUrl =
            'index.php?book_id=' . $bookId .
            '&level_id=' . $levelId .
            '&unit_id=0';

        if (
            $bookId <= 0
            || $levelId <= 0
            || $unitNumber === ''
            || $title === ''
        ) {
            $_SESSION['cl_message'] = 'Please enter Unit number and title.';
            $_SESSION['cl_message_type'] = 'error';
            header('Location: ' . $returnUrl);
            exit;
        }

        try {
            /*
             * Bảo đảm Level thật sự thuộc Book đang chọn.
             * Tránh tạo Unit sai tầng Book → Level → Unit.
             */
            $levelCheck = $pdo->prepare(
                "SELECT id
                 FROM levels
                 WHERE id = ?
                   AND book_id = ?
                   AND status = 'active'
                 LIMIT 1"
            );
            $levelCheck->execute([$levelId, $bookId]);

            if (!$levelCheck->fetchColumn()) {
                throw new RuntimeException(
                    'The selected Level does not belong to this Book.'
                );
            }

            $unitColumns = clTableColumns($pdo, 'units');

            /*
             * Kiểm tra trùng Unit Number trong cùng một Level.
             */
            if (
                isset($unitColumns['unit_number'])
                && isset($unitColumns['level_id'])
            ) {
                $duplicateStmt = $pdo->prepare(
                    "SELECT id
                     FROM units
                     WHERE level_id = ?
                       AND LOWER(TRIM(unit_number)) = LOWER(TRIM(?))
                     LIMIT 1"
                );
                $duplicateStmt->execute([$levelId, $unitNumber]);

                if ($duplicateStmt->fetchColumn()) {
                    $_SESSION['cl_message'] =
                        'This Unit Number already exists in the selected Level.';
                    $_SESSION['cl_message_type'] = 'error';
                    header('Location: ' . $returnUrl);
                    exit;
                }
            }

            $sortStmt = $pdo->prepare(
                'SELECT COALESCE(MAX(sort_order), 0) + 1
                 FROM units
                 WHERE level_id = ?'
            );
            $sortStmt->execute([$levelId]);
            $sortOrder = max(1, (int)$sortStmt->fetchColumn());

            /*
             * Một số bản database cũ dùng name/unit_name,
             * một số bản mới dùng title. clInsertDynamic chỉ lấy
             * những cột thực sự tồn tại, nên block này tương thích
             * với cả hai cấu trúc.
             */
            $unitSlug = clSlug($unitNumber . '-' . $title);

            if (isset($unitColumns['slug'])) {
                $unitSlug = clUniqueSlug($pdo, 'units', $unitSlug);
            }

            $newUnitId = clInsertDynamic($pdo, 'units', [
                'book_id' => $bookId,
                'level_id' => $levelId,
                'unit_number' => $unitNumber,
                'number' => $unitNumber,
                'title' => $title,
                'name' => $title,
                'unit_name' => $title,
                'slug' => $unitSlug,
                'description' => $description !== '' ? $description : null,
                'thumbnail' => null,
                'required_xp' => 0,
                'sort_order' => $sortOrder,
                'order_index' => $sortOrder,
                'status' => 'active',
                'is_active' => 1,
                'created_at' => '__NOW__',
                'updated_at' => '__NOW__',
            ]);

            if ($newUnitId <= 0) {
                throw new RuntimeException('Unit insert returned no ID.');
            }

            $_SESSION['cl_message'] = 'Unit created successfully.';
            $_SESSION['cl_message_type'] = 'success';

            header(
                'Location: index.php?book_id=' . $bookId .
                '&level_id=' . $levelId .
                '&unit_id=' . $newUnitId
            );
            exit;
        } catch (Throwable $e) {
            /*
             * Ghi lỗi thật vào PHP error log để lần sau dễ kiểm tra,
             * nhưng chỉ hiện thông báo thân thiện cho giáo viên.
             */
            error_log(
                '[EnglishSpeak create_unit] ' .
                $e->getMessage()
            );

            $_SESSION['cl_message'] =
                'Could not create the Unit. Please check the Unit Number and try again.';
            $_SESSION['cl_message_type'] = 'error';

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

    if ($action === 'update_unit') {
        $bookId = (int)($_POST['book_id'] ?? 0);
        $levelId = (int)($_POST['level_id'] ?? 0);
        $unitId = (int)($_POST['unit_id'] ?? 0);
        $unitNumber = trim((string)($_POST['unit_number'] ?? ''));
        $title = trim((string)($_POST['title'] ?? ''));
        $description = trim((string)($_POST['description'] ?? ''));

        if ($bookId <= 0 || $levelId <= 0 || $unitId <= 0 || $unitNumber === '' || $title === '') {
            $_SESSION['cl_message'] = 'Please enter valid Unit information.';
            $_SESSION['cl_message_type'] = 'error';
            header(
                'Location: index.php?book_id=' . $bookId .
                '&level_id=' . $levelId .
                '&unit_id=' . $unitId
            );
            exit;
        }

        try {
            $cols = clTableColumns($pdo, 'units');
            $sets = [];
            $params = [];

            foreach ([
                'unit_number' => $unitNumber,
                'title' => $title,
                'description' => $description,
            ] as $field => $value) {
                if (isset($cols[$field])) {
                    $sets[] = "`{$field}` = ?";
                    $params[] = $value;
                }
            }

            if (isset($cols['updated_at'])) {
                $sets[] = '`updated_at` = NOW()';
            }

            $params[] = $unitId;
            $params[] = $levelId;
            $params[] = $bookId;

            $stmt = $pdo->prepare(
                'UPDATE units SET ' . implode(', ', $sets) .
                ' WHERE id = ? AND level_id = ? AND book_id = ?'
            );
            $stmt->execute($params);

            $_SESSION['cl_message'] = 'Unit updated successfully.';
            $_SESSION['cl_message_type'] = 'success';
        } catch (Throwable $e) {
            $_SESSION['cl_message'] = 'Could not update the Unit.';
            $_SESSION['cl_message_type'] = 'error';
        }

        header(
            'Location: index.php?book_id=' . $bookId .
            '&level_id=' . $levelId .
            '&unit_id=' . $unitId
        );
        exit;
    }

    if ($action === 'duplicate_unit') {
        $bookId = (int)($_POST['book_id'] ?? 0);
        $levelId = (int)($_POST['level_id'] ?? 0);
        $unitId = (int)($_POST['unit_id'] ?? 0);

        try {
            $stmt = $pdo->prepare(
                'SELECT * FROM units WHERE id = ? AND level_id = ? AND book_id = ? LIMIT 1'
            );
            $stmt->execute([$unitId, $levelId, $bookId]);
            $unit = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$unit) {
                throw new RuntimeException('Unit not found.');
            }

            $sortStmt = $pdo->prepare(
                'SELECT COALESCE(MAX(sort_order), 0) + 1 FROM units WHERE level_id = ?'
            );
            $sortStmt->execute([$levelId]);

            $newUnitId = clInsertDynamic($pdo, 'units', [
                'book_id' => $bookId,
                'level_id' => $levelId,
                'unit_number' => (string)$unit['unit_number'] . ' Copy',
                'title' => (string)$unit['title'] . ' Copy',
                'description' => (string)($unit['description'] ?? ''),
                'sort_order' => $nextSortOrder,
                'status' => 'active',
                'created_at' => '__NOW__',
                'updated_at' => '__NOW__',
            ]);

            $_SESSION['cl_message'] = 'Unit duplicated successfully.';
            $_SESSION['cl_message_type'] = 'success';

            header(
                'Location: index.php?book_id=' . $bookId .
                '&level_id=' . $levelId .
                '&unit_id=' . $newUnitId
            );
            exit;
        } catch (Throwable $e) {
            $_SESSION['cl_message'] = 'Could not duplicate the Unit.';
            $_SESSION['cl_message_type'] = 'error';
            header(
                'Location: index.php?book_id=' . $bookId .
                '&level_id=' . $levelId .
                '&unit_id=' . $unitId
            );
            exit;
        }
    }

    if ($action === 'move_unit') {
        $bookId = (int)($_POST['book_id'] ?? 0);
        $levelId = (int)($_POST['level_id'] ?? 0);
        $unitId = (int)($_POST['unit_id'] ?? 0);
        $direction = (string)($_POST['direction'] ?? '');

        try {
            $pdo->beginTransaction();

            $listStmt = $pdo->prepare(
                'SELECT id
                 FROM units
                 WHERE book_id = ?
                   AND level_id = ?
                   AND status = "active"
                 ORDER BY sort_order, id
                 FOR UPDATE'
            );
            $listStmt->execute([$bookId, $levelId]);

            $unitIds = array_map(
                'intval',
                $listStmt->fetchAll(PDO::FETCH_COLUMN)
            );

            $currentIndex = array_search($unitId, $unitIds, true);

            if ($currentIndex === false) {
                throw new RuntimeException('Unit not found.');
            }

            $targetIndex = $direction === 'up'
                ? $currentIndex - 1
                : $currentIndex + 1;

            if ($targetIndex >= 0 && $targetIndex < count($unitIds)) {
                [$unitIds[$currentIndex], $unitIds[$targetIndex]] =
                    [$unitIds[$targetIndex], $unitIds[$currentIndex]];
            }

            $cols = clTableColumns($pdo, 'units');
            $hasUpdatedAt = isset($cols['updated_at']);

            $sql = 'UPDATE units SET sort_order = ?';
            if ($hasUpdatedAt) {
                $sql .= ', updated_at = NOW()';
            }
            $sql .= ' WHERE id = ? AND book_id = ? AND level_id = ?';

            $updateStmt = $pdo->prepare($sql);

            foreach ($unitIds as $index => $orderedUnitId) {
                $updateStmt->execute([
                    $index + 1,
                    $orderedUnitId,
                    $bookId,
                    $levelId,
                ]);
            }

            $pdo->commit();

            $_SESSION['cl_message'] = 'Unit order updated.';
            $_SESSION['cl_message_type'] = 'success';
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            $_SESSION['cl_message'] = 'Could not move the Unit.';
            $_SESSION['cl_message_type'] = 'error';
        }

        header(
            'Location: index.php?book_id=' . $bookId .
            '&level_id=' . $levelId .
            '&unit_id=' . $unitId
        );
        exit;
    }

    if ($action === 'delete_unit') {
        $bookId = (int)($_POST['book_id'] ?? 0);
        $levelId = (int)($_POST['level_id'] ?? 0);
        $unitId = (int)($_POST['unit_id'] ?? 0);

        try {
            $countStmt = $pdo->prepare(
                'SELECT
                    (SELECT COUNT(*) FROM lessons WHERE unit_id = ?) AS lesson_count,
                    (SELECT COUNT(*)
                     FROM activities a
                     INNER JOIN lessons l ON l.id = a.lesson_id
                     WHERE l.unit_id = ?) AS activity_count'
            );
            $countStmt->execute([$unitId, $unitId]);
            $counts = $countStmt->fetch(PDO::FETCH_ASSOC) ?: [];

            $hasContent =
                (int)($counts['lesson_count'] ?? 0) > 0
                || (int)($counts['activity_count'] ?? 0) > 0;

            if ($hasContent) {
                $cols = clTableColumns($pdo, 'units');

                if (!isset($cols['status'])) {
                    throw new RuntimeException('Units table has no status column.');
                }

                $sql = "UPDATE units SET status = 'inactive'";
                if (isset($cols['updated_at'])) {
                    $sql .= ', updated_at = NOW()';
                }
                $sql .= ' WHERE id = ? AND level_id = ? AND book_id = ?';

                $stmt = $pdo->prepare($sql);
                $stmt->execute([$unitId, $levelId, $bookId]);

                $_SESSION['cl_message'] = 'Unit has content, so it was archived instead of deleted.';
                $_SESSION['cl_message_type'] = 'success';
            } else {
                $stmt = $pdo->prepare(
                    'DELETE FROM units WHERE id = ? AND level_id = ? AND book_id = ?'
                );
                $stmt->execute([$unitId, $levelId, $bookId]);

                $_SESSION['cl_message'] = 'Empty Unit deleted.';
                $_SESSION['cl_message_type'] = 'success';
            }
        } catch (Throwable $e) {
            $_SESSION['cl_message'] = 'Could not delete or archive the Unit.';
            $_SESSION['cl_message_type'] = 'error';
        }

        header(
            'Location: index.php?book_id=' . $bookId .
            '&level_id=' . $levelId .
            '&unit_id=0'
        );
        exit;
    }

    if ($action === 'create_lesson') {
        $unitId = (int)($_POST['unit_id'] ?? 0);
        $bookId = (int)($_POST['book_id'] ?? 0);
        $title = trim((string)($_POST['title'] ?? ''));
        $lessonType = trim((string)($_POST['lesson_type'] ?? 'vocabulary'));
        $description = trim((string)($_POST['description'] ?? ''));
        $unlockMode = trim((string)($_POST['unlock_mode'] ?? 'sequential_daily'));
        $unlockDate = trim((string)($_POST['unlock_date'] ?? ''));

        if (!in_array($unlockMode, ['sequential_daily', 'scheduled_date'], true)) {
            $unlockMode = 'sequential_daily';
        }
        if ($unlockMode !== 'scheduled_date') {
            $unlockDate = '';
        }

        if ($unitId > 0 && $title !== '') {
            try {
                $cols = clTableColumns($pdo, 'lessons');
                $fields = [];
                $values = [];
                $params = [];

                if (isset($cols['unit_id'])) {
                    $fields[] = 'unit_id';
                    $values[] = '?';
                    $params[] = $unitId;
                }

                if (isset($cols['title'])) {
                    $fields[] = 'title';
                    $values[] = '?';
                    $params[] = $title;
                } elseif (isset($cols['name'])) {
                    $fields[] = 'name';
                    $values[] = '?';
                    $params[] = $title;
                }

                if (isset($cols['slug'])) {
                    // Slug của lesson phải duy nhất. Lesson 1/2 có thể đã dùng slug cũ,
                    // vì vậy luôn tìm một slug chưa tồn tại trước khi INSERT.
                    $fields[] = 'slug';
                    $values[] = '?';
                    $params[] = clUniqueSlug($pdo, 'lessons', $title);
                }

                if (isset($cols['lesson_number'])) {
                    // lesson_number là số thứ tự trong Unit, không phải chuỗi title.
                    $numberSql =
                        'SELECT COUNT(*) + 1
                         FROM lessons
                         WHERE unit_id = ?';

                    if (isset($cols['status'])) {
                        $numberSql .= " AND status = 'active'";
                    }

                    $numberStmt = $pdo->prepare($numberSql);
                    $numberStmt->execute([$unitId]);
                    $nextLessonNumber = max(1, (int)$numberStmt->fetchColumn());

                    /*
                     * Database cũ có thể còn Lesson đã archive nhưng vẫn giữ
                     * lesson_number = 2. Khi tạo Lesson 2 mới, UNIQUE(unit_id,
                     * lesson_number) sẽ làm INSERT thất bại.
                     *
                     * Nếu số cần dùng đang bị một Lesson inactive chiếm,
                     * chuyển số của record inactive sang vùng số dự phòng để
                     * giải phóng Lesson 2 cho Lesson active mới.
                     */
                    if (isset($cols['status'])) {
                        $occupiedStmt = $pdo->prepare(
                            "SELECT id, status
                             FROM lessons
                             WHERE unit_id = ?
                               AND lesson_number = ?
                             LIMIT 1"
                        );
                        $occupiedStmt->execute([$unitId, $nextLessonNumber]);
                        $occupiedLesson = $occupiedStmt->fetch(PDO::FETCH_ASSOC);

                        if (
                            $occupiedLesson
                            && strtolower((string)($occupiedLesson['status'] ?? '')) !== 'active'
                        ) {
                            $reserveStmt = $pdo->prepare(
                                "SELECT COALESCE(MAX(lesson_number), 0) + 1000
                                 FROM lessons
                                 WHERE unit_id = ?"
                            );
                            $reserveStmt->execute([$unitId]);
                            $reservedNumber = max(1000, (int)$reserveStmt->fetchColumn());

                            $moveArchivedStmt = $pdo->prepare(
                                "UPDATE lessons
                                 SET lesson_number = ?" .
                                 (isset($cols['updated_at']) ? ", updated_at = NOW()" : "") .
                                " WHERE id = ? AND unit_id = ?"
                            );
                            $moveArchivedStmt->execute([
                                $reservedNumber,
                                (int)$occupiedLesson['id'],
                                $unitId
                            ]);
                        }
                    }

                    $fields[] = 'lesson_number';
                    $values[] = '?';
                    $params[] = $nextLessonNumber;
                }

                if (isset($cols['lesson_type'])) {
                    $fields[] = 'lesson_type';
                    $values[] = '?';
                    $params[] = $lessonType;
                } elseif (isset($cols['type'])) {
                    $fields[] = 'type';
                    $values[] = '?';
                    $params[] = $lessonType;
                }

                if (isset($cols['description'])) {
                    $fields[] = 'description';
                    $values[] = '?';
                    $params[] = $description;
                }

                if (isset($cols['unlock_mode'])) {
                    $fields[] = 'unlock_mode';
                    $values[] = '?';
                    $params[] = $unlockMode;
                }

                if (isset($cols['unlock_date'])) {
                    $fields[] = 'unlock_date';
                    $values[] = '?';
                    $params[] = $unlockDate !== '' ? $unlockDate : null;
                }

                if (isset($cols['sort_order'])) {
                    $nextStmt = $pdo->prepare(
                        'SELECT COALESCE(MAX(sort_order), 0) + 1 FROM lessons WHERE unit_id = ?'
                    );
                    $nextStmt->execute([$unitId]);

                    $fields[] = 'sort_order';
                    $values[] = '?';
                    $params[] = (int)$nextStmt->fetchColumn();
                }

                if (isset($cols['status'])) {
                    $fields[] = 'status';
                    $values[] = '?';
                    $params[] = 'active';
                }

                if (isset($cols['created_by_teacher_id'])) {
                    $fields[] = 'created_by_teacher_id';
                    $values[] = '?';
                    $params[] = $isAdmin ? null : $currentUserId;
                }

                if (isset($cols['created_at'])) {
                    $fields[] = 'created_at';
                    $values[] = 'NOW()';
                }

                if (isset($cols['updated_at'])) {
                    $fields[] = 'updated_at';
                    $values[] = 'NOW()';
                }

                if (empty($fields) || !isset($cols['unit_id'])) {
                    throw new RuntimeException('Lessons table is missing required columns.');
                }

                $sql = 'INSERT INTO lessons (`' . implode('`,`', $fields) . '`) VALUES (' .
                    implode(',', $values) . ')';

                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);

                // Đồng bộ lại Lesson 1 → Lesson 2 → Lesson 3... theo thứ tự đang hiển thị.
                clNormalizeActiveLessonNumbers($pdo, $unitId);

                $_SESSION['cl_message'] = 'Lesson created successfully.';
                $_SESSION['cl_message_type'] = 'success';
            } catch (Throwable $e) {
                error_log('[EnglishSpeak create_lesson] ' . $e->getMessage());
                $_SESSION['cl_message'] = 'Could not create the Lesson.';
                $_SESSION['cl_message_type'] = 'error';
            }
        } else {
            $_SESSION['cl_message'] = 'Please enter a Lesson name.';
            $_SESSION['cl_message_type'] = 'error';
        }

        header('Location: index.php?book_id=' . $bookId . '&level_id=' . (int)($_POST['level_id'] ?? 0) . '&unit_id=' . $unitId);
        exit;
    }


    if (
        !$isAdmin
        && in_array(
            $action,
            ['update_lesson', 'duplicate_lesson', 'move_lesson', 'delete_lesson'],
            true
        )
    ) {
        $guardLessonId = (int)($_POST['lesson_id'] ?? 0);
        $guardUnitId = (int)($_POST['unit_id'] ?? 0);

        $guardStmt = $pdo->prepare(
            'SELECT created_by_teacher_id
             FROM lessons
             WHERE id = ?
               AND unit_id = ?
             LIMIT 1'
        );
        $guardStmt->execute([$guardLessonId, $guardUnitId]);

        $guardOwner = $guardStmt->fetchColumn();

        if (
            $guardOwner === false
            || $guardOwner === null
            || (int)$guardOwner !== $currentUserId
        ) {
            $_SESSION['cl_message'] =
                'Bạn chỉ có thể quản lý Lesson do chính mình tạo.';
            $_SESSION['cl_message_type'] = 'error';

            header(
                'Location: index.php?book_id=' . (int)($_POST['book_id'] ?? 0) .
                '&level_id=' . (int)($_POST['level_id'] ?? 0) .
                '&unit_id=' . $guardUnitId
            );
            exit;
        }
    }

    if ($action === 'update_lesson') {
        $lessonId = (int)($_POST['lesson_id'] ?? 0);
        $unitId = (int)($_POST['unit_id'] ?? 0);
        $bookId = (int)($_POST['book_id'] ?? 0);
        $levelId = (int)($_POST['level_id'] ?? 0);
        $title = trim((string)($_POST['title'] ?? ''));
        $lessonType = trim((string)($_POST['lesson_type'] ?? 'vocabulary'));
        $description = trim((string)($_POST['description'] ?? ''));
        $unlockMode = trim((string)($_POST['unlock_mode'] ?? 'sequential_daily'));
        $unlockDate = trim((string)($_POST['unlock_date'] ?? ''));

        if (!in_array($unlockMode, ['sequential_daily', 'scheduled_date'], true)) {
            $unlockMode = 'sequential_daily';
        }
        if ($unlockMode !== 'scheduled_date') {
            $unlockDate = '';
        }

        if ($lessonId <= 0 || $unitId <= 0 || $title === '') {
            $_SESSION['cl_message'] = 'Please enter valid Lesson information.';
            $_SESSION['cl_message_type'] = 'error';
            header(
                'Location: index.php?book_id=' . $bookId .
                '&level_id=' . $levelId .
                '&unit_id=' . $unitId
            );
            exit;
        }

        try {
            $cols = clTableColumns($pdo, 'lessons');
            $sets = [];
            $params = [];

            if (isset($cols['title'])) {
                $sets[] = '`title` = ?';
                $params[] = $title;
            } elseif (isset($cols['name'])) {
                $sets[] = '`name` = ?';
                $params[] = $title;
            }

            if (isset($cols['slug'])) {
                $sets[] = '`slug` = ?';
                $params[] = clSlug($title);
            }

            if (isset($cols['lesson_type'])) {
                $sets[] = '`lesson_type` = ?';
                $params[] = $lessonType;
            } elseif (isset($cols['type'])) {
                $sets[] = '`type` = ?';
                $params[] = $lessonType;
            }

            if (isset($cols['description'])) {
                $sets[] = '`description` = ?';
                $params[] = $description;
            }

            if (isset($cols['unlock_mode'])) {
                $sets[] = '`unlock_mode` = ?';
                $params[] = $unlockMode;
            }

            if (isset($cols['unlock_date'])) {
                $sets[] = '`unlock_date` = ?';
                $params[] = $unlockDate !== '' ? $unlockDate : null;
            }

            if (isset($cols['updated_at'])) {
                $sets[] = '`updated_at` = NOW()';
            }

            if ($sets === []) {
                throw new RuntimeException('Lessons table has no editable columns.');
            }

            $params[] = $lessonId;
            $params[] = $unitId;

            $stmt = $pdo->prepare(
                'UPDATE lessons SET ' . implode(', ', $sets) .
                ' WHERE id = ? AND unit_id = ?'
            );
            $stmt->execute($params);

            $_SESSION['cl_message'] = 'Lesson updated successfully.';
            $_SESSION['cl_message_type'] = 'success';
        } catch (Throwable $e) {
            $_SESSION['cl_message'] = 'Could not update the Lesson.';
            $_SESSION['cl_message_type'] = 'error';
        }

        header(
            'Location: index.php?book_id=' . $bookId .
            '&level_id=' . $levelId .
            '&unit_id=' . $unitId
        );
        exit;
    }

    if ($action === 'duplicate_lesson') {
        $lessonId = (int)($_POST['lesson_id'] ?? 0);
        $unitId = (int)($_POST['unit_id'] ?? 0);
        $bookId = (int)($_POST['book_id'] ?? 0);
        $levelId = (int)($_POST['level_id'] ?? 0);

        try {
            $stmt = $pdo->prepare(
                'SELECT * FROM lessons WHERE id = ? AND unit_id = ? LIMIT 1'
            );
            $stmt->execute([$lessonId, $unitId]);
            $lesson = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$lesson) {
                throw new RuntimeException('Lesson not found.');
            }

            $cols = clTableColumns($pdo, 'lessons');
            $lessonTitle = (string)(
                $lesson['title']
                ?? $lesson['name']
                ?? $lesson['lesson_number']
                ?? 'Lesson'
            );
            $lessonType = (string)(
                $lesson['lesson_type']
                ?? $lesson['type']
                ?? 'vocabulary'
            );

            $sortStmt = $pdo->prepare(
                'SELECT COALESCE(MAX(sort_order), 0) + 1 FROM lessons WHERE unit_id = ?'
            );
            $sortStmt->execute([$unitId]);
            $nextSortOrder = (int)$sortStmt->fetchColumn();

            $numberSql =
                'SELECT COUNT(*) + 1
                 FROM lessons
                 WHERE unit_id = ?';

            if (isset($cols['status'])) {
                $numberSql .= " AND status = 'active'";
            }

            $numberStmt = $pdo->prepare($numberSql);
            $numberStmt->execute([$unitId]);
            $nextLessonNumber = max(1, (int)$numberStmt->fetchColumn());

            $newLessonId = clInsertDynamic($pdo, 'lessons', [
                'unit_id' => $unitId,
                'title' => $lessonTitle . ' Copy',
                'name' => $lessonTitle . ' Copy',
                'lesson_number' => $nextLessonNumber,
                'slug' => clUniqueSlug($pdo, 'lessons', $lessonTitle . ' Copy'),
                'lesson_type' => $lessonType,
                'type' => $lessonType,
                'description' => (string)($lesson['description'] ?? ''),
                'sort_order' => (int)$sortStmt->fetchColumn(),
                'status' => 'active',
                'created_by_teacher_id' => $isAdmin ? null : $currentUserId,
                'created_at' => '__NOW__',
                'updated_at' => '__NOW__',
            ]);

            clNormalizeActiveLessonNumbers($pdo, $unitId);

            $_SESSION['cl_message'] = 'Lesson duplicated successfully.';
            $_SESSION['cl_message_type'] = 'success';
        } catch (Throwable $e) {
            $_SESSION['cl_message'] = 'Could not duplicate the Lesson.';
            $_SESSION['cl_message_type'] = 'error';
        }

        header(
            'Location: index.php?book_id=' . $bookId .
            '&level_id=' . $levelId .
            '&unit_id=' . $unitId
        );
        exit;
    }

    if ($action === 'move_lesson') {
        $lessonId = (int)($_POST['lesson_id'] ?? 0);
        $unitId = (int)($_POST['unit_id'] ?? 0);
        $bookId = (int)($_POST['book_id'] ?? 0);
        $levelId = (int)($_POST['level_id'] ?? 0);
        $direction = (string)($_POST['direction'] ?? '');

        try {
            $pdo->beginTransaction();

            $currentStmt = $pdo->prepare(
                'SELECT id, sort_order
                 FROM lessons
                 WHERE id = ? AND unit_id = ?
                 FOR UPDATE'
            );
            $currentStmt->execute([$lessonId, $unitId]);
            $current = $currentStmt->fetch(PDO::FETCH_ASSOC);

            if (!$current) {
                throw new RuntimeException('Lesson not found.');
            }

            if ($direction === 'up') {
                $neighborStmt = $pdo->prepare(
                    'SELECT id, sort_order
                     FROM lessons
                     WHERE unit_id = ?
                       AND status = "active"
                       AND sort_order < ?
                     ORDER BY sort_order DESC, id DESC
                     LIMIT 1
                     FOR UPDATE'
                );
            } else {
                $neighborStmt = $pdo->prepare(
                    'SELECT id, sort_order
                     FROM lessons
                     WHERE unit_id = ?
                       AND status = "active"
                       AND sort_order > ?
                     ORDER BY sort_order ASC, id ASC
                     LIMIT 1
                     FOR UPDATE'
                );
            }

            $neighborStmt->execute([$unitId, (int)$current['sort_order']]);
            $neighbor = $neighborStmt->fetch(PDO::FETCH_ASSOC);

            if ($neighbor) {
                $updateStmt = $pdo->prepare(
                    'UPDATE lessons SET sort_order = ? WHERE id = ?'
                );
                $updateStmt->execute([(int)$neighbor['sort_order'], (int)$current['id']]);
                $updateStmt->execute([(int)$current['sort_order'], (int)$neighbor['id']]);
            }

            $pdo->commit();

            clNormalizeActiveLessonNumbers($pdo, $unitId);

            $_SESSION['cl_message'] = 'Lesson order updated.';
            $_SESSION['cl_message_type'] = 'success';
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            $_SESSION['cl_message'] = 'Could not move the Lesson.';
            $_SESSION['cl_message_type'] = 'error';
        }

        header(
            'Location: index.php?book_id=' . $bookId .
            '&level_id=' . $levelId .
            '&unit_id=' . $unitId
        );
        exit;
    }

    if ($action === 'delete_lesson') {
        $lessonId = (int)($_POST['lesson_id'] ?? 0);
        $unitId = (int)($_POST['unit_id'] ?? 0);
        $bookId = (int)($_POST['book_id'] ?? 0);
        $levelId = (int)($_POST['level_id'] ?? 0);

        try {
            $countStmt = $pdo->prepare(
                'SELECT COUNT(*) FROM activities WHERE lesson_id = ?'
            );
            $countStmt->execute([$lessonId]);
            $activityCount = (int)$countStmt->fetchColumn();

            if ($activityCount > 0) {
                $cols = clTableColumns($pdo, 'lessons');

                if (!isset($cols['status'])) {
                    throw new RuntimeException('Lessons table has no status column.');
                }

                $sql = "UPDATE lessons SET status = 'inactive'";
                if (isset($cols['updated_at'])) {
                    $sql .= ', updated_at = NOW()';
                }
                $sql .= ' WHERE id = ? AND unit_id = ?';

                $stmt = $pdo->prepare($sql);
                $stmt->execute([$lessonId, $unitId]);

                $_SESSION['cl_message'] =
                    'Lesson has Activities, so it was archived instead of deleted.';
                $_SESSION['cl_message_type'] = 'success';
            } else {
                $stmt = $pdo->prepare(
                    'DELETE FROM lessons WHERE id = ? AND unit_id = ?'
                );
                $stmt->execute([$lessonId, $unitId]);

                $_SESSION['cl_message'] = 'Empty Lesson deleted.';
                $_SESSION['cl_message_type'] = 'success';
            }
        } catch (Throwable $e) {
            $_SESSION['cl_message'] = 'Could not delete or archive the Lesson.';
            $_SESSION['cl_message_type'] = 'error';
        }

        header(
            'Location: index.php?book_id=' . $bookId .
            '&level_id=' . $levelId .
            '&unit_id=' . $unitId
        );
        exit;
    }

    if ($action === 'archive_lesson') {
        $lessonId = (int)($_POST['lesson_id'] ?? 0);
        $unitId = (int)($_POST['unit_id'] ?? 0);
        $bookId = (int)($_POST['book_id'] ?? 0);

        if ($lessonId > 0) {
            try {
                $cols = clTableColumns($pdo, 'lessons');

                if (isset($cols['status'])) {
                    $sql = 'UPDATE lessons SET status = ?';
                    $params = ['inactive'];

                    if (isset($cols['updated_at'])) {
                        $sql .= ', updated_at = NOW()';
                    }

                    $sql .= ' WHERE id = ? AND unit_id = ?';
                    $params[] = $lessonId;
                    $params[] = $unitId;

                    $stmt = $pdo->prepare($sql);
                    $stmt->execute($params);
                }

                $_SESSION['cl_message'] = 'Lesson archived.';
                $_SESSION['cl_message_type'] = 'success';
            } catch (Throwable $e) {
                $_SESSION['cl_message'] = 'Could not archive the Lesson.';
                $_SESSION['cl_message_type'] = 'error';
            }
        }

        header('Location: index.php?book_id=' . $bookId . '&level_id=' . (int)($_POST['level_id'] ?? 0) . '&unit_id=' . $unitId);
        exit;
    }
}

$clMessage = (string)($_SESSION['cl_message'] ?? '');
$clMessageType = (string)($_SESSION['cl_message_type'] ?? 'success');
unset($_SESSION['cl_message'], $_SESSION['cl_message_type']);

// ─── Query books with aggregated stats ──────
// Admin: thấy toàn bộ Book active.
// Teacher: chỉ thấy Book được Admin gán trong teacher_books.
$bookSql = '
    SELECT
        b.id,
        b.name,
        b.slug,
        b.sort_order,
        b.cover_image,
        COUNT(DISTINCT lv.id) AS level_count,
        COUNT(DISTINCT u.id) AS unit_count,
        COUNT(DISTINCT ls.id) AS lesson_count
    FROM books b
    LEFT JOIN levels lv
        ON lv.book_id = b.id
       AND lv.status = "active"
    LEFT JOIN units u
        ON u.level_id = lv.id
       AND u.status = "active"
    LEFT JOIN lessons ls
        ON ls.unit_id = u.id
       AND ls.status = "active"
';

$bookParams = [];
if ($isAdmin) {
    $bookSql .= ' WHERE b.status = "active"';
} else {
    $bookSql .= '
        INNER JOIN teacher_books tb
            ON tb.book_id = b.id
           AND tb.teacher_id = ?
        WHERE b.status = "active"
    ';
    $bookParams[] = $currentUserId;
}

$bookSql .= '
    GROUP BY b.id, b.name, b.slug, b.sort_order, b.cover_image
    ORDER BY b.sort_order, b.name
';

$booksStmt = $pdo->prepare($bookSql);
$booksStmt->execute($bookParams);
$books = $booksStmt->fetchAll(PDO::FETCH_ASSOC);

// Không cho Teacher mở trực tiếp book_id chưa được gán bằng URL.
// Nếu book_id không nằm trong danh sách được phép, trả về trạng thái chưa chọn Book.
if (!$isAdmin && $selectedBookId > 0) {
    $allowedBookIds = array_map('intval', array_column($books, 'id'));
    if (!in_array($selectedBookId, $allowedBookIds, true)) {
        $selectedBookId = 0;
        $selectedLevelId = 0;
        $selectedUnitId = 0;
    }
}

// Mọi lần chọn Book trực tiếp trong Content Library cũng cập nhật lại Topbar.
$visibleBookIds = array_map('intval', array_column($books, 'id'));
if ($selectedBookId > 0 && in_array($selectedBookId, $visibleBookIds, true)) {
    $_SESSION['teacher_book_id'] = $selectedBookId;
}

// ─── Fetch Levels for the selected Book ─────
$levels = [];
$firstLevelId = 0;

if ($selectedBookId > 0) {
    $levelsStmt = $pdo->prepare("
        SELECT
            l.id,
            l.book_id,
            l.level_number,
            l.name,
            l.slug,
            l.sort_order,
            (SELECT COUNT(*)
             FROM units u
             WHERE u.level_id = l.id
               AND u.status = 'active') AS unit_count
        FROM levels l
        WHERE l.book_id = ?
          AND l.status = 'active'
        ORDER BY l.sort_order, l.id
    ");
    $levelsStmt->execute([$selectedBookId]);
    $levels = $levelsStmt->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($levels)) {
        $firstLevelId = (int)$levels[0]['id'];
    }
}

// Auto-select first level if not specified or not part of selected book
if ($selectedBookId > 0) {
    $validLevelIds = array_map('intval', array_column($levels, 'id'));

    if ($selectedLevelId === 0 || !in_array($selectedLevelId, $validLevelIds, true)) {
        $selectedLevelId = $firstLevelId;
        $selectedUnitId = 0;
    }
}

// ─── Fetch Units from the selected Level ─────
$units = [];
$firstUnitId = 0;

if ($selectedBookId > 0 && $selectedLevelId > 0) {
    $unitsStmt = $pdo->prepare("
        SELECT
            u.id,
            u.book_id,
            u.level_id,
            u.unit_number,
            u.title,
            u.description,
            u.sort_order,
            (SELECT COUNT(*)
             FROM lessons l
             WHERE l.unit_id = u.id
               AND l.status = 'active') AS lesson_count,
            (SELECT COUNT(*)
             FROM lessons l2
             INNER JOIN activities a
                 ON a.lesson_id = l2.id
                AND a.status = 'active'
             WHERE l2.unit_id = u.id
               AND l2.status = 'active') AS activity_count
        FROM units u
        WHERE u.book_id = ?
          AND u.level_id = ?
          AND u.status = 'active'
        ORDER BY u.sort_order, u.id
    ");
    $unitsStmt->execute([$selectedBookId, $selectedLevelId]);
    $units = $unitsStmt->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($units)) {
        $firstUnitId = (int)$units[0]['id'];
    }
}

// Auto-select first unit if not specified or not part of selected level
if ($selectedLevelId > 0) {
    $validUnitIds = array_map('intval', array_column($units, 'id'));

    if ($selectedUnitId === 0 || !in_array($selectedUnitId, $validUnitIds, true)) {
        $selectedUnitId = $firstUnitId;
    }
}

// ─── Fetch lessons for selected unit ─────────
$lessons = [];
$selectedUnitInfo = null;

$teacherLessonScheduleMap = [];

if ($selectedUnitId > 0) {
    // Sửa dữ liệu cũ bị nhảy số (ví dụ 1, 2, 5) về đúng thứ tự hiển thị khi có thể.
    clNormalizeActiveLessonNumbers($pdo, $selectedUnitId);
    $unitStmt = $pdo->prepare("
        SELECT
            u.*,
            b.name AS book_name,
            lv.name AS level_name,
            lv.slug AS level_slug
        FROM units u
        INNER JOIN levels lv ON lv.id = u.level_id
        INNER JOIN books b ON b.id = lv.book_id
        WHERE u.id = ?
          AND u.level_id = ?
          AND b.id = ?
    ");
    $unitStmt->execute([$selectedUnitId, $selectedLevelId, $selectedBookId]);
    $selectedUnitInfo = $unitStmt->fetch(PDO::FETCH_ASSOC);

    $lessonsStmt = $pdo->prepare("
        SELECT l.*, 
               (SELECT COUNT(*) FROM activities a WHERE a.lesson_id = l.id AND a.status = 'active') AS activity_count
        FROM lessons l
        WHERE l.unit_id = ? AND l.status = 'active'
        ORDER BY l.sort_order
    ");
    $lessonsStmt->execute([$selectedUnitId]);
    $lessons = $lessonsStmt->fetchAll(PDO::FETCH_ASSOC);
}


if (!$isAdmin && $currentUserId > 0 && $lessons !== []) {
    try {
        $lessonIdsForSchedule = array_map('intval', array_column($lessons, 'id'));
        $schedulePlaceholders = implode(',', array_fill(0, count($lessonIdsForSchedule), '?'));

        $scheduleStmt = $pdo->prepare(
            "SELECT
                tls.id AS schedule_id,
                tls.lesson_id,
                tls.academic_year_id,
                tls.grade,
                tls.class_name,
                tls.unlock_mode,
                tls.unlock_date,
                ay.name AS year_name
             FROM teacher_lesson_schedules tls
             LEFT JOIN academic_years ay ON ay.id = tls.academic_year_id
             WHERE tls.teacher_id = ?
               AND tls.lesson_id IN ($schedulePlaceholders)
             ORDER BY tls.academic_year_id DESC, tls.class_name ASC"
        );
        $scheduleStmt->execute(array_merge([$currentUserId], $lessonIdsForSchedule));

        foreach ($scheduleStmt->fetchAll(PDO::FETCH_ASSOC) as $scheduleRow) {
            $teacherLessonScheduleMap[(int)$scheduleRow['lesson_id']][] = $scheduleRow;
        }
    } catch (Throwable $scheduleLoadError) {
        error_log('[EnglishSpeak load teacher schedules] ' . $scheduleLoadError->getMessage());
    }
}

// ─── Fetch activities for lessons ────────────
$activitiesByLesson = [];
if ($selectedUnitId > 0 && !empty($lessons)) {
    $lessonIds = array_column($lessons, 'id');
    $placeholders = implode(',', array_fill(0, count($lessonIds), '?'));
    $actStmt = $pdo->prepare("
        SELECT * FROM activities 
        WHERE lesson_id IN ($placeholders) AND status = 'active'
        ORDER BY sort_order
    ");
    $actStmt->execute($lessonIds);
    $allActivities = $actStmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($allActivities as $act) {
        $activitiesByLesson[(int)$act['lesson_id']][] = $act;
    }
}

// ─── Helpers ─────────────────────────────────
function lessonTypeIcon(string $type): string {
    $icons = [
        'vocabulary'    => '📖',
        'speaking'      => '🗣️',
        'listening'     => '🎧',
        'reading'       => '📚',
        'writing'       => '✏️',
        'pronunciation' => '🔊',
        'grammar'       => '📝',
        'game'          => '🎮',
    ];
    return $icons[$type] ?? '📄';
}

function lessonTypeClass(string $type): string {
    $valid = ['vocabulary','speaking','listening','reading','writing','game'];
    return in_array($type, $valid, true) ? 'type-' . $type : 'type-default';
}

function unitNumberShort(string $num): string {
    if (preg_match('/\d+/', $num, $m)) {
        return 'U' . $m[0];
    }
    return strtoupper(mb_substr($num, 0, 4));
}

function getUnitStatus(int $lessonCount, int $activityCount): array {
    if ($lessonCount === 0) {
        return ['label' => 'Empty', 'class' => 'status-empty'];
    }
    if ($activityCount === 0) {
        return ['label' => 'Draft', 'class' => 'status-draft'];
    }
    return ['label' => 'Ready', 'class' => 'status-ready'];
}

// ─── Selected book info for breadcrumb ───────
$selectedBookName = '';
if ($selectedBookId > 0) {
    foreach ($books as $b) {
        if ((int)$b['id'] === $selectedBookId) {
            $selectedBookName = $b['name'];
            break;
        }
    }
}

// ─── Selected level info ─────────────────────
$selectedLevelName = '';
if ($selectedLevelId > 0) {
    foreach ($levels as $level) {
        if ((int)$level['id'] === $selectedLevelId) {
            $selectedLevelName = (string)$level['name'];
            break;
        }
    }
}

// ─── Navigation card definitions ─────────────
$navCards = [
    ['id' => 'overview',      'icon' => '📋', 'label' => 'Overview',       'desc' => 'Unit summary & objectives',     'cssClass' => 'card-overview'],
    ['id' => 'activities',    'icon' => '📝', 'label' => 'Activities',     'desc' => 'Manage learning activities',    'cssClass' => 'card-activities'],
    ['id' => 'word-list',     'icon' => '📖', 'label' => 'Word List',      'desc' => 'Vocabulary & definitions',      'cssClass' => 'card-wordlist'],
    ['id' => 'flashcards',    'icon' => '🃏', 'label' => 'Flashcards',     'desc' => 'Study card sets',               'cssClass' => 'card-flashcards'],
    ['id' => 'sentence-library', 'icon' => '📝', 'label' => 'Sentence Library', 'desc' => 'Manage reusable sentence content', 'cssClass' => 'card-sentences'],
    ['id' => 'practice',      'icon' => '✍️', 'label' => 'Practice',       'desc' => 'Exercises & drills',            'cssClass' => 'card-practice'],
    ['id' => 'games',         'icon' => '🎮', 'label' => 'Games',          'desc' => 'Interactive learning games',    'cssClass' => 'card-games'],
    ['id' => 'quiz',          'icon' => '❓', 'label' => 'Quiz',           'desc' => 'Assessments & tests',           'cssClass' => 'card-quiz'],
    ['id' => 'worksheet',     'icon' => '📄', 'label' => 'Worksheet',      'desc' => 'Printable worksheets',          'cssClass' => 'card-worksheet'],
];

ob_start();
?>

<div class="cl-page-header">
    <div>
        <span class="section-kicker">Content Library</span>
        <h2>Browse & Manage Content</h2>
    </div>
    <div class="cl-page-actions">
        <a href="../sentence-library/index.php" class="button button-sm button-secondary">
            📝 Sentence Library
        </a>
        <?php if ($isAdmin): ?>
        <button type="button" class="button button-sm button-primary" id="btnAddBook">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M12 5v14M5 12h14"/></svg>
            Add Book
        </button>
        <?php endif; ?>
    </div>
</div>

<?php if ($clMessage !== ''): ?>
<div class="wl-toast wl-toast-<?= htmlspecialchars($clMessageType) ?>">
    <?= htmlspecialchars($clMessage) ?>
</div>
<script>
setTimeout(function () {
    var toast = document.querySelector('.wl-toast');
    if (toast) toast.remove();
}, 3500);
</script>
<?php endif; ?>

<div class="cl-shell">
    <!-- ═══════════════ LEFT PANEL: Books (20%) ═══════════════ -->
    <div class="cl-panel cl-panel-left">
        <div class="cl-panel-header">
            <h3>Books</h3>
            <span class="cl-count"><?= count($books) ?></span>
        </div>
        <div class="cl-panel-scroll">
            <?php foreach ($books as $book):
                $isActive = ($selectedBookId === (int)$book['id']);
                $hasCover = !empty($book['cover_image']);
            ?>
            <a href="?book_id=<?= $book['id'] ?>&level_id=0&unit_id=0" 
               class="cl-book-item <?= $isActive ? 'is-active' : '' ?>">
                <?php if ($hasCover): ?>
                <img src="<?= htmlspecialchars($book['cover_image'], ENT_QUOTES, 'UTF-8') ?>" 
                     alt="<?= htmlspecialchars($book['name'], ENT_QUOTES, 'UTF-8') ?>"
                     class="cl-book-cover"
                     loading="lazy">
                <?php else: ?>
                <div class="cl-book-cover-fallback">📘</div>
                <?php endif; ?>
                <div class="cl-book-info">
                    <strong><?= htmlspecialchars($book['name'], ENT_QUOTES, 'UTF-8') ?></strong>
                    <div class="cl-book-meta">
                        <span><?= (int)$book['level_count'] ?> level<?= $book['level_count'] != 1 ? 's' : '' ?></span>
                        <span class="cl-meta-dot"></span>
                        <span><?= (int)$book['unit_count'] ?> unit<?= $book['unit_count'] != 1 ? 's' : '' ?></span>
                    </div>
                </div>

                <?php if ($isActive && $isAdmin): ?>
                <span class="cl-book-tools" onclick="event.preventDefault();event.stopPropagation();">
                    <button
                        type="button"
                        class="cl-mini-action"
                        data-edit-book
                        data-book-id="<?= (int)$book['id'] ?>"
                        data-book-name="<?= htmlspecialchars((string)$book['name'], ENT_QUOTES, 'UTF-8') ?>"
                        data-book-slug="<?= htmlspecialchars((string)$book['slug'], ENT_QUOTES, 'UTF-8') ?>"
                        data-book-cover="<?= htmlspecialchars((string)($book['cover_image'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"
                        title="Edit Book"
                    >✏️</button>

                    <button
                        type="button"
                        class="cl-mini-action cl-mini-action-danger"
                        data-delete-book="<?= (int)$book['id'] ?>"
                        title="Delete or Archive Book"
                    >🗑</button>
                </span>
                <?php endif; ?>
            </a>
            <?php endforeach; ?>

            <?php if (empty($books)): ?>
            <div class="cl-empty">
                <div class="cl-empty-icon">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v19H6.5A2.5 2.5 0 0 1 4 18.5v-14A2.5 2.5 0 0 1 6.5 2Z"/></svg>
                </div>
                <strong><?= $isAdmin ? 'No books yet' : 'No books assigned' ?></strong>
                <p><?= $isAdmin ? 'Create your first book to start building content.' : 'Admin has not assigned a book to this teacher yet.' ?></p>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- ═══════════════ LEVEL PANEL ═══════════════ -->
    <div class="cl-panel cl-panel-levels">
        <div class="cl-panel-header">
            <h3>Levels</h3>
            <div class="cl-panel-header-actions">
                <?php if (!empty($levels)): ?>
                <span class="cl-count"><?= count($levels) ?></span>
                <?php endif; ?>

                <?php if ($isAdmin): ?>
                <button
                    type="button"
                    class="cl-header-add"
                    id="btnAddLevel"
                    <?= $selectedBookId > 0 ? '' : 'disabled' ?>
                    title="Add Level"
                >+</button>
                <?php endif; ?>
            </div>
        </div>

        <div class="cl-panel-scroll">
            <?php if ($selectedBookId > 0 && !empty($levels)): ?>
                <?php foreach ($levels as $level):
                    $isActiveLevel = ($selectedLevelId === (int)$level['id']);
                ?>
                <a
                    href="?book_id=<?= (int)$selectedBookId ?>&level_id=<?= (int)$level['id'] ?>&unit_id=0"
                    class="cl-level-item <?= $isActiveLevel ? 'is-active' : '' ?>"
                >
<span class="cl-level-info">
                        <strong><?= htmlspecialchars((string)$level['name'], ENT_QUOTES, 'UTF-8') ?></strong>
                        <small><?= (int)$level['unit_count'] ?> unit<?= (int)$level['unit_count'] === 1 ? '' : 's' ?></small>
                    </span>
                    <?php if ($isAdmin): ?>
                    <span class="cl-level-actions" onclick="event.preventDefault();event.stopPropagation();">
                        <button
                            type="button"
                            class="cl-mini-action"
                            data-edit-level
                            data-level-id="<?= (int)$level['id'] ?>"
                            data-level-name="<?= htmlspecialchars((string)$level['name'], ENT_QUOTES, 'UTF-8') ?>"
                            data-level-number="<?= (int)$level['level_number'] ?>"
                            data-level-slug="<?= htmlspecialchars((string)$level['slug'], ENT_QUOTES, 'UTF-8') ?>"
                            title="Edit Level"
                        >✏️</button>

                        <button
                            type="button"
                            class="cl-mini-action cl-mini-action-danger"
                            data-delete-level="<?= (int)$level['id'] ?>"
                            title="Delete or Archive Level"
                        >🗑</button>
                    </span>
                    <?php endif; ?>
                </a>
                <?php endforeach; ?>
            <?php elseif ($selectedBookId > 0): ?>
                <div class="cl-empty">
                    <strong>No levels yet</strong>
                    <p>Add levels before creating units.</p>
                </div>
            <?php else: ?>
                <div class="cl-empty">
                    <strong>Select a book</strong>
                    <p>Choose a book to view its levels.</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- ═══════════════ UNIT PANEL ═══════════════ -->
    <div class="cl-panel cl-panel-middle">
        <div class="cl-panel-header">
            <h3>Units</h3>
            <?php if (!empty($units)): ?>
            <span class="cl-count"><?= count($units) ?></span>
            <?php endif; ?>
        </div>

        <!-- Unit Toolbar -->
        <div class="cl-unit-toolbar<?= $selectedLevelId === 0 ? ' is-disabled' : '' ?>" id="unitToolbar">
            <span class="cl-tb-label">UNITS</span>
            <?php if ($isAdmin): ?>
            <button class="cl-tb-btn-add" id="btnAddUnit" type="button"<?= $selectedLevelId === 0 ? ' disabled' : '' ?>>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"/></svg>
                Add Unit
            </button>
            <?php endif; ?>
            <div class="cl-tb-search">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
                <input type="text" placeholder="Search units..." aria-label="Search units"<?= $selectedLevelId === 0 ? ' disabled' : '' ?>>
            </div>
            <select class="cl-tb-sort" aria-label="Sort units"<?= $selectedLevelId === 0 ? ' disabled' : '' ?>>
                <option value="order">Sort</option>
                <option value="name-asc">Name A–Z</option>
                <option value="name-desc">Name Z–A</option>
                <option value="lessons-desc">Most Lessons</option>
                <option value="lessons-asc">Fewest Lessons</option>
            </select>
        </div>

        <?php if ($selectedLevelId === 0): ?>
        <!-- Hint when no level selected -->
        <div class="cl-unit-toolbar-hint">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
            Select a level first to manage its units.
        </div>
        <?php endif; ?>

        <div class="cl-panel-scroll">
            <?php if ($selectedLevelId > 0 && !empty($units)):
                $unitCount = count($units);
                foreach ($units as $idx => $unit):
                $lCount = (int)$unit['lesson_count'];
                $aCount = (int)$unit['activity_count'];
                $status = getUnitStatus($lCount, $aCount);
                $isActive = ($selectedUnitId === (int)$unit['id']);
            ?>
            <div class="cl-unit-item <?= $isActive ? 'is-active' : '' ?>" data-unit-id="<?= $unit['id'] ?>">
                <a href="?book_id=<?= $selectedBookId ?>&level_id=<?= $selectedLevelId ?>&unit_id=<?= $unit['id'] ?>"
                   class="cl-unit-link-wrap"
                   style="display:flex;align-items:center;gap:10px;flex:1;min-width:0;text-decoration:none;color:inherit;">
<div class="cl-unit-info">
                        <strong><?= htmlspecialchars($unit['unit_number'] . ': ' . $unit['title'], ENT_QUOTES, 'UTF-8') ?></strong>
                        <?php if (!empty($unit['description'])): ?>
                        <span class="cl-unit-desc"><?= htmlspecialchars($unit['description'], ENT_QUOTES, 'UTF-8') ?></span>
                        <?php endif; ?>
                        <div class="cl-unit-meta">
                            <span><?= $lCount ?> lesson<?= $lCount !== 1 ? 's' : '' ?></span>
                            <span>&middot;</span>
                            <span><?= $aCount ?> act.</span>
                        </div>
                    </div>
                </a>
                <span class="cl-unit-status <?= $status['class'] ?>"><?= $status['label'] ?></span>
                <!-- Action buttons (move up/down + context menu) -->
                <div class="cl-unit-actions" onclick="event.stopPropagation()">
                    <?php if ($idx > 0): ?>
                    <form method="post" class="cl-unit-move-form">
                        <input type="hidden" name="action" value="move_unit">
                        <input type="hidden" name="book_id" value="<?= (int)$selectedBookId ?>">
                        <input type="hidden" name="level_id" value="<?= (int)$selectedLevelId ?>">
                        <input type="hidden" name="unit_id" value="<?= (int)$unit['id'] ?>">
                        <input type="hidden" name="direction" value="up">
                        <button type="submit" class="cl-unit-action" title="Move up">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="m18 15-6-6-6 6"/>
                            </svg>
                        </button>
                    </form>
                    <?php else: ?>
                    <span class="cl-unit-action" style="visibility:hidden">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="m18 15-6-6-6 6"/></svg>
                    </span>
                    <?php endif; ?>
                    <?php if ($idx < $unitCount - 1): ?>
                    <form method="post" class="cl-unit-move-form">
                        <input type="hidden" name="action" value="move_unit">
                        <input type="hidden" name="book_id" value="<?= (int)$selectedBookId ?>">
                        <input type="hidden" name="level_id" value="<?= (int)$selectedLevelId ?>">
                        <input type="hidden" name="unit_id" value="<?= (int)$unit['id'] ?>">
                        <input type="hidden" name="direction" value="down">
                        <button type="submit" class="cl-unit-action" title="Move down">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="m6 9 6 6 6-6"/>
                            </svg>
                        </button>
                    </form>
                    <?php else: ?>
                    <span class="cl-unit-action" style="visibility:hidden">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="m6 9 6 6 6-6"/></svg>
                    </span>
                    <?php endif; ?>
                    <div class="cl-unit-action-menu">
                        <button class="cl-unit-action-menu-btn" data-action="menu" data-unit-id="<?= $unit['id'] ?>" aria-label="Unit actions">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="5" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="12" cy="19" r="1"/></svg>
                        </button>
                        <div class="cl-unit-action-dropdown" data-dropdown="<?= $unit['id'] ?>">
                            <button
                                data-action="edit"
                                data-unit-id="<?= (int)$unit['id'] ?>"
                                data-unit-number="<?= htmlspecialchars((string)$unit['unit_number'], ENT_QUOTES, 'UTF-8') ?>"
                                data-unit-title="<?= htmlspecialchars((string)$unit['title'], ENT_QUOTES, 'UTF-8') ?>"
                                data-unit-description="<?= htmlspecialchars((string)($unit['description'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"
                            >
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                                Edit
                            </button>
                            <button data-action="duplicate" data-unit-id="<?= $unit['id'] ?>">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
                                Duplicate
                            </button>
                            <div class="cl-dropdown-divider"></div>
                            <form method="post" onsubmit="return confirm('Delete this unit?');">
                                <input type="hidden" name="action" value="delete_unit">
                                <input type="hidden" name="book_id" value="<?= (int)$selectedBookId ?>">
                                <input type="hidden" name="level_id" value="<?= (int)$selectedLevelId ?>">
                                <input type="hidden" name="unit_id" value="<?= (int)$unit['id'] ?>">
                                <button type="submit" class="text-danger">
                                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 6h18"/><path d="M8 6V4h8v2"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6M14 11v6"/></svg>
                                    Delete
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            <?php elseif ($selectedLevelId > 0): ?>
            <div class="cl-empty">
                <div class="cl-empty-icon">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M3 3h18v18H3z"/><path d="M7 7h10M7 11h10M7 15h6"/></svg>
                </div>
                <strong>No units yet</strong>
                <p>Create your first unit to start organizing lessons.</p>
                <button class="cl-btn-create" id="btnCreateUnitEmpty" type="button">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"/></svg>
                    Create Unit
                </button>
            </div>
            <?php else: ?>
            <div class="cl-empty">
                <div class="cl-empty-icon">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M15 15l-1.5 1.5L12 18l-1.5-1.5L9 15"/><path d="M9 9l1.5-1.5L12 6l1.5 1.5L15 9"/><path d="M12 3v3m0 12v3M3 12h3m12 0h3"/></svg>
                </div>
                <strong>Select a level</strong>
                <p>Choose a level to view its units.</p>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- ═══════════════ MAIN PANEL: Lesson Workspace (55%) ═══════════════ -->
    <div class="cl-panel cl-panel-main">
        <!-- Toolbar — always visible -->
        <div class="cl-workspace-toolbar">
            <button
                type="button"
                class="cl-tb-btn-primary"
                id="btnNewLesson"
                <?= $selectedUnitId > 0 ? '' : 'disabled' ?>
            >
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"/></svg>
                New Lesson
            </button>
            <div class="cl-tb-search">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
                <input type="text" placeholder="Search lessons..." aria-label="Search lessons">
            </div>
            <select class="cl-tb-select" aria-label="Filter by type">
                <option value="">Filter: All Types</option>
                <option value="vocabulary">Vocabulary</option>
                <option value="speaking">Speaking</option>
                <option value="listening">Listening</option>
                <option value="reading">Reading</option>
                <option value="writing">Writing</option>
                <option value="pronunciation">Pronunciation</option>
                <option value="grammar">Grammar</option>
                <option value="game">Game</option>
            </select>
            <select class="cl-tb-select" aria-label="Sort lessons">
                <option value="order">Sort: Default</option>
                <option value="name-asc">Name A–Z</option>
                <option value="name-desc">Name Z–A</option>
                <option value="newest">Newest First</option>
                <option value="oldest">Oldest First</option>
            </select>
        </div>

        <!-- Workspace Body -->
        <?php if ($selectedUnitId > 0 && $selectedUnitInfo): ?>
        <!-- ══ Unit Selected: Show Workspace ══ -->
        <div class="cl-workspace-body">
            <div class="cl-breadcrumb">
                <span><?= htmlspecialchars($selectedBookName, ENT_QUOTES, 'UTF-8') ?></span>
                <span class="cl-bc-sep">›</span>
                <span><?= htmlspecialchars($selectedLevelName, ENT_QUOTES, 'UTF-8') ?></span>
                <span class="cl-bc-sep">›</span>
                <span class="cl-bc-current"><?= htmlspecialchars($selectedUnitInfo['unit_number'], ENT_QUOTES, 'UTF-8') ?></span>
            </div>

            <div class="cl-unit-header">
                <h2><?= htmlspecialchars($selectedUnitInfo['title'] ?? $selectedUnitInfo['unit_number'], ENT_QUOTES, 'UTF-8') ?></h2>
                <?php if (!empty($selectedUnitInfo['description'])): ?>
                <p><?= htmlspecialchars($selectedUnitInfo['description'], ENT_QUOTES, 'UTF-8') ?></p>
                <?php endif; ?>
            </div>

            <!-- Lesson Library -->
            <div class="cl-lesson-library">
                <div class="cl-lesson-library-head">
                    <div>
                        <span class="section-kicker">Lessons</span>
                        <h3><?= count($lessons) ?> lesson<?= count($lessons) === 1 ? '' : 's' ?></h3>
                    </div>


                </div>

                <?php if (empty($lessons)): ?>
                    <div class="cl-empty-workspace" style="min-height:260px;">
                        <div class="cl-empty-workspace-icon">📘</div>
                        <h3>No lessons yet</h3>
                        <p>Create the first Lesson for this Unit.</p>
                        <button type="button" class="button button-primary" id="btnCreateFirstLesson">
                            + Create Lesson
                        </button>
                    </div>
                <?php else: ?>
                    <div class="cl-lesson-list" id="lessonList">
                        <?php
                        $lessonCount = count($lessons);
                        foreach ($lessons as $lessonIndex => $lesson):
                    ?>
                            <?php
                                $lessonTitle = (string)($lesson['title'] ?? $lesson['name'] ?? $lesson['lesson_number'] ?? 'Lesson');
                                $lessonType = (string)($lesson['lesson_type'] ?? $lesson['type'] ?? 'vocabulary');
                                $activityCount = (int)($lesson['activity_count'] ?? 0);
                                $lessonOwnerId = array_key_exists('created_by_teacher_id', $lesson)
                                    && $lesson['created_by_teacher_id'] !== null
                                    ? (int)$lesson['created_by_teacher_id']
                                    : 0;
                                $canManageLesson = $isAdmin || ($lessonOwnerId > 0 && $lessonOwnerId === $currentUserId);
                            ?>
                            <div
                                class="cl-lesson-row"
                                data-title="<?= htmlspecialchars(mb_strtolower($lessonTitle), ENT_QUOTES, 'UTF-8') ?>"
                                data-type="<?= htmlspecialchars($lessonType, ENT_QUOTES, 'UTF-8') ?>"
                                data-lesson-id="<?= (int)$lesson['id'] ?>"
                            >
                                <div class="cl-lesson-main">
                                    <div class="cl-lesson-icon">
                                        <?= lessonTypeIcon($lessonType) ?>
                                    </div>

                                    <div class="cl-lesson-info">
                                        <strong><?= htmlspecialchars($lessonTitle, ENT_QUOTES, 'UTF-8') ?></strong>

                                        <?php if (!empty($lesson['description'])): ?>
                                            <span><?= htmlspecialchars((string)$lesson['description'], ENT_QUOTES, 'UTF-8') ?></span>
                                        <?php endif; ?>

                                        <div class="cl-lesson-meta">
                                            <span><?= htmlspecialchars(ucfirst($lessonType), ENT_QUOTES, 'UTF-8') ?></span>
                                            <span>•</span>
                                            <span><?= $activityCount ?> activit<?= $activityCount === 1 ? 'y' : 'ies' ?></span>
                                        </div>

                                        <?php if (!$isAdmin): ?>
                                            <?php $lessonSchedules = $teacherLessonScheduleMap[(int)$lesson['id']] ?? []; ?>
                                            <?php if ($lessonSchedules !== []): ?>
                                                <div style="margin-top:7px;display:grid;gap:4px;">
                                                    <?php foreach ($lessonSchedules as $schedule): ?>
                                                        <div style="display:flex;align-items:center;gap:7px;flex-wrap:wrap;">
                                                            <small style="color:#5f6f84;">
                                                                📅 <?= htmlspecialchars((string)($schedule['class_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?>
                                                                <?php if (!empty($schedule['year_name'])): ?>
                                                                    • <?= htmlspecialchars((string)$schedule['year_name'], ENT_QUOTES, 'UTF-8') ?>
                                                                <?php endif; ?>
                                                                •
                                                                <?php if (($schedule['unlock_mode'] ?? '') === 'scheduled_date' && !empty($schedule['unlock_date'])): ?>
                                                                    Mở ngày <?= htmlspecialchars(date('d/m/Y', strtotime((string)$schedule['unlock_date'])), ENT_QUOTES, 'UTF-8') ?>
                                                                <?php else: ?>
                                                                    Mỗi ngày mở 1 Lesson
                                                                <?php endif; ?>
                                                            </small>
                                                            <form method="post" style="margin:0;display:inline;" onsubmit="return confirm('Xóa lịch mở này? Lesson gốc và các lịch khác sẽ được giữ nguyên.');">
                                                                <input type="hidden" name="action" value="delete_lesson_schedule">
                                                                <input type="hidden" name="schedule_id" value="<?= (int)($schedule['schedule_id'] ?? 0) ?>">
                                                                <input type="hidden" name="book_id" value="<?= (int)$selectedBookId ?>">
                                                                <input type="hidden" name="level_id" value="<?= (int)$selectedLevelId ?>">
                                                                <input type="hidden" name="unit_id" value="<?= (int)$selectedUnitId ?>">
                                                                <button type="submit" title="Xóa lịch mở" aria-label="Xóa lịch mở" style="border:0;background:transparent;padding:0;cursor:pointer;font-size:13px;line-height:1;color:#d14343;">🗑 Xóa</button>
                                                            </form>
                                                        </div>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <div class="cl-lesson-actions">
                                    <?php if ($canManageLesson): ?>
                                    <?php if ($lessonIndex > 0): ?>
                                    <button
                                        type="button"
                                        class="cl-lesson-icon-action"
                                        data-lesson-action="move"
                                        data-direction="up"
                                        data-lesson-id="<?= (int)$lesson['id'] ?>"
                                        title="Move up"
                                    >↑</button>
                                    <?php endif; ?>

                                    <?php if ($lessonIndex < $lessonCount - 1): ?>
                                    <button
                                        type="button"
                                        class="cl-lesson-icon-action"
                                        data-lesson-action="move"
                                        data-direction="down"
                                        data-lesson-id="<?= (int)$lesson['id'] ?>"
                                        title="Move down"
                                    >↓</button>
                                    <?php endif; ?>

                                    <?php endif; ?>

                                    <a
                                        href="../lessons/detail.php?id=<?= (int)$lesson['id'] ?>"
                                        class="button button-sm button-secondary"
                                    >
                                        Open
                                    </a>

                                    <?php if (!$isAdmin): ?>
                                    <button
                                        type="button"
                                        class="button button-sm button-secondary"
                                        data-lesson-action="schedule"
                                        data-lesson-id="<?= (int)$lesson['id'] ?>"
                                        data-lesson-title="<?= htmlspecialchars($lessonTitle, ENT_QUOTES, 'UTF-8') ?>"
                                    >
                                        Lịch mở
                                    </button>
                                    <?php endif; ?>

                                    <?php if ($canManageLesson): ?>


                                    <button
                                        type="button"
                                        class="button button-sm button-secondary"
                                        data-lesson-action="edit"
                                        data-lesson-id="<?= (int)$lesson['id'] ?>"
                                        data-lesson-title="<?= htmlspecialchars($lessonTitle, ENT_QUOTES, 'UTF-8') ?>"
                                        data-lesson-type="<?= htmlspecialchars($lessonType, ENT_QUOTES, 'UTF-8') ?>"
                                        data-lesson-description="<?= htmlspecialchars((string)($lesson['description'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"
                                        data-lesson-unlock-mode="<?= htmlspecialchars((string)($lesson['unlock_mode'] ?? 'sequential_daily'), ENT_QUOTES, 'UTF-8') ?>"
                                        data-lesson-unlock-date="<?= htmlspecialchars((string)($lesson['unlock_date'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"
                                    >
                                        Edit
                                    </button>

                                    <button
                                        type="button"
                                        class="cl-lesson-icon-action"
                                        data-lesson-action="duplicate"
                                        data-lesson-id="<?= (int)$lesson['id'] ?>"
                                        title="Duplicate Lesson"
                                    >⧉</button>

                                    <button
                                        type="button"
                                        class="cl-lesson-icon-action cl-lesson-icon-danger"
                                        data-lesson-action="delete"
                                        data-lesson-id="<?= (int)$lesson['id'] ?>"
                                        title="Delete or Archive Lesson"
                                    >🗑</button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <?php elseif ($selectedLevelId > 0): ?>
        <!-- ══ Level selected but no unit: Elegant empty + toolbar ══ -->
        <div class="cl-empty-workspace">
            <div class="cl-empty-workspace-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                    <rect x="3" y="3" width="18" height="18" rx="3"/>
                    <path d="M7 7h10M7 11h10M7 15h6"/>
                </svg>
            </div>
            <h3>Select a Unit</h3>
            <p>Choose a unit from the Unit panel to explore its lessons, activities, and learning resources.</p>
        </div>

        <?php else: ?>
        <!-- ══ No book selected: Default empty + toolbar ══ -->
        <div class="cl-empty-workspace">
            <div class="cl-empty-workspace-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
                    <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/>
                    <path d="M6.5 2H20v19H6.5A2.5 2.5 0 0 1 4 18.5v-14A2.5 2.5 0 0 1 6.5 2Z"/>
                </svg>
            </div>
            <h3>Content Library</h3>
            <p>Select a book, then choose a level to browse its units, lessons, and learning activities.</p>
        </div>
        <?php endif; ?>
    </div>
</div>





<style>
.cl-unit-move-form {
    display: inline-flex;
    margin: 0;
    padding: 0;
}
</style>

<style>
/* Book → Level → Unit → Lesson */
.cl-shell {
    grid-template-columns: minmax(180px, 18%) minmax(150px, 17%) minmax(230px, 24%) minmax(420px, 41%) !important;
}

.cl-panel-levels {
    min-width: 0;
}

.cl-level-item {
    display: grid;
    grid-template-columns: minmax(0, 1fr) auto;
    align-items: center;
    gap: 10px;
    margin: 8px 10px;
    padding: 11px 10px;
    border: 1px solid transparent;
    border-radius: 12px;
    color: var(--text);
    text-decoration: none;
    transition: .18s ease;
}

.cl-level-item:hover {
    background: #f7f9ff;
    border-color: var(--border);
}

.cl-level-item.is-active {
    background: #eef4ff;
    border-color: #b9ceff;
    box-shadow: 0 5px 14px rgba(55, 94, 190, .08);
}

.cl-level-number {
    width: 42px;
    height: 42px;
    display: grid;
    place-items: center;
    border-radius: 11px;
    background: #e7f1ff;
    color: #1672c4;
    font-size: 14px;
    font-weight: 800;
}

.cl-level-info {
    min-width: 0;
    display: grid;
    gap: 3px;
}

.cl-level-info strong {
    overflow: hidden;
    font-size: 13px;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.cl-level-info small {
    color: var(--muted);
    font-size: 11px;
}

.cl-level-arrow {
    color: var(--primary);
    font-size: 20px;
    text-align: center;
}

@media (max-width: 1280px) {
    .cl-shell {
        grid-template-columns: 190px 170px 250px minmax(430px, 1fr) !important;
        overflow-x: auto;
    }
}
</style>



<style>
.cl-book-item {
    position: relative;
}

.cl-book-tools {
    position: absolute;
    top: 7px;
    right: 7px;
    display: flex;
    gap: 4px;
}

.cl-mini-action,
.cl-header-add {
    width: 28px;
    height: 28px;
    display: grid;
    place-items: center;
    padding: 0;
    border: 1px solid var(--border);
    border-radius: 8px;
    background: var(--surface);
    color: var(--text);
    cursor: pointer;
    font-size: 12px;
}

.cl-mini-action:hover,
.cl-header-add:hover {
    border-color: var(--primary);
    background: #eef4ff;
}

.cl-mini-action-danger:hover {
    border-color: #efb4b4;
    background: #fff1f1;
    color: var(--danger);
}

.cl-panel-header-actions {
    display: flex;
    align-items: center;
    gap: 7px;
}

.cl-header-add:disabled {
    opacity: .45;
    cursor: not-allowed;
}

.cl-level-item {
    grid-template-columns: minmax(0, 1fr) auto !important;
}

.cl-level-actions {
    display: flex;
    align-items: center;
    gap: 4px;
}
</style>

<style>
.cl-book-wizard {
    max-width: 760px !important;
}

.cl-wizard-progress {
    display: grid;
    grid-template-columns: auto 1fr auto 1fr auto;
    align-items: center;
    gap: 10px;
    margin-bottom: 24px;
}

.cl-wizard-step {
    display: grid;
    justify-items: center;
    gap: 5px;
    color: var(--muted);
    font-size: 11px;
    font-weight: 700;
}

.cl-wizard-step span {
    width: 34px;
    height: 34px;
    display: grid;
    place-items: center;
    border: 1px solid var(--border);
    border-radius: 50%;
    background: var(--surface);
}

.cl-wizard-step.is-active,
.cl-wizard-step.is-done {
    color: var(--primary);
}

.cl-wizard-step.is-active span,
.cl-wizard-step.is-done span {
    border-color: var(--primary);
    background: var(--primary);
    color: #fff;
}

.cl-wizard-line {
    height: 2px;
    background: var(--border);
}

.cl-wizard-pane {
    display: none;
    min-height: 330px;
}

.cl-wizard-pane.is-active {
    display: block;
}

.cl-wizard-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 14px;
}

.cl-form-help {
    display: block;
    margin-top: 5px;
    color: var(--muted);
    font-size: 11px;
}

.cl-template-grid {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 12px;
}

.cl-template-card {
    position: relative;
    display: grid;
    justify-items: center;
    gap: 6px;
    padding: 18px 12px;
    border: 1px solid var(--border);
    border-radius: 14px;
    background: var(--surface);
    cursor: pointer;
    text-align: center;
}

.cl-template-card:has(input:checked) {
    border-color: var(--primary);
    background: #eef4ff;
    box-shadow: 0 6px 18px rgba(45, 92, 190, .10);
}

.cl-template-card input {
    position: absolute;
    opacity: 0;
    pointer-events: none;
}

.cl-template-icon {
    font-size: 30px;
}

.cl-template-card small {
    color: var(--muted);
    font-size: 11px;
}

.cl-level-preview,
.cl-review-levels {
    margin-top: 18px;
    padding: 15px;
    border: 1px solid var(--border);
    border-radius: 14px;
    background: #fafcff;
}

#levelPreview,
#reviewLevels {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 10px;
}

.cl-level-chip {
    padding: 7px 10px;
    border-radius: 999px;
    background: #eaf3ff;
    color: #176bae;
    font-size: 12px;
    font-weight: 750;
}

.cl-review-card {
    display: grid;
    grid-template-columns: 84px minmax(0, 1fr);
    align-items: center;
    gap: 16px;
    padding: 18px;
    border: 1px solid var(--border);
    border-radius: 16px;
    background: var(--surface);
}

.cl-review-cover {
    width: 84px;
    height: 104px;
    display: grid;
    place-items: center;
    overflow: hidden;
    border-radius: 14px;
    background: #eaf3ff;
    font-size: 39px;
}

.cl-review-cover img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.cl-review-card h3 {
    margin: 4px 0 5px;
}

.cl-review-card p {
    margin: 0;
    color: var(--muted);
}

.cl-wizard-note {
    margin-top: 15px;
    padding: 12px 14px;
    border-radius: 12px;
    background: #fff8e8;
    color: #805b14;
    font-size: 12px;
}

.cl-wizard-actions {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    margin-top: 22px;
    padding-top: 18px;
    border-top: 1px solid var(--border);
}

.cl-wizard-actions-right {
    display: flex;
    gap: 9px;
}

@media (max-width: 720px) {
    .cl-wizard-grid,
    .cl-template-grid {
        grid-template-columns: 1fr;
    }

    .cl-review-card {
        grid-template-columns: 64px minmax(0, 1fr);
    }

    .cl-review-cover {
        width: 64px;
        height: 82px;
    }
}
</style>

<style>
.cl-lesson-library {
    padding-top: 8px;
}

.cl-lesson-library-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    margin-bottom: 14px;
}

.cl-lesson-library-head h3 {
    margin: 2px 0 0;
}

.cl-lesson-list {
    display: grid;
    gap: 10px;
}

.cl-lesson-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 18px;
    padding: 14px 16px;
    border: 1px solid var(--border);
    border-radius: 14px;
    background: var(--surface);
}

.cl-lesson-main {
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 0;
}

.cl-lesson-icon {
    display: grid;
    place-items: center;
    width: 44px;
    height: 44px;
    flex: 0 0 44px;
    border-radius: 12px;
    background: #eef4ff;
    font-size: 20px;
}

.cl-lesson-info {
    display: grid;
    gap: 3px;
    min-width: 0;
}

.cl-lesson-info > span {
    color: var(--muted);
    font-size: 12px;
}

.cl-lesson-meta {
    display: flex;
    align-items: center;
    gap: 6px;
    color: var(--muted);
    font-size: 11px;
}

.cl-lesson-actions {
    display: flex;
    align-items: center;
    gap: 7px;
    flex: 0 0 auto;
}

.cl-lesson-icon-action {
    width: 30px;
    height: 30px;
    display: grid;
    place-items: center;
    padding: 0;
    border: 1px solid var(--border);
    border-radius: 8px;
    background: var(--surface);
    color: var(--text);
    cursor: pointer;
    font-size: 13px;
    font-weight: 800;
}

.cl-lesson-icon-action:hover {
    border-color: var(--primary);
    background: #eef4ff;
    color: var(--primary);
}

.cl-lesson-icon-danger:hover {
    border-color: #efb4b4;
    background: #fff1f1;
    color: var(--danger);
}
<?php if (!$isAdmin): ?>
/* Teacher: Book / Level / Unit structure is read-only. */
[data-edit-unit], [data-duplicate-unit], [data-delete-unit],
.cl-unit-actions, .cl-unit-menu, .cl-unit-more { display:none !important; }
<?php endif; ?>
</style>




<!-- Add / Edit Unit Modal -->
<div class="wl-modal-overlay" id="unitManageModal">
    <div class="wl-modal" style="max-width:620px;">
        <div class="wl-modal-header">
            <h3 id="unitManageTitle">Add Unit</h3>
            <button type="button" class="wl-modal-close" data-close-unit-modal>&times;</button>
        </div>

        <form method="post" id="unitManageForm">
            <input type="hidden" name="action" id="unitManageAction" value="create_unit">
            <input type="hidden" name="book_id" value="<?= (int)$selectedBookId ?>">
            <input type="hidden" name="level_id" value="<?= (int)$selectedLevelId ?>">
            <input type="hidden" name="unit_id" id="manageUnitId">

            <div class="cl-wizard-grid">
                <div class="form-group">
                    <label class="form-label">Unit Number <span class="required">*</span></label>
                    <input
                        type="text"
                        name="unit_number"
                        id="manageUnitNumber"
                        class="form-control"
                        placeholder="e.g. Unit 1"
                        required
                    >
                </div>

                <div class="form-group">
                    <label class="form-label">Unit Title <span class="required">*</span></label>
                    <input
                        type="text"
                        name="title"
                        id="manageUnitTitle"
                        class="form-control"
                        placeholder="e.g. In the school playground"
                        required
                    >
                </div>
            </div>

            <div class="form-group">
                <label class="form-label">Description</label>
                <textarea
                    name="description"
                    id="manageUnitDescription"
                    class="form-control"
                    rows="3"
                    placeholder="Optional short note..."
                ></textarea>
            </div>

            <div class="button-group" style="justify-content:flex-end;">
                <button type="button" class="button button-secondary" data-close-unit-modal>
                    Cancel
                </button>
                <button type="submit" class="button button-primary" id="unitManageSubmit">
                    Create Unit
                </button>
            </div>
        </form>
    </div>
</div>

<form method="post" id="unitActionForm" hidden>
    <input type="hidden" name="action" id="unitActionName">
    <input type="hidden" name="book_id" value="<?= (int)$selectedBookId ?>">
    <input type="hidden" name="level_id" value="<?= (int)$selectedLevelId ?>">
    <input type="hidden" name="unit_id" id="unitActionId">
    <input type="hidden" name="direction" id="unitActionDirection">
</form>

<!-- Edit Book Modal -->
<div class="wl-modal-overlay" id="editBookModal">
    <div class="wl-modal" style="max-width:620px;">
        <div class="wl-modal-header">
            <h3>Edit Book</h3>
            <button type="button" class="wl-modal-close" data-close-edit-book>&times;</button>
        </div>

        <form method="post">
            <input type="hidden" name="action" value="update_book">
            <input type="hidden" name="book_id" id="editBookId">

            <div class="form-group">
                <label class="form-label">Book Name <span class="required">*</span></label>
                <input type="text" name="book_name" id="editBookName" class="form-control" required>
            </div>

            <div class="cl-wizard-grid">
                <div class="form-group">
                    <label class="form-label">Slug</label>
                    <input type="text" name="book_slug" id="editBookSlug" class="form-control">
                </div>

                <div class="form-group">
                    <label class="form-label">Cover Image</label>
                    <input type="text" name="cover_image" id="editBookCover" class="form-control">
                </div>
            </div>

            <div class="form-group">
                <label class="form-label">Description</label>
                <textarea name="book_description" id="editBookDescription" class="form-control" rows="3"></textarea>
            </div>

            <div class="button-group" style="justify-content:flex-end;">
                <button type="button" class="button button-secondary" data-close-edit-book>Cancel</button>
                <button type="submit" class="button button-primary">Save Changes</button>
            </div>
        </form>
    </div>
</div>

<!-- Delete Book Form -->
<form method="post" id="deleteBookForm" hidden>
    <input type="hidden" name="action" value="delete_book">
    <input type="hidden" name="book_id" id="deleteBookId">
</form>

<!-- Add / Edit Level Modal -->
<div class="wl-modal-overlay" id="levelManageModal">
    <div class="wl-modal" style="max-width:560px;">
        <div class="wl-modal-header">
            <h3 id="levelManageTitle">Add Level</h3>
            <button type="button" class="wl-modal-close" data-close-level-modal>&times;</button>
        </div>

        <form method="post" id="levelManageForm">
            <input type="hidden" name="action" id="levelManageAction" value="create_level">
            <input type="hidden" name="book_id" value="<?= (int)$selectedBookId ?>">
            <input type="hidden" name="level_id" id="manageLevelId">

            <div class="form-group">
                <label class="form-label">Level Name <span class="required">*</span></label>
                <input
                    type="text"
                    name="level_name"
                    id="manageLevelName"
                    class="form-control"
                    placeholder="e.g. Lớp 1"
                    required
                >
            </div>

            <div class="cl-wizard-grid">
                <div class="form-group">
                    <label class="form-label">Level Number</label>
                    <input
                        type="number"
                        name="level_number"
                        id="manageLevelNumber"
                        class="form-control"
                        value="1"
                    >
                </div>

                <div class="form-group">
                    <label class="form-label">Slug</label>
                    <input
                        type="text"
                        name="level_slug"
                        id="manageLevelSlug"
                        class="form-control"
                        placeholder="grade-1"
                    >
                </div>
            </div>

            <div class="button-group" style="justify-content:flex-end;">
                <button type="button" class="button button-secondary" data-close-level-modal>Cancel</button>
                <button type="submit" class="button button-primary" id="levelManageSubmit">Create Level</button>
            </div>
        </form>
    </div>
</div>

<form method="post" id="deleteLevelForm" hidden>
    <input type="hidden" name="action" value="delete_level">
    <input type="hidden" name="book_id" value="<?= (int)$selectedBookId ?>">
    <input type="hidden" name="level_id" id="deleteLevelId">
</form>

<!-- Add Book Wizard -->
<div class="wl-modal-overlay" id="bookModalOverlay">
    <div class="wl-modal cl-book-wizard">
        <div class="wl-modal-header">
            <div>
                <span class="section-kicker">Add Book</span>
                <h3>Create Book & Levels</h3>
            </div>
            <button type="button" class="wl-modal-close" id="bookModalClose">&times;</button>
        </div>

        <form method="post" id="bookWizardForm">
            <input type="hidden" name="action" value="create_book">

            <div class="cl-wizard-progress">
                <div class="cl-wizard-step is-active" data-step-indicator="1">
                    <span>1</span>
                    <small>Book</small>
                </div>
                <div class="cl-wizard-line"></div>
                <div class="cl-wizard-step" data-step-indicator="2">
                    <span>2</span>
                    <small>Levels</small>
                </div>
                <div class="cl-wizard-line"></div>
                <div class="cl-wizard-step" data-step-indicator="3">
                    <span>3</span>
                    <small>Review</small>
                </div>
            </div>

            <section class="cl-wizard-pane is-active" data-wizard-pane="1">
                <div class="form-group">
                    <label class="form-label">Book Name <span class="required">*</span></label>
                    <input
                        type="text"
                        name="book_name"
                        id="wizardBookName"
                        class="form-control"
                        placeholder="e.g. Family and Friends"
                        required
                    >
                </div>

                <div class="cl-wizard-grid">
                    <div class="form-group">
                        <label class="form-label">Slug</label>
                        <input
                            type="text"
                            name="book_slug"
                            id="wizardBookSlug"
                            class="form-control"
                            placeholder="family-and-friends"
                        >
                        <small class="cl-form-help">Leave blank to create automatically.</small>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Cover Image</label>
                        <input
                            type="text"
                            name="cover_image"
                            id="wizardCoverImage"
                            class="form-control"
                            placeholder="uploads/books/cover.jpg"
                        >
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Description</label>
                    <textarea
                        name="book_description"
                        id="wizardBookDescription"
                        class="form-control"
                        rows="3"
                        placeholder="Optional short description..."
                    ></textarea>
                </div>
            </section>

            <section class="cl-wizard-pane" data-wizard-pane="2">
                <div class="form-group">
                    <label class="form-label">Level Template <span class="required">*</span></label>

                    <div class="cl-template-grid">
                        <label class="cl-template-card">
                            <input type="radio" name="level_template" value="global-success" checked>
                            <span class="cl-template-icon">📘</span>
                            <strong>Global Success</strong>
                            <small>Lớp 1 → Lớp 5</small>
                        </label>

                        <label class="cl-template-card">
                            <input type="radio" name="level_template" value="everybody-up">
                            <span class="cl-template-icon">📗</span>
                            <strong>Everybody Up</strong>
                            <small>Starter → Up 6</small>
                        </label>

                        <label class="cl-template-card">
                            <input type="radio" name="level_template" value="custom">
                            <span class="cl-template-icon">✏️</span>
                            <strong>Custom</strong>
                            <small>Enter your own Levels</small>
                        </label>
                    </div>
                </div>

                <div class="form-group cl-custom-levels" id="customLevelsWrap" hidden>
                    <label class="form-label">Levels <span class="required">*</span></label>
                    <textarea
                        name="custom_levels"
                        id="customLevels"
                        class="form-control"
                        rows="7"
                        placeholder="One Level per line&#10;Starter&#10;Level 1&#10;Level 2"
                    ></textarea>
                    <small class="cl-form-help">Enter one Level name per line.</small>
                </div>

                <div class="cl-level-preview">
                    <span class="section-kicker">Preview</span>
                    <div id="levelPreview"></div>
                </div>
            </section>

            <section class="cl-wizard-pane" data-wizard-pane="3">
                <div class="cl-review-card">
                    <div class="cl-review-cover" id="reviewCover">📘</div>
                    <div>
                        <span class="section-kicker">Book</span>
                        <h3 id="reviewBookName">New Book</h3>
                        <p id="reviewBookDescription">No description</p>
                    </div>
                </div>

                <div class="cl-review-levels">
                    <span class="section-kicker">Levels to create</span>
                    <div id="reviewLevels"></div>
                </div>

                <div class="cl-wizard-note">
                    Units will be added after the Book is created.
                </div>
            </section>

            <div class="cl-wizard-actions">
                <button type="button" class="button button-secondary" id="bookWizardCancel">
                    Cancel
                </button>

                <div class="cl-wizard-actions-right">
                    <button type="button" class="button button-secondary" id="bookWizardBack" hidden>
                        Back
                    </button>

                    <button type="button" class="button button-primary" id="bookWizardNext">
                        Next
                    </button>

                    <button type="submit" class="button button-primary" id="bookWizardCreate" hidden>
                        Create Book
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Create Lesson Modal -->
<div class="wl-modal-overlay" id="lessonModalOverlay">
    <div class="wl-modal" style="max-width:620px;">
        <div class="wl-modal-header">
            <h3 id="lessonModalTitle">Create Lesson</h3>
            <button type="button" class="wl-modal-close" id="lessonModalClose">&times;</button>
        </div>

        <form method="post" id="lessonManageForm">
            <input type="hidden" name="action" id="lessonManageAction" value="create_lesson">
            <input type="hidden" name="lesson_id" id="lessonManageId">
            <input type="hidden" name="book_id" value="<?= (int)$selectedBookId ?>">
            <input type="hidden" name="level_id" value="<?= (int)$selectedLevelId ?>">
            <input type="hidden" name="unit_id" value="<?= (int)$selectedUnitId ?>">

            <div class="form-group">
                <label class="form-label">Lesson Name <span class="required">*</span></label>
                <input
                    type="text"
                    name="title"
                    id="lessonManageTitleInput"
                    class="form-control"
                    placeholder="e.g. Lesson 1"
                    required
                    autofocus
                >
            </div>

            <div class="form-group">
                <label class="form-label">Type</label>
                <select name="lesson_type" id="lessonManageType" class="form-control">
                    <option value="vocabulary">Vocabulary</option>
                    <option value="speaking">Speaking</option>
                    <option value="listening">Listening</option>
                    <option value="reading">Reading</option>
                    <option value="writing">Writing</option>
                    <option value="pronunciation">Pronunciation</option>
                    <option value="grammar">Grammar</option>
                    <option value="game">Game / Review</option>
                </select>
            </div>

            <div class="form-group">
                <label class="form-label">Description</label>
                <textarea
                    name="description"
                    id="lessonManageDescription"
                    class="form-control"
                    rows="3"
                    placeholder="Optional short note..."
                ></textarea>
            </div>

            <div class="form-group">
                <label class="form-label">Lesson unlock</label>
                <select name="unlock_mode" id="lessonManageUnlockMode" class="form-control">
                    <option value="sequential_daily">Mỗi ngày mở 1 Lesson</option>
                    <option value="scheduled_date">Mở vào ngày được chỉ định</option>
                </select>
                <small style="display:block;margin-top:6px;color:#7b8aa0;">
                    Không thay đổi XP, Passing Score hoặc tiến độ đã có.
                </small>
            </div>

            <div class="form-group" id="lessonUnlockDateGroup" style="display:none;">
                <label class="form-label">Ngày mở Lesson</label>
                <input
                    type="date"
                    name="unlock_date"
                    id="lessonManageUnlockDate"
                    class="form-control"
                >
            </div>

            <div class="button-group" style="justify-content:flex-end;margin-top:20px;">
                <button type="button" class="button button-secondary" id="lessonModalCancel">
                    Cancel
                </button>

                <button type="submit" class="button button-primary" id="lessonManageSubmit">
                    Create Lesson
                </button>
            </div>
        </form>
    </div>
</div>


<?php if (!$isAdmin): ?>
<!-- Teacher-specific Lesson Schedule Modal -->
<div class="wl-modal-overlay" id="lessonScheduleModalOverlay">
    <div class="wl-modal" style="max-width:620px;">
        <div class="wl-modal-header">
            <h3 id="lessonScheduleModalTitle">Lịch mở Lesson</h3>
            <button type="button" class="wl-modal-close" id="lessonScheduleModalClose">&times;</button>
        </div>

        <form method="post" id="lessonScheduleForm">
            <input type="hidden" name="action" value="save_lesson_schedule">
            <input type="hidden" name="lesson_id" id="lessonScheduleLessonId">
            <input type="hidden" name="book_id" value="<?= (int)$selectedBookId ?>">
            <input type="hidden" name="level_id" value="<?= (int)$selectedLevelId ?>">
            <input type="hidden" name="unit_id" value="<?= (int)$selectedUnitId ?>">

            <div style="padding:10px 12px;margin-bottom:14px;border-radius:10px;background:#f8fbff;color:#52647b;font-size:13px;">
                Bạn chỉ đặt <strong>lịch học cho lớp của mình</strong>.
                Nội dung Lesson gốc vẫn chỉ xem và không bị thay đổi.
            </div>

            <div class="form-group">
                <label class="form-label">Năm học <span class="required">*</span></label>
                <select name="academic_year_id" class="form-control" required>
                    <option value="">Chọn năm học</option>
                    <?php foreach ($teacherScheduleYears as $year): ?>
                        <option value="<?= (int)$year['id'] ?>">
                            <?= htmlspecialchars((string)$year['year_label'], ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label class="form-label">Khối</label>
                <select name="grade" class="form-control">
                    <option value="">Không chọn</option>
                    <?php for ($g = 1; $g <= 5; $g++): ?>
                        <option value="<?= $g ?>">Khối <?= $g ?></option>
                    <?php endfor; ?>
                </select>
            </div>

            <div class="form-group">
                <label class="form-label">Lớp áp dụng <span class="required">*</span></label>
                <input
                    type="text"
                    name="class_name"
                    class="form-control"
                    list="teacherScheduleClassOptions"
                    placeholder="Ví dụ 4/1"
                    autocomplete="off"
                    required
                >
                <datalist id="teacherScheduleClassOptions">
                    <?php foreach ($teacherScheduleClasses as $className): ?>
                        <option value="<?= htmlspecialchars($className, ENT_QUOTES, 'UTF-8') ?>"></option>
                    <?php endforeach; ?>
                </datalist>
            </div>

            <div class="form-group">
                <label class="form-label">Cách mở</label>
                <select name="schedule_unlock_mode" id="lessonScheduleUnlockMode" class="form-control">
                    <option value="sequential_daily">Mỗi ngày mở 1 Lesson</option>
                    <option value="scheduled_date">Mở vào ngày được chỉ định</option>
                </select>
            </div>

            <div class="form-group" id="lessonScheduleDateGroup" style="display:none;">
                <label class="form-label">Ngày mở Lesson</label>
                <input
                    type="date"
                    name="schedule_unlock_date"
                    id="lessonScheduleUnlockDate"
                    class="form-control"
                >
            </div>

            <div class="button-group" style="justify-content:flex-end;margin-top:20px;">
                <button type="button" class="button button-secondary" id="lessonScheduleCancel">Cancel</button>
                <button type="submit" class="button button-primary">Lưu lịch mở</button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<form method="post" id="lessonActionForm" hidden>
    <input type="hidden" name="action" id="lessonActionName">
    <input type="hidden" name="book_id" value="<?= (int)$selectedBookId ?>">
    <input type="hidden" name="level_id" value="<?= (int)$selectedLevelId ?>">
    <input type="hidden" name="unit_id" value="<?= (int)$selectedUnitId ?>">
    <input type="hidden" name="lesson_id" id="lessonActionId">
    <input type="hidden" name="direction" id="lessonActionDirection">
</form>

<script>
(function() {
    // Hide only the ambiguous global Topbar button labelled exactly "Add".
    function hideGlobalTopbarAdd() {
        document.querySelectorAll('button, a').forEach(function(element) {
            var label = (element.textContent || '')
                .replace(/\s+/g, ' ')
                .trim();

            if (label === 'Add' || label === '+ Add') {
                element.style.setProperty('display', 'none', 'important');
            }
        });
    }

    hideGlobalTopbarAdd();

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', hideGlobalTopbarAdd);
    }

    window.addEventListener('load', hideGlobalTopbarAdd);
    setTimeout(hideGlobalTopbarAdd, 250);

    var topbarObserver = new MutationObserver(function() {
        hideGlobalTopbarAdd();
    });

    topbarObserver.observe(document.documentElement, {
        childList: true,
        subtree: true
    });

    setTimeout(function() {
        topbarObserver.disconnect();
    }, 3000);
// ═══════════════════════════════════════════════════════════
    // BOOK & LEVEL MANAGEMENT
    // ═══════════════════════════════════════════════════════════
    var editBookModal = document.getElementById('editBookModal');
    var levelManageModal = document.getElementById('levelManageModal');

    function openOverlay(overlay) {
        overlay?.classList.add('is-open');
    }

    function closeOverlay(overlay) {
        overlay?.classList.remove('is-open');
    }

    document.querySelectorAll('[data-edit-book]').forEach(function(button) {
        button.addEventListener('click', function() {
            document.getElementById('editBookId').value = this.dataset.bookId || '';
            document.getElementById('editBookName').value = this.dataset.bookName || '';
            document.getElementById('editBookSlug').value = this.dataset.bookSlug || '';
            document.getElementById('editBookCover').value = this.dataset.bookCover || '';
            document.getElementById('editBookDescription').value = '';
            openOverlay(editBookModal);
        });
    });

    document.querySelectorAll('[data-close-edit-book]').forEach(function(button) {
        button.addEventListener('click', function() {
            closeOverlay(editBookModal);
        });
    });

    editBookModal?.addEventListener('click', function(event) {
        if (event.target === editBookModal) {
            closeOverlay(editBookModal);
        }
    });

    document.querySelectorAll('[data-delete-book]').forEach(function(button) {
        button.addEventListener('click', function() {
            var message =
                'Delete this Book?\n\n' +
                'If the Book already has Levels or Units, it will be archived instead of permanently deleted.';

            if (!confirm(message)) return;

            document.getElementById('deleteBookId').value = this.dataset.deleteBook || '';
            document.getElementById('deleteBookForm').submit();
        });
    });

    function openCreateLevel() {
        document.getElementById('levelManageTitle').textContent = 'Add Level';
        document.getElementById('levelManageAction').value = 'create_level';
        document.getElementById('manageLevelId').value = '';
        document.getElementById('manageLevelName').value = '';
        document.getElementById('manageLevelNumber').value = '1';
        document.getElementById('manageLevelSlug').value = '';
        document.getElementById('levelManageSubmit').textContent = 'Create Level';
        openOverlay(levelManageModal);
    }

    document.getElementById('btnAddLevel')?.addEventListener('click', openCreateLevel);

    document.querySelectorAll('[data-edit-level]').forEach(function(button) {
        button.addEventListener('click', function() {
            document.getElementById('levelManageTitle').textContent = 'Edit Level';
            document.getElementById('levelManageAction').value = 'update_level';
            document.getElementById('manageLevelId').value = this.dataset.levelId || '';
            document.getElementById('manageLevelName').value = this.dataset.levelName || '';
            document.getElementById('manageLevelNumber').value = this.dataset.levelNumber || '0';
            document.getElementById('manageLevelSlug').value = this.dataset.levelSlug || '';
            document.getElementById('levelManageSubmit').textContent = 'Save Changes';
            openOverlay(levelManageModal);
        });
    });

    document.querySelectorAll('[data-close-level-modal]').forEach(function(button) {
        button.addEventListener('click', function() {
            closeOverlay(levelManageModal);
        });
    });

    levelManageModal?.addEventListener('click', function(event) {
        if (event.target === levelManageModal) {
            closeOverlay(levelManageModal);
        }
    });

    document.querySelectorAll('[data-delete-level]').forEach(function(button) {
        button.addEventListener('click', function() {
            var message =
                'Delete this Level?\n\n' +
                'If it already has Units, it will be archived instead of permanently deleted.';

            if (!confirm(message)) return;

            document.getElementById('deleteLevelId').value = this.dataset.deleteLevel || '';
            document.getElementById('deleteLevelForm').submit();
        });
    });

    // ═══════════════════════════════════════════════════════════
    // ADD BOOK WIZARD
    // ═══════════════════════════════════════════════════════════
    var bookModal = document.getElementById('bookModalOverlay');
    var wizardStep = 1;
    var wizardPanes = Array.from(document.querySelectorAll('[data-wizard-pane]'));
    var wizardIndicators = Array.from(document.querySelectorAll('[data-step-indicator]'));
    var wizardBack = document.getElementById('bookWizardBack');
    var wizardNext = document.getElementById('bookWizardNext');
    var wizardCreate = document.getElementById('bookWizardCreate');
    var wizardName = document.getElementById('wizardBookName');
    var wizardSlug = document.getElementById('wizardBookSlug');
    var wizardDescription = document.getElementById('wizardBookDescription');
    var wizardCover = document.getElementById('wizardCoverImage');
    var customLevelsWrap = document.getElementById('customLevelsWrap');
    var customLevels = document.getElementById('customLevels');

    var levelTemplates = {
        'global-success': ['Lớp 1', 'Lớp 2', 'Lớp 3', 'Lớp 4', 'Lớp 5'],
        'everybody-up': ['Starter', 'Up 1', 'Up 2', 'Up 3', 'Up 4', 'Up 5', 'Up 6']
    };

    function slugify(value) {
        return (value || '')
            .toLowerCase()
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
    }

    function selectedTemplate() {
        var checked = document.querySelector('input[name="level_template"]:checked');
        return checked ? checked.value : 'global-success';
    }

    function currentLevels() {
        var template = selectedTemplate();

        if (template === 'custom') {
            return (customLevels.value || '')
                .split(/\r?\n/)
                .map(function(value) { return value.trim(); })
                .filter(Boolean);
        }

        return levelTemplates[template] || [];
    }

    function renderLevelChips(containerId) {
        var container = document.getElementById(containerId);
        if (!container) return;

        var levels = currentLevels();
        container.innerHTML = levels.length
            ? levels.map(function(level) {
                return '<span class="cl-level-chip">' + level.replace(/[&<>"']/g, function(char) {
                    return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[char];
                }) + '</span>';
            }).join('')
            : '<span style="color:var(--muted);font-size:12px;">No Levels yet.</span>';
    }

    function updateReview() {
        document.getElementById('reviewBookName').textContent =
            wizardName.value.trim() || 'New Book';

        document.getElementById('reviewBookDescription').textContent =
            wizardDescription.value.trim() || 'No description';

        var reviewCover = document.getElementById('reviewCover');
        var coverValue = wizardCover.value.trim();

        reviewCover.innerHTML = coverValue
            ? '<img src="' + coverValue.replace(/"/g, '&quot;') + '" alt="">'
            : '📘';

        renderLevelChips('reviewLevels');
    }

    function showWizardStep(step) {
        wizardStep = Math.max(1, Math.min(3, step));

        wizardPanes.forEach(function(pane) {
            pane.classList.toggle(
                'is-active',
                Number(pane.dataset.wizardPane) === wizardStep
            );
        });

        wizardIndicators.forEach(function(indicator) {
            var number = Number(indicator.dataset.stepIndicator);
            indicator.classList.toggle('is-active', number === wizardStep);
            indicator.classList.toggle('is-done', number < wizardStep);
        });

        wizardBack.hidden = wizardStep === 1;
        wizardNext.hidden = wizardStep === 3;
        wizardCreate.hidden = wizardStep !== 3;

        if (wizardStep === 2) {
            renderLevelChips('levelPreview');
        }

        if (wizardStep === 3) {
            updateReview();
        }
    }

    function openBookWizard() {
        if (!bookModal) return;
        bookModal.classList.add('is-open');
        showWizardStep(1);
        setTimeout(function() {
            wizardName?.focus();
        }, 80);
    }

    function closeBookWizard() {
        bookModal?.classList.remove('is-open');
    }

    document.getElementById('btnAddBook')?.addEventListener('click', openBookWizard);
    document.getElementById('bookModalClose')?.addEventListener('click', closeBookWizard);
    document.getElementById('bookWizardCancel')?.addEventListener('click', closeBookWizard);

    bookModal?.addEventListener('click', function(event) {
        if (event.target === bookModal) {
            closeBookWizard();
        }
    });

    wizardName?.addEventListener('input', function() {
        if (wizardSlug && wizardSlug.dataset.edited !== '1') {
            wizardSlug.value = slugify(this.value);
        }
    });

    wizardSlug?.addEventListener('input', function() {
        this.dataset.edited = '1';
    });

    document.querySelectorAll('input[name="level_template"]').forEach(function(input) {
        input.addEventListener('change', function() {
            customLevelsWrap.hidden = selectedTemplate() !== 'custom';
            renderLevelChips('levelPreview');
        });
    });

    customLevels?.addEventListener('input', function() {
        renderLevelChips('levelPreview');
    });

    wizardNext?.addEventListener('click', function() {
        if (wizardStep === 1 && !wizardName.value.trim()) {
            wizardName.focus();
            return;
        }

        if (wizardStep === 2 && currentLevels().length === 0) {
            customLevels?.focus();
            return;
        }

        showWizardStep(wizardStep + 1);
    });

    wizardBack?.addEventListener('click', function() {
        showWizardStep(wizardStep - 1);
    });

    // ═══════════════════════════════════════════════════════════
    // UNIT CRUD
    // ═══════════════════════════════════════════════════════════
    var unitManageModal = document.getElementById('unitManageModal');

    function openUnitModal(mode, data) {
        var isEdit = mode === 'edit';

        document.getElementById('unitManageTitle').textContent =
            isEdit ? 'Edit Unit' : 'Add Unit';

        document.getElementById('unitManageAction').value =
            isEdit ? 'update_unit' : 'create_unit';

        document.getElementById('manageUnitId').value =
            isEdit ? (data.id || '') : '';

        document.getElementById('manageUnitNumber').value =
            isEdit ? (data.number || '') : '';

        document.getElementById('manageUnitTitle').value =
            isEdit ? (data.title || '') : '';

        document.getElementById('manageUnitDescription').value =
            isEdit ? (data.description || '') : '';

        document.getElementById('unitManageSubmit').textContent =
            isEdit ? 'Save Changes' : 'Create Unit';

        unitManageModal?.classList.add('is-open');
    }

    function closeUnitModal() {
        unitManageModal?.classList.remove('is-open');
    }

    document.getElementById('btnAddUnit')?.addEventListener('click', function() {
        openUnitModal('create', {});
    });

    document.getElementById('btnCreateUnitEmpty')?.addEventListener('click', function() {
        openUnitModal('create', {});
    });

    document.querySelectorAll('[data-close-unit-modal]').forEach(function(button) {
        button.addEventListener('click', closeUnitModal);
    });

    unitManageModal?.addEventListener('click', function(event) {
        if (event.target === unitManageModal) {
            closeUnitModal();
        }
    });

    function submitUnitAction(action, unitId, direction) {
        document.getElementById('unitActionName').value = action;
        document.getElementById('unitActionId').value = unitId || '';
        document.getElementById('unitActionDirection').value = direction || '';
        document.getElementById('unitActionForm').submit();
    }

    // ═══════════════════════════════════════════════════════════
    // UNIT MANAGEMENT — Action dropdowns, search, sort, ordering
    // ═══════════════════════════════════════════════════════════

    // ─── Close all open dropdowns ──────────────────
    function closeAllDropdowns() {
        document.querySelectorAll('.cl-unit-action-dropdown.is-open').forEach(function(d) {
            d.classList.remove('is-open');
        });
    }

    // ─── Dropdown toggle ──────────────────────────
    document.querySelectorAll('.cl-unit-action-menu-btn').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            var dropdown = this.parentElement.querySelector('.cl-unit-action-dropdown');
            if (!dropdown) return;

            var isOpen = dropdown.classList.contains('is-open');
            closeAllDropdowns();
            if (!isOpen) {
                dropdown.classList.add('is-open');
            }
        });
    });

    // ─── Unit action menu ───────────────────────
    document.querySelectorAll('.cl-unit-action-dropdown button').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();

            var action = this.getAttribute('data-action');
            var unitId = this.getAttribute('data-unit-id');
            closeAllDropdowns();

            if (action === 'edit') {
                openUnitModal('edit', {
                    id: unitId,
                    number: this.getAttribute('data-unit-number') || '',
                    title: this.getAttribute('data-unit-title') || '',
                    description: this.getAttribute('data-unit-description') || ''
                });
                return;
            }

            if (action === 'duplicate') {
                if (confirm('Duplicate this Unit? Lessons are not copied in this step.')) {
                    submitUnitAction('duplicate_unit', unitId, '');
                }
                return;
            }

            if (action === 'archive') {
                if (confirm('Delete this Unit? Empty Units are deleted. Units with content are archived.')) {
                    submitUnitAction('delete_unit', unitId, '');
                }
            }
        });
    });

// ─── Close dropdowns on outside click ─────────
    document.addEventListener('click', function() {
        closeAllDropdowns();
    });

    // ─── Unit search filtering ────────────────────
    var unitSearchInput = document.querySelector('.cl-unit-toolbar .cl-tb-search input');
    if (unitSearchInput) {
        unitSearchInput.addEventListener('input', function() {
            var query = this.value.toLowerCase().trim();
            var unitItems = document.querySelectorAll('.cl-panel-middle .cl-unit-item');
            var visibleCount = 0;

            unitItems.forEach(function(item) {
                var text = (item.textContent || '').toLowerCase();
                var matches = query === '' || text.indexOf(query) !== -1;
                item.style.display = matches ? '' : 'none';
                if (matches) visibleCount++;
            });

            console.log('Unit search: "' + query + '" — ' + visibleCount + ' matches');
        });
    }

    // ─── Unit sort ────────────────────────────────
    var unitSortSelect = document.querySelector('.cl-unit-toolbar .cl-tb-sort');

    if (unitSortSelect) {
        unitSortSelect.addEventListener('change', function() {
            var sortValue = this.value;
            var list = document.querySelector('.cl-panel-middle .cl-panel-scroll');

            if (!list) return;

            var items = Array.from(
                list.querySelectorAll('.cl-unit-item')
            );

            items.sort(function(a, b) {
                var aTitle = (
                    a.querySelector('.cl-unit-info strong')?.textContent || ''
                ).trim().toLowerCase();

                var bTitle = (
                    b.querySelector('.cl-unit-info strong')?.textContent || ''
                ).trim().toLowerCase();

                var aLessons = parseInt(
                    a.querySelector('.cl-unit-meta span')?.textContent || '0',
                    10
                ) || 0;

                var bLessons = parseInt(
                    b.querySelector('.cl-unit-meta span')?.textContent || '0',
                    10
                ) || 0;

                var aOriginal = parseInt(a.dataset.originalOrder || '0', 10);
                var bOriginal = parseInt(b.dataset.originalOrder || '0', 10);

                if (sortValue === 'name-asc') {
                    return aTitle.localeCompare(bTitle);
                }

                if (sortValue === 'name-desc') {
                    return bTitle.localeCompare(aTitle);
                }

                if (sortValue === 'lessons-desc') {
                    return bLessons - aLessons || aTitle.localeCompare(bTitle);
                }

                if (sortValue === 'lessons-asc') {
                    return aLessons - bLessons || aTitle.localeCompare(bTitle);
                }

                return aOriginal - bOriginal;
            });

            items.forEach(function(item) {
                list.appendChild(item);
            });
        });

        document.querySelectorAll(
            '.cl-panel-middle .cl-unit-item'
        ).forEach(function(item, index) {
            item.dataset.originalOrder = String(index);
        });
    }

    // ─── Lesson create/edit modal ─────────────────
    var lessonModal = document.getElementById('lessonModalOverlay');

    function openLessonModal(mode, data) {
        var isEdit = mode === 'edit';

        document.getElementById('lessonModalTitle').textContent =
            isEdit ? 'Edit Lesson' : 'Create Lesson';

        document.getElementById('lessonManageAction').value =
            isEdit ? 'update_lesson' : 'create_lesson';

        document.getElementById('lessonManageId').value =
            isEdit ? (data.id || '') : '';

        document.getElementById('lessonManageTitleInput').value =
            isEdit ? (data.title || '') : '';

        document.getElementById('lessonManageType').value =
            isEdit ? (data.type || 'vocabulary') : 'vocabulary';

        document.getElementById('lessonManageDescription').value =
            isEdit ? (data.description || '') : '';

        var unlockMode = isEdit ? (data.unlockMode || 'sequential_daily') : 'sequential_daily';
        var unlockDate = isEdit ? (data.unlockDate || '') : '';
        document.getElementById('lessonManageUnlockMode').value = unlockMode;
        document.getElementById('lessonManageUnlockDate').value = unlockDate;
        toggleLessonUnlockDate();

        document.getElementById('lessonManageSubmit').textContent =
            isEdit ? 'Save Changes' : 'Create Lesson';

        lessonModal?.classList.add('is-open');

        setTimeout(function() {
            document.getElementById('lessonManageTitleInput')?.focus();
        }, 60);
    }

    function toggleLessonUnlockDate() {
        var mode = document.getElementById('lessonManageUnlockMode')?.value || 'sequential_daily';
        var group = document.getElementById('lessonUnlockDateGroup');
        var dateInput = document.getElementById('lessonManageUnlockDate');

        if (group) {
            group.style.display = mode === 'scheduled_date' ? '' : 'none';
        }
        if (dateInput) {
            dateInput.required = mode === 'scheduled_date';
            if (mode !== 'scheduled_date') {
                dateInput.value = '';
            }
        }
    }

    document.getElementById('lessonManageUnlockMode')?.addEventListener('change', toggleLessonUnlockDate);


    var lessonScheduleModal = document.getElementById('lessonScheduleModalOverlay');

    function toggleTeacherScheduleDate() {
        var mode = document.getElementById('lessonScheduleUnlockMode')?.value || 'sequential_daily';
        var group = document.getElementById('lessonScheduleDateGroup');
        var dateInput = document.getElementById('lessonScheduleUnlockDate');

        if (group) group.style.display = mode === 'scheduled_date' ? '' : 'none';
        if (dateInput) {
            dateInput.required = mode === 'scheduled_date';
            if (mode !== 'scheduled_date') dateInput.value = '';
        }
    }

    document.getElementById('lessonScheduleUnlockMode')?.addEventListener('change', toggleTeacherScheduleDate);

    document.querySelectorAll('[data-lesson-action="schedule"]').forEach(function(button) {
        button.addEventListener('click', function() {
            var id = this.dataset.lessonId || '';
            var title = this.dataset.lessonTitle || 'Lesson';

            var idInput = document.getElementById('lessonScheduleLessonId');
            var titleEl = document.getElementById('lessonScheduleModalTitle');
            if (idInput) idInput.value = id;
            if (titleEl) titleEl.textContent = 'Lịch mở • ' + title;

            var mode = document.getElementById('lessonScheduleUnlockMode');
            var dateInput = document.getElementById('lessonScheduleUnlockDate');
            if (mode) mode.value = 'sequential_daily';
            if (dateInput) dateInput.value = '';
            toggleTeacherScheduleDate();

            lessonScheduleModal?.classList.add('is-open');
        });
    });

    function closeLessonScheduleModal() {
        lessonScheduleModal?.classList.remove('is-open');
    }

    document.getElementById('lessonScheduleModalClose')?.addEventListener('click', closeLessonScheduleModal);
    document.getElementById('lessonScheduleCancel')?.addEventListener('click', closeLessonScheduleModal);
    lessonScheduleModal?.addEventListener('click', function(event) {
        if (event.target === lessonScheduleModal) closeLessonScheduleModal();
    });

    function closeLessonModal() {
        lessonModal?.classList.remove('is-open');
    }

    [
        document.getElementById('btnNewLesson'),
        document.getElementById('btnCreateFirstLesson')
    ].forEach(function(button) {
        if (button && !button.disabled) {
            button.addEventListener('click', function() {
                openLessonModal('create', {});
            });
        }
    });

    document.getElementById('lessonModalClose')?.addEventListener('click', closeLessonModal);
    document.getElementById('lessonModalCancel')?.addEventListener('click', closeLessonModal);

    lessonModal?.addEventListener('click', function(event) {
        if (event.target === lessonModal) {
            closeLessonModal();
        }
    });

    function submitLessonAction(action, lessonId, direction) {
        document.getElementById('lessonActionName').value = action;
        document.getElementById('lessonActionId').value = lessonId || '';
        document.getElementById('lessonActionDirection').value = direction || '';
        document.getElementById('lessonActionForm').submit();
    }

    document.querySelectorAll('[data-lesson-action]').forEach(function(button) {
        button.addEventListener('click', function() {
            var action = this.dataset.lessonAction;
            var lessonId = this.dataset.lessonId || '';

            if (action === 'edit') {
                openLessonModal('edit', {
                    id: lessonId,
                    title: this.dataset.lessonTitle || '',
                    type: this.dataset.lessonType || 'vocabulary',
                    description: this.dataset.lessonDescription || '',
                    unlockMode: this.dataset.lessonUnlockMode || 'sequential_daily',
                    unlockDate: this.dataset.lessonUnlockDate || ''
                });
                return;
            }

            if (action === 'duplicate') {
                if (confirm('Duplicate this Lesson? Activities are not copied in this step.')) {
                    submitLessonAction('duplicate_lesson', lessonId, '');
                }
                return;
            }

            if (action === 'move') {
                submitLessonAction(
                    'move_lesson',
                    lessonId,
                    this.dataset.direction || ''
                );
                return;
            }

            if (action === 'delete') {
                if (confirm(
                    'Delete this Lesson?\n\n' +
                    'An empty Lesson will be deleted. A Lesson with Activities will be archived.'
                )) {
                    submitLessonAction('delete_lesson', lessonId, '');
                }
            }
        });
    });

    // ─── Lesson search and type filter ────────────
    var lessonSearch = document.querySelector('.cl-workspace-toolbar .cl-tb-search input');
    var lessonTypeFilter = document.querySelector('.cl-workspace-toolbar .cl-tb-select');
    var lessonRows = Array.from(document.querySelectorAll('.cl-lesson-row'));

    function filterLessons() {
        var query = lessonSearch ? lessonSearch.value.toLowerCase().trim() : '';
        var type = lessonTypeFilter ? lessonTypeFilter.value : '';

        lessonRows.forEach(function(row) {
            var matchesText = query === '' || (row.dataset.title || '').indexOf(query) !== -1;
            var matchesType = type === '' || (row.dataset.type || '') === type;
            row.style.display = matchesText && matchesType ? '' : 'none';
        });
    }

    lessonSearch?.addEventListener('input', filterLessons);
    lessonTypeFilter?.addEventListener('change', filterLessons);

    // The second select is the sort control.
    var workspaceSelects = document.querySelectorAll('.cl-workspace-toolbar .cl-tb-select');
    var lessonSort = workspaceSelects.length > 1 ? workspaceSelects[1] : null;

    lessonSort?.addEventListener('change', function() {
        var list = document.getElementById('lessonList');
        if (!list) return;

        var rows = Array.from(list.querySelectorAll('.cl-lesson-row'));
        var mode = this.value;

        rows.sort(function(a, b) {
            var aTitle = a.dataset.title || '';
            var bTitle = b.dataset.title || '';

            if (mode === 'name-desc') {
                return bTitle.localeCompare(aTitle);
            }

            return aTitle.localeCompare(bTitle);
        });

        rows.forEach(function(row) {
            list.appendChild(row);
        });
    });
})();
</script>

<?php
$content = ob_get_clean();
require __DIR__ . '/../layouts/app.php';