<?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') {
    $id = $_GET['id'] ?? null;

    if ($id) {
        $res = supabase_rest('GET', "tournaments?id=eq.{$id}&select=*", [], SUPABASE_SERVICE_KEY);
        $tournament = ($res['status'] === 200 && !empty($res['data'])) ? $res['data'][0] : null;

        $standings = [];
        if ($tournament) {
            $standingsRes = supabase_rest('GET', "tournament_participants?tournament_id=eq.{$id}&select=*,player:profiles(username,display_name)&order=points.desc", [], $token);
            if ($standingsRes['status'] === 200 && is_array($standingsRes['data'])) {
                foreach ($standingsRes['data'] as $row) {
                    $standings[] = array_merge($row['player'] ?? [], ['points' => $row['points'] ?? 0]);
                }
            }
        }

        echo json_encode(['tournament' => $tournament, 'standings' => $standings]);
    } else {
        $res = supabase_rest('GET', 'tournaments?select=*&order=created_at.desc&limit=30', [], SUPABASE_SERVICE_KEY);
        echo json_encode(['tournaments' => $res['data'] ?? []]);
    }
} elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';

    if ($action === 'join') {
        $tournamentId = $input['tournament_id'] ?? '';
        $res = supabase_rest('POST', 'tournament_participants', [
            'tournament_id' => $tournamentId,
            'points' => 0,
            'games_played' => 0
        ], $token);

        if ($res['status'] >= 200 && $res['status'] < 300) {
            echo json_encode(['ok' => true]);
        } else {
            http_response_code(400);
            echo json_encode(['error' => 'could not join', 'details' => $res['data']]);
        }
    } else {
        echo json_encode(['error' => 'invalid action']);
    }
}
