<?php

use App\Http\Controllers\Auth\DiscordController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\LeaderboardController;
use App\Http\Controllers\MatchController;
use App\Http\Controllers\MatchmakingController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\TournamentController;
use App\Http\Controllers\Admin;
use Illuminate\Support\Facades\Route;

// ─── Public ───────────────────────────────────────────────────────────────────
Route::get('/', fn () => view('home'))->name('home');
Route::get('/login', fn () => view('auth.login'))->name('login');
Route::get('/leaderboard', [LeaderboardController::class, 'index'])->name('leaderboard.index');

// Public profile (view another player by ID) — no auth needed
Route::get('/player/{id}', [ProfileController::class, 'showPlayer'])->name('player.show');

// Public tournament list — no auth needed
Route::get('/tournaments', [TournamentController::class, 'index'])->name('tournament.public');
Route::get('/tournaments/{id}', [TournamentController::class, 'show'])->name('tournament.public.show');

// ─── Discord OAuth ────────────────────────────────────────────────────────────
Route::get('/auth/discord',          [DiscordController::class, 'redirect'])->name('auth.discord');
Route::get('/auth/discord/callback', [DiscordController::class, 'callback'])->name('auth.discord.callback');
Route::post('/auth/discord/unlink',  [DiscordController::class, 'unlink'])->name('auth.discord.unlink')->middleware('auth');

// ─── Steam OAuth ──────────────────────────────────────────────────────────────
Route::get('/auth/steam',            [App\Http\Controllers\Auth\SteamController::class, 'redirect'])->name('auth.steam');
Route::get('/auth/steam/callback',   [App\Http\Controllers\Auth\SteamController::class, 'callback'])->name('auth.steam.callback');
Route::post('/auth/steam/unlink',    [App\Http\Controllers\Auth\SteamController::class, 'unlink'])->name('auth.steam.unlink')->middleware('auth');

// ─── Logout ───────────────────────────────────────────────────────────────────
Route::post('/auth/logout',          [DiscordController::class, 'logout'])->name('auth.logout')->middleware('auth');

