<?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 = 'Tỉnh & Trường';
$pageSubtitle = 'Quản lý danh mục Tỉnh/Trường dùng chung cho giáo viên và học sinh';
$activeTeacherNav = 'locations';

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

$flashSuccess = '';
$flashError = '';
$importResults = [];

function esNormHeader(string $value): string
{
    $value = mb_strtolower(trim($value), 'UTF-8');
    $map = [
        'đ'=>'d','á'=>'a','à'=>'a','ả'=>'a','ã'=>'a','ạ'=>'a','ă'=>'a','ắ'=>'a','ằ'=>'a','ẳ'=>'a','ẵ'=>'a','ặ'=>'a',
        'â'=>'a','ấ'=>'a','ầ'=>'a','ẩ'=>'a','ẫ'=>'a','ậ'=>'a','é'=>'e','è'=>'e','ẻ'=>'e','ẽ'=>'e','ẹ'=>'e','ê'=>'e',
        'ế'=>'e','ề'=>'e','ể'=>'e','ễ'=>'e','ệ'=>'e','í'=>'i','ì'=>'i','ỉ'=>'i','ĩ'=>'i','ị'=>'i','ó'=>'o','ò'=>'o',
        'ỏ'=>'o','õ'=>'o','ọ'=>'o','ô'=>'o','ố'=>'o','ồ'=>'o','ổ'=>'o','ỗ'=>'o','ộ'=>'o','ơ'=>'o','ớ'=>'o','ờ'=>'o',
        'ở'=>'o','ỡ'=>'o','ợ'=>'o','ú'=>'u','ù'=>'u','ủ'=>'u','ũ'=>'u','ụ'=>'u','ư'=>'u','ứ'=>'u','ừ'=>'u','ử'=>'u',
        'ữ'=>'u','ự'=>'u','ý'=>'y','ỳ'=>'y','ỷ'=>'y','ỹ'=>'y','ỵ'=>'y'
    ];
    return preg_replace('/[^a-z0-9]+/', '', strtr($value, $map)) ?? '';
}

function esReadSpreadsheet(string $tmpName, string $ext): array
{
    $rows = [];

    if ($ext === 'csv') {
        $fh = fopen($tmpName, 'rb');
        if (!$fh) throw new RuntimeException('Không đọc được file CSV.');
        while (($data = fgetcsv($fh)) !== false) {
            $rows[] = $data;
        }
        fclose($fh);
        return $rows;
    }

    if (!class_exists('ZipArchive')) {
        throw new RuntimeException('PHP chưa bật ZipArchive nên chưa đọc được file .xlsx.');
    }

    $zip = new ZipArchive();
    if ($zip->open($tmpName) !== true) {
        throw new RuntimeException('Không mở được file Excel.');
    }

    $shared = [];
    $sharedXml = $zip->getFromName('xl/sharedStrings.xml');
    if ($sharedXml !== false) {
        $xml = simplexml_load_string($sharedXml);
        if ($xml) {
            foreach ($xml->si as $si) {
                $parts = [];
                if (isset($si->t)) $parts[] = (string)$si->t;
                foreach ($si->r as $r) $parts[] = (string)$r->t;
                $shared[] = implode('', $parts);
            }
        }
    }

    $sheetXml = $zip->getFromName('xl/worksheets/sheet1.xml');
    $zip->close();

    if ($sheetXml === false) {
        throw new RuntimeException('Không tìm thấy Sheet1 trong file Excel.');
    }

    $xml = simplexml_load_string($sheetXml);
    if (!$xml) throw new RuntimeException('File Excel không hợp lệ.');

    foreach ($xml->sheetData->row as $row) {
        $out = [];
        foreach ($row->c as $cell) {
            $ref = (string)$cell['r'];
            preg_match('/^[A-Z]+/', $ref, $m);
            $letters = $m[0] ?? 'A';
            $col = 0;
            for ($i = 0; $i < strlen($letters); $i++) {
                $col = $col * 26 + (ord($letters[$i]) - 64);
            }
            $col--;

            $type = (string)$cell['t'];
            if ($type === 's') {
                $value = $shared[(int)$cell->v] ?? '';
            } elseif ($type === 'inlineStr') {
                $value = (string)$cell->is->t;
            } else {
                $value = (string)$cell->v;
            }
            $out[$col] = trim((string)$value);
        }

        if ($out !== []) {
            ksort($out);
            $max = max(array_keys($out));
            $rows[] = array_map(static fn($i) => $out[$i] ?? '', range(0, $max));
        }
    }

    return $rows;
}

