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

switch ($action) {
    case 'start': handleStart($userId, $input); break;
    case 'queue': handleQueue($userId, $input); break;
    case 'status': handleStatus($userId); break;
    case 'move': handleMove($userId, $input); break;
    case 'get': handleGet($userId, $input); break;
    case 'resign': handleResign($userId, $input); break;
    case 'complete': handleComplete($userId, $input); break;
    case 'dequeue': handleDequeue($userId); break;
    case 'heartbeat': handleDominoHeartbeat($userId, $input); break;
    case 'leave': handleDominoLeave($userId, $input); break;
    default: jsonError('Invalid action');
}

function handleDequeue(string $userId): void {
    $sdb = supabaseService();
    $sdb->delete('domino_queue', ['user_id' => 'eq.' . $userId]);
    jsonResponse(['success' => true]);
}

function handleStart(string $userId, array $input): void {
    $sdb = supabaseService();
    $mode = $input['mode'] ?? 'bot';
    $botLevel = $input['bot_level'] ?? 'intermediate';

    $players = [$userId, 'bot_' . $botLevel];

    $matchData = [
        'status' => 'in_progress',
        'players' => $players,
        'current_turn' => 0,
        'board' => [],
        'hands' => (object)[],
        'boneyard' => [],
        'moves' => [],
        'scores' => ['0' => 0, '1' => 0],
        'game_state' => ['move_count' => 0, 'round' => 1, 'mode' => $mode, 'bot_level' => $botLevel],
        'host_id' => $userId,
        'created_by' => $userId
    ];

    $match = $sdb->insert('domino_matches', $matchData);
    $id = $match[0]['id'] ?? $match['id'] ?? null;

    if ($id) {
        jsonResponse(['id' => $id, 'status' => 'in_progress']);
    } else {
        jsonError('Failed to create match');
    }
}

