<?php
declare(strict_types=1);

session_start();

if (empty($_SESSION['student_id'])) {
    header('Location: student-login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';

/** @return array<string, array<string, mixed>> */
function rankingColumns(PDO $pdo, string $table): array
{
    static $cache = [];
    if (isset($cache[$table])) {
        return $cache[$table];
    }

    try {
        $safeTable = str_replace('`', '``', $table);
        $rows = $pdo->query("SHOW COLUMNS FROM `{$safeTable}`")->fetchAll(PDO::FETCH_ASSOC);
        $cache[$table] = [];
        foreach ($rows as $row) {
            $field = (string)($row['Field'] ?? '');
            if ($field !== '') {
                $cache[$table][$field] = $row;
            }
        }
    } catch (Throwable $e) {
        $cache[$table] = [];
    }

    return $cache[$table];
}

function rankingHasTable(PDO $pdo, string $table): bool
{
    return rankingColumns($pdo, $table) !== [];
}

function rankingFirstColumn(array $columns, array $candidates): ?string
{
    foreach ($candidates as $candidate) {
        if (isset($columns[$candidate])) {
            return $candidate;
        }
    }
    return null;
}

function rankingAvatar(array $student): string
{
    $avatarSource = trim((string)($student['avatar_source_value'] ?? ''));
    $customPath = trim((string)($student['custom_avatar_path_value'] ?? ''));

    if ($customPath !== '') {
        if ($avatarSource === 'preset' && str_starts_with($customPath, 'assets/avatars/presets/')) {
            return '../' . ltrim($customPath, '/');
        }
        if ($avatarSource === 'upload' && str_starts_with($customPath, 'uploads/student-avatars/')) {
            return '../' . ltrim($customPath, '/');
        }
    }

    $avatar = trim((string)($student['avatar_value'] ?? ''));
    if ($avatar !== '') {
        if (preg_match('/^(https?:\/\/|\/|\.\.\/|assets\/|uploads\/)/i', $avatar)) {
            return $avatar;
        }
        if (mb_strlen($avatar) <= 8) {
            return $avatar;
        }
    }

    $gender = mb_strtolower(trim((string)($student['gender_value'] ?? '')));
    return in_array($gender, ['female', 'girl', 'nữ', 'nu'], true) ? '👧' : '👦';
}

function rankingAvatarHtml(array $student, string $className): string
{
    $avatar = rankingAvatar($student);
    if (preg_match('/^(https?:\/\/|\/|\.\.\/|assets\/|uploads\/)/i', $avatar)) {
        return '<img class="' . htmlspecialchars($className, ENT_QUOTES, 'UTF-8') . '" src="'
            . htmlspecialchars($avatar, ENT_QUOTES, 'UTF-8') . '" alt="">';
    }

    return '<div class="' . htmlspecialchars($className, ENT_QUOTES, 'UTF-8') . '">'
        . htmlspecialchars($avatar, ENT_QUOTES, 'UTF-8') . '</div>';
}

function rankingMonthLabel(DateTimeImmutable $date): string
{
    return 'Tháng ' . $date->format('n') . ' / ' . $date->format('Y');
}

$pdo = getDbConnection();
$studentId = (int)$_SESSION['student_id'];
$studentColumns = rankingColumns($pdo, 'students');

$nameColumn = rankingFirstColumn($studentColumns, ['full_name', 'name', 'student_name']);
$statusColumn = rankingFirstColumn($studentColumns, ['status', 'account_status']);
$avatarColumn = rankingFirstColumn($studentColumns, ['avatar_url', 'avatar', 'profile_photo', 'photo']);
$avatarSourceColumn = rankingFirstColumn($studentColumns, ['avatar_source']);
$customAvatarPathColumn = rankingFirstColumn($studentColumns, ['custom_avatar_path']);
$genderColumn = rankingFirstColumn($studentColumns, ['gender', 'sex']);
$provinceColumn = rankingFirstColumn($studentColumns, ['province', 'province_name', 'province_id']);
$schoolColumn = rankingFirstColumn($studentColumns, ['school_name', 'school', 'school_id']);
$gradeColumn = rankingFirstColumn($studentColumns, ['grade', 'grade_level', 'current_grade', 'student_grade']);

if ($nameColumn === null) {
    http_response_code(500);
    exit('Bảng students chưa có cột tên học sinh.');
}

$scope = (string)($_GET['scope'] ?? 'nationwide');
if (!in_array($scope, ['nationwide', 'province', 'school'], true)) {
    $scope = 'nationwide';
}

$selectedProvince = trim((string)($_GET['province'] ?? $_GET['school_province'] ?? ''));
$selectedSchool = trim((string)($_GET['school'] ?? ''));

$grade = max(0, min(5, (int)($_GET['grade'] ?? 0)));
$monthInput = trim((string)($_GET['month'] ?? date('Y-m')));
if (!preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $monthInput)) {
    $monthInput = date('Y-m');
}

$selectedMonth = DateTimeImmutable::createFromFormat('!Y-m', $monthInput) ?: new DateTimeImmutable('first day of this month');
$monthStart = $selectedMonth->format('Y-m-01 00:00:00');
$monthEnd = $selectedMonth->modify('+1 month')->format('Y-m-01 00:00:00');
$periodLabel = rankingMonthLabel($selectedMonth);

$currentSelect = [
    's.id',
    "s.`{$nameColumn}` AS student_name",
    $customAvatarPathColumn !== null ? "s.`{$customAvatarPathColumn}` AS custom_avatar_path_value" : "'' AS custom_avatar_path_value",
    $avatarSourceColumn !== null ? "s.`{$avatarSourceColumn}` AS avatar_source_value" : "'' AS avatar_source_value",
    $avatarColumn !== null ? "s.`{$avatarColumn}` AS avatar_value" : "'' AS avatar_value",
    $genderColumn !== null ? "s.`{$genderColumn}` AS gender_value" : "'' AS gender_value",
    $provinceColumn !== null ? "s.`{$provinceColumn}` AS province_value" : 'NULL AS province_value',
    $schoolColumn !== null ? "s.`{$schoolColumn}` AS school_value" : 'NULL AS school_value',
    $gradeColumn !== null ? "s.`{$gradeColumn}` AS grade_value" : 'NULL AS grade_value',
];
$currentStmt = $pdo->prepare('SELECT ' . implode(', ', $currentSelect) . ' FROM students s WHERE s.id = ? LIMIT 1');
$currentStmt->execute([$studentId]);
$currentStudentData = $currentStmt->fetch(PDO::FETCH_ASSOC);

if (!$currentStudentData) {
    session_destroy();
    header('Location: student-login.php');
    exit;
}

$currentProvince = $currentStudentData['province_value'] ?? null;
$currentSchool = $currentStudentData['school_value'] ?? null;

/*
 * Danh sách tỉnh / trường cho bộ lọc Ranking.
 * Học sinh chủ động chọn phạm vi muốn xem; không tự ép theo hồ sơ hiện tại.
 */
$provinceOptions = [];
if ($provinceColumn !== null) {
    $provinceSql = "SELECT DISTINCT TRIM(`{$provinceColumn}`) AS province_name
                    FROM students
                    WHERE `{$provinceColumn}` IS NOT NULL
                      AND TRIM(`{$provinceColumn}`) <> ''
                    ORDER BY province_name";
    $provinceOptions = $pdo->query($provinceSql)->fetchAll(PDO::FETCH_COLUMN);
}

$schoolOptions = [];
if ($schoolColumn !== null) {
    $schoolSelect = [
        "DISTINCT TRIM(`{$schoolColumn}`) AS school_name",
        $provinceColumn !== null
            ? "TRIM(COALESCE(`{$provinceColumn}`, '')) AS province_name"
            : "'' AS province_name",
    ];

    $schoolSql = "SELECT " . implode(', ', $schoolSelect) . "
                  FROM students
                  WHERE `{$schoolColumn}` IS NOT NULL
                    AND TRIM(`{$schoolColumn}`) <> ''
                  ORDER BY school_name";
    $schoolOptions = $pdo->query($schoolSql)->fetchAll(PDO::FETCH_ASSOC);
}

/*
 * Ranking dùng xp_transactions làm sổ giao dịch XP duy nhất.
 * Chỉ cộng các giao dịch XP trong tháng đang chọn.
 */
/*
 * Cấu trúc xp_transactions của EnglishSpeak đã chốt:
 * student_id, xp_change, created_at.
 * Không dò tên cột nữa để tránh nhận sai nguồn XP.
 */
$txStudentColumn = 'student_id';
$txAmountColumn = 'xp_change';
$txDateColumn = 'created_at';
$xpSetupReady = true;

$rankSelect = [
    's.id',
    "s.`{$nameColumn}` AS student_name",
    $customAvatarPathColumn !== null ? "s.`{$customAvatarPathColumn}` AS custom_avatar_path_value" : "'' AS custom_avatar_path_value",
    $avatarSourceColumn !== null ? "s.`{$avatarSourceColumn}` AS avatar_source_value" : "'' AS avatar_source_value",
    $avatarColumn !== null ? "s.`{$avatarColumn}` AS avatar_value" : "'' AS avatar_value",
    $genderColumn !== null ? "s.`{$genderColumn}` AS gender_value" : "'' AS gender_value",
];

$params = [];
$where = ['1=1'];

if ($statusColumn !== null) {
    $where[] = "(s.`{$statusColumn}` = 'active' OR s.`{$statusColumn}` IS NULL OR s.`{$statusColumn}` = '')";
}

if ($scope === 'province' && $provinceColumn !== null && $selectedProvince !== '') {
    $where[] = "TRIM(s.`{$provinceColumn}`) = ?";
    $params[] = $selectedProvince;
}

if ($scope === 'school' && $schoolColumn !== null && $selectedSchool !== '') {
    if ($provinceColumn !== null && $selectedProvince !== '') {
        $where[] = "TRIM(s.`{$provinceColumn}`) = ?";
        $params[] = $selectedProvince;
    }

    $where[] = "TRIM(s.`{$schoolColumn}`) = ?";
    $params[] = $selectedSchool;
}

if ($grade > 0 && $gradeColumn !== null) {
    $where[] = "s.`{$gradeColumn}` = ?";
    $params[] = $grade;
}

if ($xpSetupReady) {
    /*
     * Xếp hạng:
     * 1. Tổng XP trong tháng.
     * 2. Nếu bằng XP, điểm học tập trung bình cao hơn xếp trên.
     * Điểm chỉ dùng nội bộ, không hiển thị.
     */
    $rankSelect[] = 'COALESCE(xp_month.ranking_xp, 0) AS ranking_xp';
    $rankSelect[] = 'COALESCE(score_month.ranking_score, 0) AS ranking_score';

    $join = "LEFT JOIN (
            SELECT `{$txStudentColumn}` AS student_id,
                   SUM(`{$txAmountColumn}`) AS ranking_xp
            FROM xp_transactions
            WHERE `{$txDateColumn}` >= ?
              AND `{$txDateColumn}` < ?
            GROUP BY `{$txStudentColumn}`
        ) xp_month ON xp_month.student_id = s.id
        LEFT JOIN (
            SELECT student_id,
                   AVG(best_score) AS ranking_score
            FROM student_content_progress
            WHERE content_type = 'activity'
              AND status = 'completed'
              AND last_attempt_at >= ?
              AND last_attempt_at < ?
            GROUP BY student_id
        ) score_month ON score_month.student_id = s.id";

    $params = [
        $monthStart, $monthEnd,
        $monthStart, $monthEnd,
        ...$params,
    ];

    $groupBy = '';
} else {
    $rankSelect[] = '0 AS ranking_xp';
    $rankSelect[] = '0 AS ranking_score';
    $join = '';
    $groupBy = '';
}

