<?php
declare(strict_types=1);

require __DIR__ . '/../partials/auth.php';
require_once __DIR__ . '/../../config/database.php';

if (($_SESSION['user_role'] ?? '') !== 'admin') {
    http_response_code(403);
    exit('Bạn không có quyền truy cập chức năng này.');
}

$pdo = getDbConnection();

$pageTitle = 'Giáo viên';
$pageSubtitle = 'Quản lý tài khoản và phạm vi trường của giáo viên';
$activeTeacherNav = 'teachers';

if (empty($_SESSION['teacher_csrf_token'])) {
    $_SESSION['teacher_csrf_token'] = bin2hex(random_bytes(32));
}

$flashSuccess = '';
$flashError = '';
$tempPasswordResult = null;

function esTeacherTempPassword(int $length = 8): string
{
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789';
    $max = strlen($chars) - 1;
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[random_int(0, $max)];
    }
    return $password;
}


function esEnsureTeacherReferralCode(PDO $pdo, int $teacherId): string
{
    if ($teacherId <= 0) {
        return '';
    }

    $check = $pdo->prepare(
        "SELECT referral_code
         FROM teacher_referral_codes
         WHERE teacher_id = :teacher_id
         LIMIT 1"
    );
    $check->execute(['teacher_id' => $teacherId]);

    $existing = trim((string)($check->fetchColumn() ?: ''));
    if ($existing !== '') {
        return $existing;
    }

    for ($attempt = 0; $attempt < 20; $attempt++) {
        // Example: GV7A3F91C2
        $code = 'GV' . strtoupper(bin2hex(random_bytes(4)));

        try {
            $insert = $pdo->prepare(
                "INSERT INTO teacher_referral_codes
                    (teacher_id, referral_code, status, created_at, updated_at)
                 VALUES
                    (:teacher_id, :referral_code, 'active', NOW(), NOW())"
            );
            $insert->execute([
                'teacher_id' => $teacherId,
                'referral_code' => $code,
            ]);

            return $code;
        } catch (PDOException $e) {
            if ((string)$e->getCode() !== '23000') {
                throw $e;
            }

            $check->execute(['teacher_id' => $teacherId]);
            $existing = trim((string)($check->fetchColumn() ?: ''));
            if ($existing !== '') {
                return $existing;
            }
        }
    }

    throw new RuntimeException('Không thể tạo mã referral cho giáo viên.');
}

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

    try {
        if ($csrf === '' || !hash_equals((string)$_SESSION['teacher_csrf_token'], $csrf)) {
            throw new RuntimeException('Yêu cầu không hợp lệ. Vui lòng tải lại trang.');
        }

        if ($action === 'approve_teacher') {
            $userId = max(0, (int)($_POST['user_id'] ?? 0));
            if ($userId <= 0) {
                throw new RuntimeException('Giáo viên không hợp lệ.');
            }

            $stmt = $pdo->prepare(
                "UPDATE users
                 SET status = 'active',
                     updated_at = NOW()
                 WHERE id = :id
                   AND role = 'teacher'
                   AND status = 'pending'"
            );
            $stmt->execute(['id' => $userId]);

            if ($stmt->rowCount() < 1) {
                throw new RuntimeException('Không tìm thấy tài khoản giáo viên đang chờ duyệt.');
            }

            $referralCode = esEnsureTeacherReferralCode($pdo, $userId);
            $flashSuccess = 'Đã duyệt tài khoản giáo viên. Mã referral: ' . $referralCode;
        } elseif ($action === 'toggle_teacher') {
            $userId = max(0, (int)($_POST['user_id'] ?? 0));
            if ($userId <= 0) {
                throw new RuntimeException('Giáo viên không hợp lệ.');
            }

            $stmt = $pdo->prepare(
                "UPDATE users
                 SET status = CASE WHEN status = 'active' THEN 'locked' ELSE 'active' END,
                     updated_at = NOW()
                 WHERE id = :id
                   AND role = 'teacher'"
            );
            $stmt->execute(['id' => $userId]);

            if ($stmt->rowCount() < 1) {
                throw new RuntimeException('Không tìm thấy giáo viên cần cập nhật.');
            }

            $flashSuccess = 'Đã cập nhật trạng thái tài khoản giáo viên.';
        } elseif ($action === 'update_scope') {
            $userId = max(0, (int)($_POST['user_id'] ?? 0));
            $provinceId = max(0, (int)($_POST['province_id'] ?? 0));
            $schoolId = max(0, (int)($_POST['school_id'] ?? 0));
            $bookIds = array_values(array_unique(array_filter(array_map('intval', (array)($_POST['book_ids'] ?? [])), static fn($id) => $id > 0)));

            if ($userId <= 0) throw new RuntimeException('Giáo viên không hợp lệ.');
            if ($provinceId <= 0 || $schoolId <= 0) {
                throw new RuntimeException('Vui lòng chọn Tỉnh và Trường.');
            }

            $checkTeacher = $pdo->prepare(
                "SELECT id FROM users WHERE id = :id AND role = 'teacher' LIMIT 1"
            );
            $checkTeacher->execute(['id' => $userId]);
            if (!$checkTeacher->fetchColumn()) {
                throw new RuntimeException('Không tìm thấy tài khoản giáo viên.');
            }

            $scopeStmt = $pdo->prepare(
                "SELECT
                    p.id AS province_id,
                    p.name AS province_name,
                    s.id AS school_id,
                    s.name AS school_name
                 FROM schools s
                 INNER JOIN provinces p ON p.id = s.province_id
                 WHERE s.id = :school_id
                   AND p.id = :province_id
                   AND s.status = 'active'
                   AND p.status = 'active'
                 LIMIT 1"
            );
            $scopeStmt->execute([
                'school_id' => $schoolId,
                'province_id' => $provinceId,
            ]);
            $scope = $scopeStmt->fetch(PDO::FETCH_ASSOC);

            if (!$scope) {
                throw new RuntimeException('Trường đã chọn không thuộc Tỉnh này hoặc đang ngừng hoạt động.');
            }

            $profile = $pdo->prepare(
                "INSERT INTO teacher_profiles
                    (user_id, province_id, school_id, province, school_name)
                 VALUES
                    (:user_id, :province_id, :school_id, :province, :school_name)
                 ON DUPLICATE KEY UPDATE
                    province_id = VALUES(province_id),
                    school_id = VALUES(school_id),
                    province = VALUES(province),
                    school_name = VALUES(school_name),
                    updated_at = NOW()"
            );
            $profile->execute([
                'user_id' => $userId,
                'province_id' => $provinceId,
                'school_id' => $schoolId,
                'province' => (string)$scope['province_name'],
                'school_name' => (string)$scope['school_name'],
            ]);

            // Chỉ nhận các bộ sách đang hoạt động.
            $validBookIds = [];
            if ($bookIds !== []) {
                $placeholders = implode(',', array_fill(0, count($bookIds), '?'));
                $bookCheck = $pdo->prepare("SELECT id FROM books WHERE status = 'active' AND id IN ($placeholders)");
                $bookCheck->execute($bookIds);
                $validBookIds = array_map('intval', $bookCheck->fetchAll(PDO::FETCH_COLUMN));
            }

            $pdo->beginTransaction();
            try {
                $deleteBooks = $pdo->prepare("DELETE FROM teacher_books WHERE teacher_id = :teacher_id");
                $deleteBooks->execute(['teacher_id' => $userId]);

                if ($validBookIds !== []) {
                    $insertBook = $pdo->prepare("INSERT INTO teacher_books (teacher_id, book_id) VALUES (:teacher_id, :book_id)");
                    foreach ($validBookIds as $bookId) {
                        $insertBook->execute(['teacher_id' => $userId, 'book_id' => $bookId]);
                    }
                }
                $pdo->commit();
            } catch (Throwable $bookError) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                throw $bookError;
            }

            $flashSuccess = 'Đã cập nhật Tỉnh/Trường và bộ sách của giáo viên.';
        } elseif ($action === 'save_collaborator') {
            $userId = max(0, (int)($_POST['user_id'] ?? 0));
            $isCollaborator = isset($_POST['is_collaborator']) && (string)$_POST['is_collaborator'] === '1';
            $accessPolicy = (string)($_POST['access_policy'] ?? 'standard');
            $freeUntilRaw = trim((string)($_POST['free_until'] ?? ''));
            $note = trim((string)($_POST['collaborator_note'] ?? ''));
            $allowedPolicies = ['standard', 'free_until', 'admin_granted'];
            if ($userId <= 0) throw new RuntimeException('Giáo viên không hợp lệ.');
            if (!in_array($accessPolicy, $allowedPolicies, true)) throw new RuntimeException('Chính sách cộng tác viên không hợp lệ.');
            $teacherCheck = $pdo->prepare("SELECT id FROM users WHERE id = :id AND role = 'teacher' LIMIT 1");
            $teacherCheck->execute(['id' => $userId]);
            if (!$teacherCheck->fetchColumn()) throw new RuntimeException('Không tìm thấy giáo viên.');
            $freeUntil = null;
            if ($accessPolicy === 'free_until') {
                if ($freeUntilRaw === '') throw new RuntimeException('Vui lòng chọn ngày miễn phí đến.');
                $date = DateTime::createFromFormat('Y-m-d', $freeUntilRaw);
                if (!$date || $date->format('Y-m-d') !== $freeUntilRaw) throw new RuntimeException('Ngày miễn phí không hợp lệ.');
                $freeUntil = $freeUntilRaw;
            }
            $adminId = max(0, (int)($_SESSION['user_id'] ?? 0));
            $stmt = $pdo->prepare("INSERT INTO teacher_collaborators (teacher_id, status, access_policy, free_until, note, granted_by, granted_at) VALUES (:teacher_id, :status, :access_policy, :free_until, :note, :granted_by, NOW()) ON DUPLICATE KEY UPDATE status=VALUES(status), access_policy=VALUES(access_policy), free_until=VALUES(free_until), note=VALUES(note), granted_by=VALUES(granted_by), updated_at=NOW()");
            $stmt->execute(['teacher_id'=>$userId,'status'=>$isCollaborator?'active':'inactive','access_policy'=>$accessPolicy,'free_until'=>$freeUntil,'note'=>$note!==''?$note:null,'granted_by'=>$adminId>0?$adminId:null]);
            $flashSuccess = $isCollaborator ? 'Đã cập nhật cộng tác viên nội dung.' : 'Đã tắt trạng thái cộng tác viên nội dung.';
        } elseif ($action === 'add_content_assignment') {
            $userId = max(0, (int)($_POST['user_id'] ?? 0));
            $bookId = max(0, (int)($_POST['book_id'] ?? 0));
            $levelId = max(0, (int)($_POST['level_id'] ?? 0));
            $assignmentRole = (string)($_POST['assignment_role'] ?? 'author');
            $allowedRoles = ['author', 'reviewer', 'lead'];

            if ($userId <= 0 || $bookId <= 0 || $levelId <= 0) {
                throw new RuntimeException('Vui lòng chọn đầy đủ Giáo viên, Bộ sách và Level/Khối.');
            }
            if (!in_array($assignmentRole, $allowedRoles, true)) {
                throw new RuntimeException('Vai trò phân công không hợp lệ.');
            }

            $teacherCheck = $pdo->prepare("SELECT id FROM users WHERE id = :id AND role = 'teacher' LIMIT 1");
            $teacherCheck->execute(['id' => $userId]);
            if (!$teacherCheck->fetchColumn()) {
                throw new RuntimeException('Không tìm thấy giáo viên.');
            }

            $levelCols = $pdo->query("SHOW COLUMNS FROM levels")->fetchAll(PDO::FETCH_COLUMN);
            if (!in_array('book_id', $levelCols, true)) {
                throw new RuntimeException('Bảng levels chưa có cột book_id để xác định Level thuộc Bộ sách.');
            }
            $levelCheck = $pdo->prepare(
                "SELECT l.id
                 FROM levels l
                 INNER JOIN books b ON b.id = l.book_id
                 WHERE l.id = :level_id
                   AND l.book_id = :book_id
                   AND b.status = 'active'
                 LIMIT 1"
            );
            $levelCheck->execute(['level_id' => $levelId, 'book_id' => $bookId]);
            if (!$levelCheck->fetchColumn()) {
                throw new RuntimeException('Level/Khối không thuộc Bộ sách đã chọn.');
            }

            $adminId = max(0, (int)($_SESSION['user_id'] ?? 0));
            $insertAssignment = $pdo->prepare(
                "INSERT INTO teacher_content_assignments
                    (teacher_id, book_id, level_id, role, status, assigned_by, assigned_at)
                 VALUES
                    (:teacher_id, :book_id, :level_id, :role, 'active', :assigned_by, NOW())
                 ON DUPLICATE KEY UPDATE
                    status = 'active',
                    assigned_by = VALUES(assigned_by),
                    assigned_at = NOW()"
            );
            $insertAssignment->execute([
                'teacher_id' => $userId,
                'book_id' => $bookId,
                'level_id' => $levelId,
                'role' => $assignmentRole,
                'assigned_by' => $adminId > 0 ? $adminId : null,
            ]);

            $flashSuccess = 'Đã thêm phân công nội dung V3.2.';
        } elseif ($action === 'remove_content_assignment') {
            $assignmentId = max(0, (int)($_POST['assignment_id'] ?? 0));
            $userId = max(0, (int)($_POST['user_id'] ?? 0));
            if ($assignmentId <= 0 || $userId <= 0) {
                throw new RuntimeException('Phân công không hợp lệ.');
            }

            $deleteAssignment = $pdo->prepare(
                "DELETE FROM teacher_content_assignments
                 WHERE id = :id AND teacher_id = :teacher_id"
            );
            $deleteAssignment->execute(['id' => $assignmentId, 'teacher_id' => $userId]);
            if ($deleteAssignment->rowCount() < 1) {
                throw new RuntimeException('Không tìm thấy phân công cần xóa.');
            }

            $flashSuccess = 'Đã xóa phân công nội dung V3.2.';
        } elseif ($action === 'approve_school') {
            $userId = max(0, (int)($_POST['user_id'] ?? 0));
            $pendingSchoolId = max(0, (int)($_POST['pending_school_id'] ?? 0));
            $officialName = trim((string)($_POST['official_school_name'] ?? ''));
            $mergeSchoolId = max(0, (int)($_POST['merge_school_id'] ?? 0));

            if ($userId <= 0 || $pendingSchoolId <= 0) {
                throw new RuntimeException('Yêu cầu duyệt trường không hợp lệ.');
            }

            $pendingStmt = $pdo->prepare(
                "SELECT
                    u.id AS user_id,
                    u.status AS user_status,
                    tp.province_id,
                    tp.school_id,
                    tp.province,
                    tp.school_name,
                    s.name AS pending_school_name,
                    s.status AS school_status
                 FROM users u
                 INNER JOIN teacher_profiles tp ON tp.user_id = u.id
                 INNER JOIN schools s ON s.id = tp.school_id
                 WHERE u.id = :user_id
                   AND u.role = 'teacher'
                   AND s.id = :school_id
                 LIMIT 1"
            );
            $pendingStmt->execute([
                'user_id' => $userId,
                'school_id' => $pendingSchoolId,
            ]);
            $pending = $pendingStmt->fetch(PDO::FETCH_ASSOC);

            if (!$pending) {
                throw new RuntimeException('Không tìm thấy trường đang chờ duyệt của giáo viên.');
            }

            $provinceId = (int)$pending['province_id'];
            if ($provinceId <= 0) {
                throw new RuntimeException('Trường đang chờ duyệt chưa có Tỉnh hợp lệ.');
            }

            $pdo->beginTransaction();
            try {
                if ($mergeSchoolId > 0) {
                    // Ghép vào một trường chính thức đã có trong cùng Tỉnh.
                    $targetStmt = $pdo->prepare(
                        "SELECT s.id, s.name, p.name AS province_name
                         FROM schools s
                         INNER JOIN provinces p ON p.id = s.province_id
                         WHERE s.id = :school_id
                           AND s.province_id = :province_id
                           AND s.status = 'active'
                           AND p.status = 'active'
                         LIMIT 1"
                    );
                    $targetStmt->execute([
                        'school_id' => $mergeSchoolId,
                        'province_id' => $provinceId,
                    ]);
                    $target = $targetStmt->fetch(PDO::FETCH_ASSOC);

                    if (!$target) {
                        throw new RuntimeException('Trường dùng để ghép không hợp lệ hoặc không thuộc cùng Tỉnh.');
                    }

                    $moveProfiles = $pdo->prepare(
                        "UPDATE teacher_profiles
                         SET school_id = :target_school_id,
                             school_name = :target_school_name,
                             province = :province_name,
                             updated_at = NOW()
                         WHERE user_id = :user_id
                           AND school_id = :pending_school_id"
                    );
                    $moveProfiles->execute([
                        'target_school_id' => (int)$target['id'],
                        'target_school_name' => (string)$target['name'],
                        'province_name' => (string)$target['province_name'],
                        'pending_school_id' => $pendingSchoolId,
                    ]);

                    // Mở các tài khoản giáo viên cùng yêu cầu trường vừa được ghép.
                    $unlock = $pdo->prepare(
                        "UPDATE users u
                         INNER JOIN teacher_profiles tp ON tp.user_id = u.id
                         SET u.status = 'active',
                             u.updated_at = NOW()
                         WHERE u.role = 'teacher'
                           AND tp.school_id = :target_school_id"
                    );
                    $unlock->execute(['target_school_id' => (int)$target['id']]);

                    $activatedTeachers = $pdo->prepare(
                        "SELECT u.id
                         FROM users u
                         INNER JOIN teacher_profiles tp ON tp.user_id = u.id
                         WHERE u.role = 'teacher'
                           AND u.status = 'active'
                           AND tp.school_id = :school_id"
                    );
                    $activatedTeachers->execute(['school_id' => (int)$target['id']]);
                    foreach ($activatedTeachers->fetchAll(PDO::FETCH_COLUMN) as $activatedTeacherId) {
                        esEnsureTeacherReferralCode($pdo, (int)$activatedTeacherId);
                    }

                    // Nếu trường chờ duyệt không còn giáo viên nào tham chiếu thì xóa bản ghi tạm.
                    $stillUsed = $pdo->prepare(
                        "SELECT COUNT(*) FROM teacher_profiles WHERE school_id = :school_id"
                    );
                    $stillUsed->execute(['school_id' => $pendingSchoolId]);
                    if ((int)$stillUsed->fetchColumn() === 0) {
                        $deletePending = $pdo->prepare(
                            "DELETE FROM schools WHERE id = :school_id AND status = 'inactive'"
                        );
                        $deletePending->execute(['school_id' => $pendingSchoolId]);
                    }

                    $flashSuccess = 'Đã ghép trường và mở tài khoản giáo viên.';
                } else {
                    // Duyệt trường mới. Admin có thể sửa lại tên chính thức ngay tại đây.
                    if ($officialName === '') {
                        throw new RuntimeException('Vui lòng nhập tên trường chính thức.');
                    }

                    $dupStmt = $pdo->prepare(
                        "SELECT id, name
                         FROM schools
                         WHERE province_id = :province_id
                           AND id <> :school_id
                           AND LOWER(TRIM(name)) = LOWER(TRIM(:name))
                         LIMIT 1"
                    );
                    $dupStmt->execute([
                        'province_id' => $provinceId,
                        'school_id' => $pendingSchoolId,
                        'name' => $officialName,
                    ]);
                    if ($dupStmt->fetch(PDO::FETCH_ASSOC)) {
                        throw new RuntimeException('Tên trường chính thức này đã tồn tại. Hãy dùng chức năng Ghép trường có sẵn.');
                    }

                    $provinceStmt = $pdo->prepare(
                        "SELECT name FROM provinces WHERE id = :province_id AND status = 'active' LIMIT 1"
                    );
                    $provinceStmt->execute(['province_id' => $provinceId]);
                    $provinceName = (string)($provinceStmt->fetchColumn() ?: '');
                    if ($provinceName === '') {
                        throw new RuntimeException('Tỉnh của trường không còn hoạt động.');
                    }

                    $approve = $pdo->prepare(
                        "UPDATE schools
                         SET name = :name,
                             status = 'active',
                             updated_at = NOW()
                         WHERE id = :school_id"
                    );
                    $approve->execute([
                        'name' => $officialName,
                        'school_id' => $pendingSchoolId,
                    ]);

                    $syncProfiles = $pdo->prepare(
                        "UPDATE teacher_profiles
                         SET province = :province_name,
                             school_name = :school_name,
                             updated_at = NOW()
                         WHERE school_id = :school_id"
                    );
                    $syncProfiles->execute([
                        'province_name' => $provinceName,
                        'school_name' => $officialName,
                        'school_id' => $pendingSchoolId,
                    ]);

                    $unlock = $pdo->prepare(
                        "UPDATE users u
                         INNER JOIN teacher_profiles tp ON tp.user_id = u.id
                         SET u.status = 'active',
                             u.updated_at = NOW()
                         WHERE u.role = 'teacher'
                           AND tp.school_id = :school_id"
                    );
                    $unlock->execute(['school_id' => $pendingSchoolId]);

                    $activatedTeachers = $pdo->prepare(
                        "SELECT u.id
                         FROM users u
                         INNER JOIN teacher_profiles tp ON tp.user_id = u.id
                         WHERE u.role = 'teacher'
                           AND u.status = 'active'
                           AND tp.school_id = :school_id"
                    );
                    $activatedTeachers->execute(['school_id' => $pendingSchoolId]);
                    foreach ($activatedTeachers->fetchAll(PDO::FETCH_COLUMN) as $activatedTeacherId) {
                        esEnsureTeacherReferralCode($pdo, (int)$activatedTeacherId);
                    }

                    $flashSuccess = 'Đã duyệt trường, chuẩn hóa tên và mở tài khoản giáo viên.';
                }

                $pdo->commit();
            } catch (Throwable $approveError) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                throw $approveError;
            }
        } elseif ($action === 'reset_teacher_password') {
            $userId = max(0, (int)($_POST['user_id'] ?? 0));
            if ($userId <= 0) {
                throw new RuntimeException('Giáo viên không hợp lệ.');
            }

            $teacherStmt = $pdo->prepare(
                "SELECT id, full_name, username, email
                 FROM users
                 WHERE id = :id
                   AND role = 'teacher'
                 LIMIT 1"
            );
            $teacherStmt->execute(['id' => $userId]);
            $teacherRow = $teacherStmt->fetch(PDO::FETCH_ASSOC);

            if (!$teacherRow) {
                throw new RuntimeException('Không tìm thấy tài khoản giáo viên.');
            }

            // Mật khẩu tạm cố định khi Admin reset tài khoản giáo viên.
            // Chỉ giá trị hash được lưu trong database.
            $temporaryPassword = '12345678';
            $passwordHash = password_hash($temporaryPassword, PASSWORD_DEFAULT);

            $updatePassword = $pdo->prepare(
                "UPDATE users
                 SET password_hash = :password_hash,
                     updated_at = NOW()
                 WHERE id = :id
                   AND role = 'teacher'"
            );
            $updatePassword->execute([
                'password_hash' => $passwordHash,
                'id' => $userId,
            ]);

            $tempPasswordResult = [
                'name' => (string)$teacherRow['full_name'],
                'username' => (string)$teacherRow['username'],
                'email' => (string)($teacherRow['email'] ?? ''),
                'password' => $temporaryPassword,
            ];
            $flashSuccess = 'Đã đặt lại mật khẩu giáo viên. Mật khẩu tạm: 12345678';
        } elseif ($action === 'delete_teacher') {
            $userId = max(0, (int)($_POST['user_id'] ?? 0));
            if ($userId <= 0) {
                throw new RuntimeException('Giáo viên không hợp lệ.');
            }

            $checkTeacher = $pdo->prepare(
                "SELECT id, full_name FROM users
                 WHERE id = :id AND role = 'teacher'
                 LIMIT 1"
            );
            $checkTeacher->execute(['id' => $userId]);
            $teacherToDelete = $checkTeacher->fetch(PDO::FETCH_ASSOC);

            if (!$teacherToDelete) {
                throw new RuntimeException('Không tìm thấy tài khoản giáo viên.');
            }

            $pdo->beginTransaction();
            try {
                // Chỉ xóa hồ sơ/phạm vi và liên kết bộ sách của giáo viên.
                // Không xóa học sinh, tiến độ học tập hoặc XP của học sinh.
                $deleteTeacherBooks = $pdo->prepare("DELETE FROM teacher_books WHERE teacher_id = :user_id");
                $deleteTeacherBooks->execute(['user_id' => $userId]);

                $deleteContentAssignments = $pdo->prepare("DELETE FROM teacher_content_assignments WHERE teacher_id = :user_id");
                $deleteContentAssignments->execute(['user_id' => $userId]);

                $deleteProfile = $pdo->prepare(
                    "DELETE FROM teacher_profiles WHERE user_id = :user_id"
                );
                $deleteProfile->execute(['user_id' => $userId]);

                $deleteUser = $pdo->prepare(
                    "DELETE FROM users WHERE id = :id AND role = 'teacher'"
                );
                $deleteUser->execute(['id' => $userId]);

                if ($deleteUser->rowCount() < 1) {
                    throw new RuntimeException('Không thể xóa tài khoản giáo viên.');
                }

                $pdo->commit();
                $flashSuccess = 'Đã xóa tài khoản giáo viên.';
            } catch (Throwable $deleteError) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                throw $deleteError;
            }
        }

        $_SESSION['teacher_csrf_token'] = bin2hex(random_bytes(32));
    } catch (Throwable $e) {
        error_log('Admin teachers error: ' . $e->getMessage());
        $flashError = $e instanceof RuntimeException
            ? $e->getMessage()
            : 'Không thể cập nhật giáo viên.';
    }
}

