<?php
// =============================================================================
// /api/webview/sports/sport_l_table.php — league standings (computed from
// finished events). Picks the most-active league by default; pass ?league_id=N
// to override.
// =============================================================================
require_once __DIR__ . '/../_wv_common.php';

wv_maybe_bootstrap_sports();

$league_id = (int)($_GET['league_id'] ?? 0);
if ($league_id <= 0) {
    $row = db_one(
        'SELECT l.id, l.name
         FROM sports_events e JOIN sports_leagues l ON l.id = e.league_id
         WHERE e.status = "FT"
         GROUP BY l.id ORDER BY COUNT(*) DESC LIMIT 1');
    $league_id = $row ? (int)$row['id'] : 0;
}

$league = $league_id > 0 ? db_one('SELECT * FROM sports_leagues WHERE id=?', [$league_id]) : null;
$rows   = $league_id > 0 ? db_all(
    'SELECT * FROM sports_events WHERE league_id = ? AND status = "FT" ORDER BY kickoff_ts ASC',
    [$league_id]) : [];

// Compute standings: PL / W / D / L / GF / GA / GD / Pts
$tbl = [];
foreach ($rows as $r) {
    $h = $r['home_team']; $a = $r['away_team']; $hs = (int)$r['home_score']; $as = (int)$r['away_score'];
    foreach ([$h, $a] as $t) {
        if (!isset($tbl[$t])) $tbl[$t] = ['team' => $t, 'pl' => 0, 'w' => 0, 'd' => 0, 'l' => 0, 'gf' => 0, 'ga' => 0, 'pts' => 0];
        $tbl[$t]['pl']++;
    }
    $tbl[$h]['gf'] += $hs; $tbl[$h]['ga'] += $as;
    $tbl[$a]['gf'] += $as; $tbl[$a]['ga'] += $hs;
    if ($hs > $as) { $tbl[$h]['w']++; $tbl[$a]['l']++; $tbl[$h]['pts'] += 3; }
    elseif ($hs < $as) { $tbl[$a]['w']++; $tbl[$h]['l']++; $tbl[$a]['pts'] += 3; }
    else { $tbl[$h]['d']++; $tbl[$a]['d']++; $tbl[$h]['pts']++; $tbl[$a]['pts']++; }
}
foreach ($tbl as &$t) { $t['gd'] = $t['gf'] - $t['ga']; } unset($t);
usort($tbl, fn($a, $b) => [$b['pts'], $b['gd'], $b['gf']] <=> [$a['pts'], $a['gd'], $a['gf']]);

wv_html_head('League Table', '<style>
.wrap{padding:16px;max-width:1100px;margin:0 auto}
.title{font-size:18px;font-weight:800;margin-bottom:4px}
.sub{color:var(--muted);font-size:12px;margin-bottom:14px}
table{width:100%;border-collapse:collapse;background:var(--card);border:1px solid #2a2a2a;border-radius:10px;overflow:hidden}
th,td{padding:8px 10px;text-align:right;font-size:12px;border-bottom:1px solid #1e1e1e;}
th{background:#1a1a1a;color:var(--accent);font-size:11px;text-transform:uppercase;letter-spacing:.05em;}
th:first-child,td:first-child{text-align:left;color:#fff;font-weight:600;}
tr:last-child td{border-bottom:0;}
.empty{padding:60px 0;text-align:center;color:var(--muted);font-size:13px;}
</style>');
?>
<div class="wrap">
    <p class="title">League Table</p>
    <p class="sub"><?php echo $league ? htmlspecialchars($league['name'], ENT_QUOTES, 'UTF-8') : 'No league selected'; ?></p>
    <?php if (!$tbl): ?>
        <div class="empty">Standings will appear once matches are played.</div>
    <?php else: ?>
    <table>
        <thead><tr><th>Team</th><th>PL</th><th>W</th><th>D</th><th>L</th><th>GF</th><th>GA</th><th>GD</th><th>Pts</th></tr></thead>
        <tbody>
            <?php foreach ($tbl as $t): ?>
                <tr>
                    <td><?php echo htmlspecialchars($t['team'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo $t['pl']; ?></td>
                    <td><?php echo $t['w']; ?></td>
                    <td><?php echo $t['d']; ?></td>
                    <td><?php echo $t['l']; ?></td>
                    <td><?php echo $t['gf']; ?></td>
                    <td><?php echo $t['ga']; ?></td>
                    <td><?php echo $t['gd']; ?></td>
                    <td style="color:var(--accent);font-weight:700"><?php echo $t['pts']; ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</div>
<?php wv_html_foot();
