resolveUserId(); if (!$userId) { return response()->json(['active' => false]); } $this->ensureReadyTables(); /* * GIGAX FIX: * O QueueController já cria o lobby e os participantes. * Este hub agora garante que, ao existir um lobby ready_check para o usuário, * as tabelas match_ready_checks e match_ready_players sejam preenchidas/reativadas. */ $this->bootstrapReadyCheckForUser((int) $userId); $this->expireOldReadyChecks(); $check = DB::table('match_ready_checks as rc') ->join('mix_training_matches as m', 'm.id', '=', 'rc.lobby_id') ->where('rc.user_id', (int) $userId) ->where(function ($query) { $query->where(function ($pending) { $pending->where('rc.status', 'pending') ->where('rc.expires_at', '>', now()); })->orWhere('rc.status', 'accepted'); }) ->whereIn('m.status', ['ready_check', 'veto', 'in_progress']) ->select( 'rc.lobby_id', 'rc.status as user_ready_status', 'rc.expires_at', 'm.title', 'm.map_name', 'm.training_type', 'm.status as lobby_status', 'm.ready_status', 'm.ready_check_status', 'm.host_id', 'm.voice_mode', 'm.discord_invite_url', 'm.discord_room_name', 'm.teamspeak_channel_name', 'm.teamspeak_password', 'm.anti_cheat_required' ) ->orderByDesc('rc.id') ->first(); if (!$check) { return response()->json(['active' => false]); } $players = DB::table('match_ready_checks') ->join('users', 'users.id', '=', 'match_ready_checks.user_id') ->leftJoin('match_ready_players as mrp', function ($join) { $join->on('mrp.user_id', '=', 'match_ready_checks.user_id') ->on('mrp.match_id', '=', 'match_ready_checks.lobby_id'); }) ->leftJoin('lobby_match_captains as captain', function ($join) { $join->on('captain.user_id', '=', 'match_ready_checks.user_id') ->on('captain.training_match_id', '=', 'match_ready_checks.lobby_id'); }) ->where('match_ready_checks.lobby_id', $check->lobby_id) ->select( 'users.id', 'users.nickname', 'users.avatar_url', 'users.avatar', 'match_ready_checks.status', DB::raw('ISNULL(mrp.team, 1) as team'), DB::raw('CASE WHEN captain.user_id IS NULL THEN 0 ELSE 1 END as is_captain') ) ->orderBy('team') ->orderByDesc('is_captain') ->orderBy('users.nickname') ->get(); $accepted = $players->where('status', 'accepted')->count(); $declined = $players->where('status', 'declined')->count(); $pending = $players->where('status', 'pending')->count(); $timeout = $players->where('status', 'timeout')->count(); $secondsRemaining = max(0, now()->diffInSeconds(\Carbon\Carbon::parse($check->expires_at), false)); // GIGAX_V161_C1S_DYNAMIC_READY: // DM/C1S usa a quantidade REAL de jogadores presentes no ready-check. // Os modos competitivos oficiais continuam usando REQUIRED_COUNT=10. $requiredCount = $this->requiredReadyCount((int) $check->lobby_id); /* * GIGAX_V162_C1S_TS3_AUTO_TRIGGER * O QA/autopilot confirma bots diretamente no banco. Nesse caminho o * ultimo ACCEPT pode nao passar por accept(), portanto o READY aparece * completo no modal mas a criacao do TS3 nunca e disparada. * * O proprio status detecta C1S 100% confirmado e executa a transicao * idempotente. Se o TS3 falhar, markLobbyAccepted() mantem o lobby vivo. */ $allReady = ( $accepted >= $requiredCount && $declined === 0 && $pending === 0 && $timeout === 0 ); if ($allReady && $this->isC1sLobby((int) $check->lobby_id) && !in_array(strtolower((string) $check->lobby_status), ['in_progress', 'finished', 'cancelled'], true)) { $this->markLobbyAccepted((int) $check->lobby_id); $freshMatch = DB::table('mix_training_matches') ->where('id', (int) $check->lobby_id) ->first(); if ($freshMatch) { $check->lobby_status = $freshMatch->status ?? $check->lobby_status; $check->ready_status = $freshMatch->ready_status ?? $check->ready_status; $check->ready_check_status = $freshMatch->ready_check_status ?? $check->ready_check_status; $check->teamspeak_channel_name = $freshMatch->teamspeak_channel_name ?? $check->teamspeak_channel_name; $check->teamspeak_password = $freshMatch->teamspeak_password ?? $check->teamspeak_password; } } // O frontend precisa do CID real. teamspeak_channel_name pode ficar NULL // mesmo com a sala criada, porque o CID oficial vive nesta tabela. $ts3Channels = null; try { if (Schema::hasTable('lobby_ts3_channels')) { $ts3Channels = DB::table('lobby_ts3_channels') ->where('training_match_id', (int) $check->lobby_id) ->first(); } } catch (\Throwable $ignored) {} $ts3ChannelId = (int) ($ts3Channels->root_channel_id ?? 0); $ts3ChannelName = (string) ($ts3Channels->root_channel_name ?? $check->teamspeak_channel_name ?? ''); $ts3Host = (string) (config('teamspeak.host') ?: config('services.teamspeak.host') ?: env('TEAMSPEAK_HOST', '')); $ts3Port = (int) (config('teamspeak.server_port') ?: config('services.teamspeak.port') ?: env('TEAMSPEAK_PORT', 2026)); return response()->json([ 'active' => true, 'lobby_id' => (int) $check->lobby_id, 'match_id' => (int) $check->lobby_id, 'title' => $check->title ?: 'GIGAX MATCH', 'map_name' => $check->map_name ?: 'Crossfire', 'training_type' => $check->training_type ?: 'Competitivo', 'expires_at' => $check->expires_at, 'seconds_remaining' => $secondsRemaining, 'accepted_count' => $accepted, 'declined_count' => $declined, 'pending_count' => $pending, 'timeout_count' => $timeout, 'required_count' => $requiredCount, 'all_ready' => $allReady, 'lobby_status' => $check->lobby_status, 'host_id' => (int) ($check->host_id ?? 0), 'is_organizer' => ((int) ($check->host_id ?? 0) === (int) $userId), 'next_url' => url('/lobby/' . (int) $check->lobby_id), 'players' => $players, 'team_a' => $players->where('team', 1)->values(), 'team_b' => $players->where('team', 2)->values(), 'status' => $this->resolvePublicMatchStatus($accepted, $declined, $timeout, $requiredCount), 'voice' => [ 'mode' => in_array(strtolower((string) $check->voice_mode), ['discord', 'teamspeak'], true) ? strtolower((string) $check->voice_mode) : (in_array(strtolower((string) $check->voice_mode), ['b', 'teamspeak3', 'ts3'], true) ? 'teamspeak' : 'discord'), 'discord_invite_url' => $check->discord_invite_url, 'discord_room_name' => $check->discord_room_name, // V162: dados achatados para Blades antigos. 'teamspeak_channel_id' => $ts3ChannelId > 0 ? $ts3ChannelId : null, 'teamspeak_channel_name' => $ts3ChannelName !== '' ? $ts3ChannelName : null, 'teamspeak_direct_channel_name' => $ts3ChannelName !== '' ? $ts3ChannelName : null, 'teamspeak_password' => $check->teamspeak_password, 'teamspeak_host' => $ts3Host, 'teamspeak_port' => $ts3Port, // V162: payload usado pelo modal novo (voice.ts3.*). 'ts3' => [ 'enabled' => $ts3Host !== '', 'host' => $ts3Host, 'server_port' => $ts3Port, 'channel_id' => $ts3ChannelId > 0 ? $ts3ChannelId : null, 'team_room_name' => $ts3ChannelName !== '' ? $ts3ChannelName : null, 'root_channel_name' => $ts3ChannelName !== '' ? $ts3ChannelName : null, 'password' => $check->teamspeak_password, 'single_room' => $this->isC1sLobby((int) $check->lobby_id), ], 'discord_fallback_url' => config('services.discord.invite_url') ?: env('DISCORD_INVITE_URL'), ], 'anti_cheat' => [ 'required' => (bool) ($check->anti_cheat_required ?? true), 'status' => (bool) ($check->anti_cheat_required ?? true) ? 'required' : 'optional', 'label' => (bool) ($check->anti_cheat_required ?? true) ? 'Anti-cheat obrigatório' : 'Anti-cheat opcional', ], ]); } /** * Organizador define o canal de voz da partida. * Discord é o padrão; TeamSpeak só é ativado quando necessário. */ public function updateVoiceMode(Request $request) { $userId = $this->resolveUserId(); $lobbyId = $this->resolveLobbyId($request); $mode = strtolower((string) $request->input('voice_mode', 'discord')); if (!$userId || !$lobbyId) { return response()->json([ 'success' => false, 'message' => 'Partida ou usuário inválido.', ], 422); } if (!in_array($mode, ['discord', 'teamspeak'], true)) { return response()->json([ 'success' => false, 'message' => 'Modo de voz inválido.', ], 422); } $match = DB::table('mix_training_matches') ->where('id', (int) $lobbyId) ->select('id', 'host_id', 'voice_mode', 'status') ->first(); if (!$match) { return response()->json([ 'success' => false, 'message' => 'Partida não encontrada.', ], 404); } if ((int) $match->host_id !== (int) $userId) { return response()->json([ 'success' => false, 'message' => 'Somente o organizador pode escolher Discord ou TeamSpeak 3.', ], 403); } DB::table('mix_training_matches') ->where('id', (int) $lobbyId) ->update([ 'voice_mode' => $mode, 'updated_at' => now(), ]); Log::info('GIGAX: organizador alterou o canal de voz', [ 'match_id' => (int) $lobbyId, 'organizer_id' => (int) $userId, 'voice_mode' => $mode, ]); return response()->json([ 'success' => true, 'voice_mode' => $mode, 'message' => $mode === 'teamspeak' ? 'TeamSpeak 3 definido para esta partida.' : 'Discord definido para esta partida.', ]); } public function accept(Request $request) { $userId = $this->resolveUserId(); $lobbyId = $this->resolveLobbyId($request); if (!$userId || !$lobbyId) { return response()->json(['success' => false, 'message' => 'Dados inválidos.'], 422); } $this->ensureReadyTables(); $this->bootstrapReadyCheckForLobby((int) $lobbyId); $now = now(); $updated = DB::table('match_ready_checks') ->where('lobby_id', $lobbyId) ->where('user_id', $userId) ->where('expires_at', '>', $now) ->update([ 'status' => 'accepted', 'responded_at' => $now, 'updated_at' => $now, ]); try { DB::table('match_ready_players') ->where('match_id', $lobbyId) ->where('user_id', $userId) ->update([ 'is_ready' => 1, 'confirmed_at' => $now, 'updated_at' => $now, ]); } catch (\Throwable $ignored) {} if (!$updated) { return response()->json([ 'success' => false, 'message' => 'Ready check não encontrado, expirado ou já encerrado.', ], 409); } $summary = $this->getReadySummary($lobbyId); $requiredCount = $this->requiredReadyCount((int) $lobbyId); if (($summary['accepted'] ?? 0) >= $requiredCount && ($summary['non_accepted'] ?? 0) === 0) { $this->markLobbyAccepted($lobbyId); } return response()->json([ 'success' => true, 'accepted_count' => $summary['accepted'] ?? 0, 'required_count' => $requiredCount, 'all_ready' => (($summary['accepted'] ?? 0) >= $requiredCount && ($summary['non_accepted'] ?? 0) === 0), ]); } public function decline(Request $request) { $userId = $this->resolveUserId(); $lobbyId = $this->resolveLobbyId($request); if (!$userId || !$lobbyId) { return response()->json(['success' => false, 'message' => 'Dados inválidos.'], 422); } $now = now(); $updated = DB::table('match_ready_checks') ->where('lobby_id', $lobbyId) ->where('user_id', $userId) ->update([ 'status' => 'declined', 'responded_at' => $now, 'updated_at' => $now, ]); try { DB::table('match_ready_players') ->where('match_id', $lobbyId) ->where('user_id', $userId) ->update([ 'is_ready' => 0, 'confirmed_at' => null, 'updated_at' => $now, ]); } catch (\Throwable $ignored) {} if (!$updated) { return response()->json([ 'success' => false, 'message' => 'Ready check não encontrado.', ], 404); } $this->cancelLobby($lobbyId, 'declined'); return response()->json(['success' => true]); } private function bootstrapReadyCheckForUser(int $userId): void { $lobby = DB::table('mix_training_matches as m') ->join('mix_training_participants as tp', 'tp.training_match_id', '=', 'm.id') ->where('tp.user_id', $userId) ->whereNull('tp.left_at') ->where('m.status', 'ready_check') ->select('m.id') ->orderByDesc('m.created_at') ->orderByDesc('m.id') ->first(); if ($lobby) { $this->bootstrapReadyCheckForLobby((int) $lobby->id); } } private function bootstrapReadyCheckForLobby(int $lobbyId): void { try { $lobby = DB::table('mix_training_matches') ->where('id', $lobbyId) ->where('status', 'ready_check') ->first(); if (!$lobby) { return; } $participants = DB::table('mix_training_participants') ->where('training_match_id', $lobbyId) ->whereNull('left_at') ->orderBy('team') ->orderBy('joined_at') ->get(); if ($participants->count() < 2) { return; } $now = now(); /* * GIGAX_V164_READY_SINGLE_CLOCK * * status() chama este bootstrap em cada polling. Se o READY ja existe, * o polling NAO pode criar um novo prazo apenas no registro da partida. * O prazo oficial da rodada e o expires_at ja gravado nos checks. * * Isso evita o caso em que mix_training_matches parecia ter acabado de * reiniciar o READY, enquanto match_ready_checks ja estava expirado. */ $existingDeadline = DB::table('match_ready_checks') ->where('lobby_id', $lobbyId) ->where('status', 'pending') ->whereNotNull('expires_at') ->min('expires_at'); $expiresAt = $existingDeadline ? \Carbon\Carbon::parse($existingDeadline) : $now->copy()->addSeconds(self::READY_SECONDS); foreach ($participants as $participant) { $userId = (int) $participant->user_id; $team = (int) ($participant->team ?: 1); $existingCheck = DB::table('match_ready_checks') ->where('lobby_id', $lobbyId) ->where('user_id', $userId) ->first(); if ($existingCheck) { // Não renova expires_at durante polling de status. } else { DB::table('match_ready_checks')->insert([ 'lobby_id' => $lobbyId, 'user_id' => $userId, 'status' => 'pending', 'expires_at' => $expiresAt, 'responded_at' => null, 'created_at' => $now, 'updated_at' => $now, ]); } $existingPlayer = DB::table('match_ready_players') ->where('match_id', $lobbyId) ->where('user_id', $userId) ->first(); if ($existingPlayer) { DB::table('match_ready_players') ->where('id', $existingPlayer->id) ->update([ 'team' => $team, 'updated_at' => $now, ]); } else { DB::table('match_ready_players')->insert([ 'match_id' => $lobbyId, 'user_id' => $userId, 'team' => $team, 'is_ready' => 0, 'confirmed_at' => null, 'created_at' => $now, 'updated_at' => $now, ]); } } $update = [ 'ready_status' => 'pending', 'ready_check_status' => 'pending', 'updated_at' => $now, ]; // Polling nao renova o relogio da rodada. Preenche apenas metadados // ausentes e sempre usando o mesmo deadline dos match_ready_checks. if (Schema::hasColumn('mix_training_matches', 'ready_check_started_at') && empty($lobby->ready_check_started_at)) { $update['ready_check_started_at'] = $now; } if (Schema::hasColumn('mix_training_matches', 'ready_check_expires_at') && empty($lobby->ready_check_expires_at)) { $update['ready_check_expires_at'] = $expiresAt; } DB::table('mix_training_matches') ->where('id', $lobbyId) ->update($update); } catch (\Throwable $e) { Log::error('Erro ao inicializar ready-check no MatchHubController', [ 'lobby_id' => $lobbyId, 'error' => $e->getMessage(), ]); } } private function ensureReadyTables(): void { try { DB::statement(" IF OBJECT_ID('dbo.match_ready_checks', 'U') IS NULL BEGIN CREATE TABLE dbo.match_ready_checks ( id INT IDENTITY(1,1) PRIMARY KEY, lobby_id INT NOT NULL, user_id INT NOT NULL, status NVARCHAR(30) NOT NULL DEFAULT 'pending', expires_at DATETIME2 NOT NULL, responded_at DATETIME2 NULL, created_at DATETIME2 NULL, updated_at DATETIME2 NULL ) END " ); DB::statement(" IF OBJECT_ID('dbo.match_ready_players', 'U') IS NULL BEGIN CREATE TABLE dbo.match_ready_players ( id INT IDENTITY(1,1) PRIMARY KEY, match_id INT NOT NULL, user_id INT NOT NULL, team INT NOT NULL DEFAULT 1, is_ready BIT NOT NULL DEFAULT 0, confirmed_at DATETIME2 NULL, created_at DATETIME2 NULL, updated_at DATETIME2 NULL ) END " ); } catch (\Throwable $e) { Log::warning('Falha ao garantir tabelas do hub 5v5', ['error' => $e->getMessage()]); } } private function resolveUserId(): ?int { $userId = session('user_id') ?: Auth::id(); return $userId ? (int) $userId : null; } private function resolveLobbyId(Request $request): int { return (int) ($request->input('lobby_id') ?: $request->input('match_id') ?: 0); } private function expireOldReadyChecks(): void { try { /* * GIGAX_V163_READY_TIMEOUT_RACE_FIX * * A primeira consulta serve apenas para localizar candidatos. * Antes de transformar um jogador em timeout, revalidamos no UPDATE * que ele continua pending E realmente expirado. * * Assim, se o READY tiver sido renovado/confirmado entre o SELECT e * o UPDATE, o jogador nao recebe timeout e nao perde a vaga. */ $expiredLobbyIds = DB::table('match_ready_checks as rc') ->join('mix_training_matches as m', 'm.id', '=', 'rc.lobby_id') ->where('rc.status', 'pending') ->where('rc.expires_at', '<=', now()) ->where('m.status', 'ready_check') ->distinct() ->pluck('rc.lobby_id'); if ($expiredLobbyIds->isEmpty()) { return; } foreach ($expiredLobbyIds as $lobbyId) { $lobbyId = (int) $lobbyId; $now = now(); $expiredUserIds = DB::table('match_ready_checks') ->where('lobby_id', $lobbyId) ->where('status', 'pending') ->where('expires_at', '<=', $now) ->pluck('user_id') ->map(fn ($id) => (int) $id) ->filter() ->values(); if ($expiredUserIds->isEmpty()) { continue; } $updated = DB::table('match_ready_checks') ->where('lobby_id', $lobbyId) ->whereIn('user_id', $expiredUserIds->all()) ->where('status', 'pending') ->where('expires_at', '<=', $now) ->update([ 'status' => 'timeout', 'responded_at' => $now, 'updated_at' => $now, ]); // Nada mudou: outro request confirmou/renovou o READY. if ($updated <= 0) { continue; } try { DB::table('match_ready_players') ->where('match_id', $lobbyId) ->whereIn('user_id', $expiredUserIds->all()) ->where(function ($query) { $query->whereNull('is_ready')->orWhere('is_ready', 0); }) ->update([ 'confirmed_at' => null, 'updated_at' => $now, ]); } catch (\Throwable $ignored) {} $this->cancelLobby($lobbyId, 'timeout'); } } catch (\Throwable $e) { Log::warning('Falha ao expirar ready check', [ 'error' => $e->getMessage(), ]); } } private function getReadySummary(int $lobbyId): array { $rows = DB::table('match_ready_checks') ->where('lobby_id', $lobbyId) ->select('status', DB::raw('COUNT(*) as total')) ->groupBy('status') ->get(); $summary = [ 'accepted' => 0, 'pending' => 0, 'declined' => 0, 'timeout' => 0, 'non_accepted' => 0, ]; foreach ($rows as $row) { $status = (string) $row->status; $summary[$status] = (int) $row->total; } $summary['non_accepted'] = ($summary['pending'] ?? 0) + ($summary['declined'] ?? 0) + ($summary['timeout'] ?? 0); return $summary; } /** * GIGAX_V161_C1S_DYNAMIC_READY * * C1S/DM e uma modalidade sem veto. Quando todos os jogadores presentes * no ready-check confirmam, entra diretamente em in_progress e cria/move * a sala unica do TeamSpeak. * * Demais modos mantem exatamente o fluxo legado deste controller. */ private function requiredReadyCount(int $lobbyId): int { try { /* * GIGAX_V165_DYNAMIC_READY_X1_X8 * * Personalizada e AWP podem ser X1 ate X8. O READY precisa usar a * capacidade REAL configurada na partida (max_players/team_size), * em vez do fallback legado fixo de 10 jogadores. * * C1S/DM tambem usa capacidade variavel. MIX/5L e demais modos * oficiais continuam exatamente com REQUIRED_COUNT = 10. */ $match = DB::table('mix_training_matches') ->where('id', $lobbyId) ->select('training_type', 'mode_code', 'match_category', 'team_size', 'max_players') ->first(); if (!$match) { return self::REQUIRED_COUNT; } $trainingType = strtolower(trim((string) ($match->training_type ?? ''))); $modeCode = strtolower(trim((string) ($match->mode_code ?? ''))); $matchCategory = strtolower(trim((string) ($match->match_category ?? ''))); $isC1s = ($trainingType === 'c1s') || in_array($modeCode, ['c1s', 'dm', 'deathmatch'], true) || in_array($matchCategory, ['c1s', 'dm', 'deathmatch'], true); $isCustom = ($modeCode === 'custom') || ($matchCategory === 'custom') || preg_match('/^modox[1-8]$/', $trainingType) === 1; $isAwp = ($modeCode === 'awp') || ($matchCategory === 'awp') || in_array($trainingType, ['sniperx5', 'sniper', 'awp'], true); /* * GIGAX V175: * DM/C1S é uma sala de entrada flexível. Quando o ADMIN/HOST manda * iniciar, o READY deve exigir somente quem está PRESENTE naquele * instante. Ex.: card 8v8 com 2 jogadores -> READY 2/2. * * Personalizada/AWP continuam usando a capacidade configurada X1-X8. */ if ($isC1s) { $active = (int) DB::table('mix_training_participants') ->where('training_match_id', $lobbyId) ->whereNull('left_at') ->count(); if ($active >= 2 && $active <= 16) { return $active; } } if ($isCustom || $isAwp) { $maxPlayers = (int) ($match->max_players ?? 0); if ($maxPlayers < 2 || $maxPlayers > 16) { $teamSize = (int) ($match->team_size ?? 0); if ($teamSize >= 1 && $teamSize <= 8) { $maxPlayers = $teamSize * 2; } } if ($maxPlayers >= 2 && $maxPlayers <= 16) { return $maxPlayers; } // Fallback seguro apenas para registros legados sem capacidade. $active = (int) DB::table('mix_training_participants') ->where('training_match_id', $lobbyId) ->whereNull('left_at') ->count(); if ($active >= 2 && $active <= 16) { return $active; } } } catch (\Throwable $e) { Log::warning('GIGAX V165: falha ao calcular quantidade dinamica do READY', [ 'lobby_id' => $lobbyId, 'error' => $e->getMessage(), ]); } // MIX, 5L e modos competitivos oficiais permanecem 5v5. return self::REQUIRED_COUNT; } private function isC1sLobby(int $lobbyId): bool { try { $type = DB::table('mix_training_matches') ->where('id', $lobbyId) ->value('training_type'); return strtolower(trim((string) $type)) === 'c1s'; } catch (\Throwable $e) { return false; } } /** * TS3 V164: jogador sem UID ou offline nao e falha de infraestrutura. * Nunca ignora erros de clientmove, verificacao de CID ou canais. */ private function ts3MoveAllowsStart(array $move): bool { if (($move['success'] ?? false) === true) { return true; } if (!array_key_exists('verified', $move) || !is_array($move['verified']) || !array_key_exists('missing', $move) || !is_array($move['missing']) || !isset($move['channels']) || !is_array($move['channels'])) { return false; } foreach ($move['missing'] as $reason) { $reason = (string) $reason; if (!str_contains($reason, '(offline no TS3)') && !str_contains($reason, '(UID TS3 não vinculado)')) { return false; } } return true; } private function startC1sTeamSpeakAfterReady(int $lobbyId): array { try { $match = DB::table('mix_training_matches') ->where('id', $lobbyId) ->select('voice_mode') ->first(); $rawMode = strtolower(trim((string) ($match->voice_mode ?? ''))); $isTeamSpeak = in_array($rawMode, ['b', 'teamspeak', 'teamspeak3', 'ts3'], true); if (!$isTeamSpeak) { Log::info('GIGAX V161: C1S pronto, TS3 ignorado pelo voice_mode', [ 'lobby_id' => $lobbyId, 'voice_mode' => $rawMode, ]); return ['success' => true, 'skipped' => true, 'mode' => $rawMode]; } /** @var TeamSpeakService $ts3 */ $ts3 = app(TeamSpeakService::class); $provision = $ts3->provisionMatchChannels($lobbyId); if (!($provision['success'] ?? false)) { Log::error('GIGAX V161: falha ao criar sala unica C1S no TS3', [ 'lobby_id' => $lobbyId, 'result' => $provision, ]); return ['success' => false, 'provision' => $provision]; } $move = method_exists($ts3, 'moveMatchPlayersWithRetry') ? $ts3->moveMatchPlayersWithRetry($lobbyId, 10, 80) : $ts3->moveMatchPlayers($lobbyId); Log::info('GIGAX V161: sala unica C1S/DM provisionada apos READY', [ 'lobby_id' => $lobbyId, 'provision' => $provision, 'move' => $move, ]); return [ 'success' => $this->ts3MoveAllowsStart($move), 'provision' => $provision, 'move' => $move, ]; } catch (\Throwable $e) { Log::error('GIGAX V161: excecao ao iniciar TS3 C1S/DM', [ 'lobby_id' => $lobbyId, 'error' => $e->getMessage(), ]); return ['success' => false, 'message' => $e->getMessage()]; } } /** * GIGAX_V173_DIRECT_VOICE_AFTER_READY * * Personalizada/AWP/5L e demais modos sem veto precisam provisionar a voz * imediatamente depois do READY. Para TeamSpeak, cria a raiz + Time A/B e * tenta mover os jogadores. C1S continua usando o fluxo especial de sala unica. */ private function startVoiceAfterReady(int $lobbyId): array { try { $match = DB::table('mix_training_matches') ->where('id', $lobbyId) ->select('voice_mode') ->first(); $rawMode = strtolower(trim((string) ($match->voice_mode ?? ''))); $isTeamSpeak = in_array($rawMode, ['b', 'teamspeak', 'teamspeak3', 'ts3'], true); if ($isTeamSpeak) { /** @var TeamSpeakService $ts3 */ $ts3 = app(TeamSpeakService::class); $provision = $ts3->provisionMatchChannels($lobbyId); if (!($provision['success'] ?? false)) { Log::error('GIGAX V173: falha ao provisionar TS3 apos READY', [ 'lobby_id' => $lobbyId, 'result' => $provision, ]); return [ 'success' => false, 'mode' => 'teamspeak', 'provision' => $provision, ]; } $move = method_exists($ts3, 'moveMatchPlayersWithRetry') ? $ts3->moveMatchPlayersWithRetry($lobbyId, 10, 80) : $ts3->moveMatchPlayers($lobbyId); $result = [ 'success' => $this->ts3MoveAllowsStart($move), 'mode' => 'teamspeak', 'provision' => $provision, 'move' => $move, ]; Log::info('GIGAX V173: TS3 provisionado apos READY', [ 'lobby_id' => $lobbyId, 'result' => $result, ]); return $result; } /** @var VoiceMatchService $voice */ $voice = app(VoiceMatchService::class); $result = $voice->startForMatch($lobbyId); Log::info('GIGAX V173: voz acionada apos READY', [ 'lobby_id' => $lobbyId, 'mode' => $result['mode'] ?? $rawMode, 'result' => $result, ]); return $result; } catch (\Throwable $e) { Log::error('GIGAX V173: excecao ao acionar voz apos READY', [ 'lobby_id' => $lobbyId, 'error' => $e->getMessage(), ]); return ['success' => false, 'message' => $e->getMessage()]; } } private function markLobbyAccepted(int $lobbyId): void { if ($this->isC1sLobby($lobbyId)) { $now = now(); /* * GIGAX_V162_C1S_TS3_SAFE_ORDER * Nao muda para in_progress antes do TeamSpeak estar provisionado. * Isso impede o card/modal de desaparecer quando o TS3 falha. */ $voiceResult = $this->startC1sTeamSpeakAfterReady($lobbyId); if (!($voiceResult['success'] ?? false)) { $message = (string) ( data_get($voiceResult, 'provision.message') ?: data_get($voiceResult, 'move.message') ?: ($voiceResult['message'] ?? 'Falha ao preparar TeamSpeak 3.') ); $failedUpdate = [ 'ready_status' => 'accepted', 'ready_check_status' => 'accepted', 'status' => 'ready_check', 'updated_at' => $now, ]; if (Schema::hasColumn('mix_training_matches', 'voice_status')) { $failedUpdate['voice_status'] = 'error'; } if (Schema::hasColumn('mix_training_matches', 'voice_notes')) { $failedUpdate['voice_notes'] = mb_substr($message, 0, 500); } if (Schema::hasColumn('mix_training_matches', 'ready_check_expires_at')) { $failedUpdate['ready_check_expires_at'] = null; } DB::table('mix_training_matches') ->where('id', $lobbyId) ->update($failedUpdate); Log::error('GIGAX V162: C1S confirmado, mas TS3 falhou; partida mantida aberta', [ 'lobby_id' => $lobbyId, 'voice' => $voiceResult, ]); return; } $update = [ 'ready_status' => 'accepted', 'ready_check_status' => 'accepted', 'status' => 'in_progress', 'updated_at' => $now, ]; if (Schema::hasColumn('mix_training_matches', 'started_at')) { $update['started_at'] = $now; } if (Schema::hasColumn('mix_training_matches', 'veto_status')) { $update['veto_status'] = 'completed'; } if (Schema::hasColumn('mix_training_matches', 'ready_check_expires_at')) { $update['ready_check_expires_at'] = null; } DB::table('mix_training_matches') ->where('id', $lobbyId) ->update($update); return; } /* * GIGAX_V173_VETO_RULE_RESTORE * * Regra do projeto: * - MIX oficial e CAMPEONATOS -> seguem para veto. * - Personalizada X1-X8, AWP, 5L e demais modos sem veto -> iniciam * diretamente e acionam a voz escolhida apos o READY. * * MIX oficial e identificado pelo vinculo mix_queues.match_id para nao * confundir uma personalizada que tenha campos residuais de fila. */ $match = DB::table('mix_training_matches') ->where('id', $lobbyId) ->first(); if (!$match) { return; } $trainingType = strtolower(trim((string) ($match->training_type ?? ''))); $queueMode = strtolower(trim((string) ($match->queue_mode ?? ''))); $isChampionship = in_array( $trainingType, ['campeonatos', 'campeonato', 'championship', 'tournament'], true ); $isMix = false; try { if (Schema::hasTable('mix_queues') && Schema::hasColumn('mix_queues', 'match_id')) { $isMix = DB::table('mix_queues') ->where('match_id', $lobbyId) ->exists(); } } catch (\Throwable $e) { Log::warning('GIGAX V173: falha ao confirmar origem MIX', [ 'lobby_id' => $lobbyId, 'error' => $e->getMessage(), ]); } $usesVeto = $isChampionship || $isMix; $now = now(); if ($usesVeto) { $update = [ 'ready_status' => 'accepted', 'ready_check_status' => 'accepted', 'status' => 'veto', 'updated_at' => $now, ]; if (Schema::hasColumn('mix_training_matches', 'veto_status')) { $update['veto_status'] = 'pending'; } if (Schema::hasColumn('mix_training_matches', 'veto_started_at')) { $update['veto_started_at'] = $now; } if (Schema::hasColumn('mix_training_matches', 'ready_check_expires_at')) { $update['ready_check_expires_at'] = null; } DB::table('mix_training_matches') ->where('id', $lobbyId) ->update($update); Log::info('GIGAX V173: READY concluido com veto', [ 'lobby_id' => $lobbyId, 'training_type' => $trainingType, 'queue_mode' => $queueMode, 'is_mix' => $isMix, 'is_championship' => $isChampionship, ]); return; } /* * Modos sem veto: primeiro prepara a voz. Assim o Lobby Pronto nao * avanca para in_progress sem antes tentar criar as salas do TS3. */ $voiceResult = $this->startVoiceAfterReady($lobbyId); if (!($voiceResult['success'] ?? false)) { $message = (string) ( data_get($voiceResult, 'provision.message') ?: data_get($voiceResult, 'move.message') ?: ($voiceResult['message'] ?? 'Falha ao preparar comunicacao da partida.') ); $failedUpdate = [ 'ready_status' => 'accepted', 'ready_check_status' => 'accepted', 'status' => 'ready_check', 'updated_at' => $now, ]; if (Schema::hasColumn('mix_training_matches', 'voice_status')) { $failedUpdate['voice_status'] = 'error'; } if (Schema::hasColumn('mix_training_matches', 'voice_notes')) { $failedUpdate['voice_notes'] = mb_substr($message, 0, 500); } if (Schema::hasColumn('mix_training_matches', 'ready_check_expires_at')) { $failedUpdate['ready_check_expires_at'] = null; } DB::table('mix_training_matches') ->where('id', $lobbyId) ->update($failedUpdate); Log::error('GIGAX V173: READY concluido, mas voz falhou; partida mantida aberta', [ 'lobby_id' => $lobbyId, 'training_type' => $trainingType, 'voice' => $voiceResult, ]); return; } $update = [ 'ready_status' => 'accepted', 'ready_check_status' => 'accepted', 'status' => 'in_progress', 'updated_at' => $now, ]; if (Schema::hasColumn('mix_training_matches', 'started_at')) { $update['started_at'] = $match->started_at ?? $now; } if (Schema::hasColumn('mix_training_matches', 'veto_status')) { $update['veto_status'] = 'completed'; } if (Schema::hasColumn('mix_training_matches', 'veto_started_at')) { $update['veto_started_at'] = null; } if (Schema::hasColumn('mix_training_matches', 'veto_ended_at')) { $update['veto_ended_at'] = $now; } if (Schema::hasColumn('mix_training_matches', 'ready_check_expires_at')) { $update['ready_check_expires_at'] = null; } DB::table('mix_training_matches') ->where('id', $lobbyId) ->update($update); Log::info('GIGAX V173: READY concluido sem veto; partida iniciada', [ 'lobby_id' => $lobbyId, 'training_type' => $trainingType, 'queue_mode' => $queueMode, 'voice_mode' => $match->voice_mode ?? null, ]); } private function cancelLobby(int $lobbyId, string $reason = 'declined'): void { $now = now(); /* * GIGAX_V163_READY_CANCEL_GUARD * * Timeout so pode remover quem JA foi confirmado como timeout por * expireOldReadyChecks(). Nunca inclui pending/declined no caminho timeout. * * O lock da partida impede que um cancelamento antigo sobrescreva uma * transicao que ja avancou para veto/in_progress. */ $didCancel = DB::transaction(function () use ($lobbyId, $reason, $now) { $match = DB::table('mix_training_matches') ->where('id', $lobbyId) ->lockForUpdate() ->first(); if (!$match || (string) ($match->status ?? '') !== 'ready_check') { return false; } $failedQuery = DB::table('match_ready_checks') ->where('lobby_id', $lobbyId); if ($reason === 'declined') { $failedQuery->where('status', 'declined'); } elseif ($reason === 'timeout') { $failedQuery->where('status', 'timeout'); } else { $failedQuery->whereIn('status', ['declined', 'timeout']); } $failedIds = $failedQuery ->lockForUpdate() ->pluck('user_id') ->map(fn ($id) => (int) $id) ->filter() ->values(); // Sem recusado/timeout real, nao ha nada para cancelar. if ($failedIds->isEmpty()) { return false; } DB::table('mix_training_participants') ->where('training_match_id', $lobbyId) ->whereIn('user_id', $failedIds->all()) ->whereNull('left_at') ->update(['left_at' => $now]); DB::table('match_ready_players') ->where('match_id', $lobbyId) ->whereIn('user_id', $failedIds->all()) ->update([ 'is_ready' => 0, 'confirmed_at' => null, 'updated_at' => $now, ]); $activeCount = (int) DB::table('mix_training_participants') ->where('training_match_id', $lobbyId) ->whereNull('left_at') ->count(); $update = [ 'ready_status' => 'waiting', 'ready_check_status' => 'waiting', 'status' => 'waiting', 'updated_at' => $now, ]; if (Schema::hasColumn('mix_training_matches', 'current_players')) { $update['current_players'] = $activeCount; } if (Schema::hasColumn('mix_training_matches', 'ready_check_expires_at')) { $update['ready_check_expires_at'] = null; } DB::table('mix_training_matches') ->where('id', $lobbyId) ->where('status', 'ready_check') ->update($update); return true; }); if (!$didCancel) { Log::info('GIGAX READY REQUEUE: cancelamento ignorado por estado atualizado', [ 'lobby_id' => $lobbyId, 'reason' => $reason, ]); return; } try { for ($i = 0; $i < self::REQUIRED_COUNT; $i++) { $activeCount = (int) DB::table('mix_training_participants') ->where('training_match_id', $lobbyId) ->whereNull('left_at') ->count(); if ($activeCount >= self::REQUIRED_COUNT) { break; } $refill = app(QueueController::class)->refillWaitingMatchFromQueue($lobbyId); if (!(bool) ($refill['refilled'] ?? false)) { break; } } } catch (\Throwable $e) { Log::warning('GIGAX READY REQUEUE: falha ao completar vagas', [ 'lobby_id' => $lobbyId, 'reason' => $reason, 'error' => $e->getMessage(), ]); } Log::info('GIGAX READY REQUEUE: confirmados preservados', [ 'lobby_id' => $lobbyId, 'reason' => $reason, ]); } private function resolvePublicMatchStatus(int $accepted, int $declined, int $timeout, int $requiredCount = self::REQUIRED_COUNT): string { if ($declined > 0) { return 'Jogador recusou'; } if ($timeout > 0) { return 'Tempo esgotado'; } if ($accepted >= $requiredCount) { return 'Todos aceitaram'; } return 'Aguardando jogadores'; } }