query('game', request()->input('game', session('gx_active_game', 'crossfire'))))); $slug = preg_replace('/[^a-z0-9_-]/', '', $slug) ?: 'crossfire'; $supported = ['crossfire', 'cs2', 'valorant', 'lol', 'dota2', 'r6', 'fortnite', 'apex', 'rocket']; if (!in_array($slug, $supported, true)) { $slug = 'crossfire'; } session(['gx_active_game' => $slug]); return $slug; } private function normalizeMatchGameSlug($value = null): string { $slug = strtolower(trim((string) $value)); $slug = preg_replace('/[^a-z0-9_-]/', '', $slug) ?: 'crossfire'; return $slug; } public function __construct() { $this->middleware(function ($request, $next) { if (!Session::has('user_id')) { if ($request->expectsJson() || $request->ajax()) { return response()->json([ 'success' => false, 'message' => 'Sessao expirada. Faca login novamente.' ], 401); } return redirect()->route('login') ->with('error', 'Sessao expirada. Faca login novamente.'); } return $next($request); }); } private function acGateForUser(int $userId): array { try { return app(GigaxClientGateController::class)->readinessForUser($userId); } catch (\Throwable $e) { Log::error('AC7_GATE_ERROR', ['user_id' => $userId, 'error' => $e->getMessage()]); return ['ready' => false, 'state' => 'unavailable', 'message' => 'Validacao do AC7 indisponivel. Tente novamente.']; } } private function acGateDenied(int $userId): ?array { $gate = $this->acGateForUser($userId); if (($gate['ready'] ?? false) === true) { return null; } return [ 'success' => false, 'code' => 'AC7_REQUIRED', 'ac_state' => (string) ($gate['state'] ?? 'offline'), 'message' => (string) ($gate['message'] ?? 'Conecte o AC7 pelo JOGAR AGORA.'), 'download_url' => $gate['download_url'] ?? null, ]; } private function acGateDeniedParticipants(int $lobbyId): ?array { $ids = DB::table('mix_training_participants') ->where('training_match_id', $lobbyId) ->whereNull('left_at') ->pluck('user_id'); foreach ($ids as $id) { $userId = (int) $id; if ($denied = $this->acGateDenied($userId)) { Log::warning('AC7_GATE_LOBBY_BLOCKED', [ 'lobby_id' => $lobbyId, 'user_id' => $userId, 'ac_state' => $denied['ac_state'], ]); return [ 'success' => false, 'code' => 'AC7_PARTICIPANT_OFFLINE', 'message' => 'Todos os jogadores precisam conectar o AC7 pelo JOGAR AGORA antes de iniciar. Jogador sem protecao: #' . $userId, 'user_id' => $userId, ]; } } return null; } /* GIGAX_V198_PERSONALIZADAS_AO_VIVO: consulta leve, apenas dados ativos */ private function gxCustomLiveSignature(): string { $matches = DB::table('mix_training_matches') ->whereIn('status', ['waiting', 'ready_check', 'veto', 'in_progress']) ->orderBy('id') ->get(['id', 'status', 'updated_at']); $ids = $matches->pluck('id')->map(fn ($id) => (int) $id)->all(); $players = empty($ids) ? collect() : DB::table('mix_training_participants') ->whereIn('training_match_id', $ids) ->whereNull('left_at') ->orderBy('training_match_id')->orderBy('user_id') ->get(['training_match_id', 'user_id', 'team']); return hash('sha256', json_encode([$matches, $players])); } public function index() { /* GIGAX_V198_PERSONALIZADAS_AO_VIVO */ if (request()->query('gx_custom_live') === '1') { return response()->json([ 'success' => true, 'signature' => $this->gxCustomLiveSignature(), ])->header('Cache-Control', 'no-store, no-cache, must-revalidate'); } $userId = (int) Session::get('user_id'); $activeGameSlug = $this->activeGameSlugFromRequest(); $currentUser = DB::table('users') ->select( 'id', 'nickname', 'avatar_url', 'league_tag', 'skill_level', DB::raw('COALESCE(rank_points, 0) as rank_points'), 'last_seen_at' ) ->where('id', $userId) ->first(); $currentUser = $currentUser ?: (object) [ 'id' => $userId, 'nickname' => Session::get('user_nickname', 'Jogador'), 'avatar_url' => '/default-avatar.png', 'league_tag' => null, 'skill_level' => 1, 'rank_points' => 0, 'last_seen_at' => null, ]; $queues = collect(); $firstQueue = null; $queuePlayers = collect(); $inQueue = false; if (Schema::hasTable('mix_queues') && Schema::hasTable('mix_queue_players')) { $queues = collect(DB::select(" SELECT q.id, q.queue_number, q.status, q.match_id, q.created_at FROM mix_queues q WHERE q.status = 'waiting' ORDER BY q.created_at ASC, q.id ASC ")); $firstQueue = $queues->first(); if ($firstQueue) { $queuePlayers = collect(DB::select(" SELECT qp.user_id, qp.position, u.nickname, u.avatar_url, u.league_tag, u.skill_level FROM mix_queue_players qp JOIN users u ON u.id = qp.user_id WHERE qp.queue_id = ? ORDER BY qp.position ASC, qp.id ASC ", [$firstQueue->id])); $firstQueue->players = $queuePlayers->values()->all(); $firstQueue->player_count = $queuePlayers->count(); $inQueue = $queuePlayers->contains(fn ($player) => (int) ($player->user_id ?? 0) === $userId); } } $lobbyCounts = DB::table('mix_training_participants') ->select('training_match_id', DB::raw('COUNT(*) as current_players')) ->whereNull('left_at') ->groupBy('training_match_id'); $baseLobbyQuery = DB::table('mix_training_matches as tm') ->join('users as u', 'u.id', '=', 'tm.host_id') ->leftJoinSub($lobbyCounts, 'lp', function ($join) { $join->on('lp.training_match_id', '=', 'tm.id'); }) ->select( 'tm.id', 'tm.title', 'tm.training_type', 'tm.map_name', DB::raw("CASE WHEN LOWER(COALESCE(tm.training_type,'')) = 'c1s' THEN 16 ELSE tm.max_players END as max_players"), 'tm.host_id', 'tm.status', 'tm.created_at', 'tm.started_at', 'u.nickname as host_name', DB::raw("'crossfire' as game_slug"), DB::raw('COALESCE(lp.current_players, 0) as current_players') ); $activeLobbies = (clone $baseLobbyQuery) ->whereIn('tm.status', ['waiting', 'ready_check', 'veto']) ->orderByRaw("CASE WHEN tm.status = 'ready_check' THEN 0 WHEN tm.status = 'veto' THEN 1 ELSE 2 END") ->orderByDesc('tm.created_at') ->get(); $liveMatches = (clone $baseLobbyQuery) ->where('tm.status', 'in_progress') ->orderByDesc('tm.started_at') ->orderByDesc('tm.created_at') ->get(); $activeLobbies = $this->hydrateLobbyCards(collect($activeLobbies)); $liveMatches = $this->hydrateLobbyCards(collect($liveMatches), true); $onlineUsers = DB::table('users') ->select('id', 'nickname', 'avatar_url', 'league_tag', 'skill_level', 'last_seen_at') ->where('id', '!=', $userId) ->orderByDesc('last_seen_at') ->limit(20) ->get(); try { $rankingQuery = DB::table('users') ->select( 'users.id as user_id', 'users.nickname', 'users.avatar_url', 'users.league_tag', 'users.skill_level', 'users.last_seen_at', DB::raw('COALESCE(users.rank_points, 0) as total_points'), DB::raw('0 as matches_played'), DB::raw('1 as kd_ratio') ); if (Schema::hasTable('mix_ranking_cache')) { $rankingQuery = DB::table('mix_ranking_cache as rc') ->join('users', 'users.id', '=', 'rc.user_id') ->select( 'users.id as user_id', 'users.nickname', 'users.avatar_url', 'users.league_tag', 'users.skill_level', 'users.last_seen_at', DB::raw('COALESCE(rc.total_points, COALESCE(users.rank_points, 0)) as total_points'), DB::raw('COALESCE(rc.matches_played, 0) as matches_played'), DB::raw('COALESCE(rc.kd_ratio, 1) as kd_ratio') ); } $topPlayers = $rankingQuery ->orderByDesc('total_points') ->orderBy('nickname') ->limit(10) ->get() ->values() ->map(function ($player, $index) { $player->position = $index + 1; $player->avatar_url = !empty($player->avatar_url) ? $player->avatar_url : '/default-avatar.png'; return $player; }); } catch (\Throwable $e) { Log::warning('Erro ao montar ranking/top players do lobby.', ['error' => $e->getMessage()]); $topPlayers = collect(); } $ranking = $topPlayers->map(function ($player) { $player->rank_points = $player->total_points ?? 0; $player->mmr = $player->total_points ?? 0; $player->position = $player->position ?? 0; $player->movement = 'stable'; $player->movement_label = 'estavel'; $player->is_online = !empty($player->last_seen_at) ? now()->diffInMinutes(\Carbon\Carbon::parse($player->last_seen_at)) <= 5 : false; return $player; }); $totalPlayers = Schema::hasTable('users') ? (int) DB::table('users')->count() : 0; $totalMatches = Schema::hasTable('mix_training_matches') ? (int) DB::table('mix_training_matches')->count() : 0; $onlinePlayers = 0; if (Schema::hasTable('users') && Schema::hasColumn('users', 'last_seen_at')) { $onlinePlayers = (int) DB::table('users') ->where('last_seen_at', '>=', now()->subMinutes(5)) ->count(); } $globalStats = (object) [ 'total_players' => $totalPlayers, 'total_matches' => $totalMatches, 'online_players' => $onlinePlayers, ]; $topMaps = collect(); if (Schema::hasTable('mix_training_matches') && Schema::hasColumn('mix_training_matches', 'map_name')) { $topMaps = collect(DB::select(" SELECT TOP 6 COALESCE(NULLIF(map_name, ''), 'Crossfire') as map_played, COUNT(*) as matches, CAST(0 as decimal(10,1)) as avg_kills FROM mix_training_matches GROUP BY COALESCE(NULLIF(map_name, ''), 'Crossfire') ORDER BY COUNT(*) DESC, COALESCE(NULLIF(map_name, ''), 'Crossfire') ASC ")); } $maxMatches = (int) ($topMaps->max('matches') ?? 1); $featuredTournaments = collect(); if (Schema::hasTable('tournaments')) { $featuredTournaments = collect(DB::table('tournaments')->orderByDesc('id')->limit(6)->get()); } $matchesPlayed = 0; if (Schema::hasTable('mix_training_participants')) { $matchesPlayed = (int) DB::table('mix_training_participants') ->where('user_id', $userId) ->distinct('training_match_id') ->count('training_match_id'); } $userStats = (object) [ 'rank_points' => (int) ($currentUser->rank_points ?? 0), 'matches_played' => $matchesPlayed, 'win_rate' => 0, ]; $foundMatch = DB::table('mix_training_participants as tp') ->join('mix_training_matches as tm', 'tm.id', '=', 'tp.training_match_id') ->join('users as u', 'u.id', '=', 'tm.host_id') ->where('tp.user_id', $userId) ->whereNull('tp.left_at') ->whereIn('tm.status', ['waiting', 'ready_check', 'veto', 'in_progress', 'live', 'started', 'active', 'playing']) ->select('tm.id', 'tm.title', 'tm.status', 'tm.map_name', 'tm.training_type', DB::raw("'crossfire' as game_slug"), 'u.nickname as host_name') ->orderByRaw("CASE WHEN tm.status = 'ready_check' THEN 0 WHEN tm.status = 'in_progress' THEN 1 WHEN tm.status = 'veto' THEN 2 ELSE 3 END") ->first(); $foundMatchVoiceIntegration = null; if ($foundMatch && (string) ($foundMatch->status ?? '') === 'in_progress') { $foundMatchVoiceIntegration = app(VoiceMatchService::class)->buildMatchIntegration((int) $foundMatch->id, $userId); } return view('Lobby', [ 'currentUser' => $currentUser, 'userId' => $userId, 'avatar' => $currentUser->avatar_url ?? '/default-avatar.png', 'nickname' => $currentUser->nickname ?? 'Jogador', 'skill' => $currentUser->skill_level ?? 1, 'points' => $currentUser->rank_points ?? 0, 'onlineUsers' => $onlineUsers, 'ranking' => $ranking, 'topPlayers' => $topPlayers, 'activeLobbies' => $activeLobbies, 'liveMatches' => $liveMatches, 'foundMatch' => $foundMatch, 'foundMatchVoiceIntegration' => $foundMatchVoiceIntegration, 'verificationSummary' => $userId ? app(CompetitiveVerificationService::class)->getVerificationSnapshot((int) $userId) : null, 'partyState' => $this->partySummary($userId), 'penaltyState' => $this->readyPenaltyState($userId), 'queues' => $queues, 'firstQueue' => $firstQueue, 'queuePlayers' => $queuePlayers, 'inQueue' => $inQueue, 'globalStats' => $globalStats, 'topMaps' => $topMaps, 'maxMatches' => $maxMatches, 'featuredTournaments' => $featuredTournaments, 'userStats' => $userStats, 'isAdmin' => in_array(strtolower((string) Session::get('user_role', 'user')), ['admin', 'administrator', 'owner', 'moderator', 'mod', 'support', 'staff'], true), 'gxActiveGameSlug' => $activeGameSlug, ]); } // V199: serializa a participacao pelo mesmo registro de usuario (SQL Server). private function gxV199LockUser(int $userId): void { if ($userId <= 0 || !DB::table('users')->where('id', $userId)->lockForUpdate()->exists()) { throw new \RuntimeException('Usuario nao autenticado ou inexistente.'); } } private function gxV199WaitingMixQueue(int $userId): bool { return DB::table('mix_queue_players as qp') ->join('mix_queues as q', 'q.id', '=', 'qp.queue_id') ->where('qp.user_id', $userId) ->where('q.status', 'waiting') ->exists(); } public function create(Request $request) { try { return DB::transaction(function () use ($request) { $userId = (int) (Session::get('user_id') ?: \Illuminate\Support\Facades\Auth::id()); $this->gxV199LockUser($userId); if ($this->gxV199WaitingMixQueue($userId)) { return redirect()->back()->with('error', 'Saia da fila MIX (OPEN/RANKED/LIGA) antes de criar uma partida personalizada.'); } return $this->gxV199CreateOriginal($request); }, 3); } catch (\Throwable $e) { Log::error('V199 falha no bloqueio MIX x personalizada', ['error' => $e->getMessage()]); return redirect()->back()->with('error', 'Nao foi possivel validar sua participacao. Tente novamente.'); } } private function gxV199CreateOriginal(Request $request) { // Nunca aceita provedor de voz enviado pelo cliente. $request->request->remove('voice_mode'); $validator = Validator::make($request->all(), [ 'title' => 'required|string|max:100', 'training_type' => 'required|string|in:casualx5,acessox5,seriebx5,serieax5,todosmodosvip,treino5lx5,campeonatos,modox1,modox2,modox8,c1s,sniperx5', 'map_name' => 'nullable|string|max:50', 'max_players' => 'required|integer|min:2|max:20', 'password' => 'nullable|string|max:20', ]); if ($validator->fails()) { return redirect()->back()->withErrors($validator)->withInput(); } $userId = (int) Session::get('user_id'); // GIGAX_LOBBY_UNICO: nenhuma conta pode criar outro lobby enquanto // possuir vínculo ativo em qualquer partida/lobby não encerrado. $gxActiveLobby = DB::table('mix_training_participants as gx_tp') ->join('mix_training_matches as gx_tm', 'gx_tm.id', '=', 'gx_tp.training_match_id') ->where('gx_tp.user_id', $userId) ->whereNull('gx_tp.left_at') ->whereIn('gx_tm.status', [ 'waiting', 'ready_check', 'veto', 'in_progress', 'live', 'started', 'active', 'playing' ]) ->select('gx_tm.id', 'gx_tm.title', 'gx_tm.status') ->orderByDesc('gx_tm.id') ->first(); if ($gxActiveLobby) { return redirect()->back()->with( 'error', 'Você já participa do lobby #' . $gxActiveLobby->id . ' e não pode criar outro.' ); } // GIGAX_CAPACIDADE_OFICIAL_V2 // O servidor define a capacidade real; nao confia em max_players do formulario. $gxMode = strtolower(trim((string) $request->input('training_type', ''))); $gxCapacity = match ($gxMode) { 'modox1', 'x1' => 2, 'modox2', 'x2' => 4, 'modox8', 'x8' => 16, 'casualx5', 'acessox5', 'seriebx5', 'serieax5', 'todosmodosvip', 'treino5lx5', 'campeonatos', 'sniperx5' => 10, 'c1s' => 16, default => null, }; if ($gxCapacity !== null) { $request->merge(['max_players' => $gxCapacity]); } // GIGAX: capacidade oficial por modalidade. // O servidor sempre prevalece sobre o max_players vindo do formulario. $gxTrainingType = strtolower(trim((string) $request->input('training_type', ''))); $gxOfficialMaxPlayers = match ($gxTrainingType) { 'modox1' => 2, // 1 x 1 'modox2' => 4, // 2 x 2 'modox8' => 16, // 8 x 8 'casualx5', 'acessox5', 'seriebx5', 'serieax5', 'todosmodosvip', 'treino5lx5', 'campeonatos', 'sniperx5' => 10, 'c1s' => 16, default => null, }; if ($gxOfficialMaxPlayers !== null) { $request->merge(['max_players' => $gxOfficialMaxPlayers]); } if ($penalty = $this->readyPenaltyState($userId)) { return redirect()->back()->with('error', 'Voce esta em cooldown de ready-check por ' . $penalty['seconds_left'] . 's.'); } if ($acDenied = $this->acGateDenied($userId)) { return redirect()->back()->withInput()->with('error', $acDenied['message']); } try { DB::beginTransaction(); $insertData = [ 'title' => trim((string) $request->title), 'training_type' => $request->training_type, 'map_name' => $request->map_name ?: 'Crossfire', 'max_players' => (int) $request->max_players, 'host_id' => $userId, 'password' => $request->password, 'status' => 'waiting', 'veto_status' => 'pending', 'veto_round' => 0, 'created_at' => now(), 'updated_at' => now(), ]; if (Schema::hasColumn('mix_training_matches', 'game_slug')) { $insertData['game_slug'] = $this->activeGameSlugFromRequest(); } if (Schema::hasColumn('mix_training_matches', 'voice_mode')) { // GIGAX_VOICE_CANONICAL_V1: usa somente a configuração global. $insertData['voice_mode'] = app(\App\Services\GlobalVoiceProviderService::class)->matchValue(); } $lobbyId = DB::table('mix_training_matches')->insertGetId($insertData); DB::table('mix_training_participants')->insert([ 'training_match_id' => $lobbyId, 'user_id' => $userId, 'team' => 1, 'joined_at' => now(), 'left_at' => null, ]); DB::commit(); return redirect() ->route('lobby.index') ->with('success', 'Lobby criado com sucesso. Você permanecerá no Lobby até o ready-check abrir.') ->with('gx_active_lobby_id', $lobbyId); } catch (\Throwable $e) { DB::rollBack(); Log::error('Erro ao criar lobby', ['error' => $e->getMessage()]); return redirect()->back()->with('error', 'Erro ao criar lobby.'); } } public function show($id) { $userId = (int) Session::get('user_id'); $lobby = $this->fetchLobby((int) $id, ['waiting', 'ready_check', 'veto', 'in_progress']); if (!$lobby) { return redirect()->route('lobby.index')->with('error', 'Lobby nao encontrado.'); } // Nao redireciona automaticamente para evitar loop HUB <-> lobby. // A tela do lobby decide se mostra ready-check, veto ou partida em andamento. $participants = $this->fetchParticipants((int) $id); $captains = $this->captainLookup($participants); foreach ($participants as $participant) { $participant->is_captain = in_array((int) $participant->user_id, $captains, true) ? 1 : 0; } $isParticipant = $participants->contains(fn ($participant) => (int) $participant->user_id === $userId); $isHost = (int) $lobby->host_id === $userId; return view('lobby-show', [ 'lobby' => $lobby, 'participants' => $participants, 'isParticipant' => $isParticipant, 'isHost' => $isHost, 'userId' => $userId, ]); } public function match($id) { $userId = (int) Session::get('user_id'); $lobby = $this->fetchLobby((int) $id, ['ready_check', 'veto', 'in_progress']); if (!$lobby) { return redirect()->route('lobby.show', $id)->with('error', 'Partida nao encontrada ou indisponivel.'); } $participants = $this->fetchParticipants((int) $id); $captains = $this->captainLookup($participants); foreach ($participants as $participant) { $participant->is_captain = in_array((int) $participant->user_id, $captains, true) ? 1 : 0; } $teamA = $participants->filter(fn ($participant) => (int) $participant->team === 1)->values(); $teamB = $participants->filter(fn ($participant) => (int) $participant->team === 2)->values(); $readyAcceptedCount = $participants->filter(fn ($participant) => (int) ($participant->ready_is_ready ?? 0) === 1)->count(); $readyTotalCount = $participants->count(); $report = null; if (Schema::hasTable('lobby_match_reports')) { $report = DB::table('lobby_match_reports') ->where('training_match_id', $id) ->orderByDesc('id') ->first(); } $voiceIntegration = app(VoiceMatchService::class)->buildMatchIntegration((int) $id, $userId); return view('lobby-match', [ 'lobby' => $lobby, 'teamA' => $teamA, 'teamB' => $teamB, 'report' => $report, 'userId' => $userId, 'readyAcceptedCount' => $readyAcceptedCount, 'readyTotalCount' => $readyTotalCount, 'voiceIntegration' => $voiceIntegration, ]); } public function status($id) { $lobby = DB::table('mix_training_matches') ->select( 'id', 'status', DB::raw("CASE WHEN LOWER(COALESCE(training_type,'')) = 'c1s' THEN 16 ELSE max_players END as max_players"), 'started_at', 'ended_at', 'ready_status', 'ready_check_status', 'ready_check_started_at', 'ready_check_expires_at', 'training_type' ) ->where('id', $id) ->first(); if (!$lobby) { return response()->json(['success' => false, 'status' => 'not_found'], 404); } $participants = DB::table('mix_training_participants') ->where('training_match_id', $id) ->whereNull('left_at') ->count(); $voiceIntegration = null; if (in_array((string) $lobby->status, ['veto', 'in_progress'], true)) { try { $voiceIntegration = app(VoiceMatchService::class)->buildMatchIntegration((int) $id, (int) Session::get('user_id')); } catch (\Throwable $e) { Log::warning('Falha ao carregar acesso de voz no status do lobby.', [ 'lobby_id' => (int) $id, 'error' => $e->getMessage(), ]); } } return response()->json([ 'success' => true, 'status' => $lobby->status, 'participants' => $participants, 'started_at' => $lobby->started_at, 'ended_at' => $lobby->ended_at, 'ready_check' => $this->formattedReadyCheckState((int) $id), 'penalty' => $this->readyPenaltyState((int) Session::get('user_id')), 'voice_integration' => $voiceIntegration, 'next_url' => $lobby->status === 'veto' ? route('veto.show', $id) : ($lobby->status === 'in_progress' ? route('lobby.match', $id) : null), ]); } public function join(Request $request, $id) { try { return DB::transaction(function () use ($request, $id) { $userId = (int) (Session::get('user_id') ?: \Illuminate\Support\Facades\Auth::id()); $this->gxV199LockUser($userId); if ($this->gxV199WaitingMixQueue($userId)) { return response()->json([ 'success' => false, 'message' => 'Saia da fila MIX antes de entrar em uma partida personalizada.', ], 423); } return $this->gxV199JoinOriginal($request, $id); }, 3); } catch (\Throwable $e) { Log::error('V199 falha ao validar ingresso', ['error' => $e->getMessage()]); return response()->json(['success'=>false,'message'=>'Falha ao validar participacao.'], 503); } } private function gxV199JoinOriginal(Request $request, $id) { $userId = (int) Session::get('user_id'); if ($acDenied = $this->acGateDenied($userId)) { return response()->json($acDenied, 423); } if ($penalty = $this->readyPenaltyState($userId)) { return response()->json(['success' => false, 'message' => 'Cooldown de ready-check ativo por ' . $penalty['seconds_left'] . 's.'], 423); } try { DB::beginTransaction(); $lobby = DB::table('mix_training_matches') ->where('id', $id) ->whereIn('status', ['waiting', 'veto']) ->lockForUpdate() ->first(); if (!$lobby) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'Lobby nao encontrado ou indisponivel.'], 404); } if (!empty($lobby->password) && (string) $request->input('password') !== (string) $lobby->password) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'Senha incorreta.'], 403); } // GIGAX C1S: modo individual, de 2 ate 16 jogadores. // Corrige inclusive salas antigas criadas como 2/4. $isC1s = strtolower(trim((string) ($lobby->training_type ?? ''))) === 'c1s'; if ($isC1s && (int) ($lobby->max_players ?? 0) !== 16) { DB::table('mix_training_matches') ->where('id', $id) ->update([ 'max_players' => 16, 'updated_at' => now(), ]); $lobby->max_players = 16; } $alreadyInThisLobby = DB::table('mix_training_participants') ->where('training_match_id', $id) ->where('user_id', $userId) ->whereNull('left_at') ->exists(); if ($alreadyInThisLobby) { $gxRequestedTeam = (int) $request->attributes->get('gigax_v6_invite_team', 0); if ($gxRequestedTeam !== 0 && (int) $request->attributes->get('gigax_v6_invite_match_id', 0) === (int) $id) { $gxExistingTeam = (int) DB::table('mix_training_participants') ->where('training_match_id', $id)->where('user_id', $userId) ->whereNull('left_at')->value('team'); if ($gxExistingTeam !== $gxRequestedTeam) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'Voce ja esta nesta partida em outro time.'], 409); } } DB::commit(); return response()->json([ 'success' => true, 'message' => 'Voce ja esta neste lobby.', 'lobby_id' => (int) $id, 'already_joined' => true, 'stay_in_lobby' => true, ]); } $anotherLobby = DB::table('mix_training_participants as tp') ->join('mix_training_matches as tm', 'tm.id', '=', 'tp.training_match_id') ->where('tp.user_id', $userId) ->whereNull('tp.left_at') ->whereIn('tm.status', ['waiting', 'ready_check', 'veto', 'in_progress', 'live', 'started', 'active', 'playing']) ->exists(); if ($anotherLobby) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'Voce ja participa de outro lobby ativo.']); } $currentPlayers = DB::table('mix_training_participants') ->where('training_match_id', $id) ->whereNull('left_at') ->lockForUpdate() ->count(); if ($currentPlayers >= (int) $lobby->max_players) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'Lobby cheio.']); } if ($isC1s) { if ((int) $request->attributes->get('gigax_v6_invite_team', 0) !== 0) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'C1S nao permite escolha de time.'], 409); } // A coluna team continua preenchida apenas por compatibilidade de schema. // No C1S ela NAO representa equipes: todos jogam individualmente. $team = 1; } else { $teamA = DB::table('mix_training_participants') ->where('training_match_id', $id) ->whereNull('left_at') ->where('team', 1) ->count(); $teamB = DB::table('mix_training_participants') ->where('training_match_id', $id) ->whereNull('left_at') ->where('team', 2) ->count(); // GIGAX_V6_CONVITE_TIME: somente o controller de aceite do convite // pode fornecer este atributo INTERNO (nao vem de input/query do usuario). // A partida ja esta bloqueada por lockForUpdate nesta transacao. $gxInviteTeam = (int) $request->attributes->get('gigax_v6_invite_team', 0); $gxInviteMatch = (int) $request->attributes->get('gigax_v6_invite_match_id', 0); if ($gxInviteTeam !== 0) { $gxInviteModes = ['modox1', 'modox2', 'modox5', 'modox8', 'treino5lx5', 'sniperx5']; $gxMode = strtolower(trim((string) ($lobby->training_type ?? ''))); $gxMax = (int) ($lobby->max_players ?? 0); if ($gxInviteMatch !== (int) $id || !in_array($gxInviteTeam, [1, 2], true) || !in_array($gxMode, $gxInviteModes, true) || $gxMax < 2 || $gxMax % 2 !== 0) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'Destino do convite invalido para esta partida.'], 409); } $gxSideCapacity = intdiv($gxMax, 2); $gxSideCount = $gxInviteTeam === 1 ? $teamA : $teamB; if ($gxSideCount >= $gxSideCapacity) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'O time ' . ($gxInviteTeam === 1 ? 'A (BL)' : 'B (GR)') . ' esta cheio. Solicite outro convite.'], 409); } $team = $gxInviteTeam; } else { // Sem escolha explicita: comportamento original, inclusive para ENTRAR. $team = $teamA <= $teamB ? 1 : 2; } } DB::table('mix_training_participants')->insert([ 'training_match_id' => $id, 'user_id' => $userId, 'team' => $team, 'joined_at' => now(), 'left_at' => null, ]); // GIGAX_SYNC_CURRENT_PLAYERS_V1 $gxCurrentPlayers = DB::table('mix_training_participants') ->where('training_match_id', $id) ->whereNull('left_at') ->count(); DB::table('mix_training_matches') ->where('id', $id) ->update([ 'current_players' => $gxCurrentPlayers, 'updated_at' => now(), ]); $newCount = $currentPlayers + 1; $effectiveMaxPlayers = $isC1s ? 16 : (int) $lobby->max_players; // C1S pode ser iniciado manualmente pelo host a partir de 2 jogadores. // O ready-check automatico so abre quando atingir 16/16. $becameFull = $newCount >= $effectiveMaxPlayers && $lobby->status === 'waiting'; DB::commit(); if ($becameFull) { try { $readyState = $this->activateReadyCheckAutomatically((int) $id); return response()->json([ 'success' => true, 'message' => 'Lobby completo. Ready-check aberto.', 'lobby_id' => (int) $id, 'ready_check' => $readyState, 'stay_in_lobby' => true, ]); } catch (\Throwable $e) { Log::error('Erro ao abrir ready-check automatico do lobby completo', [ 'lobby_id' => (int) $id, 'error' => $e->getMessage(), ]); return response()->json([ 'success' => true, 'message' => 'Entrou no lobby. A sala ficou completa, mas o ready-check nao abriu automaticamente.', 'lobby_id' => (int) $id, 'stay_in_lobby' => true, ]); } } return response()->json([ 'success' => true, 'message' => 'Entrou no lobby com sucesso.', 'lobby_id' => (int) $id, 'stay_in_lobby' => true, ]); } catch (\Throwable $e) { DB::rollBack(); Log::error('Erro ao entrar no lobby', [ 'error' => $e->getMessage(), 'lobby_id' => $id, 'user_id' => $userId, ]); return response()->json(['success' => false, 'message' => 'Erro ao entrar no lobby.'], 500); } } public function leave($id) { $userId = (int) Session::get('user_id'); try { DB::beginTransaction(); $participant = DB::table('mix_training_participants') ->where('training_match_id', $id) ->where('user_id', $userId) ->whereNull('left_at') ->lockForUpdate() ->first(); if (!$participant) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'Voce nao esta neste lobby.'], 404); } DB::table('mix_training_participants') ->where('id', $participant->id) ->update([ 'left_at' => now(), ]); $remaining = DB::table('mix_training_participants') ->where('training_match_id', $id) ->whereNull('left_at') ->count(); if ($remaining === 0) { DB::table('mix_training_matches') ->where('id', $id) ->update([ 'status' => 'cancelled', 'ended_at' => now(), 'updated_at' => now(), ]); } DB::commit(); return response()->json(['success' => true, 'message' => 'Voce saiu do lobby.']); } catch (\Throwable $e) { DB::rollBack(); Log::error('Erro ao sair do lobby', [ 'error' => $e->getMessage(), 'lobby_id' => $id, 'user_id' => $userId, ]); return response()->json(['success' => false, 'message' => 'Erro ao sair do lobby.'], 500); } } public function start($id) { $userId = (int) Session::get('user_id'); if ($penalty = $this->readyPenaltyState($userId)) { return response()->json(['success' => false, 'message' => 'Cooldown de ready-check ativo por ' . $penalty['seconds_left'] . 's.'], 423); } try { $lobby = DB::table('mix_training_matches') ->where('id', $id) ->where('host_id', $userId) ->whereIn('status', ['waiting', 'ready_check', 'veto']) ->first(); if (!$lobby) { return response()->json(['success' => false, 'message' => 'Lobby nao encontrado ou voce nao e o host.'], 403); } if ($lobby->status === 'veto') { return response()->json([ 'success' => true, 'message' => 'Veto em andamento.', 'redirect' => route('veto.show', $id), ]); } if ($lobby->status === 'ready_check') { return response()->json([ 'success' => true, 'message' => 'Ready-check ja esta ativo.', 'ready_check' => $this->formattedReadyCheckState((int) $id), ]); } return $this->startReadyCheck($id); } catch (\Throwable $e) { Log::error('Erro ao iniciar lobby', [ 'error' => $e->getMessage(), 'lobby_id' => $id, 'user_id' => $userId, ]); return response()->json(['success' => false, 'message' => 'Erro ao iniciar o lobby.'], 500); } } public function joinLeague(Request $request) { $userId = (int) Session::get('user_id'); $request->validate([ 'tag' => 'required|string|max:30', ]); DB::table('users') ->where('id', $userId) ->update([ 'league_tag' => strtoupper(trim((string) $request->tag)), 'updated_at' => now(), ]); return redirect()->back()->with('success', 'Tag atualizada com sucesso.'); } public function close($id) { $userId = (int) Session::get('user_id'); try { DB::beginTransaction(); $lobby = DB::table('mix_training_matches') ->where('id', $id) ->where('host_id', $userId) ->whereIn('status', ['waiting', 'veto', 'in_progress']) ->lockForUpdate() ->first(); if (!$lobby) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'Lobby nao encontrado ou sem permissao.'], 403); } $data = [ 'status' => 'cancelled', 'ended_at' => now(), ]; if (Schema::hasColumn('mix_training_matches', 'updated_at')) { $data['updated_at'] = now(); } DB::table('mix_training_matches') ->where('id', $id) ->update($data); DB::table('mix_training_participants') ->where('training_match_id', $id) ->whereNull('left_at') ->update(['left_at' => now()]); DB::commit(); $voiceResult = null; try { $voiceResult = app(VoiceMatchService::class)->finishForMatch((int) $id); } catch (\Throwable $e) { Log::warning('Falha ao limpar salas de voz ao fechar lobby', [ 'lobby_id' => $id, 'error' => $e->getMessage(), ]); } return response()->json([ 'success' => true, 'message' => 'Lobby encerrado com sucesso.', 'voice' => $voiceResult, ]); } catch (\Throwable $e) { DB::rollBack(); Log::error('Erro ao fechar lobby', [ 'error' => $e->getMessage(), 'lobby_id' => $id, 'user_id' => $userId, ]); return response()->json(['success' => false, 'message' => 'Erro ao fechar lobby.'], 500); } } /** * Abre o ready-check automaticamente quando a sala atinge max_players. * Não depende do usuário que completou a sala ser o host. */ private function activateReadyCheckAutomatically(int $lobbyId): ?array { if ($this->acGateDeniedParticipants($lobbyId)) { Log::warning('AC7_GATE_AUTO_READY_BLOCKED', ['lobby_id' => $lobbyId]); return null; } DB::beginTransaction(); try { $lobby = DB::table('mix_training_matches') ->where('id', $lobbyId) ->where('status', 'waiting') ->lockForUpdate() ->first(); if (!$lobby) { DB::rollBack(); return $this->formattedReadyCheckState($lobbyId); } $participants = $this->fetchParticipants($lobbyId); if ($participants->count() < (int) $lobby->max_players) { DB::rollBack(); return null; } $readyDuration = 120; $now = now(); $state = [ 'lobby_id' => $lobbyId, 'host_id' => (int) $lobby->host_id, 'required_user_ids' => $participants->pluck('user_id')->map(fn ($value) => (int) $value)->values()->all(), 'accepted_user_ids' => [], 'declined_user_ids' => [], 'started_at' => $now->toIso8601String(), 'expires_at' => $now->copy()->addSeconds($readyDuration)->toIso8601String(), 'duration' => $readyDuration, ]; Cache::put($this->readyCheckCacheKey($lobbyId), $state, now()->addMinutes(10)); if (Schema::hasTable('match_ready_players')) { DB::table('match_ready_players')->where('match_id', $lobbyId)->delete(); foreach ($participants as $participant) { $insert = [ 'match_id' => $lobbyId, 'user_id' => (int) $participant->user_id, 'team' => (int) ($participant->team ?: 1), 'is_ready' => 0, 'confirmed_at' => null, 'created_at' => $now, ]; if (Schema::hasColumn('match_ready_players', 'updated_at')) { $insert['updated_at'] = $now; } if (Schema::hasColumn('match_ready_players', 'status')) { $insert['status'] = 'pending'; } DB::table('match_ready_players')->insert($insert); } } $update = [ 'status' => 'ready_check', 'updated_at' => $now, ]; if (Schema::hasColumn('mix_training_matches', 'ready_check_started_at')) { $update['ready_check_started_at'] = $now; } if (Schema::hasColumn('mix_training_matches', 'ready_check_expires_at')) { $update['ready_check_expires_at'] = $now->copy()->addSeconds($readyDuration); } DB::table('mix_training_matches') ->where('id', $lobbyId) ->update($update); DB::commit(); return $this->formattedReadyCheckState($lobbyId); } catch (\Throwable $e) { DB::rollBack(); throw $e; } } public function startReadyCheck($id) { $userId = (int) Session::get('user_id'); try { DB::beginTransaction(); // GIGAX V175: o READY pode ser iniciado pelo HOST ou por ADMIN. // Necessário para DM/C1S, onde o administrador precisa poder forçar // o início com os jogadores que já estão presentes na sala. $lobby = DB::table('mix_training_matches') ->where('id', $id) ->whereIn('status', ['waiting', 'ready_check']) ->lockForUpdate() ->first(); if (!$lobby) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'Lobby nao encontrado.'], 404); } $role = strtolower(trim((string) DB::table('users')->where('id', $userId)->value('role'))); $normalizedRole = preg_replace('/[\s_-]+/', '', $role); $isAdmin = in_array($normalizedRole, [ 'admin', 'adm', 'administrador', 'administrator', 'superadmin', 'superadministrador', ], true); $isHost = (int) ($lobby->host_id ?? 0) === $userId; if (!$isHost && !$isAdmin) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'Apenas o host ou um administrador pode iniciar a partida.'], 403); } $participants = $this->fetchParticipants((int) $id); if ($acDenied = $this->acGateDeniedParticipants((int) $id)) { DB::rollBack(); return response()->json($acDenied, 423); } if ($participants->count() < 2) { DB::rollBack(); return response()->json(['success' => false, 'message' => 'Sao necessarios ao menos 2 jogadores para abrir o ready-check.'], 422); } $readyDuration = 120; $state = [ 'lobby_id' => (int) $id, 'host_id' => (int) ($lobby->host_id ?? $userId), 'required_user_ids' => $participants->pluck('user_id')->map(fn ($value) => (int) $value)->values()->all(), 'accepted_user_ids' => [], 'declined_user_ids' => [], 'started_at' => now()->toIso8601String(), 'expires_at' => now()->addSeconds($readyDuration)->toIso8601String(), 'duration' => $readyDuration, ]; Cache::put($this->readyCheckCacheKey((int) $id), $state, now()->addMinutes(10)); if (Schema::hasTable('match_ready_players')) { DB::table('match_ready_players')->where('match_id', (int) $id)->delete(); foreach ($participants as $participant) { DB::table('match_ready_players')->insert([ 'match_id' => (int) $id, 'user_id' => (int) $participant->user_id, 'team' => (int) ($participant->team ?: 1), 'is_ready' => 0, 'confirmed_at' => null, 'created_at' => now(), 'updated_at' => null, ]); } } $matchUpdate = [ 'status' => 'ready_check', 'updated_at' => now(), ]; if (Schema::hasColumn('mix_training_matches', 'ready_check_started_at')) { $matchUpdate['ready_check_started_at'] = now(); } if (Schema::hasColumn('mix_training_matches', 'ready_check_expires_at')) { $matchUpdate['ready_check_expires_at'] = now()->addSeconds($readyDuration); } DB::table('mix_training_matches') ->where('id', $id) ->update($matchUpdate); DB::commit(); return response()->json([ 'success' => true, 'message' => 'Ready-check iniciado.', 'ready_check' => $this->formattedReadyCheckState((int) $id), ]); } catch (\Throwable $e) { DB::rollBack(); Log::error('Erro ao iniciar ready-check', [ 'error' => $e->getMessage(), 'lobby_id' => $id, 'user_id' => $userId, ]); return response()->json(['success' => false, 'message' => 'Erro ao abrir o ready-check.'], 500); } } public function acceptReadyCheck(Request $request, $id) { $userId = (int) Session::get('user_id'); $lobbyId = (int) $id; try { Log::info('READY CHECK INICIO', [ 'match_id' => $lobbyId, 'user_id' => $userId, 'method' => $request->method(), ]); if ($userId <= 0) { if ($request->isMethod('get') || !$request->expectsJson()) { return redirect()->route('login')->with('error', 'Sessao expirada. Faca login novamente.'); } return response()->json([ 'success' => false, 'message' => 'Sessao expirada. Faca login novamente.', ], 401); } $lobby = DB::table('mix_training_matches') ->where('id', $lobbyId) ->whereIn('status', ['ready_check', 'waiting', 'veto', 'in_progress']) ->first(); if (!$lobby) { if ($request->isMethod('get') || !$request->expectsJson()) { return redirect()->route('lobby.index')->with('error', 'Partida nao encontrada ou ready-check encerrado.'); } return response()->json([ 'success' => false, 'message' => 'Lobby nao encontrado ou ready-check encerrado.', ], 404); } $participant = DB::table('mix_training_participants') ->where('training_match_id', $lobbyId) ->where('user_id', $userId) ->whereNull('left_at') ->first(); if (!$participant) { if ($request->isMethod('get') || !$request->expectsJson()) { return redirect()->route('lobby.index')->with('error', 'Voce nao participa desta partida.'); } return response()->json([ 'success' => false, 'message' => 'Voce nao participa deste lobby.', ], 403); } if (!Schema::hasTable('match_ready_players')) { if ($request->isMethod('get') || !$request->expectsJson()) { return redirect()->route('lobby.index')->with('error', 'Tabela match_ready_players nao existe.'); } return response()->json([ 'success' => false, 'message' => 'Tabela match_ready_players nao existe. Rode o SQL de criacao do ready-check.', ], 500); } if ($acDenied = $this->acGateDenied($userId)) { if ($request->isMethod('get') || !$request->expectsJson()) { return redirect()->route('lobby.show', $lobbyId)->with('error', $acDenied['message']); } return response()->json($acDenied, 423); } $now = now(); $readyRow = DB::table('match_ready_players') ->where('match_id', $lobbyId) ->where('user_id', $userId) ->first(); if ($readyRow) { $payload = [ 'is_ready' => 1, 'confirmed_at' => $now, ]; if (Schema::hasColumn('match_ready_players', 'updated_at')) { $payload['updated_at'] = $now; } if (Schema::hasColumn('match_ready_players', 'status')) { $payload['status'] = 'accepted'; } DB::table('match_ready_players') ->where('match_id', $lobbyId) ->where('user_id', $userId) ->update($payload); } else { $insert = [ 'match_id' => $lobbyId, 'user_id' => $userId, 'team' => (int) ($participant->team ?: 1), 'is_ready' => 1, 'confirmed_at' => $now, 'created_at' => $now, 'updated_at' => $now, ]; if (Schema::hasColumn('match_ready_players', 'status')) { $insert['status'] = 'accepted'; } DB::table('match_ready_players')->insert($insert); } $requiredCount = (int) DB::table('mix_training_participants') ->where('training_match_id', $lobbyId) ->whereNull('left_at') ->count(); $acceptedCount = (int) DB::table('match_ready_players') ->where('match_id', $lobbyId) ->where('is_ready', 1) ->count(); $state = Cache::get($this->readyCheckCacheKey($lobbyId)); if (is_array($state)) { $state['accepted_user_ids'] = array_values(array_unique(array_merge( array_map('intval', $state['accepted_user_ids'] ?? []), [$userId] ))); $state['declined_user_ids'] = array_values(array_diff( array_map('intval', $state['declined_user_ids'] ?? []), [$userId] )); Cache::put($this->readyCheckCacheKey($lobbyId), $state, now()->addMinutes(10)); } Log::info('READY CHECK UPDATE', [ 'match_id' => $lobbyId, 'user_id' => $userId, 'accepted' => $acceptedCount, 'required' => $requiredCount, ]); if ($requiredCount > 0 && $acceptedCount >= $requiredCount) { if ($acDenied = $this->acGateDeniedParticipants($lobbyId)) { if ($request->isMethod('get') || !$request->expectsJson()) { return redirect()->route('lobby.show', $lobbyId)->with('error', $acDenied['message']); } return response()->json($acDenied, 423); } Cache::forget($this->readyCheckCacheKey($lobbyId)); $redirect = $this->advanceLobbyAfterReadyCheck($lobbyId); if ($request->isMethod('get') || $request->boolean('redirect') || !$request->expectsJson()) { return redirect($redirect)->with('success', 'Todos aceitaram. Partida liberada.'); } $voiceIntegration = null; try { $voiceIntegration = app(VoiceMatchService::class)->buildMatchIntegration($lobbyId, $userId); } catch (\Throwable $e) { Log::warning('Falha ao montar acesso de voz apos ready-check.', [ 'lobby_id' => $lobbyId, 'error' => $e->getMessage(), ]); } return response()->json([ 'success' => true, 'message' => 'Todos aceitaram. Comunicacao liberada.', 'accepted_count' => $acceptedCount, 'required_count' => $requiredCount, 'all_ready' => true, 'redirect' => $redirect, 'voice_integration' => $voiceIntegration, 'ready_check' => null, ]); } $redirect = route('lobby.match', $lobbyId); if ($request->isMethod('get') || $request->boolean('redirect') || !$request->expectsJson()) { return redirect($redirect)->with('success', 'Aceite registrado.'); } return response()->json([ 'success' => true, 'message' => 'Aceite registrado.', 'accepted_count' => $acceptedCount, 'required_count' => $requiredCount, 'redirect' => $redirect, 'all_ready' => false, 'ready_check' => $this->formattedReadyCheckState($lobbyId), ]); } catch (\Throwable $e) { Log::error('READY CHECK ERRO', [ 'match_id' => $lobbyId, 'user_id' => $userId, 'message' => $e->getMessage(), 'line' => $e->getLine(), 'file' => $e->getFile(), ]); if ($request->isMethod('get') || $request->boolean('redirect') || !$request->expectsJson()) { return redirect()->route('lobby.index')->with('error', 'Erro ao aceitar partida: ' . $e->getMessage()); } return response()->json([ 'success' => false, 'message' => $e->getMessage(), ], 500); } } public function declineReadyCheck($id) { $userId = (int) Session::get('user_id'); if ($penalty = $this->readyPenaltyState($userId)) { return response()->json(['success' => false, 'message' => 'Cooldown ativo por ' . $penalty['seconds_left'] . 's.'], 423); } $state = $this->rawReadyCheckState((int) $id); if (!$state) { return response()->json(['success' => false, 'message' => 'Ready-check nao esta ativo.'], 404); } if (!in_array($userId, $state['required_user_ids'], true)) { return response()->json(['success' => false, 'message' => 'Voce nao participa deste lobby.'], 403); } $state['declined_user_ids'] = array_values(array_unique(array_merge($state['declined_user_ids'], [$userId]))); Cache::forget($this->readyCheckCacheKey((int) $id)); $this->applyReadyPenalty($userId, 'decline'); DB::table('mix_training_matches') ->where('id', $id) ->update([ 'status' => 'waiting', 'updated_at' => now(), ]); return response()->json([ 'success' => true, 'message' => 'Ready-check cancelado. Lobby voltou para aguardando.', 'ready_check' => null, ]); } /** * No LobbyController: * - CAMPEONATOS usa VETO. * - Qualquer outra partida criada aqui e PERSONALIZADA e NAO usa VETO. * O MIX oficial e tratado separadamente pelo QueueController. */ private function lobbyUsesVeto(object $lobby): bool { return strtolower(trim((string) ($lobby->training_type ?? ''))) === 'campeonatos'; } private function advanceLobbyAfterReadyCheck(int $lobbyId): string { $lobby = DB::table('mix_training_matches')->where('id', $lobbyId)->first(); $participantCount = DB::table('mix_training_participants') ->where('training_match_id', $lobbyId) ->whereNull('left_at') ->count(); try { app(VoiceMatchService::class)->startForMatch($lobbyId); } catch (\Throwable $e) { Log::warning('Falha ao iniciar integracao de voz da partida', [ 'lobby_id' => $lobbyId, 'error' => $e->getMessage(), ]); } if ($lobby && $this->lobbyUsesVeto($lobby) && (int) $lobby->max_players === 10 && $participantCount >= 10) { $this->startVetoProcess($lobbyId); return route('veto.show', $lobbyId); } DB::table('mix_training_matches') ->where('id', $lobbyId) ->update([ 'status' => 'in_progress', 'started_at' => now(), 'updated_at' => now(), ]); return route('lobby.match', $lobbyId); } private function readyCheckCacheKey(int $lobbyId): string { return 'lobby_ready_check_' . $lobbyId; } private function rawReadyCheckState(int $lobbyId): ?array { $state = Cache::get($this->readyCheckCacheKey($lobbyId)); if (is_array($state)) { return $state; } $lobby = DB::table('mix_training_matches') ->where('id', $lobbyId) ->where('status', 'ready_check') ->first(); if (!$lobby) { return null; } $participants = DB::table('mix_training_participants') ->where('training_match_id', $lobbyId) ->whereNull('left_at') ->pluck('user_id') ->map(fn ($value) => (int) $value) ->values() ->all(); if (empty($participants)) { return null; } $startedAt = now()->subSeconds(1); $expiresAt = now()->addSeconds(120); if (Schema::hasColumn('mix_training_matches', 'ready_check_started_at') && !empty($lobby->ready_check_started_at)) { $startedAt = \Carbon\Carbon::parse($lobby->ready_check_started_at); } if (Schema::hasColumn('mix_training_matches', 'ready_check_expires_at') && !empty($lobby->ready_check_expires_at)) { $expiresAt = \Carbon\Carbon::parse($lobby->ready_check_expires_at); if ($expiresAt->timestamp <= now()->timestamp) { $expiresAt = now()->addSeconds(120); } } $acceptedIds = []; if (Schema::hasTable('match_ready_players')) { $acceptedIds = DB::table('match_ready_players') ->where('match_id', $lobbyId) ->where('is_ready', 1) ->pluck('user_id') ->map(fn ($value) => (int) $value) ->values() ->all(); } return [ 'lobby_id' => $lobbyId, 'host_id' => (int) ($lobby->host_id ?? 0), 'required_user_ids' => $participants, 'accepted_user_ids' => $acceptedIds, 'declined_user_ids' => [], 'started_at' => $startedAt->toIso8601String(), 'expires_at' => $expiresAt->toIso8601String(), 'duration' => 120, ]; } private function formattedReadyCheckState(int $lobbyId): ?array { $state = $this->rawReadyCheckState($lobbyId); if (!$state) { return null; } $participants = $this->fetchParticipants($lobbyId)->map(function ($participant) { return [ 'user_id' => (int) $participant->user_id, 'nickname' => $participant->nickname, 'avatar_url' => $participant->avatar_url, 'team' => (int) $participant->team, 'accepted' => (int) ($participant->ready_is_ready ?? 0) === 1, 'confirmed_at' => $participant->ready_confirmed_at ?? null, ]; })->values(); $acceptedIds = []; if (Schema::hasTable('match_ready_players')) { $acceptedIds = DB::table('match_ready_players') ->where('match_id', $lobbyId) ->where('is_ready', 1) ->pluck('user_id') ->map(fn ($value) => (int) $value) ->values() ->all(); } if (empty($acceptedIds)) { $acceptedIds = array_map('intval', $state['accepted_user_ids'] ?? []); } $declinedIds = array_map('intval', $state['declined_user_ids'] ?? []); $requiredIds = array_map('intval', $state['required_user_ids'] ?? []); $expiresAt = isset($state['expires_at']) ? strtotime((string) $state['expires_at']) : now()->addSeconds(120)->timestamp; $secondsLeft = max(0, $expiresAt - now()->timestamp); return [ 'active' => true, 'lobby_id' => $lobbyId, 'accepted_count' => count($acceptedIds), 'required_count' => count($requiredIds), 'seconds_left' => $secondsLeft, 'expires_at' => $state['expires_at'] ?? now()->addSeconds(120)->toIso8601String(), 'participants' => $participants->map(function ($participant) use ($acceptedIds, $declinedIds) { $participant['accepted'] = in_array((int) $participant['user_id'], $acceptedIds, true); $participant['declined'] = in_array((int) $participant['user_id'], $declinedIds, true); return $participant; })->all(), ]; } private function fetchLobby(int $id, array $statuses = ['waiting', 'ready_check', 'veto', 'in_progress']) { $lobby = DB::table('mix_training_matches as tm') ->join('users as u', 'u.id', '=', 'tm.host_id') ->leftJoinSub( DB::table('mix_training_participants') ->select('training_match_id', DB::raw('COUNT(*) as current_players')) ->whereNull('left_at') ->groupBy('training_match_id'), 'lp', function ($join) { $join->on('lp.training_match_id', '=', 'tm.id'); } ) ->select('tm.*', 'u.nickname as host_name', DB::raw('COALESCE(lp.current_players, 0) as current_players')) ->where('tm.id', $id) ->whereIn('tm.status', $statuses) ->first(); if ($lobby && strtolower(trim((string) ($lobby->training_type ?? ''))) === 'c1s') { $lobby->max_players = 16; } return $lobby; } private function fetchParticipants(int $lobbyId): Collection { $query = DB::table('mix_training_participants as tp') ->join('users as u', 'u.id', '=', 'tp.user_id') ->select( 'tp.id', 'tp.training_match_id', 'tp.user_id', 'tp.team', 'tp.joined_at', 'u.nickname', 'u.avatar_url', 'u.skill_level', 'u.league_tag', DB::raw('COALESCE(mrp.is_ready, 0) as ready_is_ready'), DB::raw('mrp.confirmed_at as ready_confirmed_at'), DB::raw("(SELECT TOP 1 t.name FROM mix_team_members tm JOIN mix_teams t ON t.id = tm.team_id WHERE tm.user_id = u.id AND tm.status = 'active' AND t.status = 'active' ORDER BY t.rank_points DESC, t.id DESC) as clan_name") ) ->leftJoin('match_ready_players as mrp', function ($join) { $join->on('mrp.match_id', '=', 'tp.training_match_id') ->on('mrp.user_id', '=', 'tp.user_id'); }) ->where('tp.training_match_id', $lobbyId) ->whereNull('tp.left_at') ->orderBy('tp.team') ->orderBy('tp.joined_at'); if (Schema::hasTable('lobby_match_captains')) { $query->leftJoin('lobby_match_captains as capt', function ($join) { $join->on('capt.training_match_id', '=', 'tp.training_match_id') ->on('capt.user_id', '=', 'tp.user_id'); }); $query->addSelect(DB::raw('COALESCE(capt.user_id, 0) as captain_user_id')); } else { $query->addSelect(DB::raw('0 as captain_user_id')); } return $query->get(); } private function captainLookup(Collection $participants): array { $captainIds = $participants ->filter(fn ($participant) => (int) ($participant->captain_user_id ?? 0) > 0) ->pluck('user_id') ->map(fn ($value) => (int) $value) ->values() ->all(); if (!empty($captainIds)) { return $captainIds; } $fallback = []; $teamA = $participants->first(fn ($participant) => (int) $participant->team === 1); $teamB = $participants->first(fn ($participant) => (int) $participant->team === 2); if ($teamA) { $fallback[] = (int) $teamA->user_id; } if ($teamB) { $fallback[] = (int) $teamB->user_id; } return $fallback; } private function assignCaptains(int $lobbyId): void { if (!Schema::hasTable('lobby_match_captains')) { return; } $players = DB::table('mix_training_participants as tp') ->join('users as u', 'u.id', '=', 'tp.user_id') ->select( 'tp.user_id', 'tp.team', DB::raw('COALESCE(u.rank_points, COALESCE(u.mmr, 0)) as skill_value') ) ->where('tp.training_match_id', $lobbyId) ->whereNull('tp.left_at') ->get(); foreach ([1, 2] as $team) { $captain = $players->where('team', $team)->sortByDesc('skill_value')->first(); if (!$captain) { continue; } DB::table('lobby_match_captains')->updateOrInsert( ['training_match_id' => $lobbyId, 'team' => $team], [ 'user_id' => $captain->user_id, 'assigned_at' => now(), 'updated_at' => now(), 'created_at' => now(), ] ); } } private function startVetoProcess(int $lobbyId): void { $lobby = DB::table('mix_training_matches')->where('id', $lobbyId)->first(); if (!$lobby) { return; } // Este controller somente pode criar VETO para CAMPEONATOS. // Personalizada: remove/ignora qualquer estado de veto. if (strtolower(trim((string) ($lobby->training_type ?? ''))) !== 'campeonatos') { $update = [ 'status' => 'in_progress', 'updated_at' => now(), ]; if (Schema::hasColumn('mix_training_matches', 'started_at')) { $update['started_at'] = $lobby->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(); } DB::table('mix_training_matches')->where('id', $lobbyId)->update($update); return; } $this->assignCaptains($lobbyId); DB::table('mix_training_matches') ->where('id', $lobbyId) ->update([ 'status' => 'veto', 'veto_status' => 'pending', 'veto_round' => 0, 'current_veto_team' => 'A', 'updated_at' => now(), ]); } public function partySummaryEndpoint() { return response()->json([ 'success' => true, 'party' => $this->partySummary((int) Session::get('user_id')), 'penalty' => $this->readyPenaltyState((int) Session::get('user_id')), ]); } public function createParty(Request $request) { $userId = (int) Session::get('user_id'); $size = (int) $request->input('size', 2); if (!in_array($size, [2, 5], true)) { $size = 2; } $existingCode = Cache::get($this->partyUserKey($userId)); if ($existingCode) { $this->leavePartyRoom($userId, (string) $existingCode); } $code = strtoupper(substr(bin2hex(random_bytes(3)), 0, 6)); $party = [ 'code' => $code, 'leader_id' => $userId, 'max_size' => $size, 'members' => [$userId], 'created_at' => now()->toIso8601String(), ]; Cache::put($this->partyRoomKey($code), $party, now()->addHours(6)); Cache::put($this->partyUserKey($userId), $code, now()->addHours(6)); return response()->json(['success' => true, 'party' => $this->partySummary($userId)]); } public function joinParty(Request $request) { $userId = (int) Session::get('user_id'); $code = strtoupper(trim((string) $request->input('code'))); if ($code === '') { return response()->json(['success' => false, 'message' => 'Informe um codigo de party.'], 422); } $party = Cache::get($this->partyRoomKey($code)); if (!$party) { return response()->json(['success' => false, 'message' => 'Party nao encontrada.'], 404); } $currentCode = Cache::get($this->partyUserKey($userId)); if ($currentCode && $currentCode !== $code) { $this->leavePartyRoom($userId, (string) $currentCode); } $members = array_values(array_unique(array_map('intval', $party['members'] ?? []))); if (!in_array($userId, $members, true) && count($members) >= (int) ($party['max_size'] ?? 2)) { return response()->json(['success' => false, 'message' => 'Party cheia.'], 422); } $members[] = $userId; $party['members'] = array_values(array_unique(array_map('intval', $members))); Cache::put($this->partyRoomKey($code), $party, now()->addHours(6)); foreach ($party['members'] as $memberId) { Cache::put($this->partyUserKey((int) $memberId), $code, now()->addHours(6)); } return response()->json(['success' => true, 'party' => $this->partySummary($userId)]); } public function leaveParty() { $userId = (int) Session::get('user_id'); $code = Cache::get($this->partyUserKey($userId)); if (!$code) { return response()->json(['success' => true, 'party' => null]); } $this->leavePartyRoom($userId, (string) $code); return response()->json(['success' => true, 'party' => $this->partySummary($userId)]); } private function partySummary(int $userId): ?array { $code = Cache::get($this->partyUserKey($userId)); if (!$code) { return null; } $party = Cache::get($this->partyRoomKey((string) $code)); if (!$party) { Cache::forget($this->partyUserKey($userId)); return null; } $memberIds = array_values(array_unique(array_map('intval', $party['members'] ?? []))); if (empty($memberIds)) { Cache::forget($this->partyRoomKey((string) $code)); Cache::forget($this->partyUserKey($userId)); return null; } $members = DB::table('users') ->select('id', 'nickname', 'avatar_url', 'league_tag', 'skill_level') ->whereIn('id', $memberIds) ->orderByRaw('CASE WHEN id = ? THEN 0 ELSE 1 END', [$party['leader_id'] ?? $userId]) ->get() ->map(function ($member) use ($party) { return [ 'id' => (int) $member->id, 'nickname' => $member->nickname, 'avatar_url' => $member->avatar_url, 'league_tag' => $member->league_tag, 'skill_level' => (int) ($member->skill_level ?? 1), 'is_leader' => (int) $member->id === (int) ($party['leader_id'] ?? 0), ]; })->values()->all(); return [ 'code' => (string) $code, 'leader_id' => (int) ($party['leader_id'] ?? 0), 'max_size' => (int) ($party['max_size'] ?? 2), 'members' => $members, 'member_count' => count($members), 'is_leader' => (int) ($party['leader_id'] ?? 0) === $userId, ]; } private function leavePartyRoom(int $userId, string $code): void { $party = Cache::get($this->partyRoomKey($code)); Cache::forget($this->partyUserKey($userId)); if (!$party) { return; } $members = array_values(array_diff(array_map('intval', $party['members'] ?? []), [$userId])); if (empty($members)) { Cache::forget($this->partyRoomKey($code)); return; } if ((int) ($party['leader_id'] ?? 0) === $userId) { $party['leader_id'] = (int) $members[0]; } $party['members'] = $members; Cache::put($this->partyRoomKey($code), $party, now()->addHours(6)); foreach ($members as $memberId) { Cache::put($this->partyUserKey((int) $memberId), $code, now()->addHours(6)); } } private function partyRoomKey(string $code): string { return 'lobby_party_room_' . strtoupper($code); } private function partyUserKey(int $userId): string { return 'lobby_party_user_' . $userId; } private function applyReadyPenalty(int $userId, string $reason = 'timeout'): void { $seconds = $reason === 'decline' ? 180 : 120; Cache::put($this->readyPenaltyKey($userId), [ 'user_id' => $userId, 'reason' => $reason, 'expires_at' => now()->addSeconds($seconds)->toIso8601String(), 'seconds' => $seconds, ], now()->addSeconds($seconds + 30)); } private function readyPenaltyState(int $userId): ?array { $state = Cache::get($this->readyPenaltyKey($userId)); if (!$state) { return null; } $expiresAt = strtotime((string) ($state['expires_at'] ?? '')); if (!$expiresAt || $expiresAt <= now()->timestamp) { Cache::forget($this->readyPenaltyKey($userId)); return null; } return [ 'reason' => $state['reason'] ?? 'timeout', 'expires_at' => $state['expires_at'], 'seconds_left' => max(0, $expiresAt - now()->timestamp), 'label' => ($state['reason'] ?? 'timeout') === 'decline' ? 'Recusa de ready-check' : 'Timeout de ready-check', ]; } private function readyPenaltyKey(int $userId): string { return 'lobby_ready_penalty_' . $userId; } private function hydrateLobbyCards(Collection $matches, bool $live = false): Collection { if ($matches->isEmpty()) { return $matches; } $participantRows = collect(DB::table('mix_training_participants as tp') ->join('users as u', 'u.id', '=', 'tp.user_id') ->select( 'tp.training_match_id', 'tp.team', 'u.id as user_id', 'u.nickname', 'u.avatar_url', 'u.league_tag', 'u.skill_level', DB::raw('COALESCE(mrp.is_ready, 0) as ready_is_ready'), DB::raw('mrp.confirmed_at as ready_confirmed_at') ) ->leftJoin('match_ready_players as mrp', function ($join) { $join->on('mrp.match_id', '=', 'tp.training_match_id') ->on('mrp.user_id', '=', 'tp.user_id'); }) ->whereIn('tp.training_match_id', $matches->pluck('id')->all()) ->whereNull('tp.left_at') ->orderBy('tp.training_match_id') ->orderBy('tp.team') ->orderBy('tp.joined_at') ->get()); $grouped = $participantRows->groupBy('training_match_id'); return $matches->map(function ($match) use ($grouped, $live) { $match->game_slug = $this->normalizeMatchGameSlug($match->game_slug ?? 'crossfire'); $participants = collect($grouped->get($match->id, collect())); $match->ready_total_count = $participants->count(); $match->ready_accepted_count = $participants->filter(fn ($p) => (int) ($p->ready_is_ready ?? 0) === 1)->count(); $match->ready_pending_count = max(0, $match->ready_total_count - $match->ready_accepted_count); $teamA = $participants->filter(fn ($p) => (int) ($p->team ?? 0) === 1)->values(); $teamB = $participants->filter(fn ($p) => (int) ($p->team ?? 0) === 2)->values(); if ($teamA->isEmpty() && $teamB->isEmpty()) { $split = (int) ceil($participants->count() / 2); $teamA = $participants->take($split)->values(); $teamB = $participants->slice($split)->values(); } // GIGAX V169: cards do lobby respeitam X1-X8 (antes eram fixos em 5 por time). $teamCapacity = (int) ($match->team_size ?? 0); if ($teamCapacity < 1 || $teamCapacity > 8) { $maxPlayersForCard = max(2, (int) ($match->max_players ?? 10)); $teamCapacity = max(1, min(8, (int) ceil($maxPlayersForCard / 2))); } $match->left_players = $teamA->take($teamCapacity)->values()->all(); $match->right_players = $teamB->take($teamCapacity)->values()->all(); $match->left_team = $teamA->isNotEmpty() ? ($teamA->first()->league_tag ?: $teamA->first()->nickname) : ($match->host_name ?? 'KRX'); $match->right_team = $teamB->isNotEmpty() ? ($teamB->first()->league_tag ?: $teamB->first()->nickname) : strtoupper((string) ($match->training_type ?? 'scrim')); $match->team_a_count = $teamA->count(); $match->team_b_count = $teamB->count(); $match->current_players = (int) ($match->current_players ?? $participants->count()); $match->max_players = (int) ($match->max_players ?? 10); if ($live || (string) ($match->status ?? '') === 'in_progress') { $match->left_score = (int) ($match->team_a_count ?? 0); $match->right_score = (int) ($match->team_b_count ?? 0); } return $match; }); } }