<?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'] ?? '';
$db = supabase($token);

switch ($action) {
    case 'create':
        $room = $db->insert('domino_matches', [
            'room_code' => generateRoomCode(),
            'status' => 'waiting',
            'players' => json_encode([$userId]),
            'board' => '[]',
            'hands' => '{}',
            'scores' => '{}',
            'created_by' => $userId
        ]);
        jsonResponse($room[0] ?? $room);
        break;

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

        $players = json_decode($match['players'], true) ?: [];
        if (in_array($userId, $players)) jsonError('Already in room');
        $players[] = $userId;

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

    case 'play':
        $matchId = $input['match_id'] ?? '';
        $board = $input['board'] ?? null;
        $hands = $input['hands'] ?? null;
        if (!$matchId) jsonError('match_id required');

        $update = [];
        if ($board !== null) $update['board'] = json_encode($board);
        if ($hands !== null) $update['hands'] = json_encode($hands);
        if (!empty($update)) $db->update('domino_matches', $update, ['id' => 'eq.' . $matchId]);
        jsonResponse(['success' => true]);
        break;

    case 'end':
        $matchId = $input['match_id'] ?? '';
        $scores = $input['scores'] ?? [];
        if (!$matchId) jsonError('match_id required');

        $db->update('domino_matches', [
            'status' => 'completed',
            'scores' => json_encode($scores)
        ], ['id' => 'eq.' . $matchId]);
        jsonResponse(['success' => true]);
        break;

    default:
        jsonError('Invalid action');
}

function generateRoomCode(): string {
    return strtoupper(substr(bin2hex(random_bytes(3)), 0, 6));
}