$sql = 'SELECT ' . implode(', ', $rankSelect)
    . ' FROM students s '
    . $join
    . ' WHERE ' . implode(' AND ', $where)
    . ' ' . $groupBy
    . ' ORDER BY ranking_xp DESC, ranking_score DESC, student_name ASC, s.id ASC';

$rankingStmt = $pdo->prepare($sql);
$rankingStmt->execute($params);
$allRows = $rankingStmt->fetchAll(PDO::FETCH_ASSOC);

$ranking = [];
$zeroXpRows = [];
$previousXp = null;
$previousScore = null;
$previousRank = 0;
$positiveIndex = 0;

foreach ($allRows as $row) {
    $xp = max(0, (int)round((float)($row['ranking_xp'] ?? 0)));
    $score = max(0.0, (float)($row['ranking_score'] ?? 0));

    $row['ranking_xp'] = $xp;
    $row['ranking_score'] = $score;

    if ($xp <= 0) {
        $row['rank'] = 0;
        $zeroXpRows[] = $row;
        continue;
    }

    $positiveIndex++;

    $sameRank = $previousXp !== null
        && $xp === $previousXp
        && abs($score - (float)$previousScore) < 0.000001;

    $rank = $sameRank ? $previousRank : $positiveIndex;
    $row['rank'] = $rank;
    $ranking[] = $row;

    $previousXp = $xp;
    $previousScore = $score;
    $previousRank = $rank;
}