function esStatus(string $value): string
{
    $value = strtolower(trim($value));
    return in_array($value, ['inactive', 'ngung', 'ngừng', '0'], true) ? 'inactive' : 'active';
}

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 === 'add_province') {
            $name = trim((string)($_POST['province_name'] ?? ''));
            $code = trim((string)($_POST['province_code'] ?? ''));

            if ($name === '') throw new RuntimeException('Vui lòng nhập tên Tỉnh.');

            $stmt = $pdo->prepare(
                "INSERT INTO provinces (name, code, status)
                 VALUES (:name, :code, 'active')
                 ON DUPLICATE KEY UPDATE
                    code = CASE WHEN VALUES(code) IS NULL OR VALUES(code) = '' THEN code ELSE VALUES(code) END,
                    status = 'active',
                    updated_at = NOW()"
            );
            $stmt->execute(['name' => $name, 'code' => $code !== '' ? $code : null]);

            $flashSuccess = 'Đã lưu Tỉnh.';
        } elseif ($action === 'add_school') {
            $provinceId = max(0, (int)($_POST['province_id'] ?? 0));
            $name = trim((string)($_POST['school_name'] ?? ''));
            $code = trim((string)($_POST['school_code'] ?? ''));

            if ($provinceId <= 0) throw new RuntimeException('Vui lòng chọn Tỉnh.');
            if ($name === '') throw new RuntimeException('Vui lòng nhập tên Trường.');

            $stmt = $pdo->prepare(
                "INSERT INTO schools (province_id, name, school_code, status)
                 VALUES (:province_id, :name, :school_code, 'active')
                 ON DUPLICATE KEY UPDATE
                    school_code = CASE WHEN VALUES(school_code) IS NULL OR VALUES(school_code) = '' THEN school_code ELSE VALUES(school_code) END,
                    status = 'active',
                    updated_at = NOW()"
            );
            $stmt->execute([
                'province_id' => $provinceId,
                'name' => $name,
                'school_code' => $code !== '' ? $code : null,
            ]);

            $flashSuccess = 'Đã lưu Trường.';
        } elseif ($action === 'update_province') {
            $id = max(0, (int)($_POST['province_id'] ?? 0));
            $name = trim((string)($_POST['province_name'] ?? ''));
            $code = trim((string)($_POST['province_code'] ?? ''));

            if ($id <= 0) throw new RuntimeException('Tỉnh không hợp lệ.');
            if ($name === '') throw new RuntimeException('Tên Tỉnh không được để trống.');

            $oldStmt = $pdo->prepare("SELECT name FROM provinces WHERE id = :id LIMIT 1");
            $oldStmt->execute(['id' => $id]);
            $oldName = $oldStmt->fetchColumn();
            if ($oldName === false) throw new RuntimeException('Không tìm thấy Tỉnh.');

            $dupStmt = $pdo->prepare("SELECT id FROM provinces WHERE name = :name AND id <> :id LIMIT 1");
            $dupStmt->execute(['name' => $name, 'id' => $id]);
            if ($dupStmt->fetchColumn()) {
                throw new RuntimeException('Tên Tỉnh này đã tồn tại.');
            }

            $pdo->beginTransaction();
            try {
                $stmt = $pdo->prepare(
                    "UPDATE provinces
                     SET name = :name,
                         code = :code,
                         updated_at = NOW()
                     WHERE id = :id"
                );
                $stmt->execute([
                    'name' => $name,
                    'code' => $code !== '' ? $code : null,
                    'id' => $id,
                ]);

                // Đồng bộ cột tên tỉnh dạng chữ trong hồ sơ giáo viên.
                $sync = $pdo->prepare(
                    "UPDATE teacher_profiles
                     SET province = :name,
                         updated_at = NOW()
                     WHERE province_id = :id"
                );
                $sync->execute(['name' => $name, 'id' => $id]);

                $pdo->commit();
                $flashSuccess = 'Đã cập nhật tên Tỉnh.';
            } catch (Throwable $updateError) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                throw $updateError;
            }
        } elseif ($action === 'toggle_province') {
            $id = max(0, (int)($_POST['province_id'] ?? 0));
            if ($id <= 0) throw new RuntimeException('Tỉnh không hợp lệ.');

            $stmt = $pdo->prepare(
                "UPDATE provinces
                 SET status = IF(status = 'active', 'inactive', 'active'),
                     updated_at = NOW()
                 WHERE id = :id"
            );
            $stmt->execute(['id' => $id]);
            $flashSuccess = 'Đã cập nhật trạng thái Tỉnh.';
        } elseif ($action === 'update_school') {
            $id = max(0, (int)($_POST['school_id'] ?? 0));
            $provinceId = max(0, (int)($_POST['province_id'] ?? 0));
            $name = trim((string)($_POST['school_name'] ?? ''));
            $code = trim((string)($_POST['school_code'] ?? ''));

            if ($id <= 0) throw new RuntimeException('Trường không hợp lệ.');
            if ($provinceId <= 0) throw new RuntimeException('Vui lòng chọn Tỉnh.');
            if ($name === '') throw new RuntimeException('Tên Trường không được để trống.');

            $schoolStmt = $pdo->prepare("SELECT id FROM schools WHERE id = :id LIMIT 1");
            $schoolStmt->execute(['id' => $id]);
            if (!$schoolStmt->fetchColumn()) {
                throw new RuntimeException('Không tìm thấy Trường.');
            }

            $provinceStmt = $pdo->prepare("SELECT id, name FROM provinces WHERE id = :id LIMIT 1");
            $provinceStmt->execute(['id' => $provinceId]);
            $province = $provinceStmt->fetch(PDO::FETCH_ASSOC);
            if (!$province) {
                throw new RuntimeException('Không tìm thấy Tỉnh.');
            }

            $dupStmt = $pdo->prepare(
                "SELECT id FROM schools
                 WHERE province_id = :province_id
                   AND name = :name
                   AND id <> :id
                 LIMIT 1"
            );
            $dupStmt->execute([
                'province_id' => $provinceId,
                'name' => $name,
                'id' => $id,
            ]);
            if ($dupStmt->fetchColumn()) {
                throw new RuntimeException('Tên Trường này đã tồn tại trong Tỉnh đã chọn.');
            }

            $pdo->beginTransaction();
            try {
                $update = $pdo->prepare(
                    "UPDATE schools
                     SET province_id = :province_id,
                         name = :name,
                         school_code = :school_code,
                         updated_at = NOW()
                     WHERE id = :id"
                );
                $update->execute([
                    'province_id' => $provinceId,
                    'name' => $name,
                    'school_code' => $code !== '' ? $code : null,
                    'id' => $id,
                ]);

                // Đồng bộ tên/phạm vi dạng chữ trong hồ sơ giáo viên đang gắn với school_id này.
                $sync = $pdo->prepare(
                    "UPDATE teacher_profiles
                     SET province_id = :province_id,
                         province = :province_name,
                         school_name = :school_name,
                         updated_at = NOW()
                     WHERE school_id = :school_id"
                );
                $sync->execute([
                    'province_id' => $provinceId,
                    'province_name' => (string)$province['name'],
                    'school_name' => $name,
                    'school_id' => $id,
                ]);

                $pdo->commit();
                $flashSuccess = 'Đã cập nhật Trường.';
            } catch (Throwable $updateError) {
                if ($pdo->inTransaction()) $pdo->rollBack();
                throw $updateError;
            }
        } elseif ($action === 'toggle_school') {
            $id = max(0, (int)($_POST['school_id'] ?? 0));
            if ($id <= 0) throw new RuntimeException('Trường không hợp lệ.');

            $stmt = $pdo->prepare(
                "UPDATE schools
                 SET status = IF(status = 'active', 'inactive', 'active'),
                     updated_at = NOW()
                 WHERE id = :id"
            );
            $stmt->execute(['id' => $id]);
            $flashSuccess = 'Đã cập nhật trạng thái Trường.';
        } elseif ($action === 'import_locations') {
            if (empty($_FILES['location_file']) || !is_array($_FILES['location_file'])) {
                throw new RuntimeException('Hãy chọn file danh mục Tỉnh/Trường.');
            }

            $upload = $_FILES['location_file'];
            if ((int)($upload['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
                throw new RuntimeException('Không thể tải file lên.');
            }

            $originalName = (string)($upload['name'] ?? '');
            $tmpName = (string)($upload['tmp_name'] ?? '');
            $ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

            if (!in_array($ext, ['xlsx', 'csv'], true)) {
                throw new RuntimeException('Chỉ hỗ trợ file .xlsx hoặc .csv.');
            }

            $sheetRows = esReadSpreadsheet($tmpName, $ext);
            if ($sheetRows === []) throw new RuntimeException('File không có dữ liệu.');

            $headers = array_map('esNormHeader', array_map('strval', $sheetRows[0]));
            $aliases = [
                'province' => ['tinh', 'province', 'provincename'],
                'province_code' => ['matinh', 'provincecode', 'codeprovince'],
                'school' => ['truong', 'school', 'schoolname', 'tentruong'],
                'school_code' => ['matruong', 'schoolcode', 'codeschool'],
                'status' => ['trangthai', 'status'],
            ];

            $indexes = [];
            foreach ($aliases as $field => $names) {
                foreach ($headers as $i => $header) {
                    if (in_array($header, $names, true)) {
                        $indexes[$field] = $i;
                        break;
                    }
                }
            }

            if (!isset($indexes['province'])) {
                throw new RuntimeException('File phải có cột Tỉnh.');
            }

            $pdo->beginTransaction();

            $provinceStmt = $pdo->prepare(
                "INSERT INTO provinces (name, code, status)
                 VALUES (:name, :code, :status)
                 ON DUPLICATE KEY UPDATE
                    code = CASE WHEN VALUES(code) IS NULL OR VALUES(code) = '' THEN code ELSE VALUES(code) END,
                    status = VALUES(status),
                    updated_at = NOW()"
            );

            $provinceIdStmt = $pdo->prepare("SELECT id FROM provinces WHERE name = :name LIMIT 1");

            $schoolStmt = $pdo->prepare(
                "INSERT INTO schools (province_id, name, school_code, status)
                 VALUES (:province_id, :name, :school_code, :status)
                 ON DUPLICATE KEY UPDATE
                    school_code = CASE WHEN VALUES(school_code) IS NULL OR VALUES(school_code) = '' THEN school_code ELSE VALUES(school_code) END,
                    status = VALUES(status),
                    updated_at = NOW()"
            );

            $created = 0;
            $skipped = 0;

            foreach (array_slice($sheetRows, 1) as $rowIndex => $data) {
                $get = static fn(string $field) =>
                    isset($indexes[$field]) ? trim((string)($data[$indexes[$field]] ?? '')) : '';

                $provinceName = $get('province');
                $provinceCode = $get('province_code');
                $schoolName = $get('school');
                $schoolCode = $get('school_code');
                $status = esStatus($get('status'));

                if ($provinceName === '') {
                    $skipped++;
                    $importResults[] = ['row' => $rowIndex + 2, 'province' => '', 'school' => $schoolName, 'status' => 'Bỏ qua: thiếu Tỉnh', 'ok' => false];
                    continue;
                }

                $provinceStmt->execute([
                    'name' => $provinceName,
                    'code' => $provinceCode !== '' ? $provinceCode : null,
                    'status' => $status,
                ]);

                $provinceIdStmt->execute(['name' => $provinceName]);
                $provinceId = (int)$provinceIdStmt->fetchColumn();

                if ($provinceId <= 0) {
                    throw new RuntimeException("Không xác định được Tỉnh ở dòng " . ($rowIndex + 2) . '.');
                }

                if ($schoolName !== '') {
                    $schoolStmt->execute([
                        'province_id' => $provinceId,
                        'name' => $schoolName,
                        'school_code' => $schoolCode !== '' ? $schoolCode : null,
                        'status' => $status,
                    ]);
                }

                $created++;
                $importResults[] = [
                    'row' => $rowIndex + 2,
                    'province' => $provinceName,
                    'school' => $schoolName,
                    'status' => $schoolName !== '' ? 'Đã lưu Tỉnh + Trường' : 'Đã lưu Tỉnh',
                    'ok' => true
                ];
            }

            $pdo->commit();
            $flashSuccess = "Đã xử lý {$created} dòng" . ($skipped > 0 ? ", bỏ qua {$skipped} dòng." : '.');
        }

        $_SESSION['teacher_csrf_token'] = bin2hex(random_bytes(32));
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        error_log('Admin locations error: ' . $e->getMessage());
        $flashError = $e instanceof RuntimeException
            ? $e->getMessage()
            : 'Không thể cập nhật danh mục Tỉnh/Trường.';
    }
}

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

