<?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';

$token = requireAuth();
$userId = getUserId($token);
$input = getInput();
$action = $input['action'] ?? '';
$gameKey = $input['game_key'] ?? '';

$validGames = ['chess', 'ludo', 'domino', 'backgammon'];
if ($gameKey && !in_array($gameKey, $validGames)) { jsonError('Invalid game_key', 400); }

function resolveTable(string $gameKey): string {
    return match($gameKey) {
        'chess' => 'matches',
        'domino' => 'domino_matches',
        'backgammon' => 'backgammon_matches',
        default => 'ludo_matches',
    };
}

switch ($action) {
    case 'create_room':
        $db = supabase($token);
        $table = resolveTable($gameKey);
        $result = null;
        $code = '';
        for ($attempt = 0; $attempt < 5; $attempt++) {
            $code = strtoupper(substr(bin2hex(random_bytes(3)), 0, 6));
            $existing = $db->get($table, ['room_code' => 'eq.' . $code, 'status' => 'eq.waiting', 'limit' => 1]);
            if (!empty($existing) && !isset($existing['error'])) continue;
            $result = $db->insert($table, [
                'room_code' => $code,
                'status' => 'waiting',
                'players' => json_encode([$userId]),
                'created_by' => $userId
            ]);
            break;
        }
        if (!$result) jsonError('Failed to generate unique room code', 500);
        jsonResponse(['room_code' => $code, 'match' => $result[0] ?? $result]);
        break;

    case 'join_room':
        $roomCode = $input['room_code'] ?? '';
        if (!$roomCode) jsonError('room_code required');
        $sdb = supabaseService();
        $table = resolveTable($gameKey);
        $match = $sdb->get($table, ['room_code' => 'eq.' . $roomCode, 'status' => 'eq.waiting', 'select' => 'id,players,player_count', 'limit' => 1]);
        if (!is_array($match) || empty($match) || isset($match['error'])) jsonError('Room not found', 404);
        $match = $match[0];

        $players = is_array($match['players']) ? $match['players'] : json_decode($match['players'] ?? '[]', true);
        if (in_array($userId, $players)) {
            jsonResponse(['success' => true, 'match_id' => $match['id']]);
            break;
        }
        $maxPlayers = $match['player_count'] ?? ($gameKey === 'domino' ? 2 : 4);
        if (count($players) >= $maxPlayers) jsonError('Room is full', 409);

        $players[] = $userId;
        $newStatus = count($players) >= $maxPlayers ? 'in_progress' : 'waiting';
        $sdb->update($table, ['players' => $players, 'status' => $newStatus], ['id' => 'eq.' . $match['id']]);
        jsonResponse(['success' => true, 'match_id' => $match['id']]);
        break;

    default:
        jsonError('Invalid action');
}