$provinces = $pdo->query(
    "SELECT id, name
     FROM provinces
     WHERE status = 'active'
     ORDER BY name ASC"
)->fetchAll(PDO::FETCH_ASSOC);

$schools = $pdo->query(
    "SELECT id, province_id, name
     FROM schools
     WHERE status = 'active'
     ORDER BY name ASC"
)->fetchAll(PDO::FETCH_ASSOC);

$books = $pdo->query(
    "SELECT id, name
     FROM books
     WHERE status = 'active'
     ORDER BY sort_order ASC, name ASC"
)->fetchAll(PDO::FETCH_ASSOC);

// V3.2: Level/Khối theo từng Bộ sách. Đọc tên cột mềm để không phá schema V3.1.
$levels = [];
try {
    $levelColumns = $pdo->query("SHOW COLUMNS FROM levels")->fetchAll(PDO::FETCH_COLUMN);
    if (in_array('book_id', $levelColumns, true)) {
        $levelNameColumn = in_array('name', $levelColumns, true) ? 'name'
            : (in_array('title', $levelColumns, true) ? 'title'
            : (in_array('level_name', $levelColumns, true) ? 'level_name' : 'id'));
        $levelStatusSql = in_array('status', $levelColumns, true) ? " WHERE status = 'active'" : '';
        $levelOrder = in_array('sort_order', $levelColumns, true) ? 'book_id ASC, sort_order ASC, id ASC' : 'book_id ASC, id ASC';
        $levels = $pdo->query(
            "SELECT id, book_id, `{$levelNameColumn}` AS name FROM levels{$levelStatusSql} ORDER BY {$levelOrder}"
        )->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Throwable $levelError) {
    error_log('Admin teacher levels error: ' . $levelError->getMessage());
}

$teacherCollaboratorMap = [];
try {
    foreach ($pdo->query("SELECT teacher_id, status, access_policy, free_until, note FROM teacher_collaborators ORDER BY teacher_id")->fetchAll(PDO::FETCH_ASSOC) as $collabRow) {
        $teacherCollaboratorMap[(int)$collabRow['teacher_id']] = $collabRow;
    }
} catch (Throwable $e) {}

$teacherContentAssignmentMap = [];
try {
    $assignmentRows = $pdo->query(
        "SELECT tca.id, tca.teacher_id, tca.book_id, tca.level_id, tca.role, tca.status,
                b.name AS book_name,
                COALESCE(l.name, CONCAT('Level #', l.id)) AS level_name
         FROM teacher_content_assignments tca
         INNER JOIN books b ON b.id = tca.book_id
         INNER JOIN levels l ON l.id = tca.level_id
         WHERE tca.status = 'active'
         ORDER BY tca.teacher_id ASC, b.name ASC, l.id ASC, tca.role ASC"
    )->fetchAll(PDO::FETCH_ASSOC);
    foreach ($assignmentRows as $assignmentRow) {
        $teacherContentAssignmentMap[(int)$assignmentRow['teacher_id']][] = $assignmentRow;
    }
} catch (Throwable $assignmentMapError) {
    // Nếu tên level không phải `name`, fallback lấy dữ liệu rồi ghép từ mảng $levels.
    try {
        $levelNameMap = [];
        foreach ($levels as $levelRow) $levelNameMap[(int)$levelRow['id']] = (string)$levelRow['name'];
        $bookNameMap = [];
        foreach ($books as $bookRow) $bookNameMap[(int)$bookRow['id']] = (string)$bookRow['name'];
        foreach ($pdo->query("SELECT id, teacher_id, book_id, level_id, role, status FROM teacher_content_assignments WHERE status = 'active' ORDER BY teacher_id, book_id, level_id, role")->fetchAll(PDO::FETCH_ASSOC) as $assignmentRow) {
            $assignmentRow['book_name'] = $bookNameMap[(int)$assignmentRow['book_id']] ?? ('Book #' . (int)$assignmentRow['book_id']);
            $assignmentRow['level_name'] = $levelNameMap[(int)$assignmentRow['level_id']] ?? ('Level #' . (int)$assignmentRow['level_id']);
            $teacherContentAssignmentMap[(int)$assignmentRow['teacher_id']][] = $assignmentRow;
        }
    } catch (Throwable $fallbackAssignmentError) {
        error_log('Admin teacher content assignment map error: ' . $fallbackAssignmentError->getMessage());
    }
}

$teacherBookMap = [];
foreach ($pdo->query("SELECT teacher_id, book_id FROM teacher_books")->fetchAll(PDO::FETCH_ASSOC) as $tb) {
    $teacherBookMap[(int)$tb['teacher_id']][] = (int)$tb['book_id'];
}

// Lớp đang được từng giáo viên quản lý.
// Nguồn chuẩn: teacher_class_assignments do giáo viên khai báo theo năm học.
// Không suy lớp từ students vì một trường có thể có nhiều giáo viên/lớp.
$teacherClassMap = [];

try {
    $assignmentColumns = $pdo->query("SHOW COLUMNS FROM teacher_class_assignments")->fetchAll(PDO::FETCH_COLUMN);

    $teacherCol = in_array('teacher_id', $assignmentColumns, true)
        ? 'teacher_id'
        : (in_array('user_id', $assignmentColumns, true) ? 'user_id' : '');

    $classCol = in_array('class_name', $assignmentColumns, true)
        ? 'class_name'
        : (in_array('class', $assignmentColumns, true) ? 'class' : '');

    $gradeCol = in_array('grade', $assignmentColumns, true)
        ? 'grade'
        : (in_array('grade_id', $assignmentColumns, true) ? 'grade_id' : '');

    $statusCol = in_array('status', $assignmentColumns, true) ? 'status' : '';

    if ($teacherCol !== '' && $classCol !== '') {
        $select = "`{$teacherCol}` AS teacher_id, `{$classCol}` AS class_name";
        if ($gradeCol !== '') {
            $select .= ", `{$gradeCol}` AS grade_value";
        } else {
            $select .= ", NULL AS grade_value";
        }

        $sql = "SELECT {$select} FROM teacher_class_assignments";
        if ($statusCol !== '') {
            $sql .= " WHERE `{$statusCol}` <> 'archived'";
        }
        $sql .= " ORDER BY `{$teacherCol}` ASC";
        if ($gradeCol !== '') $sql .= ", `{$gradeCol}` ASC";
        $sql .= ", `{$classCol}` ASC";

        foreach ($pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC) as $row) {
            $teacherId = (int)($row['teacher_id'] ?? 0);
            $className = trim((string)($row['class_name'] ?? ''));
            $gradeValue = trim((string)($row['grade_value'] ?? ''));

            if ($teacherId <= 0 || $className === '') continue;

            // Hiển thị gọn: nếu tên lớp đã là 1/1, 4/1... thì giữ nguyên.
            // Nếu tên lớp chỉ là tên riêng, vẫn giữ đúng tên giáo viên đã khai báo.
            $label = $className;

            if (!isset($teacherClassMap[$teacherId])) {
                $teacherClassMap[$teacherId] = [];
            }
            if (!in_array($label, $teacherClassMap[$teacherId], true)) {
                $teacherClassMap[$teacherId][] = $label;
            }
        }
    }
} catch (Throwable $classMapError) {
    error_log('Admin teacher class map error: ' . $classMapError->getMessage());
}


