<?php

namespace App\Http\Controllers;

use App\Models\Torneo;
use App\Models\Equipo;
use App\Models\Evento;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class TorneoController extends Controller
{
    public function standings(Request $request, $id)
    {
        $selectedGroup = $request->query('grupo');
        $torneo = Torneo::with('equipos.club')->findOrFail($id);
        
        $tournamentService = new \App\Services\TournamentService();
        $stats = $tournamentService->getStandings($id, true);
        
        $grupos = array_keys($stats);

        if ($selectedGroup && isset($stats[$selectedGroup])) {
            $stats = [$selectedGroup => $stats[$selectedGroup]];
        }

        $followedTeamIds = [];
        if (session('user_logged_in') && session('user_id')) {
            $followedTeamIds = \App\Models\EquipoSeguimiento::where('id_usuario', session('user_id'))
                ->where('tipo_usuario', session('user_tipo'))
                ->pluck('id_equipo')
                ->toArray();
        }

        return view('torneos.standings', compact('torneo', 'stats', 'grupos', 'selectedGroup', 'followedTeamIds'));
    }

    public function topScorers(Request $request, $id)
    {
        $torneo = Torneo::findOrFail($id);
        $selectedGroup = $request->query('grupo');

        $query = \App\Models\EventoJugador::with(['jugador.clubActual'])
            ->whereHas('evento', function($q) use ($id) {
                $q->where('id_torneo', $id)->whereNotNull('marcador_local');
            });

        if ($selectedGroup) {
            $query->whereHas('evento.equipoLocal.torneos', function($q) use ($id, $selectedGroup) {
                $q->where('torneos.id', $id)->where('torneo_equipo.grupo', $selectedGroup);
            });
        }

        $scorers = $query->select('id_jugador', DB::raw('SUM(puntos) as total_puntos'), DB::raw('COUNT(id_evento) as partidos_jugados'))
            ->groupBy('id_jugador')
            ->orderByDesc('total_puntos')
            ->take(20)->get();

        $grupos = DB::table('torneo_equipo')->where('id_torneo', $id)->distinct()->pluck('grupo')->filter();

        return view('torneos.scorers', compact('torneo', 'scorers', 'grupos', 'selectedGroup'));
    }

    public function playoffs(Request $request, $id)
    {
        $selectedGroup = $request->query('grupo');
        $torneo = Torneo::with('equipos.club')->findOrFail($id);

        // Get groups from pivot
        $grupos = DB::table('torneo_equipo')->where('id_torneo', $id)->distinct()->pluck('grupo')->filter();

        $ts = new \App\Services\TournamentService();
        $bracket = $ts->getPlayoffBrackets($id);

        // Map to simpler keys if needed by view
        $bracket = [
            'cuartos' => collect($bracket[\App\Models\Evento::FASE_CUARTOS] ?? []),
            'semis'   => collect($bracket[\App\Models\Evento::FASE_SEMIS] ?? []),
            'final'   => collect($bracket[\App\Models\Evento::FASE_FINAL] ?? []),
        ];

        return view('torneos.playoffs', compact('torneo', 'bracket', 'grupos', 'selectedGroup'));
    }
}
