<?php

header('Content-Type: application/json');
require_once __DIR__ . '/../includes/cors.php';

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

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../config/constants.php';

$action = $_GET['action'] ?? (getInput()['action'] ?? '');

switch ($action) {
    case 'tournament':
        getTournament();
        break;
    case 'standings':
        getStandings();
        break;
    case 'rounds':
        getRounds();
        break;
    case 'pairings':
        getPairings();
        break;
    case 'my-games':
        getMyGames();
        break;
    case 'bracket':
        getBracket();
        break;
    case 'arena-join':
        arenaJoin();
        break;
    case 'arena-status':
        arenaStatus();
        break;
    case 'arena-standings':
        arenaStandings();
        break;
    default:
        jsonError('Invalid action');
}

function swissApi(string $method, string $path, ?array $body = null): array {
    $url = SWISS_API . $path;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($body) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    }

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $data = json_decode($response, true);
    if ($httpCode >= 400) {
        return ['error' => $data['message'] ?? 'Swiss API error', 'code' => $httpCode];
    }
    return $data ?? [];
}

function getTournament(): void {
    $id = $_GET['id'] ?? '';
    if (!$id) jsonError('id required');

    // Get from Supabase
    require_once __DIR__ . '/../includes/supabase.php';
    $db = supabaseService();
    $tournaments = $db->get('el3ab_tournaments', ['id' => 'eq.' . $id, 'limit' => 1]);
    $tournament = is_array($tournaments) && !empty($tournaments) && !isset($tournaments['error']) ? $tournaments[0] : null;

    if (!$tournament) jsonError('Tournament not found', 404);

    // Get Swiss API data if linked
    if (!empty($tournament['swiss_api_tournament_id'])) {
        $swiss = swissApi('GET', '/tournaments/' . $tournament['swiss_api_tournament_id']);
        if (!isset($swiss['error'])) {
            $tournament['swiss_data'] = $swiss;
        }
    }

    // Get registrations count
    $regs = $db->get('tournament_registrations', ['tournament_id' => 'eq.' . $id, 'status' => 'eq.registered', 'select' => 'id']);
    $tournament['player_count'] = is_array($regs) && !isset($regs['error']) ? count($regs) : 0;

    jsonResponse($tournament);
}

function getStandings(): void {
    $tournamentId = $_GET['tournament_id'] ?? '';
    if (!$tournamentId) jsonError('tournament_id required');

    require_once __DIR__ . '/../includes/supabase.php';
    $db = supabaseService();
    $tournament = $db->get('el3ab_tournaments', ['id' => 'eq.' . $tournamentId, 'select' => 'swiss_api_tournament_id', 'limit' => 1]);

    if (empty($tournament) || isset($tournament['error'])) jsonError('Not found', 404);
    $swissId = $tournament[0]['swiss_api_tournament_id'] ?? null;

    if ($swissId) {
        $standings = swissApi('GET', '/tournaments/' . $swissId . '/standings');
        if (!isset($standings['error'])) {
            jsonResponse(['standings' => $standings]);
        }
    }

    jsonResponse(['standings' => []]);
}