$topTen = array_slice($ranking, 0, 10);
$topByRank = [];
foreach ($topTen as $row) {
    if ((int)$row['rank'] <= 3 && !isset($topByRank[(int)$row['rank']])) {
        $topByRank[(int)$row['rank']] = $row;
    }
}

$podiumOrder = [2, 1, 3];
$topThree = [];
foreach ($podiumOrder as $podiumRank) {
    if (isset($topByRank[$podiumRank])) {
        $topThree[] = $topByRank[$podiumRank];
    }
}

$rankingRows = array_values(array_filter($topTen, static fn(array $row): bool => (int)$row['rank'] > 3));
$currentRankRow = null;
foreach ([...$ranking, ...$zeroXpRows] as $row) {
    if ((int)$row['id'] === $studentId) {
        $currentRankRow = $row;
        break;
    }
}

if ($currentRankRow === null) {
    $currentRankRow = [
        'id' => $studentId,
        'student_name' => (string)$currentStudentData['student_name'],
        'avatar_value' => $currentStudentData['avatar_value'] ?? '',
        'avatar_source_value' => $currentStudentData['avatar_source_value'] ?? '',
        'custom_avatar_path_value' => $currentStudentData['custom_avatar_path_value'] ?? '',
        'gender_value' => $currentStudentData['gender_value'] ?? '',
        'ranking_xp' => 0,
        'ranking_score' => 0,
        'rank' => 0,
    ];
}

$tenthXp = isset($topTen[9]) ? (int)$topTen[9]['ranking_xp'] : 0;
$currentXp = (int)$currentRankRow['ranking_xp'];
$xpToTopTen = max(0, $tenthXp - $currentXp + ($tenthXp > $currentXp ? 1 : 0));
$isTopTen = (int)$currentRankRow['rank'] > 0 && (int)$currentRankRow['rank'] <= 10;

$scopeLabel = match ($scope) {
    'province' => $selectedProvince !== ''
        ? 'Top 10 • ' . $selectedProvince
        : 'Top 10 theo tỉnh',
    'school' => $selectedSchool !== ''
        ? 'Top 10 • ' . $selectedSchool
        : 'Top 10 theo trường',
    default => 'Top 10 toàn quốc',
};

// Nhãn hiển thị đầu bảng xếp hạng theo đúng bộ lọc hiện tại.
$scopeHeading = match ($scope) {
    'province' => $selectedProvince !== '' ? 'TỈNH ' . mb_strtoupper($selectedProvince, 'UTF-8') : 'THEO TỈNH',
    'school' => $selectedSchool !== '' ? mb_strtoupper($selectedSchool, 'UTF-8') : 'THEO TRƯỜNG',
    default => 'TOÀN QUỐC',
};
if ($grade > 0) {
    $scopeHeading .= ' – KHỐI ' . $grade;
}
$topPeriodLabel = 'Top 10 | Tháng ' . $selectedMonth->format('n') . '/' . $selectedMonth->format('Y');
$availableMonths = [];
for ($i = 0; $i < 6; $i++) {
    $month = (new DateTimeImmutable('first day of this month'))->modify("-{$i} months");
    $availableMonths[$month->format('Y-m')] = rankingMonthLabel($month);
}

$pageTitle = '';
$pageSubtitle = '';
$activeStudentNav = 'ranking';
include __DIR__ . '/../includes/student-layout-start.php';
?>

<link rel="stylesheet" href="../assets/css/student-app.css">
<style>
:root{
    --rk-bg:#eef7ff;
    --rk-surface:#fff;
    --rk-text:#17324d;
    --rk-muted:#6f8799;
    --rk-primary:#197fc4;
    --rk-primary-dark:#0b67ac;
    --rk-soft:#e7f4ff;
    --rk-border:#dbe9f3;
    --rk-shadow:0 7px 22px rgba(29,80,116,.09);
    --rk-width:520px;
    --rk-nav-height:78px;
}

*{box-sizing:border-box}

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

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

.student-app{
    width:min(100%,var(--rk-width))!important;
    min-height:100vh!important;
    margin:0 auto!important;
    background:#f7fbff!important;
    box-shadow:0 0 28px rgba(27,73,108,.08)!important;
}

