=== LINHAS 1890-2010 === 1890: ->value('role')); 1891: 1892: if (!in_array($role, ['admin', 'administrator', 'administrador', 'owner'], true)) { 1893: return response()->json([ 1894: 'success' => false, 1895: 'message' => 'Apenas administradores podem forçar criação de partida' 1896: ], 403); 1897: } 1898: 1899: try { 1900: if ($queueId) { 1901: $result = $this->createMatchForQueue($queueId); 1902: } else { 1903: $result = $this->checkAndCreateMatchForAnyQueue(); 1904: } 1905: 1906: return response()->json([ 1907: 'success' => $result !== null, 1908: 'lobby_id' => $result, 1909: 'message' => $result ? 'Lobby criado com sucesso!' : 'Não foi possível criar lobby' 1910: ]); 1911: } catch (\Exception $e) { 1912: Log::error("Erro ao forçar criação de lobby: " . $e->getMessage()); 1913: return response()->json([ 1914: 'success' => false, 1915: 'message' => 'Erro ao criar lobby' 1916: ], 500); 1917: } 1918: } 1919: 1920: /** 1921: * POST /queue/create-lobby - Cria um lobby diretamente sem fila 1922: */ 1923: public function createDirectLobby(Request $request) 1924: { 1925: $userId = $this->extractUserId($request); 1926: 1927: $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [ 1928: 'title' => 'required|string|max:100', 1929: 'training_type' => 'required|in:casualx5,acessox5,seriebx5,serieax5,todosmodosvip,treino5lx5,campx5,x1,x2,x8,c1sx5,sniperx5,free', 1930: 'map_name' => 'nullable|string|max:50', 1931: 'max_players' => 'required|integer|min:2|max:20', 1932: 'password' => 'nullable|string|max:20' 1933: ]); 1934: 1935: if ($validator->fails()) { 1936: return response()->json([ 1937: 'success' => false, 1938: 'errors' => $validator->errors() 1939: ], 422); 1940: } 1941: 1942: try { 1943: DB::beginTransaction(); 1944: 1945: // Verificar se o usuário já está em um lobby ativo 1946: $activeLobby = DB::selectOne(" 1947: SELECT tp.*, tm.title 1948: FROM mix_training_participants tp 1949: JOIN mix_training_matches tm ON tp.training_match_id = tm.id 1950: WHERE tp.user_id = ? AND tp.left_at IS NULL AND tm.status IN ('waiting', 'veto', 'in_progress') 1951: ", [$userId]); 1952: 1953: if ($activeLobby) { 1954: DB::rollBack(); 1955: return response()->json([ 1956: 'success' => false, 1957: 'message' => 'Você já está em um lobby ativo: ' . $activeLobby->title, 1958: 'lobby_id' => $activeLobby->training_match_id 1959: ]); 1960: } 1961: 1962: // Criar lobby diretamente 1963: $lobbyId = DB::table('mix_training_matches')->insertGetId([ 1964: 'title' => $request->title, 1965: 'training_type' => $request->training_type, 1966: 'map_name' => $request->map_name ?? 'Crossfire', 1967: 'max_players' => $request->max_players, 1968: 'current_players' => 1, 1969: 'host_id' => $userId, 1970: 'password' => $request->password, 1971: 'voice_mode' => app(\App\Services\GlobalVoiceProviderService::class)->matchValue(), 1972: 'status' => 'waiting', 1973: 'veto_status' => 'pending', 1974: 'veto_round' => 0, 1975: 'created_at' => Carbon::now() 1976: ]); 1977: 1978: // Adicionar host como participante 1979: DB::table('mix_training_participants')->insert([ 1980: 'training_match_id' => $lobbyId, 1981: 'user_id' => $userId, 1982: 'team' => 1, 1983: 'joined_at' => Carbon::now(), 1984: 'left_at' => null 1985: ]); 1986: 1987: DB::commit(); 1988: 1989: Log::info("Lobby criado diretamente", [ 1990: 'lobby_id' => $lobbyId, 1991: 'user_id' => $userId, 1992: 'title' => $request->title 1993: ]); 1994: 1995: return response()->json([ 1996: 'success' => true, 1997: 'lobby_id' => $lobbyId, 1998: 'message' => 'Lobby criado com sucesso!' 1999: ]); 2000: 2001: } catch (\Exception $e) { 2002: DB::rollBack(); 2003: Log::error("Erro ao criar lobby diretamente: " . $e->getMessage()); 2004: return response()->json([ 2005: 'success' => false, 2006: 'message' => 'Erro ao criar lobby: ' . $e->getMessage() 2007: ], 500); 2008: } 2009: } 2010: === LINHAS 2730-2870 === 2730: try { 2731: Log::info('KRUX 5V5: createLobbyFromQueue iniciado', ['queue_id' => $queueId]); 2732: DB::beginTransaction(); 2733: 2734: $queueRow = DB::selectOne("" 2735: . "SELECT TOP 1 *\n" 2736: . "FROM mix_queues WITH (UPDLOCK, ROWLOCK)\n" 2737: . "WHERE id = ?" 2738: , [$queueId]); 2739: 2740: if (!$queueRow) { 2741: DB::rollBack(); 2742: Log::warning('KRUX 5V5: fila não encontrada', ['queue_id' => $queueId]); 2743: return null; 2744: } 2745: 2746: $existingMatchId = (int) ($queueRow->match_id ?? 0); 2747: if ($existingMatchId > 0) { 2748: DB::commit(); 2749: return $existingMatchId; 2750: } 2751: 2752: if ((string) ($queueRow->status ?? '') !== 'waiting') { 2753: DB::rollBack(); 2754: Log::warning('KRUX 5V5: fila não está waiting', [ 2755: 'queue_id' => $queueId, 2756: 'status' => $queueRow->status ?? null, 2757: ]); 2758: return null; 2759: } 2760: 2761: $queueMode = $this->normalizeQueueMode((string) ($queueRow->queue_mode ?? 'casual')); 2762: $gameSlug = strtolower(trim((string) ($queueRow->game_slug ?? 'crossfire'))) ?: 'crossfire'; 2763: $trainingType = $this->trainingTypeFromQueueMode($queueMode); 2764: 2765: $players = DB::select("" 2766: . "SELECT TOP (" . self::MAX_QUEUE_SIZE . ")\n" 2767: . " qp.id, qp.queue_id, qp.user_id, qp.position, qp.joined_at,\n" 2768: . " ISNULL(qp.queue_mode, ?) AS queue_mode,\n" 2769: . " u.nickname, ISNULL(u.skill_level, 1) AS skill_level\n" 2770: . "FROM mix_queue_players qp WITH (UPDLOCK, ROWLOCK)\n" 2771: . "JOIN users u ON u.id = qp.user_id\n" 2772: . "WHERE qp.queue_id = ?\n" 2773: . "ORDER BY qp.position ASC, qp.id ASC" 2774: , [$queueMode, $queueId]); 2775: 2776: if (count($players) < self::MAX_QUEUE_SIZE) { 2777: DB::rollBack(); 2778: Log::warning('KRUX 5V5: fila ainda não tem 10 jogadores', [ 2779: 'queue_id' => $queueId, 2780: 'players' => count($players), 2781: ]); 2782: return null; 2783: } 2784: 2785: // Antes de inserir participantes, libera qualquer vínculo antigo de 2786: // partida já encerrada. Impede falso duplicate-key no índice de lobby ativo. 2787: foreach ($players as $selectedPlayer) { 2788: $this->cleanupStaleFinishedParticipantLinks((int) $selectedPlayer->user_id); 2789: } 2790: 2791: $now = Carbon::now(); 2792: $matchData = [ 2793: 'title' => $this->modePublicName($queueMode) . ' 5v5 #' . $queueId . ' - ' . $now->format('d/m/Y H:i'), 2794: 'training_type' => $trainingType, 2795: 'map_name' => 'Crossfire', 2796: 'max_players' => self::MAX_QUEUE_SIZE, 2797: 'host_id' => (int) $players[0]->user_id, 2798: 'status' => 'ready_check', 2799: 'created_at' => $now, 2800: 'updated_at' => $now, 2801: ]; 2802: 2803: $optionalMatchColumns = [ 2804: 'current_players' => self::MAX_QUEUE_SIZE, 2805: 'password' => null, 2806: 'veto_status' => 'pending', 2807: 'veto_round' => 0, 2808: 'current_veto_team' => 'A', 2809: 'selected_map_id' => null, 2810: 'veto_started_at' => null, 2811: 'veto_ended_at' => null, 2812: 'queue_mode' => $queueMode, 2813: 'game_slug' => $gameSlug, 2814: 'voice_mode' => app(\App\Services\GlobalVoiceProviderService::class)->matchValue(), 2815: 'voice_status' => 'pending', 2816: 'anti_cheat_required' => (bool) (app(GigaxAcValidationService::class)->status()['required'] ?? true) ? 1 : 0, 2817: 'ready_status' => 'pending', 2818: 'ready_check_status' => 'pending', 2819: 'ready_check_started_at' => $now, 2820: 'ready_check_expires_at' => $now->copy()->addSeconds(self::READY_CHECK_TIMEOUT_SECONDS), 2821: ]; 2822: 2823: foreach ($optionalMatchColumns as $column => $value) { 2824: try { 2825: if (Schema::hasColumn('mix_training_matches', $column)) { 2826: $matchData[$column] = $value; 2827: } 2828: } catch (\Throwable $ignored) { 2829: // Mantém compatibilidade com ambientes onde Schema pode falhar. 2830: } 2831: } 2832: 2833: $lobbyId = (int) DB::table('mix_training_matches')->insertGetId($matchData); 2834: 2835: [$teamA, $teamB] = $this->balanceQueuePlayers($players); 2836: 2837: $insertParticipant = function ($player, int $team) use ($lobbyId, $now): void { 2838: $data = [ 2839: 'training_match_id' => $lobbyId, 2840: 'user_id' => (int) $player->user_id, 2841: 'team' => $team, 2842: 'joined_at' => $now, 2843: 'left_at' => null, 2844: ]; 2845: 2846: foreach (array_keys($data) as $column) { 2847: try { 2848: if (!Schema::hasColumn('mix_training_participants', $column)) { 2849: unset($data[$column]); 2850: } 2851: } catch (\Throwable $ignored) {} 2852: } 2853: 2854: DB::table('mix_training_participants')->insert($data); 2855: }; 2856: 2857: foreach ($teamA as $player) { 2858: $insertParticipant($player, 1); 2859: } 2860: 2861: foreach ($teamB as $player) { 2862: $insertParticipant($player, 2); 2863: } 2864: 2865: try { 2866: $this->createReadyCheckRecords($lobbyId, $teamA, $teamB); 2867: } catch (\Throwable $e) { 2868: Log::warning('KRUX 5V5: ready-check auxiliar falhou, lobby mantido', [ 2869: 'lobby_id' => $lobbyId, 2870: 'error' => $e->getMessage(), === LINHAS 3050-3130 === 3050: foreach ($players as $index => $player) { 3051: $round = intdiv($index, 2); 3052: 3053: if ($round % 2 === 0) { 3054: if ($index % 2 === 0) { 3055: $teamA[] = $player; 3056: } else { 3057: $teamB[] = $player; 3058: } 3059: } else { 3060: if ($index % 2 === 0) { 3061: $teamB[] = $player; 3062: } else { 3063: $teamA[] = $player; 3064: } 3065: } 3066: } 3067: 3068: // Segurança final: garante 5x5. 3069: while (count($teamA) > 5) { 3070: $teamB[] = array_pop($teamA); 3071: } 3072: 3073: while (count($teamB) > 5) { 3074: $teamA[] = array_pop($teamB); 3075: } 3076: 3077: return [ 3078: array_slice(array_values($teamA), 0, 5), 3079: array_slice(array_values($teamB), 0, 5), 3080: ]; 3081: } 3082: 3083: 3084: private function ensureReadyCheckStructures(): void 3085: { 3086: // Estrutura já existe no banco. Não executar DDL/Schema em requisição web. 3087: return; 3088: } 3089: 3090: private function createReadyCheckRecords(int $lobbyId, array $teamA, array $teamB): void 3091: { 3092: $this->ensureReadyCheckTablesAndColumns(); 3093: 3094: $now = Carbon::now(); 3095: $expiresAt = $now->copy()->addSeconds(self::READY_CHECK_TIMEOUT_SECONDS); 3096: 3097: $matchUpdate = [ 3098: 'status' => 'ready_check', 3099: 'updated_at' => $now, 3100: ]; 3101: 3102: foreach ([ 3103: 'ready_status' => 'pending', 3104: 'ready_check_status' => 'pending', 3105: 'ready_check_started_at' => $now, 3106: 'ready_check_expires_at' => $expiresAt, 3107: ] as $column => $value) { 3108: try { 3109: if (Schema::hasColumn('mix_training_matches', $column)) { 3110: $matchUpdate[$column] = $value; 3111: } 3112: } catch (\Throwable $ignored) {} 3113: } 3114: 3115: DB::table('mix_training_matches') 3116: ->where('id', $lobbyId) 3117: ->update($matchUpdate); 3118: 3119: DB::table('match_ready_players')->where('match_id', $lobbyId)->delete(); 3120: DB::table('match_ready_checks')->where('lobby_id', $lobbyId)->delete(); 3121: 3122: $insertReady = function ($player, int $team) use ($lobbyId, $now, $expiresAt): void { 3123: $readyPlayer = [ 3124: 'match_id' => $lobbyId, 3125: 'user_id' => (int) $player->user_id, 3126: 'team' => $team, 3127: 'is_ready' => 0, 3128: 'confirmed_at' => null, 3129: 'created_at' => $now, 3130: 'updated_at' => $now,