$schools = $pdo->query(
    "SELECT
        s.id,
        s.name,
        s.school_code,
        s.status,
        s.created_at,
        p.id AS province_id,
        p.name AS province_name
     FROM schools s
     INNER JOIN provinces p ON p.id = s.province_id
     ORDER BY p.name ASC, s.status = 'active' DESC, s.name ASC"
)->fetchAll(PDO::FETCH_ASSOC);

ob_start();
?>
<style>
.locations-page{display:grid;gap:20px}
.locations-head h1{margin:0;font-size:26px;color:#10213d}
.locations-head p{margin:6px 0 0;color:#718096;font-size:14px}
.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}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:14px;padding:18px 20px}
.box{border:1px solid #e4eaf2;border-radius:14px;padding:15px;background:#fbfdff}
.box h3{margin:0 0 12px;color:#17324d}
.form-row{display:grid;grid-template-columns:1fr 160px auto;gap:9px}
.form-row select,.form-row input{min-height:40px;border:1px solid #dbe3ee;border-radius:10px;padding:8px 10px;background:#fff;font:inherit}
.btn{border:0;border-radius:10px;padding:9px 12px;font-weight:800;cursor:pointer}
.btn-blue{background:#2563eb;color:#fff}
.btn-orange{background:#fff2e8;color:#b45309;border:1px solid #fed7aa}
.btn-green{background:#ecfdf3;color:#166534;border:1px solid #bbf7d0}
.btn-edit{background:#eff6ff;color:#1d4ed8;border:1px solid #bfdbfe}
.import-box{padding:18px 20px}
.import-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
.import-row input[type=file]{flex:1;min-width:280px;padding:12px;border:1px dashed #b8c8dc;border-radius:10px}
.table-wrap{overflow:auto}
.tbl{width:100%;border-collapse:collapse;min-width:760px}
.tbl th,.tbl td{padding:11px 14px;border-bottom:1px solid #edf1f6;text-align:left;font-size:13px}
.tbl th{background:#f8fafc;color:#617085}
.badge{display:inline-flex;padding:4px 8px;border-radius:999px;font-size:11px;font-weight:800}
.active{background:#e9fbef;color:#26733b}
.inactive{background:#f1f3f5;color:#68717d}
.actions{display:flex;gap:6px}
.result{margin:0 20px 18px;border:1px solid #dbe7f2;border-radius:12px;overflow:auto}
@media(max-width:850px){.grid2{grid-template-columns:1fr}.form-row{grid-template-columns:1fr}.import-row input[type=file]{min-width:100%}}
</style>

<div class="locations-page">
    <div class="locations-head">
        <h1>🏫 Tỉnh &amp; Trường</h1>
        <p>Danh mục dùng chung cho đăng ký giáo viên và phạm vi quản lý học sinh.</p>
    </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>Thêm nhanh</h2>
            <p>Admin có thể thêm từng Tỉnh hoặc từng Trường.</p>
        </div>

        <div class="grid2">
            <div class="box">
                <h3>➕ Thêm Tỉnh</h3>
                <form method="post">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="action" value="add_province">
                    <div class="form-row">
                        <input type="text" name="province_name" placeholder="Tên tỉnh" required>
                        <input type="text" name="province_code" placeholder="Mã tỉnh">
                        <button class="btn btn-blue" type="submit">Lưu Tỉnh</button>
                    </div>
                </form>
            </div>

            <div class="box">
                <h3>➕ Thêm Trường</h3>
                <form method="post">
                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                    <input type="hidden" name="action" value="add_school">
                    <div class="form-row">
                        <select name="province_id" required>
                            <option value="">Chọn Tỉnh</option>
                            <?php foreach ($provinces as $province): ?>
                                <?php if (($province['status'] ?? '') === 'active'): ?>
                                    <option value="<?= (int)$province['id'] ?>"><?= htmlspecialchars((string)$province['name'], ENT_QUOTES, 'UTF-8') ?></option>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </select>
                        <input type="text" name="school_name" placeholder="Tên trường" required>
                        <button class="btn btn-blue" type="submit">Lưu Trường</button>
                    </div>
                    <div style="margin-top:9px;">
                        <input type="text" name="school_code" placeholder="Mã trường (không bắt buộc)" style="width:100%;min-height:40px;border:1px solid #dbe3ee;border-radius:10px;padding:8px 10px;">
                    </div>
                </form>
            </div>
        </div>
    </section>

    <section class="panel">
        <div class="panel-head">
            <h2>📥 Import Tỉnh &amp; Trường</h2>
            <p>Dùng khi cần nhập hàng loạt danh mục từ Excel/CSV.</p>
        </div>
        <div class="import-box">
            <div style="margin-bottom:12px;">
                <a href="mau_import_tinh_truong.xlsx" download class="btn btn-green" style="display:inline-block;text-decoration:none;">⬇️ Tải tệp mẫu</a>
                <span style="margin-left:8px;color:#64748b;font-size:12.5px;">Cột: Tỉnh, Mã tỉnh, Trường, Mã trường, Trạng thái.</span>
            </div>
            <form method="post" enctype="multipart/form-data" onsubmit="return confirm('Import danh mục Tỉnh/Trườ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="import_locations">
                <div class="import-row">
                    <input type="file" name="location_file" accept=".xlsx,.csv" required>
                    <button class="btn btn-blue" type="submit">📥 Import</button>
                </div>
            </form>
        </div>

        <?php if ($importResults !== []): ?>
            <div class="result">
                <table class="tbl">
                    <thead><tr><th>Dòng</th><th>Tỉnh</th><th>Trường</th><th>Kết quả</th></tr></thead>
                    <tbody>
                    <?php foreach ($importResults as $r): ?>
                        <tr>
                            <td><?= (int)$r['row'] ?></td>
                            <td><?= htmlspecialchars((string)$r['province'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars((string)$r['school'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td style="font-weight:700;color:<?= !empty($r['ok']) ? '#166534' : '#9a3412' ?>"><?= htmlspecialchars((string)$r['status'], ENT_QUOTES, 'UTF-8') ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </section>

    <section class="panel">
        <div class="panel-head">
            <h2>Danh sách Tỉnh</h2>
        </div>
        <div class="table-wrap">
            <table class="tbl">
                <thead><tr><th>Tỉnh</th><th>Mã</th><th>Trạng thái</th><th>Thao tác</th></tr></thead>
                <tbody>
                <?php foreach ($provinces as $p): ?>
                    <tr>
                        <td><strong><?= htmlspecialchars((string)$p['name'], ENT_QUOTES, 'UTF-8') ?></strong></td>
                        <td><?= htmlspecialchars((string)($p['code'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                        <td><span class="badge <?= ($p['status'] ?? '') === 'active' ? 'active' : 'inactive' ?>"><?= htmlspecialchars((string)$p['status'], ENT_QUOTES, 'UTF-8') ?></span></td>
                        <td>
                            <div class="actions">
                                <button
                                    class="btn btn-edit"
                                    type="button"
                                    onclick='editProvince(
                                        <?= (int)$p["id"] ?>,
                                        <?= json_encode((string)$p["name"], JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE) ?>,
                                        <?= json_encode((string)($p["code"] ?? ""), JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE) ?>
                                    )'>✏️ Sửa</button>
                                <form method="post">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                                    <input type="hidden" name="action" value="toggle_province">
                                    <input type="hidden" name="province_id" value="<?= (int)$p['id'] ?>">
                                    <button class="btn <?= ($p['status'] ?? '') === 'active' ? 'btn-orange' : 'btn-green' ?>" type="submit">
                                        <?= ($p['status'] ?? '') === 'active' ? 'Ngừng' : 'Kích hoạt' ?>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </section>

    <section class="panel" id="editProvincePanel" style="display:none;">
        <div class="panel-head">
            <h2>✏️ Sửa Tỉnh</h2>
            <p>Giữ nguyên ID của Tỉnh; các Trường và giáo viên vẫn giữ đúng liên kết.</p>
        </div>
        <div style="padding:18px 20px;">
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                <input type="hidden" name="action" value="update_province">
                <input type="hidden" name="province_id" id="editProvinceId">
                <div class="form-row">
                    <input type="text" name="province_name" id="editProvinceName" placeholder="Tên tỉnh" required>
                    <input type="text" name="province_code" id="editProvinceCode" placeholder="Mã tỉnh">
                    <div class="actions">
                        <button class="btn btn-blue" type="submit">Lưu</button>
                        <button class="btn btn-green" type="button" onclick="cancelEditProvince()">Hủy</button>
                    </div>
                </div>
            </form>
        </div>
    </section>

    <section class="panel" id="editSchoolPanel" style="display:none;">
        <div class="panel-head">
            <h2>✏️ Sửa Trường</h2>
            <p>Giữ nguyên ID của Trường; giáo viên và dữ liệu đang liên kết không bị mất.</p>
        </div>
        <div style="padding:18px 20px;">
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                <input type="hidden" name="action" value="update_school">
                <input type="hidden" name="school_id" id="editSchoolId">
                <div class="form-row">
                    <select name="province_id" id="editSchoolProvinceId" required>
                        <option value="">Chọn Tỉnh</option>
                        <?php foreach ($provinces as $province): ?>
                            <option value="<?= (int)$province['id'] ?>"><?= htmlspecialchars((string)$province['name'], ENT_QUOTES, 'UTF-8') ?></option>
                        <?php endforeach; ?>
                    </select>
                    <input type="text" name="school_name" id="editSchoolName" placeholder="Tên trường" required>
                    <div class="actions">
                        <button class="btn btn-blue" type="submit">Lưu</button>
                        <button class="btn btn-green" type="button" onclick="cancelEditSchool()">Hủy</button>
                    </div>
                </div>
                <div style="margin-top:9px;">
                    <input type="text" name="school_code" id="editSchoolCode" placeholder="Mã trường (không bắt buộc)" style="width:100%;min-height:40px;border:1px solid #dbe3ee;border-radius:10px;padding:8px 10px;">
                </div>
            </form>
        </div>
    </section>

    <section class="panel">
        <div class="panel-head">
            <h2>Danh sách Trường</h2>
        </div>
        <div class="table-wrap">
            <table class="tbl">
                <thead><tr><th>Tỉnh</th><th>Trường</th><th>Mã trường</th><th>Trạng thái</th><th>Thao tác</th></tr></thead>
                <tbody>
                <?php foreach ($schools as $s): ?>
                    <tr>
                        <td><?= htmlspecialchars((string)$s['province_name'], ENT_QUOTES, 'UTF-8') ?></td>
                        <td><strong><?= htmlspecialchars((string)$s['name'], ENT_QUOTES, 'UTF-8') ?></strong></td>
                        <td><?= htmlspecialchars((string)($s['school_code'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                        <td><span class="badge <?= ($s['status'] ?? '') === 'active' ? 'active' : 'inactive' ?>"><?= htmlspecialchars((string)$s['status'], ENT_QUOTES, 'UTF-8') ?></span></td>
                        <td>
                            <div class="actions">
                                <button
                                    class="btn btn-edit"
                                    type="button"
                                    onclick='editSchool(
                                        <?= (int)$s["id"] ?>,
                                        <?= (int)$s["province_id"] ?>,
                                        <?= json_encode((string)$s["name"], JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE) ?>,
                                        <?= json_encode((string)($s["school_code"] ?? ""), JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE) ?>
                                    )'>✏️ Sửa</button>
                                <form method="post">
                                    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars((string)$_SESSION['teacher_csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
                                    <input type="hidden" name="action" value="toggle_school">
                                    <input type="hidden" name="school_id" value="<?= (int)$s['id'] ?>">
                                    <button class="btn <?= ($s['status'] ?? '') === 'active' ? 'btn-orange' : 'btn-green' ?>" type="submit">
                                        <?= ($s['status'] ?? '') === 'active' ? 'Ngừng' : 'Kích hoạt' ?>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </section>
</div>
<script>
function editProvince(id, name, code) {
    document.getElementById('editProvinceId').value = id;
    document.getElementById('editProvinceName').value = name || '';
    document.getElementById('editProvinceCode').value = code || '';
    const panel = document.getElementById('editProvincePanel');
    panel.style.display = 'block';
    panel.scrollIntoView({behavior:'smooth', block:'center'});
    document.getElementById('editProvinceName').focus();
}
function cancelEditProvince() {
    document.getElementById('editProvincePanel').style.display = 'none';
}
function editSchool(id, provinceId, name, code) {
    document.getElementById('editSchoolId').value = id;
    document.getElementById('editSchoolProvinceId').value = String(provinceId || '');
    document.getElementById('editSchoolName').value = name || '';
    document.getElementById('editSchoolCode').value = code || '';
    const panel = document.getElementById('editSchoolPanel');
    panel.style.display = 'block';
    panel.scrollIntoView({behavior:'smooth', block:'center'});
    document.getElementById('editSchoolName').focus();
}
function cancelEditSchool() {
    document.getElementById('editSchoolPanel').style.display = 'none';
}
</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>
