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

header('Content-Type: application/json');

$token = get_auth_token();

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'unauthorized']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $action = $_GET['action'] ?? 'player';

    switch ($action) {
        case 'player':
            $playerId = $_GET['player_id'] ?? null;
            $gameKey = $_GET['game'] ?? null;

            if (!$playerId) {
                $userRes = supabase_auth('user', [], $token, 'GET');
                $playerId = $userRes['data']['id'] ?? null;
            }

            if (!$playerId) {
                http_response_code(400);
                echo json_encode(['error' => 'player_id required']);
                exit;
            }

            $query = "player_game_ratings?player_id=eq.{$playerId}";
            if ($gameKey) {
                $query .= "&game_key=eq.{$gameKey}";
            }
            $query .= '&select=game_key,mode,rating,games_played,wins,losses,draws,win_streak,best_win_streak,last_played_at';

            $res = supabase_rest('GET', $query, [], SUPABASE_SERVICE_KEY);
            echo json_encode(['ratings' => $res['data'] ?? []]);
            break;

        case 'leaderboard':
            $gameKey = $_GET['game'] ?? 'chess';
            $mode = $_GET['mode'] ?? 'blitz';
            $limit = min((int)($_GET['limit'] ?? 50), 100);

            $validGames = ['chess', 'ludo', 'backgammon', 'domino'];
            if (!in_array($gameKey, $validGames)) $gameKey = 'chess';

            $minGames = ($gameKey === 'chess') ? 1 : 1;
            $query = "player_game_ratings?game_key=eq.{$gameKey}&mode=eq.{$mode}&games_played=gte.{$minGames}&order=rating.desc&limit={$limit}&select=player_id,rating,games_played,wins,losses,draws,win_streak";
            $res = supabase_rest('GET', $query, [], SUPABASE_SERVICE_KEY);

            $ratings = $res['data'] ?? [];
            $playerIds = array_map(fn($r) => $r['player_id'], $ratings);

            $players = [];
            if (!empty($playerIds)) {
                $idList = implode(',', array_map(fn($id) => "\"$id\"", $playerIds));
                $profileRes = supabase_rest('GET', "profiles?id=in.({$idList})&select=id,username,display_name,avatar_url,level,country_code", [], SUPABASE_SERVICE_KEY);
                foreach (($profileRes['data'] ?? []) as $p) {
                    $players[$p['id']] = $p;
                }
            }

            $leaderboard = [];
            foreach ($ratings as $i => $r) {
                $profile = $players[$r['player_id']] ?? [];
                $leaderboard[] = [
                    'rank' => $i + 1,
                    'player_id' => $r['player_id'],
                    'username' => $profile['username'] ?? null,
                    'display_name' => $profile['display_name'] ?? null,
                    'avatar_url' => $profile['avatar_url'] ?? null,
                    'level' => $profile['level'] ?? 1,
                    'country_code' => $profile['country_code'] ?? null,
                    'rating' => $r['rating'],
                    'games_played' => $r['games_played'],
                    'wins' => $r['wins'],
                    'losses' => $r['losses'],
                    'win_streak' => $r['win_streak'],
                ];
            }

            echo json_encode(['leaderboard' => $leaderboard, 'game' => $gameKey, 'mode' => $mode]);
            break;

        case 'history':
            $gameKey = $_GET['game'] ?? 'chess';
            $mode = $_GET['mode'] ?? null;
            $limit = min((int)($_GET['limit'] ?? 20), 50);

            $userRes = supabase_auth('user', [], $token, 'GET');
            $playerId = $userRes['data']['id'] ?? null;

            $query = "rating_history?player_id=eq.{$playerId}&game_key=eq.{$gameKey}";
            if ($mode) $query .= "&time_control_type=eq.{$mode}";
            $query .= "&order=created_at.desc&limit={$limit}&select=rating_before,rating_after,rating_change,result,opponent_rating,created_at";

            $res = supabase_rest('GET', $query, [], SUPABASE_SERVICE_KEY);
            echo json_encode(['history' => $res['data'] ?? []]);
            break;

        case 'modes':
            $gameKey = $_GET['game'] ?? 'chess';
            $modes = [
                'chess' => ['bullet', 'blitz', 'rapid', 'classical'],
                'backgammon' => ['default'],
                'domino' => ['default'],
                'ludo' => ['default'],
            ];
            echo json_encode(['modes' => $modes[$gameKey] ?? ['default']]);
            break;

        default:
            http_response_code(400);
            echo json_encode(['error' => 'invalid action']);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'method not allowed']);
}