function handleQueue(string $userId, array $input): void {
    $sdb = supabaseService();

    // Anti-abuse: check if player can queue (cooldown after repeated abandons)
    $canQueue = supabaseRpc('can_player_queue', ['p_player_id' => $userId]);
    if (is_array($canQueue) && isset($canQueue['allowed']) && !$canQueue['allowed']) {
        jsonResponse(['error' => 'cooldown', 'seconds_remaining' => $canQueue['seconds_remaining'] ?? 60]);
        return;
    }

    // STEP 1: Remove ALL existing entries for this player (prevents ghost/self-match)
    $sdb->delete('domino_queue', ['user_id' => 'eq.' . $userId]);

    // STEP 2: Clean stale entries from other players (older than 90 seconds)
    $staleTime = gmdate('c', time() - 90);
    $sdb->delete('domino_queue', [
        'match_id' => 'is.null',
        'created_at' => 'lt.' . $staleTime
    ]);

    // STEP 3: Search for available opponent
    $searchUrl = SUPABASE_REST . '/domino_queue'
        . '?user_id=neq.' . $userId
        . '&match_id=is.null'
        . '&select=id,user_id'
        . '&order=created_at.asc'
        . '&limit=1';

    $ch = curl_init($searchUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'apikey: ' . SUPABASE_SERVICE_KEY,
        'Authorization: Bearer ' . SUPABASE_SERVICE_KEY,
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $result = curl_exec($ch);
    curl_close($ch);
    $opponents = json_decode($result, true);

    if (!empty($opponents) && isset($opponents[0])) {
        $opponent = $opponents[0];

        // STEP 4: Atomically claim opponent — prevents race conditions
        $claimResult = $sdb->update('domino_queue', [
            'match_id' => '00000000-0000-0000-0000-000000000000'
        ], [
            'id' => 'eq.' . $opponent['id'],
            'match_id' => 'is.null'
        ]);

        if (empty($claimResult) || isset($claimResult['error'])) {
            // Opponent was grabbed by someone else — add self to queue
            $sdb->insert('domino_queue', ['user_id' => $userId]);
            jsonResponse(['queued' => true]);
            return;
        }

        // STEP 5: Create match
        $players = [$opponent['user_id'], $userId];

        $matchData = [
            'status' => 'in_progress',
            'players' => $players,
            'current_turn' => 0,
            'board' => [],
            'hands' => (object)[],
            'boneyard' => [],
            'moves' => [],
            'scores' => ['0' => 0, '1' => 0],
            'game_state' => ['move_count' => 0, 'round' => 1, 'mode' => 'live'],
            'host_id' => $opponent['user_id']
        ];

        $match = $sdb->insert('domino_matches', $matchData);
        $matchId = $match[0]['id'] ?? $match['id'] ?? null;

        if ($matchId) {
            $sdb->update('domino_queue', ['match_id' => $matchId], ['id' => 'eq.' . $opponent['id']]);

            jsonResponse([
                'match_id' => $matchId,
                'player_index' => 1,
                'players' => $players,
                'color' => 'player2'
            ]);
            return;
        }
    }

    // No opponent found — add to queue
    $sdb->insert('domino_queue', ['user_id' => $userId]);
    jsonResponse(['queued' => true]);
}

function handleStatus(string $userId): void {
    $sdb = supabaseService();

    $entry = $sdb->get('domino_queue', [
        'user_id' => 'eq.' . $userId,
        'select' => 'id,match_id',
        'limit' => 1
    ]);

    if (!empty($entry) && !isset($entry['error']) && !empty($entry[0]['match_id'])) {
        $matchId = $entry[0]['match_id'];
        $sdb->delete('domino_queue', ['user_id' => 'eq.' . $userId]);

        $matches = $sdb->get('domino_matches', ['id' => 'eq.' . $matchId, 'select' => 'players', 'limit' => 1]);
        $players = [];
        if (!empty($matches) && !isset($matches['error'])) {
            $players = json_decode($matches[0]['players'] ?? '[]', true);
        }
        $playerIndex = array_search($userId, $players);

        jsonResponse([
            'match_id' => $matchId,
            'player_index' => $playerIndex !== false ? $playerIndex : 0,
            'players' => $players
        ]);
    }

    jsonResponse(['waiting' => true]);
}

function handleMove(string $userId, array $input): void {
    $matchId = $input['match_id'] ?? '';
    if (!$matchId) jsonError('match_id required');

    $sdb = supabaseService();
    $update = [];

    if (isset($input['board'])) {
        $board = $input['board'];
        $update['board'] = is_string($board) ? json_decode($board, true) : $board;
    }
    if (isset($input['hands'])) {
        $newHands = is_string($input['hands']) ? json_decode($input['hands'], true) : $input['hands'];
        // Merge with existing hands to preserve other player's data
        $existingMatch = $sdb->get('domino_matches', ['id' => 'eq.' . $matchId, 'select' => 'hands', 'limit' => 1]);
        $existingHands = [];
        if (!empty($existingMatch) && !isset($existingMatch['error']) && !empty($existingMatch[0]['hands'])) {
            $raw = $existingMatch[0]['hands'];
            $existingHands = is_string($raw) ? json_decode($raw, true) : $raw;
        }
        $mergedHands = array_merge($existingHands ?: [], $newHands ?: []);
        $update['hands'] = !empty($mergedHands) ? $mergedHands : (object)[];
    }
    if (isset($input['boneyard'])) {
        $boneyard = $input['boneyard'];
        $update['boneyard'] = is_string($boneyard) ? json_decode($boneyard, true) : $boneyard;
    }
    if (isset($input['current_turn'])) {
        $update['current_turn'] = intval($input['current_turn']);
    }
    if (isset($input['scores'])) {
        $scores = $input['scores'];
        $update['scores'] = is_string($scores) ? json_decode($scores, true) : $scores;
    }
    if (isset($input['game_state'])) {
        $existing = $sdb->get('domino_matches', ['id' => 'eq.' . $matchId, 'select' => 'game_state', 'limit' => 1]);
        $existingGs = [];
        if (!empty($existing) && !isset($existing['error']) && !empty($existing[0]['game_state'])) {
            $raw = $existing[0]['game_state'];
            $existingGs = is_string($raw) ? (json_decode($raw, true) ?: []) : (is_array($raw) && !array_is_list($raw) ? $raw : []);
        }
        $newGs = is_string($input['game_state']) ? json_decode($input['game_state'], true) : $input['game_state'];
        $merged = array_merge($existingGs, $newGs ?: []);
        $update['game_state'] = $merged;
    }
    if (isset($input['status'])) {
        $update['status'] = $input['status'];
    }
    if (isset($input['winner_id'])) {
        $update['winner_id'] = $input['winner_id'];
    }
    if (isset($input['result'])) {
        $update['result'] = $input['result'];
    }

    $update['last_activity'] = date('c');

    if (!empty($update)) {
        $update['updated_at'] = date('c');
        $sdb->update('domino_matches', $update, ['id' => 'eq.' . $matchId]);
    }
    jsonResponse(['success' => true]);
}

function handleGet(string $userId, array $input): void {
    $matchId = $input['match_id'] ?? ($_GET['match_id'] ?? '');
    if (!$matchId) jsonError('match_id required');

    $sdb = supabaseService();
    $matches = $sdb->get('domino_matches', ['id' => 'eq.' . $matchId, 'select' => '*', 'limit' => 1]);

    if (empty($matches) || isset($matches['error'])) jsonError('Not found', 404);

    $match = $matches[0];

    // Server-side turn timeout enforcement (30s for domino)
    if ($match['status'] === 'in_progress') {
        $timeout = supabaseRpc('enforce_turn_timeout', [
            'p_game_key' => 'domino',
            'p_match_id' => $matchId,
            'p_timeout_seconds' => 30
        ]);
        if (!empty($timeout['timeout'])) {
            $match['_turn_timed_out'] = true;
            $match['_timeout_player'] = $timeout['player_index'] ?? null;
            $match['_replace_with_bot'] = $timeout['replace_with_bot'] ?? false;
            // Re-fetch after timeout update
            $matches = $sdb->get('domino_matches', ['id' => 'eq.' . $matchId, 'select' => '*', 'limit' => 1]);
            if (!empty($matches) && !isset($matches['error'])) {
                $match = $matches[0];
                $match['_turn_timed_out'] = true;
                $match['_timeout_player'] = $timeout['player_index'] ?? null;
                $match['_replace_with_bot'] = $timeout['replace_with_bot'] ?? false;
            }
        }
    }

    $players = json_decode($match['players'] ?? '[]', true);
    $playerIndex = array_search($userId, $players);
    $hands = json_decode($match['hands'] ?? '{}', true);

    $response = $match;
    $response['my_hand'] = $hands[strval($playerIndex)] ?? [];
    $response['opponent_count'] = 0;
    foreach ($hands as $idx => $h) {
        if (intval($idx) !== $playerIndex) {
            $response['opponent_count'] = count($h);
        }
    }
    unset($response['hands']);

    jsonResponse($response);
}

function handleResign(string $userId, array $input): void {
    $matchId = $input['match_id'] ?? '';
    if (!$matchId) jsonError('match_id required');

    $sdb = supabaseService();
    $matches = $sdb->get('domino_matches', ['id' => 'eq.' . $matchId, 'select' => 'id,status,players', 'limit' => 1]);

    if (empty($matches) || isset($matches['error'])) jsonError('Match not found', 404);
    $match = $matches[0];
    if ($match['status'] === 'completed') jsonError('Match already ended');

    $rawPlayers = $match['players'] ?? [];
    $players = is_string($rawPlayers) ? json_decode($rawPlayers, true) : $rawPlayers;
    $playerIndex = array_search($userId, $players);
    $winnerIndex = $playerIndex === 0 ? 1 : 0;
    $winnerId = $players[$winnerIndex] ?? null;

    $sdb->update('domino_matches', [
        'status' => 'completed',
        'result' => 'player' . ($winnerIndex + 1) . '_wins',
        'winner_id' => $winnerId,
        'game_state' => ['resigned_by' => $userId, 'move_count' => 999],
        'updated_at' => date('c')
    ], ['id' => 'eq.' . $matchId]);

    jsonResponse(['result' => 'resigned']);
}

function handleComplete(string $userId, array $input): void {
    $matchId = $input['match_id'] ?? '';
    if (!$matchId) jsonError('match_id required');
    $winners = $input['winners'] ?? [];
    $reason = $input['reason'] ?? 'normal';

    $sdb = supabaseService();

    // Mark match as completed
    $sdb->update('domino_matches', [
        'status' => 'completed',
        'completed_at' => date('c'),
        'result' => $reason,
        'winners' => is_array($winners) ? $winners : [],
        'updated_at' => date('c')
    ], ['id' => 'eq.' . $matchId]);

    // Call universal rewards function
    $result = supabaseRpc('complete_match', [
        'p_game_key' => 'domino',
        'p_match_id' => $matchId,
        'p_winners' => json_encode($winners),
        'p_reason' => $reason
    ]);

    jsonResponse($result ?: ['success' => true]);
}

function handleDominoHeartbeat(string $userId, array $input): void {
    $matchId = $input['match_id'] ?? '';
    if (!$matchId) jsonError('match_id required');

    $result = supabaseRpc('match_heartbeat', [
        'p_game_key' => 'domino',
        'p_match_id' => $matchId,
        'p_player_id' => $userId
    ]);

    jsonResponse($result ?: ['status' => 'ok']);
}

function handleDominoLeave(string $userId, array $input): void {
    $matchId = $input['match_id'] ?? '';
    if (!$matchId) jsonError('match_id required');
    $playerIndex = $input['player_index'] ?? null;

    $sdb = supabaseService();

    $matches = $sdb->get('domino_matches', ['id' => 'eq.' . $matchId, 'select' => 'players,game_state', 'limit' => 1]);
    if (empty($matches) || isset($matches['error'])) jsonError('Not found');

    $rawGs = $matches[0]['game_state'] ?? [];
    $gameState = is_string($rawGs) ? (json_decode($rawGs, true) ?: []) : (is_array($rawGs) && !array_is_list($rawGs) ? $rawGs : []);

    $gameState['bot_replaced'] = $gameState['bot_replaced'] ?? [];
    $gameState['bot_replaced'][] = [
        'player_id' => $userId,
        'player_index' => $playerIndex,
        'replaced_at' => date('c'),
        'permanent' => false
    ];

    $sdb->update('domino_matches', [
        'game_state' => $gameState,
        'last_activity' => date('c')
    ], ['id' => 'eq.' . $matchId]);

    jsonResponse(['success' => true, 'bot_replaced' => true]);
}
