<?php

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

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;
    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' => []]);

    $pairings = json_decode($round[0]['pairings'] ?? '[]', true);
    $results = json_decode($round[0]['results'] ?? '[]', 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 : []]);
}
