<?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 'heartbeat': handleDominoHeartbeat($userId, $input); break;
    case 'leave': handleDominoLeave($userId, $input); break;
    default: jsonError('Invalid action');
}

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' => json_encode($players),
        'current_turn' => 0,
        'board' => '[]',
        'hands' => '{}',
        'boneyard' => '[]',
        'moves' => '[]',
        'scores' => json_encode(['0' => 0, '1' => 0]),
        'game_state' => json_encode(['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;
    }

    $sdb->delete('domino_queue', ['user_id' => 'eq.' . $userId]);

    $searchUrl = SUPABASE_REST . '/domino_queue'
        . '?user_id=neq.' . $userId
        . '&match_id=is.null'
        . '&select=id,user_id'
        . '&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];
        $players = [$opponent['user_id'], $userId];

        $matchData = [
            'status' => 'in_progress',
            'players' => json_encode($players),
            'current_turn' => 0,
            'board' => '[]',
            'hands' => '{}',
            'boneyard' => '[]',
            'moves' => '[]',
            'scores' => json_encode(['0' => 0, '1' => 0]),
            'game_state' => json_encode(['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'
            ]);
        }
    }

    $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) ? $board : json_encode($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'])) {
            $existingHands = is_string($existingMatch[0]['hands']) ? json_decode($existingMatch[0]['hands'], true) : $existingMatch[0]['hands'];
        }
        $mergedHands = array_merge($existingHands ?: [], $newHands ?: []);
        $update['hands'] = json_encode($mergedHands);
    }
    if (isset($input['boneyard'])) {
        $boneyard = $input['boneyard'];
        $update['boneyard'] = is_string($boneyard) ? $boneyard : json_encode($boneyard);
    }
    if (isset($input['current_turn'])) {
        $update['current_turn'] = intval($input['current_turn']);
    }
    if (isset($input['scores'])) {
        $update['scores'] = is_string($input['scores']) ? $input['scores'] : json_encode($input['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'])) {
            $existingGs = json_decode($existing[0]['game_state'], true) ?: [];
        }
        $newGs = is_string($input['game_state']) ? json_decode($input['game_state'], true) : $input['game_state'];
        $merged = array_merge($existingGs, $newGs ?: []);
        $update['game_state'] = json_encode($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');

    $players = json_decode($match['players'] ?? '[]', true);
    $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' => json_encode(['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' => json_encode($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');

    $gameState = json_decode($matches[0]['game_state'] ?? '{}', true);

    $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' => json_encode($gameState),
        'last_activity' => date('c')
    ], ['id' => 'eq.' . $matchId]);

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