<?php
require_once __DIR__ . '/../config/helpers.php';
cors();

if ($_SERVER['REQUEST_METHOD'] !== 'GET') json_err('Method not allowed', 405);

$db = db();

// Top scorers across all players on approved teams
$players = $db->query(
    "SELECT p.id, p.name, p.position, p.goals_scored, p.assists, p.team_id,
            t.name AS team_name
     FROM players p
     JOIN teams t ON t.id = p.team_id
     WHERE t.status = 'approved'
     ORDER BY p.goals_scored DESC, p.assists DESC
     LIMIT 50"
)->fetchAll();

// Team leaderboard
$teams = $db->query(
    "SELECT id, name, wins, draws, losses,
            (wins + draws + losses) AS total_games,
            CASE WHEN (wins+draws+losses)=0 THEN 0
                 ELSE ROUND(wins/(wins+draws+losses)*100,1) END AS win_pct
     FROM teams WHERE status='approved'
     ORDER BY wins DESC, win_pct DESC
     LIMIT 30"
)->fetchAll();

json_ok(['players' => $players, 'teams' => $teams]);
