<?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/supabase.php';
require_once __DIR__ . '/../includes/auth.php';

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $action = $_GET['action'] ?? 'list';
    $db = supabaseService();

    if ($action === 'list') {
        $tournaments = $db->get('el3ab_tournaments', [
            'select' => 'id,name,game_key,format,time_control,status,max_players,swiss_rounds,starts_at,ends_at,prize_pool_coins,entry_fee_coins',
            'order' => 'created_at.desc',
            'limit' => 50
        ]);

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

        foreach ($tournaments as &$t) {
            $regs = $db->get('tournament_registrations', [
                'tournament_id' => 'eq.' . $t['id'],
                'select' => 'id',
                'status' => 'eq.registered'
            ]);
            $t['player_count'] = is_array($regs) && !isset($regs['error']) ? count($regs) : 0;
        }

        jsonResponse(['tournaments' => $tournaments]);
    }

    if ($action === 'detail') {
        $id = $_GET['id'] ?? '';
        if (!$id) jsonError('id required');

        $tournament = $db->getOne('el3ab_tournaments', ['id' => 'eq.' . $id]);
        if (!$tournament || isset($tournament['error'])) jsonError('Not found', 404);

        jsonResponse($tournament);
    }

    if ($action === 'my-registrations') {
        $token = requireAuth();
        $userId = getUserId($token);
        $regs = $db->get('tournament_registrations', [
            'player_id' => 'eq.' . $userId,
            'status' => 'eq.registered',
            'select' => 'tournament_id'
        ]);
        jsonResponse(['registrations' => is_array($regs) && !isset($regs['error']) ? $regs : []]);
    }
}

if ($method === 'POST') {
    $token = requireAuth();
    $userId = getUserId($token);
    $input = getInput();
    $action = $input['action'] ?? '';

    $db = supabase($token);

    if ($action === 'register') {
        $tournamentId = $input['tournament_id'] ?? '';
        if (!$tournamentId) jsonError('tournament_id required');

        $existing = $db->get('tournament_registrations', [
            'tournament_id' => 'eq.' . $tournamentId,
            'player_id' => 'eq.' . $userId,
            'select' => 'id'
        ]);
        if (!empty($existing) && !isset($existing['error'])) jsonError('Already registered');

        $result = $db->insert('tournament_registrations', [
            'tournament_id' => $tournamentId,
            'player_id' => $userId,
            'status' => 'registered'
        ]);

        if (isset($result['error'])) jsonError($result['error']);
        jsonResponse(['success' => true]);
    }

    if ($action === 'cancel') {
        $tournamentId = $input['tournament_id'] ?? '';
        if (!$tournamentId) jsonError('tournament_id required');

        $db->delete('tournament_registrations', [
            'tournament_id' => 'eq.' . $tournamentId,
            'player_id' => 'eq.' . $userId
        ]);
        jsonResponse(['success' => true]);
    }
}

jsonError('Invalid request');
