<?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/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,starts_at,ends_at,prize_pool,entry_fee',
            'order' => 'starts_at.desc',
            'limit' => 20
        ]);

        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 ($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');