function getRounds(): void {
    $tournamentId = $_GET['tournament_id'] ?? '';
    if (!$tournamentId) jsonError('tournament_id required');

    require_once __DIR__ . '/../includes/supabase.php';
    $db = supabaseService();

    $rounds = $db->get('el3ab_tournament_rounds', [
        'tournament_id' => 'eq.' . $tournamentId,
        'select' => 'id,round_number,status,started_at,completed_at,pairings',
        'order' => 'round_number.asc'
    ]);

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

function getPairings(): void {
    $roundId = $_GET['round_id'] ?? '';
    if (!$roundId) jsonError('round_id required');

    require_once __DIR__ . '/../includes/supabase.php';
    $db = supabaseService();

    $round = $db->get('el3ab_tournament_rounds', ['id' => 'eq.' . $roundId, 'select' => 'pairings,results', 'limit' => 1]);

    if (empty($round) || isset($round['error'])) jsonResponse(['pairings' => []]);

    $rawP = $round[0]['pairings'] ?? '[]';
    $pairings = is_array($rawP) ? $rawP : json_decode($rawP, true);
    $rawR = $round[0]['results'] ?? '[]';
    $results = is_array($rawR) ? $rawR : json_decode($rawR, true);

    jsonResponse(['pairings' => $pairings, 'results' => $results]);
}

function getMyGames(): void {
    $token = requireAuth();
    $userId = getUserId($token);
    $tournamentId = $_GET['tournament_id'] ?? '';
    if (!$tournamentId) jsonError('tournament_id required');

    require_once __DIR__ . '/../includes/supabase.php';
    $db = supabase($token);

    $matches = $db->get('matches', [
        'tournament_id' => 'eq.' . $tournamentId,
        'or' => "(white_player_id.eq.{$userId},black_player_id.eq.{$userId})",
        'select' => 'id,white_player_id,black_player_id,result,status,tournament_round,created_at',
        'order' => 'tournament_round.asc'
    ]);

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

function getBracket(): void {
    $tournamentId = $_GET['tournament_id'] ?? '';
    if (!$tournamentId) jsonError('tournament_id required');

    require_once __DIR__ . '/../includes/supabase.php';
    $db = supabaseService();

    // Get bracket structure
    $brackets = $db->get('tournament_brackets', [
        'tournament_id' => 'eq.' . $tournamentId,
        'select' => 'id,bracket_type,total_rounds,seeds',
        'limit' => 1
    ]);

    $bracket = is_array($brackets) && !empty($brackets) && !isset($brackets['error']) ? $brackets[0] : null;
    if (!$bracket) jsonResponse(['bracket' => null, 'matches' => []]);

    // Get bracket matches
    $matches = $db->get('bracket_matches', [
        'tournament_id' => 'eq.' . $tournamentId,
        'select' => 'id,round,position,player_a_id,player_b_id,result,winner_id,status,match_id',
        'order' => 'round.asc,position.asc'
    ]);

    // Enrich with player names
    $playerIds = [];
    if (is_array($matches) && !isset($matches['error'])) {
        foreach ($matches as $m) {
            if (!empty($m['player_a_id'])) $playerIds[] = $m['player_a_id'];
            if (!empty($m['player_b_id'])) $playerIds[] = $m['player_b_id'];
        }
    }

    $players = [];
    $playerIds = array_unique($playerIds);
    if (!empty($playerIds)) {
        $idFilter = 'in.(' . implode(',', $playerIds) . ')';
        $profiles = $db->get('profiles', ['id' => $idFilter, 'select' => 'id,display_name,avatar_url']);
        if (is_array($profiles) && !isset($profiles['error'])) {
            foreach ($profiles as $p) $players[$p['id']] = $p;
        }
    }

    $enriched = [];
    if (is_array($matches) && !isset($matches['error'])) {
        foreach ($matches as $m) {
            $m['player_a_name'] = $players[$m['player_a_id']]['display_name'] ?? null;
            $m['player_b_name'] = $players[$m['player_b_id']]['display_name'] ?? null;
            $enriched[] = $m;
        }
    }

    jsonResponse([
        'bracket' => $bracket,
        'matches' => $enriched
    ]);
}

function arenaJoin(): void {
    $token = requireAuth();
    $userId = getUserId($token);
    $input = getInput();
    $tournamentId = $input['tournament_id'] ?? '';
    if (!$tournamentId) jsonError('tournament_id required');

    require_once __DIR__ . '/../includes/supabase.php';
    $db = supabaseService();

    // Verify tournament is arena type and in_progress
    $tournaments = $db->get('el3ab_tournaments', [
        'id' => 'eq.' . $tournamentId,
        'select' => 'id,format,status,time_control,game_key',
        'limit' => 1
    ]);
    $tournament = is_array($tournaments) && !empty($tournaments) ? $tournaments[0] : null;
    if (!$tournament) jsonError('Tournament not found', 404);
    if ($tournament['status'] !== 'in_progress') jsonError('Tournament is not active');
    if ($tournament['format'] !== 'arena') jsonError('Not an arena tournament');

    // Mark player as seeking — upsert into arena_seekers
    $db->upsert('arena_seekers', [
        'tournament_id' => $tournamentId,
        'player_id' => $userId,
        'status' => 'seeking',
        'joined_at' => date('c')
    ], 'tournament_id,player_id');

    // Try to pair with another seeker
    $seekers = $db->get('arena_seekers', [
        'tournament_id' => 'eq.' . $tournamentId,
        'status' => 'eq.seeking',
        'player_id' => 'neq.' . $userId,
        'order' => 'joined_at.asc',
        'limit' => 1
    ]);

    if (is_array($seekers) && !empty($seekers) && !isset($seekers['error'])) {
        $opponent = $seekers[0];
        $opponentId = $opponent['player_id'];

        // Mark both as paired
        $db->update('arena_seekers', ['status' => 'paired'], ['tournament_id' => 'eq.' . $tournamentId, 'player_id' => 'eq.' . $userId]);
        $db->update('arena_seekers', ['status' => 'paired'], ['tournament_id' => 'eq.' . $tournamentId, 'player_id' => 'eq.' . $opponentId]);

        // Create match
        $whiteId = (rand(0, 1) === 0) ? $userId : $opponentId;
        $blackId = ($whiteId === $userId) ? $opponentId : $userId;

        $match = $db->insert('matches', [
            'game_key' => $tournament['game_key'] ?? 'chess',
            'white_player_id' => $whiteId,
            'black_player_id' => $blackId,
            'status' => 'in_progress',
            'time_control' => $tournament['time_control'] ?? 'blitz_3_0',
            'tournament_id' => $tournamentId,
            'current_fen' => 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1',
            'moves' => '[]',
            'metadata' => json_encode(['mode' => 'arena'])
        ]);

        $matchId = is_array($match) && !empty($match) ? ($match[0]['id'] ?? $match['id'] ?? null) : null;
        $color = ($whiteId === $userId) ? 'w' : 'b';

        jsonResponse([
            'status' => 'paired',
            'match_id' => $matchId,
            'color' => $color,
            'opponent_id' => $opponentId,
            'time_control' => $tournament['time_control']
        ]);
    }

    jsonResponse(['status' => 'seeking']);
}

function arenaStatus(): void {
    $token = requireAuth();
    $userId = getUserId($token);
    $tournamentId = $_GET['tournament_id'] ?? '';
    if (!$tournamentId) jsonError('tournament_id required');

    require_once __DIR__ . '/../includes/supabase.php';
    $db = supabaseService();

    // Check if player has a live match in this arena
    $matches = $db->get('matches', [
        'tournament_id' => 'eq.' . $tournamentId,
        'status' => 'eq.in_progress',
        'or' => "(white_player_id.eq.{$userId},black_player_id.eq.{$userId})",
        'select' => 'id,white_player_id,black_player_id,time_control',
        'order' => 'created_at.desc',
        'limit' => 1
    ]);

    if (is_array($matches) && !empty($matches) && !isset($matches['error'])) {
        $m = $matches[0];
        jsonResponse([
            'status' => 'in_game',
            'match_id' => $m['id'],
            'color' => ($m['white_player_id'] === $userId) ? 'w' : 'b',
            'opponent_id' => ($m['white_player_id'] === $userId) ? $m['black_player_id'] : $m['white_player_id'],
            'time_control' => $m['time_control']
        ]);
    }

    // Check seeker status
    $seekers = $db->get('arena_seekers', [
        'tournament_id' => 'eq.' . $tournamentId,
        'player_id' => 'eq.' . $userId,
        'select' => 'status',
        'limit' => 1
    ]);

    $seekerStatus = is_array($seekers) && !empty($seekers) ? ($seekers[0]['status'] ?? 'idle') : 'idle';
    jsonResponse(['status' => $seekerStatus]);
}

function arenaStandings(): void {
    $tournamentId = $_GET['tournament_id'] ?? '';
    if (!$tournamentId) jsonError('tournament_id required');

    require_once __DIR__ . '/../includes/supabase.php';
    $db = supabaseService();

    // Get all completed arena matches and compute standings
    $matches = $db->get('matches', [
        'tournament_id' => 'eq.' . $tournamentId,
        'status' => 'eq.completed',
        'select' => 'white_player_id,black_player_id,result',
        'order' => 'created_at.asc'
    ]);

    $scores = [];
    if (is_array($matches) && !isset($matches['error'])) {
        foreach ($matches as $m) {
            $w = $m['white_player_id'];
            $b = $m['black_player_id'];
            if (!isset($scores[$w])) $scores[$w] = ['wins' => 0, 'draws' => 0, 'losses' => 0, 'points' => 0, 'games' => 0];
            if (!isset($scores[$b])) $scores[$b] = ['wins' => 0, 'draws' => 0, 'losses' => 0, 'points' => 0, 'games' => 0];

            $scores[$w]['games']++;
            $scores[$b]['games']++;

            if ($m['result'] === 'white_wins') {
                $scores[$w]['wins']++; $scores[$w]['points'] += 2;
                $scores[$b]['losses']++;
            } elseif ($m['result'] === 'black_wins') {
                $scores[$b]['wins']++; $scores[$b]['points'] += 2;
                $scores[$w]['losses']++;
            } elseif ($m['result'] === 'draw') {
                $scores[$w]['draws']++; $scores[$w]['points'] += 1;
                $scores[$b]['draws']++; $scores[$b]['points'] += 1;
            }
        }
    }

    // Sort by points desc
    arsort($scores);
    $sorted = [];
    $playerIds = array_keys($scores);

    // Get names
    $players = [];
    if (!empty($playerIds)) {
        $idFilter = 'in.(' . implode(',', $playerIds) . ')';
        $profiles = $db->get('profiles', ['id' => $idFilter, 'select' => 'id,display_name,avatar_url']);
        if (is_array($profiles) && !isset($profiles['error'])) {
            foreach ($profiles as $p) $players[$p['id']] = $p;
        }
    }

    $rank = 1;
    foreach ($scores as $pid => $s) {
        $sorted[] = [
            'rank' => $rank++,
            'player_id' => $pid,
            'name' => $players[$pid]['display_name'] ?? 'Player',
            'avatar_url' => $players[$pid]['avatar_url'] ?? null,
            'points' => $s['points'],
            'wins' => $s['wins'],
            'draws' => $s['draws'],
            'losses' => $s['losses'],
            'games' => $s['games']
        ];
    }

    jsonResponse(['standings' => $sorted]);
}
