<?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':
        $match = $db->insert('ludo_matches', [
            'room_code' => strtoupper(substr(bin2hex(random_bytes(3)), 0, 6)),
            'status' => 'waiting',
            'players' => json_encode([$userId]),
            'positions' => '{}',
            'dice_value' => null,
            'current_turn' => 0,
            'winners' => '[]',
            'created_by' => $userId
        ]);
        jsonResponse($match[0] ?? $match);
        break;

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

        $players = json_decode($match['players'], true) ?: [];
        $players[] = $userId;

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

    case 'roll':
        $matchId = $input['match_id'] ?? '';
        if (!$matchId) jsonError('match_id required');
        $dice = random_int(1, 6);
        $db->update('ludo_matches', ['dice_value' => $dice], ['id' => 'eq.' . $matchId]);
        jsonResponse(['dice' => $dice]);
        break;

    case 'move':
        $matchId = $input['match_id'] ?? '';
        $positions = $input['positions'] ?? null;
        $currentTurn = $input['current_turn'] ?? null;
        if (!$matchId) jsonError('match_id required');

        $update = [];
        if ($positions !== null) $update['positions'] = json_encode($positions);
        if ($currentTurn !== null) $update['current_turn'] = $currentTurn;
        if (!empty($update)) $db->update('ludo_matches', $update, ['id' => 'eq.' . $matchId]);
        jsonResponse(['success' => true]);
        break;

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

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

    default:
        jsonError('Invalid action');
}
