<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Game;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class StatisticsController extends Controller
{
    public function getPublicStats()
    {
        $totalPlayers = User::where('type', 'P')->count();

        $totalGames = Game::where('status', 'Ended')->count();
        $activeGames = Game::where('status', 'Playing')->count();

        return response()->json([
            'total_players' => $totalPlayers,
            'total_games' => $totalGames,
            'active_games' => $activeGames,
        ]);
    }

    public function getLeaderboard(Request $request)
    {
        $type = $request->query('type');

        $query = User::where('type', 'P')
            ->withCount(['wonGames' => function ($query) use ($type) {
                if ($type) {
                    $query->where('type', $type);
                }
            }])
            ->orderBy('won_games_count', 'desc')
            ->take(10);

        $leaderboard = $query->get(['id', 'nickname', 'photo_avatar_filename']);

        return response()->json($leaderboard);
    }

    public function getPersonalStats(Request $request)
    {
        $user = $request->user();

        $totalGames = Game::where('status', 'Ended')
            ->where(function ($q) use ($user) {
                $q->where('player1_user_id', $user->id)
                  ->orWhere('player2_user_id', $user->id);
            })
            ->count();

        $totalWins = Game::where('status', 'Ended')
            ->where('winner_user_id', $user->id)
            ->count();

        $totalLosses = $totalGames - $totalWins; // Simplest math

        $winRate = 0;
        if ($totalGames > 0) {
            $winRate = round(($totalWins / $totalGames) * 100, 1);
        }

        return response()->json([
            'nickname' => $user->nickname,
            'total_games' => $totalGames,
            'total_wins' => $totalWins,
            'total_losses' => $totalLosses,
            'win_rate' => $winRate . '%',
            'current_balance' => $user->coins_balance, // Extra info
        ]);
    }
}