<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: 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';

$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';
        $code = strtoupper(substr(bin2hex(random_bytes(3)), 0, 6));
        $result = $db->insert($table, [
            'room_code' => $code,
            'status' => 'waiting',
            'players' => json_encode([$userId]),
            'created_by' => $userId
        ]);
        jsonResponse(['room_code' => $code, 'match' => $result[0] ?? $result]);
        break;

    case 'join_room':
        $roomCode = $input['room_code'] ?? '';
        if (!$roomCode) jsonError('room_code required');
        $db = supabase($token);
        $table = $gameKey === 'domino' ? 'domino_matches' : 'ludo_matches';
        $match = $db->getOne($table, ['room_code' => 'eq.' . $roomCode, 'status' => 'eq.waiting']);
        if (!$match) jsonError('Room not found', 404);

        $players = json_decode($match['players'] ?? '[]', true);
        $players[] = $userId;
        $db->update($table, ['players' => json_encode($players)], ['id' => 'eq.' . $match['id']]);
        jsonResponse(['success' => true, 'match_id' => $match['id']]);
        break;

    default:
        jsonError('Invalid action');
}