$teacherReferralMap = [];
try {
    // V3.2: active teachers must have a stable referral code.
    $activeTeacherIds = $pdo->query(
        "SELECT id FROM users WHERE role = 'teacher' AND status = 'active' ORDER BY id"
    )->fetchAll(PDO::FETCH_COLUMN);

    foreach ($activeTeacherIds as $activeTeacherId) {
        esEnsureTeacherReferralCode($pdo, (int)$activeTeacherId);
    }

    foreach ($pdo->query(
        "SELECT teacher_id, referral_code, status
         FROM teacher_referral_codes
         ORDER BY teacher_id"
    )->fetchAll(PDO::FETCH_ASSOC) as $referralRow) {
        $teacherReferralMap[(int)$referralRow['teacher_id']] = $referralRow;
    }
} catch (Throwable $referralError) {
    error_log('Admin teacher referral map error: ' . $referralError->getMessage());
}

$teachers = $pdo->query(
    "SELECT
        u.id,
        u.full_name,
        u.username,
        u.email,
        u.status,
        u.last_login_at,
        u.created_at,
        tp.phone,
        tp.province_id,
        tp.school_id,
        tp.province,
        tp.school_name,
        cs.status AS school_status
     FROM users u
     LEFT JOIN teacher_profiles tp ON tp.user_id = u.id
     LEFT JOIN schools cs ON cs.id = tp.school_id
     WHERE u.role = 'teacher'
     ORDER BY
        u.status = 'pending' DESC,
        (cs.status = 'inactive' AND u.status = 'pending') DESC,
        u.status = 'active' DESC,
        u.full_name ASC,
        u.id ASC"
)->fetchAll(PDO::FETCH_ASSOC);