// ─── Authenticated ────────────────────────────────────────────────────────────
Route::middleware('auth')->group(function () {
    Route::get('/dashboard', DashboardController::class)->name('dashboard');

    // Own profile
    Route::get('/profile',       [ProfileController::class, 'show'])->name('profile.show');
    Route::get('/profile/edit',  [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile',     [ProfileController::class, 'update'])->name('profile.update');

    // Matchmaking
    Route::get('/play', [MatchmakingController::class, 'index'])->name('matchmaking.index');

    // API-style matchmaking (web session auth)
    Route::post('/api/matchmaking/join',   [MatchmakingController::class, 'join'])->name('matchmaking.join');
    Route::post('/api/matchmaking/leave',  [MatchmakingController::class, 'leave'])->name('matchmaking.leave');
    Route::get('/api/matchmaking/status',  [MatchmakingController::class, 'status'])->name('matchmaking.status');

    // Matches
    Route::get('/match/history',      [MatchController::class, 'history'])->name('match.history');
    Route::get('/match/{id}',         [MatchController::class, 'show'])->name('match.show');
    Route::post('/match/{id}/submit', [MatchController::class, 'submit'])->name('match.submit');

    // Tournaments
    Route::get('/tournament',                [TournamentController::class, 'index'])->name('tournament.index');
    Route::get('/tournament/{id}',           [TournamentController::class, 'show'])->name('tournament.show');
    Route::get('/tournament/{id}/live',      [TournamentController::class, 'live'])->name('tournament.live');
    Route::post('/tournament/{id}/register', [TournamentController::class, 'register'])->name('tournament.register');
});

// ─── Dev/Test Login (local only) ─────────────────────────────────────────────
if (app()->environment('local')) {
    Route::get('/dev/login/{id}', function (int $id) {
        $user = \App\Models\User::findOrFail($id);
        auth()->login($user, true);
        return redirect()->route('dashboard')->with('success', "Logged in as {$user->username} (dev mode)");
    })->name('dev.login');

    Route::get('/dev/users', function () {
        $users = \App\Models\User::orderByDesc('elo')->get(['id','username','elo','rank']);
        $html  = '<h2 style="font-family:sans-serif;padding:20px">Dev Login — PES League</h2><table border=1 cellpadding=8 style="font-family:sans-serif;border-collapse:collapse">';
        $html .= '<tr><th>#</th><th>Username</th><th>ELO</th><th>Rank</th><th>Action</th></tr>';
        foreach ($users as $u) {
            $url = route('dev.login', $u->id);
            $html .= "<tr><td>{$u->id}</td><td>{$u->username}</td><td>{$u->elo}</td><td>{$u->rank}</td><td><a href='{$url}'>Login as {$u->username}</a></td></tr>";
        }
        $html .= '</table>';
        return $html;
    })->name('dev.users');
}
Route::middleware(['auth', 'can:access-admin'])
    ->prefix('admin')
    ->name('admin.')
    ->group(function () {
        Route::get('/',                           [Admin\DashboardController::class, 'index'])->name('dashboard');
        Route::get('/players',                    [Admin\PlayerController::class,    'index'])->name('players');
        Route::post('/players/{id}/ban',          [Admin\PlayerController::class,    'ban'])->name('players.ban');
        Route::post('/players/{id}/unban',        [Admin\PlayerController::class,    'unban'])->name('players.unban');
        Route::get('/matches',                    [Admin\MatchController::class,     'index'])->name('matches');
        Route::post('/matches/{id}/resolve',      [Admin\MatchController::class,     'resolve'])->name('matches.resolve');
        Route::get('/tournaments',                [Admin\TournamentController::class,'index'])->name('tournaments');
        Route::post('/tournaments',               [Admin\TournamentController::class,'store'])->name('tournaments.store');
        Route::get('/tournaments/{id}',           [Admin\TournamentController::class,'show'])->name('tournaments.show');
        Route::get('/tournaments/{id}/edit',      [Admin\TournamentController::class,'edit'])->name('tournaments.edit');
        Route::put('/tournaments/{id}',           [Admin\TournamentController::class,'fullUpdate'])->name('tournaments.fullUpdate');
        Route::patch('/tournaments/{id}',         [Admin\TournamentController::class,'update'])->name('tournaments.update');
        Route::delete('/tournaments/{id}',        [Admin\TournamentController::class,'destroy'])->name('tournaments.destroy');
        Route::get('/tournaments/{id}/bracket',   [Admin\TournamentController::class,'bracket'])->name('tournament.bracket');
        Route::post('/tournaments/{id}/generate', [Admin\TournamentController::class,'generateBracket'])->name('tournament.generate');
        Route::post('/tournaments/{id}/advance',  [Admin\TournamentController::class,'advanceKnockout'])->name('tournament.advance');
        Route::post('/tournaments/{id}/match/{matchId}/score', [Admin\TournamentController::class,'submitScore'])->name('tournament.score');
        Route::post('/tournaments/{id}/assign-groups', [Admin\TournamentController::class,'assignGroups'])->name('tournament.assignGroups');
        Route::post('/tournaments/{id}/check-tiebreakers', [Admin\TournamentController::class,'checkTiebreakers'])->name('tournament.checkTiebreakers');
        Route::post('/tournaments/{id}/participants',         [Admin\TournamentController::class,'addParticipant'])->name('tournaments.participants.add');
        Route::delete('/tournaments/{id}/participants/{uid}', [Admin\TournamentController::class,'removeParticipant'])->name('tournaments.participants.remove');

        // Pick/Ban per match
        Route::get( '/tournaments/{tid}/match/{mid}/pick-ban',  [Admin\MatchPickBanController::class,'show'])->name('tournament.pickban');
        Route::post('/tournaments/{tid}/match/{mid}/bans',      [Admin\MatchPickBanController::class,'saveBans'])->name('tournament.pickban.bans');
        Route::post('/tournaments/{tid}/match/{mid}/picks',     [Admin\MatchPickBanController::class,'savePicks'])->name('tournament.pickban.picks');
        Route::get( '/tournaments/{tid}/match/{mid}/clubs-json',[Admin\MatchPickBanController::class,'clubsJson'])->name('tournament.pickban.clubs');

        // Knockout draw — save manual seed order and regenerate bracket
        Route::post('/tournaments/{id}/knockout-draw', [Admin\TournamentController::class,'knockoutDraw'])->name('tournament.knockoutDraw');

        // Club management
        Route::get( '/clubs',         [Admin\ClubController::class,'index'])->name('clubs');
        Route::post('/clubs',         [Admin\ClubController::class,'store'])->name('clubs.store');
        Route::put( '/clubs/{id}',    [Admin\ClubController::class,'update'])->name('clubs.update');
        Route::delete('/clubs/{id}',  [Admin\ClubController::class,'destroy'])->name('clubs.destroy');
        Route::get( '/clubs/search',  [Admin\ClubController::class,'search'])->name('clubs.search');
        Route::post('/clubs/import',  [Admin\ClubController::class,'import'])->name('clubs.import');
    });
