<?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'] ?? '';
$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 = ['last_activity' => date('c')];
        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');

        $sdb = supabaseService();
        $sdb->update('ludo_matches', [
            'status' => 'completed',
            'winners' => json_encode($winners),
            'completed_at' => date('c')
        ], ['id' => 'eq.' . $matchId]);

        supabaseRpc('complete_match', [
            'p_game_key' => 'ludo',
            'p_match_id' => $matchId,
            'p_winners' => json_encode($winners),
            'p_reason' => 'normal'
        ]);
        jsonResponse(['success' => true]);
        break;

    default:
        jsonError('Invalid action');
}