ob_start();
?>
<style>
.teachers-page{display:grid;gap:20px}
.teachers-head{display:flex;align-items:flex-start;justify-content:space-between;gap:14px;position:sticky;top:0;z-index:40;background:#f5f8fc;padding:12px 0 10px}
.teachers-head h1{margin:0;font-size:26px;color:#10213d}
.teachers-head p{margin:6px 0 0;color:#718096;font-size:14px}
.stat-pill{display:inline-flex;align-items:center;padding:9px 13px;border-radius:999px;background:#eef6ff;color:#1d4ed8;font-weight:800;font-size:13px}
.panel{background:#fff;border:1px solid #e6ebf2;border-radius:18px;box-shadow:0 5px 18px rgba(18,38,63,.05);overflow:hidden}
.panel-head{padding:17px 20px;border-bottom:1px solid #edf1f6}
.panel-head h2{margin:0;font-size:18px;color:#15233c}
.panel-head p{margin:5px 0 0;color:#7a8799;font-size:13px}
.notice{padding:12px 14px;border-radius:12px;font-size:13px}
.notice-ok{background:#ecfdf3;border:1px solid #bbf7d0;color:#166534}
.notice-error{background:#fff1f2;border:1px solid #fecdd3;color:#be123c}
.filter-bar{display:flex;align-items:end;gap:10px;flex-wrap:wrap;padding:14px 20px;border-bottom:1px solid #edf1f6;background:#f8fbff}
.filter-bar label{display:grid;gap:5px;color:#617085;font-size:12px;font-weight:700}
.filter-bar input,.filter-bar select{min-height:40px;border:1px solid #dbe3ee;border-radius:10px;padding:8px 10px;background:#fff;font:inherit}
.filter-bar input{min-width:250px}
.table-wrap{overflow:auto;max-height:calc(100vh - 330px);scrollbar-gutter:stable;border-top:1px solid #edf1f6}
.tbl{width:100%;border-collapse:collapse;min-width:1800px}
.tbl th,.tbl td{padding:12px 14px;border-bottom:1px solid #edf1f6;text-align:left;font-size:13px;vertical-align:middle}
.tbl th{background:#f8fafc;color:#617085;position:sticky;top:0;z-index:12;box-shadow:0 1px 0 #dbe3ee}
.top-scroll-wrap{overflow-x:auto;overflow-y:hidden;height:18px;background:#f8fbff;border-bottom:1px solid #edf1f6;position:sticky;top:76px;z-index:25}
.top-scroll-inner{height:1px}
.teacher-name{font-weight:800;color:#14243c}
.referral-code{display:inline-flex;align-items:center;padding:5px 8px;border-radius:8px;background:#f0fdf4;color:#166534;font-size:12px;font-weight:900;letter-spacing:.04em;white-space:nowrap}
.muted{color:#8491a4;font-size:12px}
.class-list{display:flex;gap:5px;flex-wrap:wrap;max-width:190px}
.class-chip{display:inline-flex;align-items:center;padding:4px 7px;border-radius:8px;background:#eef6ff;color:#1d4ed8;font-size:11px;font-weight:800}
.class-empty{color:#94a3b8;font-size:12px}
.badge{display:inline-flex;padding:4px 8px;border-radius:999px;font-size:11px;font-weight:800}
.active{background:#e9fbef;color:#26733b}
.locked{background:#fff1f2;color:#be123c}
.pending{background:#fff7ed;color:#c2410c}
.scope-form{display:grid;grid-template-columns:150px 220px auto;gap:7px;align-items:center}
.book-checks{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:6px 9px;border:1px solid #dbe3ee;border-radius:9px;background:#fff;min-height:36px}
.book-check{display:inline-flex;align-items:center;gap:5px;font-size:12px;color:#334155;white-space:nowrap}
.book-check input{margin:0}
.assignment-box{min-width:360px;display:grid;gap:8px}
.collaborator-box{min-width:230px;display:grid;gap:7px}.collaborator-toggle{display:flex;align-items:center;gap:7px;font-size:12px;white-space:nowrap}.collaborator-box select,.collaborator-box input[type=date],.collaborator-box input[type=text]{width:100%;min-height:34px;border:1px solid #dbe3ef;border-radius:8px;padding:6px 8px;background:#fff;font-size:12px}.collaborator-box input:disabled{background:#f4f6f9;color:#98a2b3}
.assignment-list{display:flex;flex-wrap:wrap;gap:6px}
.assignment-chip{display:inline-flex;align-items:center;gap:6px;padding:5px 7px;border:1px solid #dbe3ee;border-radius:9px;background:#f8fafc;font-size:11px;color:#334155}
.assignment-role{font-weight:800;color:#1d4ed8;text-transform:capitalize}
.assignment-remove{border:0;background:transparent;color:#be123c;font-weight:900;cursor:pointer;padding:0 2px}
.assignment-add{display:grid;grid-template-columns:120px 120px 95px auto;gap:5px;align-items:center}
.assignment-add select{min-height:34px;border:1px solid #dbe3ee;border-radius:8px;padding:5px 6px;background:#fff;font:inherit;font-size:11px;max-width:130px}
.assignment-add .btn{padding:7px 8px;font-size:11px}
.scope-form select{min-height:36px;border:1px solid #dbe3ee;border-radius:9px;padding:6px 8px;background:#fff;font:inherit;font-size:12px}
.btn{border:0;border-radius:9px;padding:8px 10px;font-weight:800;cursor:pointer;white-space:nowrap}
.btn-blue{background:#2563eb;color:#fff}
.btn-lock{background:#fff2e8;color:#b45309;border:1px solid #fed7aa}
.btn-unlock{background:#ecfdf3;color:#166534;border:1px solid #bbf7d0}
.btn-delete{background:#fff1f2;color:#be123c;border:1px solid #fecdd3}
.btn-reset{background:#eef6ff;color:#1d4ed8;border:1px solid #bfdbfe}
.reset-result{padding:16px 18px;background:#f1f7ff;border:1px solid #bfd8ff;border-radius:14px}
.reset-result h3{margin:0 0 10px;color:#124a89;font-size:16px}
.reset-result-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}
.reset-result-box{background:#fff;border:1px solid #dbe8f7;border-radius:10px;padding:10px}
.reset-result-box span{display:block;color:#7c8ba0;font-size:11px;margin-bottom:4px}
.reset-result-box strong{color:#15233c;word-break:break-word}
.reset-result-box.password strong{font-size:21px;letter-spacing:1px;color:#0d67c6}
.action-buttons{display:flex;align-items:center;gap:7px;flex-wrap:wrap}
.pending-badge{display:inline-flex;align-items:center;gap:5px;padding:4px 8px;border-radius:999px;background:#fff7ed;color:#c2410c;font-size:11px;font-weight:800;margin-top:5px}
.pending-box{min-width:430px;padding:10px;border:1px solid #fed7aa;border-radius:11px;background:#fffaf3}
.pending-box-title{font-weight:800;color:#9a3412;margin-bottom:7px}
.pending-box small{display:block;color:#7c5a3b;margin-bottom:8px}
.pending-grid{display:grid;grid-template-columns:minmax(170px,1fr) minmax(190px,1fr) auto;gap:7px;align-items:center}
.pending-grid input,.pending-grid select{min-height:36px;border:1px solid #dbe3ee;border-radius:9px;padding:6px 8px;background:#fff;font:inherit;font-size:12px}
.btn-approve{background:#16a34a;color:#fff}
.empty{padding:28px 20px;text-align:center;color:#7b8899}
@media(max-width:850px){.teachers-head{flex-direction:column}.scope-form{grid-template-columns:1fr}.filter-bar input{min-width:180px}}
</style>

<div class="teachers-page">
    <div class="teachers-head">
        <div>
            <h1>👩‍🏫 Quản lý giáo viên</h1>
            <p>Admin quản lý tài khoản, Tỉnh/Trường và bộ sách của giáo viên.</p>
        </div>
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;justify-content:flex-end">
            <a href="referral-report.php" class="btn btn-blue" style="text-decoration:none">🎯 Referral</a>
            <a href="contributions.php" class="btn btn-blue" style="text-decoration:none">📊 Thống kê đóng góp</a>
            <div class="stat-pill"><?= count($teachers) ?> giáo viên</div>
        </div>
    </div>

    <?php if ($flashError !== ''): ?>
        <div class="notice notice-error"><?= htmlspecialchars($flashError, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>
    <?php if ($flashSuccess !== ''): ?>
        <div class="notice notice-ok"><?= htmlspecialchars($flashSuccess, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>

    <?php if (is_array($tempPasswordResult)): ?>
        <div class="reset-result">
            <h3>🔑 Mật khẩu tạm của giáo viên</h3>
            <div class="reset-result-grid">
                <div class="reset-result-box">
                    <span>Giáo viên</span>
                    <strong><?= htmlspecialchars((string)$tempPasswordResult['name'], ENT_QUOTES, 'UTF-8') ?></strong>
                </div>
                <div class="reset-result-box">
                    <span>Tài khoản</span>
                    <strong><?= htmlspecialchars((string)$tempPasswordResult['username'], ENT_QUOTES, 'UTF-8') ?></strong>
                </div>
                <div class="reset-result-box password">
                    <span>Mật khẩu tạm</span>
                    <strong><?= htmlspecialchars((string)$tempPasswordResult['password'], ENT_QUOTES, 'UTF-8') ?></strong>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <section class="panel">
        <div class="panel-head">
            <h2>Danh sách giáo viên</h2>
            <p>Khóa tài khoản khi cần hoặc chuyển giáo viên sang trường khác.</p>
        </div>

        <div class="filter-bar">
            <label>
                Tìm giáo viên
                <input id="teacherSearch" type="search" placeholder="Tên, username, email, SĐT...">
            </label>
            <label>
                Tỉnh
                <select id="provinceFilter">
                    <option value="">Tất cả tỉnh</option>
                    <?php foreach ($provinces as $p): ?>
                        <option value="<?= (int)$p['id'] ?>"><?= htmlspecialchars((string)$p['name'], ENT_QUOTES, 'UTF-8') ?></option>
                    <?php endforeach; ?>
                </select>
            </label>
            <label>
                Trạng thái
                <select id="statusFilter">
                    <option value="">Tất cả trạng thái</option>
                    <option value="pending">Chờ duyệt</option>
                    <option value="active">Active</option>
                    <option value="locked">Đã khóa</option>
                </select>
            </label>
        </div>

        <?php if ($teachers === []): ?>
            <div class="empty">Chưa có tài khoản giáo viên.</div>
        <?php else: ?>
        <div class="top-scroll-wrap" id="teachersTopScroll" aria-label="Thanh cuộn ngang phía trên">
            <div class="top-scroll-inner" id="teachersTopScrollInner"></div>
        </div>
        <div class="table-wrap" id="teachersTableWrap">
            <table class="tbl" id="teachersTable">
                <thead>
                    <tr>
                        <th>Giáo viên</th>
                        <th>Mã referral</th>
                        <th>Liên hệ</th>
                        <th>Trường hiện tại</th>
                        <th>Lớp quản lý</th>
                        <th>Đổi Tỉnh / Trường</th>
                        <th>Bộ sách V3.1</th>
                        <th>Phân công nội dung V3.2</th>
                        <th>Cộng tác viên</th>
                        <th>Trạng thái</th>
                        <th>Đăng nhập cuối</th>
                        <th>Thao tác</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($teachers as $teacher): ?>
                    <tr
                        data-province="<?= (int)($teacher['province_id'] ?? 0) ?>"
                        data-status="<?= htmlspecialchars((string)$teacher['status'], ENT_QUOTES, 'UTF-8') ?>"
                    >
                        <td>
                            <div class="teacher-name"><?= htmlspecialchars((string)$teacher['full_name'], ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="muted">@<?= htmlspecialchars((string)$teacher['username'], ENT_QUOTES, 'UTF-8') ?> • ID <?= (int)$teacher['id'] ?></div>
                        </td>
                        <td>
                            <?php $referral = $teacherReferralMap[(int)$teacher['id']] ?? null; ?>
                            <?php if (!empty($referral['referral_code'])): ?>
                                <span class="referral-code"><?= htmlspecialchars((string)$referral['referral_code'], ENT_QUOTES, 'UTF-8') ?></span>
                                <?php if (($referral['status'] ?? 'active') !== 'active'): ?>
                                    <div class="muted" style="margin-top:4px">Inactive</div>
                                <?php endif; ?>
                            <?php elseif (($teacher['status'] ?? '') === 'pending'): ?>
                                <span class="muted">Sinh khi duyệt</span>
                            <?php else: ?>
                                <span class="muted">Chưa có mã</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div><?= htmlspecialchars((string)($teacher['phone'] ?? ''), ENT_QUOTES, 'UTF-8') ?></div>
                            <div class="muted"><?= htmlspecialchars((string)($teacher['email'] ?? ''), ENT_QUOTES, 'UTF-8') ?></div>
                        </td>
                        <td>
                            <?php if (!empty($teacher['school_name'])): ?>
                                <strong><?= htmlspecialchars((string)$teacher['school_name'], ENT_QUOTES, 'UTF-8') ?></strong>
                                <div class="muted"><?= htmlspecialchars((string)($teacher['province'] ?? ''), ENT_QUOTES, 'UTF-8') ?></div>
                                <?php if (($teacher['school_status'] ?? '') === 'inactive' && ($teacher['status'] ?? '') === 'pending'): ?>
                                    <span class="pending-badge">🕒 Chờ duyệt trường</span>
                                <?php endif; ?>
                            <?php else: ?>
                                <span class="muted">Chưa gán trường</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php $managedClasses = array_values(array_unique($teacherClassMap[(int)$teacher['id']] ?? [])); ?>
                            <?php if ($managedClasses !== []): ?>
                                <div class="class-list" title="<?= htmlspecialchars(implode(', ', $managedClasses), ENT_QUOTES, 'UTF-8') ?>">
                                    <?php foreach ($managedClasses as $className): ?>
                                        <span class="class-chip"><?= htmlspecialchars($className, ENT_QUOTES, 'UTF-8') ?></span>
                                    <?php endforeach; ?>
                                </div>
                                <div class="muted" style="margin-top:4px"><?= count($managedClasses) ?> lớp</div>
                            <?php else: ?>
                                <span class="class-empty">Chưa quản lý lớp</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php $isPendingSchool = (($teacher['school_status'] ?? '') === 'inactive' && ($teacher['status'] ?? '') === 'pending'); ?>
                            <?php if ($isPendingSchool): ?>
                                <form method="post" class="pending-box teacher-pending-form">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                                    <input type="hidden" name="action" value="approve_school">
                                    <input type="hidden" name="user_id" value="<?= (int)$teacher['id'] ?>">
                                    <input type="hidden" name="pending_school_id" value="<?= (int)$teacher['school_id'] ?>">

                                    <div class="pending-box-title">🕒 Chờ duyệt trường</div>
                                    <small>
                                        GV nhập: <strong><?= htmlspecialchars((string)$teacher['school_name'], ENT_QUOTES, 'UTF-8') ?></strong>
                                        • <?= htmlspecialchars((string)$teacher['province'], ENT_QUOTES, 'UTF-8') ?>
                                    </small>

                                    <div class="pending-grid">
                                        <input
                                            type="text"
                                            name="official_school_name"
                                            value="<?= htmlspecialchars((string)$teacher['school_name'], ENT_QUOTES, 'UTF-8') ?>"
                                            placeholder="Tên trường chính thức"
                                        >

                                        <select name="merge_school_id" class="pending-merge-school">
                                            <option value="">Tạo / duyệt với tên bên trái</option>
                                            <?php foreach ($schools as $s): ?>
                                                <?php if ((int)$s['province_id'] !== (int)($teacher['province_id'] ?? 0)) continue; ?>
                                                <option value="<?= (int)$s['id'] ?>">
                                                    Ghép vào: <?= htmlspecialchars((string)$s['name'], ENT_QUOTES, 'UTF-8') ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>

                                        <button class="btn btn-approve" type="submit">✓ Duyệt</button>
                                    </div>
                                </form>
                            <?php else: ?>
                                <form method="post" class="scope-form teacher-scope-form" id="scope-form-<?= (int)$teacher['id'] ?>">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                                    <input type="hidden" name="action" value="update_scope">
                                    <input type="hidden" name="user_id" value="<?= (int)$teacher['id'] ?>">

                                    <select name="province_id" class="scope-province" required>
                                        <option value="">Tỉnh</option>
                                        <?php foreach ($provinces as $p): ?>
                                            <option value="<?= (int)$p['id'] ?>"
                                                <?= (int)($teacher['province_id'] ?? 0) === (int)$p['id'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars((string)$p['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>

                                    <select name="school_id" class="scope-school" required>
                                        <option value="">Trường</option>
                                        <?php foreach ($schools as $s): ?>
                                            <option
                                                value="<?= (int)$s['id'] ?>"
                                                data-province-id="<?= (int)$s['province_id'] ?>"
                                                <?= (int)($teacher['school_id'] ?? 0) === (int)$s['id'] ? 'selected' : '' ?>
                                            >
                                                <?= htmlspecialchars((string)$s['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>

                                    <button class="btn btn-blue" type="submit">Lưu</button>
                                </form>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if (!$isPendingSchool): ?>
                                <?php $selectedBookIds = $teacherBookMap[(int)$teacher['id']] ?? []; ?>
                                <div class="book-checks" title="Chọn bộ sách giáo viên được phép sử dụng">
                                    <?php foreach ($books as $book): ?>
                                        <label class="book-check">
                                            <input type="checkbox" name="book_ids[]" value="<?= (int)$book['id'] ?>"
                                                form="scope-form-<?= (int)$teacher['id'] ?>"
                                                <?= in_array((int)$book['id'], $selectedBookIds, true) ? 'checked' : '' ?>>
                                            <span><?= htmlspecialchars((string)$book['name'], ENT_QUOTES, 'UTF-8') ?></span>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <span class="muted">Duyệt trường trước</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php $contentAssignments = $teacherContentAssignmentMap[(int)$teacher['id']] ?? []; ?>
                            <div class="assignment-box">
                                <?php if ($contentAssignments !== []): ?>
                                    <div class="assignment-list">
                                        <?php foreach ($contentAssignments as $ca): ?>
                                            <span class="assignment-chip">
                                                <span><?= htmlspecialchars((string)$ca['book_name'], ENT_QUOTES, 'UTF-8') ?></span>
                                                <span>•</span>
                                                <span><?= htmlspecialchars((string)$ca['level_name'], ENT_QUOTES, 'UTF-8') ?></span>
                                                <span>•</span>
                                                <span class="assignment-role"><?= htmlspecialchars((string)$ca['role'], ENT_QUOTES, 'UTF-8') ?></span>
                                                <form method="post" style="display:inline" onsubmit="return confirm('Xóa phân công này?');">
                                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                                                    <input type="hidden" name="action" value="remove_content_assignment">
                                                    <input type="hidden" name="user_id" value="<?= (int)$teacher['id'] ?>">
                                                    <input type="hidden" name="assignment_id" value="<?= (int)$ca['id'] ?>">
                                                    <button class="assignment-remove" type="submit" title="Xóa phân công">×</button>
                                                </form>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <span class="muted">Chưa có phân công V3.2</span>
                                <?php endif; ?>

                                <form method="post" class="assignment-add content-assignment-form">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                                    <input type="hidden" name="action" value="add_content_assignment">
                                    <input type="hidden" name="user_id" value="<?= (int)$teacher['id'] ?>">
                                    <select name="book_id" class="assignment-book" required>
                                        <option value="">Bộ sách</option>
                                        <?php foreach ($books as $book): ?>
                                            <option value="<?= (int)$book['id'] ?>"><?= htmlspecialchars((string)$book['name'], ENT_QUOTES, 'UTF-8') ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <select name="level_id" class="assignment-level" required disabled>
                                        <option value="">Level/Khối</option>
                                        <?php foreach ($levels as $level): ?>
                                            <option value="<?= (int)$level['id'] ?>" data-book-id="<?= (int)$level['book_id'] ?>">
                                                <?= htmlspecialchars((string)$level['name'], ENT_QUOTES, 'UTF-8') ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <select name="assignment_role" required>
                                        <option value="author">Author</option>
                                        <option value="reviewer">Reviewer</option>
                                        <option value="lead">Lead</option>
                                    </select>
                                    <button class="btn btn-blue" type="submit">+ Gán</button>
                                </form>
                            </div>
                        </td>
                        <td>
                            <?php $collab = $teacherCollaboratorMap[(int)$teacher['id']] ?? null; $collabActive = (($collab['status'] ?? '') === 'active'); $collabPolicy = (string)($collab['access_policy'] ?? 'standard'); ?>
                            <form method="post" class="collaborator-box">
                                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                                <input type="hidden" name="action" value="save_collaborator"><input type="hidden" name="user_id" value="<?= (int)$teacher['id'] ?>">
                                <label class="collaborator-toggle"><input type="checkbox" name="is_collaborator" value="1" <?= $collabActive ? 'checked' : '' ?>><strong>Cộng tác viên nội dung</strong></label>
                                <select name="access_policy" class="collaborator-policy"><option value="standard" <?= $collabPolicy === 'standard' ? 'selected' : '' ?>>Tiêu chuẩn</option><option value="free_until" <?= $collabPolicy === 'free_until' ? 'selected' : '' ?>>Miễn phí đến ngày</option><option value="admin_granted" <?= $collabPolicy === 'admin_granted' ? 'selected' : '' ?>>Admin cấp</option></select>
                                <input type="date" name="free_until" class="collaborator-free-until" value="<?= htmlspecialchars((string)($collab['free_until'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
                                <input type="text" name="collaborator_note" maxlength="500" placeholder="Ghi chú (không bắt buộc)" value="<?= htmlspecialchars((string)($collab['note'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
                                <button class="btn btn-blue" type="submit">Lưu CTV</button>
                            </form>
                        </td>
                        <td>
                            <?php
                                $teacherStatus = (string)($teacher['status'] ?? '');
                                $statusClass = $teacherStatus === 'active' ? 'active' : ($teacherStatus === 'pending' ? 'pending' : 'locked');
                                $statusLabel = $teacherStatus === 'active' ? 'Active' : ($teacherStatus === 'pending' ? 'Chờ duyệt' : 'Đã khóa');
                            ?>
                            <span class="badge <?= $statusClass ?>"><?= $statusLabel ?></span>
                        </td>
                        <td><?= htmlspecialchars((string)($teacher['last_login_at'] ?? 'Chưa đăng nhập'), ENT_QUOTES, 'UTF-8') ?></td>
                        <td>
                            <div class="action-buttons">
                                <?php if (($teacher['status'] ?? '') === 'pending' && ($teacher['school_status'] ?? '') !== 'inactive'): ?>
                                    <form method="post" onsubmit="return confirm('Duyệt tài khoản giáo viên này?');">
                                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                                        <input type="hidden" name="action" value="approve_teacher">
                                        <input type="hidden" name="user_id" value="<?= (int)$teacher['id'] ?>">
                                        <button class="btn btn-approve" type="submit">✓ Duyệt</button>
                                    </form>
                                <?php elseif (($teacher['status'] ?? '') === 'pending' && ($teacher['school_status'] ?? '') === 'inactive'): ?>
                                    <button class="btn btn-unlock" type="button" disabled title="Duyệt trường trước">Chờ duyệt</button>
                                <?php else: ?>
                                    <form method="post" onsubmit="return confirm('Cập nhật trạng thái tài khoản giáo viên này?');">
                                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                                        <input type="hidden" name="action" value="toggle_teacher">
                                        <input type="hidden" name="user_id" value="<?= (int)$teacher['id'] ?>">
                                        <button class="btn <?= ($teacher['status'] ?? '') === 'active' ? 'btn-lock' : 'btn-unlock' ?>" type="submit">
                                            <?= ($teacher['status'] ?? '') === 'active' ? '🔒 Khóa' : '🔓 Mở khóa' ?>
                                        </button>
                                    </form>
                                <?php endif; ?>

                                <form method="post"
                                      onsubmit="return confirm('Reset mật khẩu cho giáo viên <?= htmlspecialchars(addslashes((string)$teacher['full_name']), ENT_QUOTES, 'UTF-8') ?>? Mật khẩu hiện tại sẽ không còn sử dụng được.');">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                                    <input type="hidden" name="action" value="reset_teacher_password">
                                    <input type="hidden" name="user_id" value="<?= (int)$teacher['id'] ?>">
                                    <button class="btn btn-reset" type="submit">🔑 Reset MK</button>
                                </form>

                                <form method="post"
                                      onsubmit="return confirm('Xóa tài khoản giáo viên <?= htmlspecialchars(addslashes((string)$teacher['full_name']), ENT_QUOTES, 'UTF-8') ?>? Dữ liệu học tập của học sinh sẽ không bị xóa.');">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                                    <input type="hidden" name="action" value="delete_teacher">
                                    <input type="hidden" name="user_id" value="<?= (int)$teacher['id'] ?>">
                                    <button class="btn btn-delete" type="submit">🗑 Xóa</button>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </section>
</div>

<script>
(function () {
    const search = document.getElementById('teacherSearch');
    const provinceFilter = document.getElementById('provinceFilter');
    const statusFilter = document.getElementById('statusFilter');
    const rows = Array.from(document.querySelectorAll('#teachersTable tbody tr'));

    function applyFilters() {
        const q = search ? search.value.trim().toLowerCase() : '';
        const province = provinceFilter ? provinceFilter.value : '';
        const status = statusFilter ? statusFilter.value : '';

        rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            const rowProvince = (row.dataset.province || '').trim();
            const rowStatus = (row.dataset.status || '').trim();

            row.style.display =
                (q === '' || text.includes(q)) &&
                (province === '' || rowProvince === province) &&
                (status === '' || rowStatus === status)
                ? '' : 'none';
        });
    }

    if (search) search.addEventListener('input', applyFilters);
    if (provinceFilter) provinceFilter.addEventListener('change', applyFilters);
    if (statusFilter) statusFilter.addEventListener('change', applyFilters);

    document.querySelectorAll('.collaborator-box').forEach(form => {
        const policy = form.querySelector('.collaborator-policy');
        const freeUntil = form.querySelector('.collaborator-free-until');
        if (!policy || !freeUntil) return;
        const sync = () => { const needsDate = policy.value === 'free_until'; freeUntil.disabled = !needsDate; freeUntil.required = needsDate; if (!needsDate) freeUntil.value = ''; };
        policy.addEventListener('change', sync); sync();
    });

    document.querySelectorAll('.content-assignment-form').forEach(form => {
        const book = form.querySelector('.assignment-book');
        const level = form.querySelector('.assignment-level');
        if (!book || !level) return;

        const allLevelOptions = Array.from(level.querySelectorAll('option[data-book-id]'));
        function refreshLevels() {
            const selectedBook = book.value;
            level.value = '';
            allLevelOptions.forEach(option => {
                option.hidden = selectedBook === '' || option.dataset.bookId !== selectedBook;
            });
            level.disabled = selectedBook === '';
        }
        book.addEventListener('change', refreshLevels);
        refreshLevels();
    });

    document.querySelectorAll('.teacher-pending-form').forEach(form => {
        const merge = form.querySelector('.pending-merge-school');
        const official = form.querySelector('input[name="official_school_name"]');

        function refreshPendingMode() {
            const isMerge = merge && merge.value !== '';
            if (official) {
                official.disabled = isMerge;
                official.style.opacity = isMerge ? '.55' : '1';
            }
        }

        if (merge) merge.addEventListener('change', refreshPendingMode);
        refreshPendingMode();
    });

    document.querySelectorAll('.teacher-scope-form').forEach(form => {
        const province = form.querySelector('.scope-province');
        const school = form.querySelector('.scope-school');

        function refreshSchools() {
            const provinceId = province.value;
            let selectedVisible = false;

            Array.from(school.options).forEach((option, index) => {
                if (index === 0) return;
                const optionProvince = option.dataset.provinceId || '';
                option.hidden = provinceId !== '' && optionProvince !== provinceId;
                if (!option.hidden && option.selected) selectedVisible = true;
            });

            if (!selectedVisible && school.value !== '') {
                school.value = '';
            }
        }

        province.addEventListener('change', refreshSchools);
        refreshSchools();
    });
})();
</script>
<?php
?>

<script>
(function () {
    const wrap = document.getElementById('teachersTableWrap');
    const topScroll = document.getElementById('teachersTopScroll');
    const topInner = document.getElementById('teachersTopScrollInner');
    const table = document.getElementById('teachersTable');

    if (!wrap || !topScroll || !topInner || !table) return;

    let syncing = false;

    function syncWidth() {
        topInner.style.width = Math.max(table.scrollWidth, wrap.clientWidth) + 'px';
        topScroll.scrollLeft = wrap.scrollLeft;
    }

    topScroll.addEventListener('scroll', function () {
        if (syncing) return;
        syncing = true;
        wrap.scrollLeft = topScroll.scrollLeft;
        requestAnimationFrame(() => { syncing = false; });
    });

    wrap.addEventListener('scroll', function () {
        if (syncing) return;
        syncing = true;
        topScroll.scrollLeft = wrap.scrollLeft;
        requestAnimationFrame(() => { syncing = false; });
    });

    window.addEventListener('resize', syncWidth);
    window.addEventListener('load', syncWidth);
    setTimeout(syncWidth, 0);
})();
</script>

<?php
$content = ob_get_clean();
?>
<!DOCTYPE html>
<html lang="vi" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="theme-color" content="#2563eb">
    <title><?= htmlspecialchars($pageTitle . ' | EnglishSpeak', ENT_QUOTES, 'UTF-8') ?></title>
    <link rel="stylesheet" href="../assets/css/app.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/sidebar.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/topbar.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/cards.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/buttons.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/forms.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/tables.css?v=1.1">
    <link rel="stylesheet" href="../assets/css/utilities.css?v=1.1">
</head>
<body>
<div class="app-shell">
    <?php require __DIR__ . '/../partials/sidebar.php'; ?>
    <div class="sidebar-overlay" id="sidebarOverlay" aria-hidden="true"></div>
    <main class="main-area">
        <?php require __DIR__ . '/../partials/topbar.php'; ?>
        <section class="page-content"><?= $content ?></section>
        <?php require __DIR__ . '/../partials/footer.php'; ?>
    </main>
</div>
<script src="../assets/js/app.js?v=1.1"></script>
</body>
</html>
