<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../includes/supabase.php';
require_once __DIR__ . '/../includes/auth.php';

$gameKey = $_GET['game_key'] ?? 'chess';
$timeControl = $_GET['time_control'] ?? null;
$limit = min(intval($_GET['limit'] ?? 50), 100);

$db = supabaseService();

if ($gameKey === 'chess') {
    $ratingCol = 'elo_rapid';
    if ($timeControl) {
        if (str_contains($timeControl, 'bullet')) $ratingCol = 'elo_bullet';
        elseif (str_contains($timeControl, 'blitz')) $ratingCol = 'elo_blitz';
        elseif (str_contains($timeControl, 'classical')) $ratingCol = 'elo_classical';
    }

    $players = $db->get('profiles', [
        'select' => "id,username,display_name,avatar_url,country_code,level,{$ratingCol},games_played",
        'order' => "{$ratingCol}.desc.nullslast",
        'limit' => $limit,
        $ratingCol => 'not.is.null'
    ]);

    if (!is_array($players) || isset($players['error'])) {
        jsonResponse(['leaderboard' => []]);
    }

    $result = array_map(function($p) use ($ratingCol) {
        $p['rating'] = $p[$ratingCol] ?? 1200;
        return $p;
    }, $players);

    jsonResponse(['leaderboard' => $result]);
} else {
    $ratings = $db->get('player_game_ratings', [
        'game_key' => 'eq.' . $gameKey,
        'select' => 'player_id,rating,games_played',
        'order' => 'rating.desc',
        'limit' => $limit
    ]);

    jsonResponse(['leaderboard' => is_array($ratings) && !isset($ratings['error']) ? $ratings : []]);
}
