<?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 = '';

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 === '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));

            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'],
            ]);

            $flashSuccess = 'Đã cập nhật Tỉnh/Trường của giáo viên.';
        }

        $_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);

$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
     FROM users u
     LEFT JOIN teacher_profiles tp ON tp.user_id = u.id
     WHERE u.role = 'teacher'
     ORDER BY 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}
.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}
.tbl{width:100%;border-collapse:collapse;min-width:1180px}
.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}
.teacher-name{font-weight:800;color:#14243c}
.muted{color:#8491a4;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}
.scope-form{display:grid;grid-template-columns:150px 220px auto;gap:7px;align-items:center}
.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}
.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, trạng thái và phạm vi Tỉnh/Trường của giáo viên.</p>
        </div>
        <div class="stat-pill"><?= count($teachers) ?> giáo viên</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; ?>

    <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="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="table-wrap">
            <table class="tbl" id="teachersTable">
                <thead>
                    <tr>
                        <th>Giáo viên</th>
                        <th>Liên hệ</th>
                        <th>Trường hiện tại</th>
                        <th>Đổi Tỉnh / Trường</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>
                            <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 else: ?>
                                <span class="muted">Chưa gán trường</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <form method="post" class="scope-form teacher-scope-form">
                                <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>
                        </td>
                        <td>
                            <span class="badge <?= ($teacher['status'] ?? '') === 'active' ? 'active' : 'locked' ?>">
                                <?= ($teacher['status'] ?? '') === 'active' ? 'Active' : 'Đã khóa' ?>
                            </span>
                        </td>
                        <td><?= htmlspecialchars((string)($teacher['last_login_at'] ?? 'Chưa đăng nhập'), ENT_QUOTES, 'UTF-8') ?></td>
                        <td>
                            <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>
                        </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('.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
$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>
