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

switch ($action) {
    case 'create_room':
        $db = supabase($token);
        $table = $gameKey === 'domino' ? 'domino_matches' : 'ludo_matches';
        $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 = $gameKey === 'domino' ? 'domino_matches' : 'ludo_matches';
        $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');
}