.student-header{
    position:sticky!important;
    top:0!important;
    z-index:40!important;
    display:grid!important;
    grid-template-columns:46px minmax(0,1fr) 46px!important;
    align-items:center!important;
    gap:9px!important;
    min-height:76px!important;
    padding:12px 14px!important;
    background:linear-gradient(135deg,#3488ef,#17b8e4)!important;
    color:#fff!important;
    box-shadow:0 5px 15px rgba(31,135,210,.22)!important;
}

.student-header__text{
    min-width:0!important;
    text-align:center!important;
}

.student-header__text h1{
    margin:0!important;
    color:#fff!important;
    font-size:23px!important;
    font-weight:850!important;
    line-height:1.15!important;
}

.student-header__text p{
    margin:4px 0 0!important;
    color:rgba(255,255,255,.92)!important;
    font-size:12.5px!important;
}

.student-header__spacer{
    width:44px!important;
    height:44px!important;
}

.student-content{
    width:100%!important;
    padding:16px 14px 26px!important;
}

.rk-page{
    width:100%;
    padding:0;
}

.rk-toolbar{
    position:relative;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    margin-bottom:12px;
    padding:15px 16px;
    border:1px solid var(--rk-border);
    border-radius:19px;
    background:linear-gradient(135deg,#edf6ff,#e6f1ff);
    box-shadow:var(--rk-shadow);
}

.rk-title{
    display:flex;
    align-items:center;
    gap:11px;
    min-width:0;
}

.rk-title__icon{
    width:46px;
    height:46px;
    flex:0 0 46px;
    display:grid;
    place-items:center;
    border-radius:15px;
    background:#fff5cf;
    border:1px solid #f0d77b;
    font-size:26px;
}

.rk-title h1{
    margin:0;
    color:#123e62;
    font-size:18px;
    line-height:1.3;
}

.rk-title p{
    margin:5px 0 0;
    color:var(--rk-muted);
    font-size:13px;
}

.rk-settings{position:relative;flex:0 0 auto}

.rk-settings__button{
    width:42px;
    height:42px;
    display:grid;
    place-items:center;
    border:1px solid var(--rk-border);
    border-radius:13px;
    background:#fff;
    color:var(--rk-text);
    box-shadow:0 5px 15px rgba(29,80,116,.10);
    cursor:pointer;
    font-size:19px;
}

.rk-menu{
    position:absolute;
    z-index:100;
    top:50px;
    right:0;
    width:min(290px,calc(100vw - 28px));
    padding:11px;
    border:1px solid var(--rk-border);
    border-radius:17px;
    background:#fff;
    box-shadow:0 18px 42px rgba(23,50,77,.20);
}
.rk-menu[hidden]{display:none!important}
.rk-menu__label{padding:3px 7px 8px;color:var(--rk-muted);font-size:11px;font-weight:900;text-transform:uppercase}
.rk-menu__option{width:100%;display:flex;align-items:center;justify-content:space-between;padding:10px;border:0;border-radius:11px;background:transparent;color:var(--rk-text);font-weight:750;text-align:left;cursor:pointer}
.rk-menu__option.is-active{background:#eaf6ff}
.rk-menu__check{visibility:hidden;color:#1978bd}
.rk-menu__option.is-active .rk-menu__check{visibility:visible}
.rk-menu__divider{height:1px;margin:7px 4px;background:#e4edf4}
.rk-menu label{display:grid;gap:6px;padding:6px;color:var(--rk-text);font-weight:750}
.rk-menu select{width:100%;padding:9px 10px;border:1px solid var(--rk-border);border-radius:10px;background:#f8fbfe;color:var(--rk-text)}
.rk-scope-picker{display:none;margin:4px 0 2px;padding:7px;border-radius:12px;background:#f7fbff;border:1px solid #e3eef6}
.rk-scope-picker.is-open{display:block}
.rk-scope-picker .rk-help{padding:0 6px 5px;color:var(--rk-muted);font-size:11px;line-height:1.35}

.rk-period{
    margin:0 0 13px;
    text-align:center;
    color:var(--rk-muted);
    font-size:13px;
    font-weight:800;
}

.rk-podium{
    display:grid;
    grid-template-columns:repeat(3,minmax(0,1fr));
    align-items:end;
    gap:9px;
    min-height:192px;
    margin-bottom:14px;
}
.rk-podium--partial{grid-template-columns:repeat(auto-fit,minmax(95px,1fr));min-height:auto}

.rk-winner{
    min-width:0;
    display:flex;
    flex-direction:column;
    align-items:center;
    justify-content:flex-end;
    padding:11px 6px;
    border:1px solid var(--rk-border);
    border-radius:19px;
    background:#fff;
    box-shadow:var(--rk-shadow);
    text-align:center;
}
.rk-winner--1{height:192px;background:linear-gradient(180deg,#fff6d7,#fff 66%);border-color:#efd98d}
.rk-winner--2{height:176px;background:linear-gradient(180deg,#eef6ff,#fff 66%)}
.rk-winner--3{height:164px;background:linear-gradient(180deg,#eef9ef,#fff 66%);border-color:#d9ead9}
.rk-medal{font-size:30px;line-height:1;margin-bottom:6px}
.rk-avatar,.rk-avatar-img{width:56px;height:56px;margin-bottom:7px;border-radius:50%;border:3px solid rgba(255,255,255,.95);box-shadow:0 0 0 1px #c8deef}
.rk-avatar{display:grid;place-items:center;background:#dcecff;font-size:28px}
.rk-avatar-img{display:block;object-fit:cover;background:#dcecff}
.rk-name{width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--rk-text);font-size:13.5px;font-weight:850}
.rk-xp{margin-top:4px;color:#e98400;font-size:12px;font-weight:900;white-space:nowrap}

.rk-list,.rk-my,.rk-empty{
    width:100%;
    border:1px solid var(--rk-border);
    border-radius:19px;
    background:#fff;
    box-shadow:var(--rk-shadow);
}
.rk-list{padding:4px 13px}
.rk-row{display:grid;grid-template-columns:28px 40px minmax(0,1fr) auto;align-items:center;gap:9px;min-height:58px;border-bottom:1px solid #e9f0f5}
.rk-row:last-child{border-bottom:0}
.rk-row.is-me{margin:0 -7px;padding:0 7px;border-radius:12px;background:#fff8dd}
.rk-row__rank{color:var(--rk-text);font-weight:900;text-align:center}
.rk-row__avatar,.rk-row__avatar-img{width:36px;height:36px;border-radius:50%}
.rk-row__avatar{display:grid;place-items:center;background:#e4f0ff;font-size:19px}
.rk-row__avatar-img{display:block;object-fit:cover;background:#e4f0ff}
.rk-row__name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--rk-text);font-size:14px;font-weight:750}
.rk-row__xp{color:#36536e;font-size:12.5px;font-weight:850;white-space:nowrap}

.rk-empty{padding:28px 18px;text-align:center;color:var(--rk-muted)}
.rk-empty strong{display:block;margin-bottom:5px;color:var(--rk-text)}

.rk-my{margin-top:14px;padding:14px}
.rk-my__title{margin-bottom:12px;color:var(--rk-text);font-size:17px;font-weight:900}
.rk-my__content{display:grid;grid-template-columns:62px minmax(0,1fr) auto;align-items:center;gap:12px}
.rk-my__avatar,.rk-my__avatar-img{width:62px;height:62px;border-radius:18px}
.rk-my__avatar{display:grid;place-items:center;background:linear-gradient(145deg,#eeeaff,#dcd6ff);font-size:31px}
.rk-my__avatar-img{display:block;object-fit:cover;background:#eeeaff}
.rk-my__identity{min-width:0;display:grid;gap:4px}
.rk-my__identity strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--rk-text);font-size:16px}
.rk-my__identity span{color:#5d7488;font-size:13px;font-weight:750}
.rk-my__goal{max-width:132px;padding:10px;border-radius:13px;background:#f1eeff;color:#5947b5;text-align:center}
.rk-my__goal.is-top{background:#ecf8eb;color:#287a34}
.rk-my__goal strong{display:block;font-size:15px}
.rk-my__goal span{display:block;margin-top:3px;font-size:11px;line-height:1.3;font-weight:750}
.rk-disabled{opacity:.45;pointer-events:none}

.student-nav{
    position:fixed!important;
    z-index:9999!important;
    left:50%!important;
    bottom:0!important;
    width:min(100%,var(--rk-width))!important;
    min-height:var(--rk-nav-height)!important;
    display:grid!important;
    grid-template-columns:repeat(4,minmax(0,1fr))!important;
    padding:7px 8px calc(7px + env(safe-area-inset-bottom))!important;
    border-top:1px solid #dce5ed!important;
    background:rgba(255,255,255,.98)!important;
    box-shadow:0 -6px 18px rgba(32,65,93,.11)!important;
    transform:translateX(-50%)!important;
    backdrop-filter:blur(14px);
}

.student-nav__item{
    position:relative!important;
    display:flex!important;
    min-width:0!important;
    flex-direction:column!important;
    align-items:center!important;
    justify-content:center!important;
    gap:2px!important;
    color:#586879!important;
    text-decoration:none!important;
}
.student-nav__icon{width:42px!important;height:34px!important;display:grid!important;place-items:center!important;border-radius:12px!important;font-size:23px!important}
.student-nav__label{overflow:hidden!important;max-width:100%!important;color:inherit!important;font-size:11.5px!important;font-weight:750!important;white-space:nowrap!important;text-overflow:ellipsis!important}
.student-nav__item.is-active{color:var(--rk-primary)!important}
.student-nav__item.is-active .student-nav__icon{background:var(--rk-soft)!important}
.student-nav__item.is-active::after{content:"";position:absolute;top:-7px;width:52px;height:3px;border-radius:999px;background:var(--rk-primary)}

@media(max-width:390px){
    .student-content{padding-left:11px!important;padding-right:11px!important}
    .rk-toolbar{padding:14px}
    .rk-title__icon{width:42px;height:42px;flex-basis:42px;font-size:23px}
    .rk-title h1{font-size:17px}
    .rk-podium{gap:7px;min-height:180px}
    .rk-winner{padding-left:4px;padding-right:4px;border-radius:16px}
    .rk-winner--1{height:180px}
    .rk-winner--2{height:166px}
    .rk-winner--3{height:156px}
    .rk-avatar,.rk-avatar-img{width:49px;height:49px}
    .rk-avatar{font-size:25px}
    .rk-name{font-size:12px}
    .rk-xp{font-size:11px}
    .rk-list{padding-left:9px;padding-right:9px}
    .rk-row{grid-template-columns:25px 36px minmax(0,1fr) auto;gap:7px}
    .rk-row__avatar,.rk-row__avatar-img{width:33px;height:33px}
    .rk-row__name{font-size:13px}
    .rk-row__xp{font-size:11.5px}
    .rk-my__content{grid-template-columns:54px minmax(0,1fr)}
    .rk-my__avatar,.rk-my__avatar-img{width:54px;height:54px}
    .rk-my__goal{grid-column:1/-1;max-width:none;width:100%;display:flex;justify-content:center;gap:5px;padding:8px 9px}
    .rk-my__goal strong,.rk-my__goal span{display:inline;margin:0}
}

/* =========================================================
   Ranking v2 — đồng bộ Home + Đang học
   ========================================================= */
:root{
    --rk-bg:#ffffff;
    --rk-surface:#ffffff;
    --rk-text:#0b4f9c;
    --rk-muted:#315d82;
    --rk-primary:#0b4f9c;
    --rk-primary-dark:#0b4f9c;
    --rk-soft:#eef7ff;
    --rk-border:#cfe4f5;
    --rk-shadow:0 5px 16px rgba(29,80,116,.06);
}

html,body{
    background:#ffffff!important;
    color:var(--rk-text)!important;
}
.student-app{
    background:#ffffff!important;
    box-shadow:0 0 24px rgba(20,60,90,.06)!important;
}

/* Bỏ header xanh cũ */
.student-header{
    display:none!important;
}

/* Hàng trên cùng: Back + tổng XP */
.rk-topbar{
    position:sticky;
    top:0;
    z-index:90;
    width:100%;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    padding:12px 14px 8px;
    background:#ffffff;
}
.rk-back{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    width:42px;
    height:42px;
    color:#0b4f9c;
    text-decoration:none;
    font-size:32px;
    font-weight:900;
    line-height:1;
}
.rk-total-xp{
    display:inline-flex;
    align-items:center;
    gap:5px;
    min-height:38px;
    padding:6px 10px;
    border:1px solid #f1df9c;
    border-radius:14px;
    background:#fffdf4;
    color:#0b4f9c;
    font-size:15px;
    font-weight:900;
    white-space:nowrap;
}
.rk-total-xp > span{
    color:#e3a300;
    font-size:18px;
}

.student-content{
    padding-top:4px!important;
}

/* Toolbar Ranking nhẹ như pastel Home */
.rk-toolbar{
    margin-bottom:10px!important;
    padding:13px 14px!important;
    border-color:#cfe4f5!important;
    background:#eef7ff!important;
    box-shadow:none!important;
}
.rk-title__icon{
    width:42px!important;
    height:42px!important;
    flex-basis:42px!important;
    font-size:23px!important;
}
.rk-title h1{
    color:#0b4f9c!important;
    font-size:20px!important;
    font-weight:900!important;
}
.rk-title p{
    color:#315d82!important;
    font-size:13.5px!important;
    font-weight:700!important;
}
.rk-settings__button{
    color:#0b4f9c!important;
    border-color:#d7e9f7!important;
    background:#ffffff!important;
    box-shadow:none!important;
}

/* Period */
.rk-period{
    color:#315d82!important;
    font-size:13.5px!important;
    font-weight:850!important;
}

/* Podium */
.rk-winner{
    box-shadow:var(--rk-shadow)!important;
}
.rk-name{
    color:#0b4f9c!important;
    font-weight:900!important;
}
.rk-xp{
    font-size:12.5px!important;
}

/* List + my rank */
.rk-list,.rk-my,.rk-empty{
    border-color:#d4e3ee!important;
    box-shadow:var(--rk-shadow)!important;
}
.rk-row__rank,
.rk-row__name,
.rk-my__title,
.rk-my__identity strong{
    color:#0b4f9c!important;
}
.rk-row__name{
    font-weight:800!important;
}
.rk-row__xp,
.rk-my__identity span{
    color:#315d82!important;
}
.rk-my__title{
    font-size:18px!important;
    font-weight:900!important;
}

/* Menu bộ lọc */
.rk-menu{
    border-color:#d4e3ee!important;
}
.rk-menu__option,
.rk-menu label,
.rk-menu select{
    color:#0b4f9c!important;
}
.rk-menu__option.is-active{
    background:#eef7ff!important;
}

/* Menu chân đồng bộ Home */
.student-nav{
    background:#ffffff!important;
}
.student-nav__item{
    color:#315d82!important;
}
.student-nav__item.is-active{
    color:#0b4f9c!important;
}
.student-nav__item.is-active .student-nav__icon{
    background:#eef7ff!important;
}
.student-nav__item.is-active::after{
    background:#0b4f9c!important;
}
.student-nav__label{
    color:inherit!important;
    font-size:12.5px!important;
    font-weight:850!important;
}


/* =========================================================
   Ranking final polish
   - Bỏ Back + XP đầu trang
   - Cố định khối “🏆 Xếp hạng”
   - Tăng khoảng thở và cỡ chữ tháng
   ========================================================= */

.rk-topbar,
.rk-back,
.rk-total-xp{
    display:none!important;
}

.rk-toolbar{
    position:sticky!important;
    top:0!important;
    z-index:95!important;
    margin:0 0 16px!important;
    padding:13px 14px!important;
    background:#eef7ff!important;
    border-color:#cfe4f5!important;
    box-shadow:0 6px 14px rgba(29,80,116,.06)!important;
}

.rk-page{
    background:#ffffff!important;
}

.rk-period{
    margin:4px 0 18px!important;
    color:#315d82!important;
    font-size:15px!important;
    font-weight:900!important;
    line-height:1.35!important;
}

.rk-menu{
    z-index:120!important;
}

.rk-title p{display:none!important;}
.rk-ranking-context{
    margin:2px 0 5px!important;
    text-align:center;
    color:#0b4f9c!important;
    font-size:19px!important;
    font-weight:900!important;
    line-height:1.3!important;
    text-transform:uppercase;
}
.rk-period{
    margin:0 0 24px!important;
    color:#111!important;
    font-size:16px!important;
    font-weight:900!important;
    line-height:1.35!important;
}

</style>

<div class="rk-page">
    <section class="rk-toolbar">
        <div class="rk-title">
            <div class="rk-title__icon" aria-hidden="true">🏆</div>
            <div><h1>XẾP HẠNG</h1></div>
        </div>
        <div class="rk-settings">
            <button class="rk-settings__button" id="rkSettingsButton" type="button" aria-label="Tùy chọn bảng xếp hạng" aria-expanded="false">⚙️</button>
            <form class="rk-menu" id="rkSettingsMenu" method="get" hidden>
                <div class="rk-menu__label">Phạm vi xếp hạng</div>

                <button
                    class="rk-menu__option <?= $scope === 'nationwide' ? 'is-active' : '' ?>"
                    type="button"
                    data-ranking-scope="nationwide"
                ><span>🌐 Toàn quốc</span><span class="rk-menu__check">✓</span></button>

                <button
                    class="rk-menu__option <?= $scope === 'province' ? 'is-active' : '' ?> <?= $provinceColumn === null || $provinceOptions === [] ? 'rk-disabled' : '' ?>"
                    type="button"
                    data-ranking-scope="province"
                ><span>📍 Theo tỉnh</span><span class="rk-menu__check">✓</span></button>

                <div
                    class="rk-scope-picker <?= $scope === 'province' ? 'is-open' : '' ?>"
                    id="rkProvincePicker"
                >
                    <div class="rk-help">Chọn tỉnh muốn xem bảng xếp hạng.</div>
                    <label>
                        <span>📍 Tỉnh</span>
                        <select name="province" id="rkProvinceSelect">
                            <option value="">Chọn tỉnh</option>
                            <?php foreach ($provinceOptions as $provinceName): ?>
                                <option
                                    value="<?= htmlspecialchars((string)$provinceName, ENT_QUOTES, 'UTF-8') ?>"
                                    <?= $selectedProvince === (string)$provinceName ? 'selected' : '' ?>
                                >
                                    <?= htmlspecialchars((string)$provinceName, ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                </div>

                <button
                    class="rk-menu__option <?= $scope === 'school' ? 'is-active' : '' ?> <?= $schoolColumn === null || $schoolOptions === [] ? 'rk-disabled' : '' ?>"
                    type="button"
                    data-ranking-scope="school"
                ><span>🏫 Theo trường</span><span class="rk-menu__check">✓</span></button>

                <div
                    class="rk-scope-picker <?= $scope === 'school' ? 'is-open' : '' ?>"
                    id="rkSchoolPicker"
                >
                    <div class="rk-help">Chọn tỉnh trước, sau đó chọn trường.</div>

                    <label>
                        <span>📍 Tỉnh</span>
                        <select name="school_province" id="rkSchoolProvinceSelect">
                            <option value="">Tất cả tỉnh</option>
                            <?php foreach ($provinceOptions as $provinceName): ?>
                                <option
                                    value="<?= htmlspecialchars((string)$provinceName, ENT_QUOTES, 'UTF-8') ?>"
                                    <?= $selectedProvince === (string)$provinceName ? 'selected' : '' ?>
                                >
                                    <?= htmlspecialchars((string)$provinceName, ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </label>

                    <label>
                        <span>🏫 Trường</span>
                        <select name="school" id="rkSchoolSelect">
                            <option value="">Chọn trường</option>
                            <?php foreach ($schoolOptions as $schoolOption): ?>
                                <?php
                                $schoolName = (string)($schoolOption['school_name'] ?? '');
                                $schoolProvince = (string)($schoolOption['province_name'] ?? '');
                                ?>
                                <option
                                    value="<?= htmlspecialchars($schoolName, ENT_QUOTES, 'UTF-8') ?>"
                                    data-province="<?= htmlspecialchars($schoolProvince, ENT_QUOTES, 'UTF-8') ?>"
                                    <?= $selectedSchool === $schoolName ? 'selected' : '' ?>
                                >
                                    <?= htmlspecialchars($schoolName, ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                </div>

                <div class="rk-menu__divider"></div>

                <input type="hidden" name="scope" id="rkScopeInput" value="<?= htmlspecialchars($scope, ENT_QUOTES, 'UTF-8') ?>">

                <label>
                    <span>🎒 Lớp</span>
                    <select name="grade" onchange="this.form.submit()">
                        <option value="0">Tất cả lớp</option>
                        <?php for ($g=1;$g<=5;$g++): ?>
                            <option value="<?= $g ?>" <?= $grade === $g ? 'selected' : '' ?>>Lớp <?= $g ?></option>
                        <?php endfor; ?>
                    </select>
                </label>

                <label>
                    <span>📅 Thời gian</span>
                    <select name="month" onchange="this.form.submit()">
                        <?php foreach ($availableMonths as $value => $label): ?>
                            <option value="<?= htmlspecialchars($value, ENT_QUOTES, 'UTF-8') ?>" <?= $monthInput === $value ? 'selected' : '' ?>>
                                <?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </label>
            </form>
        </div>
    </section>

    <div class="rk-ranking-context"><?= htmlspecialchars($scopeHeading, ENT_QUOTES, 'UTF-8') ?></div>
    <div class="rk-period"><?= htmlspecialchars($topPeriodLabel, ENT_QUOTES, 'UTF-8') ?></div>

    <?php if ($topTen === []): ?>
        <section class="rk-empty"><strong>Chưa có dữ liệu xếp hạng</strong><span>Hoàn thành hoạt động để nhận XP đầu tiên nhé!</span></section>
    <?php else: ?>
        <section class="rk-podium <?= count($topThree) < 3 ? 'rk-podium--partial' : '' ?>">
            <?php foreach ($topThree as $student): $rank=(int)$student['rank']; ?>
                <article class="rk-winner rk-winner--<?= $rank ?>">
                    <div class="rk-medal"><?= $rank === 1 ? '🥇' : ($rank === 2 ? '🥈' : '🥉') ?></div>
                    <?= rankingAvatarHtml($student, preg_match('/^(https?:\/\/|\/|\.\.\/|assets\/|uploads\/)/i', rankingAvatar($student)) ? 'rk-avatar-img' : 'rk-avatar') ?>
                    <div class="rk-name"><?= htmlspecialchars((string)$student['student_name'], ENT_QUOTES, 'UTF-8') ?></div>
                    <div class="rk-xp"><?= number_format((int)$student['ranking_xp']) ?> XP</div>
                </article>
            <?php endforeach; ?>
        </section>

        <?php if ($rankingRows !== []): ?>
            <section class="rk-list">
                <?php foreach ($rankingRows as $student): ?>
                    <div class="rk-row <?= (int)$student['id'] === $studentId ? 'is-me' : '' ?>">
                        <div class="rk-row__rank"><?= (int)$student['rank'] ?></div>
                        <?= rankingAvatarHtml($student, preg_match('/^(https?:\/\/|\/|\.\.\/|assets\/|uploads\/)/i', rankingAvatar($student)) ? 'rk-row__avatar-img' : 'rk-row__avatar') ?>
                        <div class="rk-row__name"><?= htmlspecialchars((string)$student['student_name'], ENT_QUOTES, 'UTF-8') ?></div>
                        <div class="rk-row__xp"><?= number_format((int)$student['ranking_xp']) ?> XP</div>
                    </div>
                <?php endforeach; ?>
            </section>
        <?php endif; ?>
    <?php endif; ?>

    <section class="rk-my">
        <div class="rk-my__title">⭐ Hạng của em</div>
        <div class="rk-my__content">
            <?= rankingAvatarHtml($currentRankRow, preg_match('/^(https?:\/\/|\/|\.\.\/|assets\/|uploads\/)/i', rankingAvatar($currentRankRow)) ? 'rk-my__avatar-img' : 'rk-my__avatar') ?>
            <div class="rk-my__identity">
                <strong><?= htmlspecialchars((string)$currentRankRow['student_name'], ENT_QUOTES, 'UTF-8') ?></strong>
                <span>🏆 <?= (int)$currentRankRow['rank'] > 0 ? 'Hạng #' . (int)$currentRankRow['rank'] : 'Chưa xếp hạng' ?></span>
                <span>⭐ <?= number_format($currentXp) ?> XP</span>
            </div>
            <div class="rk-my__goal <?= $isTopTen ? 'is-top' : '' ?>">
                <?php if ($isTopTen): ?><strong>Top 10 🎉</strong><span>Tiếp tục cố gắng nhé!</span><?php elseif (count($topTen) < 10): ?><strong><?= number_format($currentXp) ?> XP</strong><span>Em đã có mặt trên bảng!</span><?php else: ?><strong><?= number_format($xpToTopTen) ?> XP</strong><span>nữa để vào Top 10</span><?php endif; ?>
            </div>
        </div>
    </section>

    
</div>

<script>
(() => {
    const button = document.getElementById('rkSettingsButton');
    const menu = document.getElementById('rkSettingsMenu');
    if (!button || !menu) return;

    const scopeInput = document.getElementById('rkScopeInput');
    const provincePicker = document.getElementById('rkProvincePicker');
    const schoolPicker = document.getElementById('rkSchoolPicker');
    const provinceSelect = document.getElementById('rkProvinceSelect');
    const schoolProvinceSelect = document.getElementById('rkSchoolProvinceSelect');
    const schoolSelect = document.getElementById('rkSchoolSelect');

    const close = () => {
        menu.hidden = true;
        button.setAttribute('aria-expanded', 'false');
    };

    const openOnly = (scope) => {
        if (provincePicker) {
            provincePicker.classList.toggle('is-open', scope === 'province');
        }
        if (schoolPicker) {
            schoolPicker.classList.toggle('is-open', scope === 'school');
        }

        menu.querySelectorAll('[data-ranking-scope]').forEach((item) => {
            item.classList.toggle('is-active', item.dataset.rankingScope === scope);
        });
    };

    const filterSchools = () => {
        if (!schoolSelect || !schoolProvinceSelect) return;

        const province = schoolProvinceSelect.value || '';

        Array.from(schoolSelect.options).forEach((option, index) => {
            if (index === 0) return;
            const optionProvince = option.dataset.province || '';
            option.hidden = province !== '' && optionProvince !== province;
        });

        const selected = schoolSelect.options[schoolSelect.selectedIndex];
        if (selected && selected.hidden) {
            schoolSelect.value = '';
        }
    };

    button.addEventListener('click', (event) => {
        event.stopPropagation();
        menu.hidden = !menu.hidden;
        button.setAttribute('aria-expanded', menu.hidden ? 'false' : 'true');
    });

    menu.addEventListener('click', (event) => {
        event.stopPropagation();

        const scopeButton = event.target.closest('[data-ranking-scope]');
        if (!scopeButton || scopeButton.classList.contains('rk-disabled')) {
            return;
        }

        const scope = scopeButton.dataset.rankingScope || 'nationwide';

        if (scopeInput) {
            scopeInput.value = scope;
        }

        if (scope === 'nationwide') {
            menu.submit();
            return;
        }

        openOnly(scope);

        if (scope === 'province' && provinceSelect) {
            provinceSelect.focus();
        }

        if (scope === 'school' && schoolProvinceSelect) {
            filterSchools();
            schoolProvinceSelect.focus();
        }
    });

    if (provinceSelect) {
        provinceSelect.addEventListener('change', () => {
            if (!provinceSelect.value) return;
            if (scopeInput) scopeInput.value = 'province';
            menu.submit();
        });
    }

    if (schoolProvinceSelect) {
        schoolProvinceSelect.addEventListener('change', () => {
            filterSchools();
        });
    }

    if (schoolSelect) {
        schoolSelect.addEventListener('change', () => {
            if (!schoolSelect.value) return;

            if (scopeInput) scopeInput.value = 'school';

            /*
             * Chuyển school_province thành province trước khi submit để backend
             * dùng cùng một tham số province cho cả phạm vi tỉnh và trường.
             */
            let provinceHidden = menu.querySelector('input[name="province"]');
            if (!provinceHidden) {
                provinceHidden = document.createElement('input');
                provinceHidden.type = 'hidden';
                provinceHidden.name = 'province';
                menu.appendChild(provinceHidden);
            }
            provinceHidden.value = schoolProvinceSelect ? schoolProvinceSelect.value : '';

            menu.submit();
        });
    }

    filterSchools();

    document.addEventListener('click', close);
    document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape') close();
    });
})();
</script>

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