<?php
require_once '../core/bootstrap.php';

$league_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if (!$league_id) {
    die('Invalid League ID.');
}

// We can directly use the logic from our API to build the table
ob_start();
$_GET['league_id'] = $league_id; // Set the GET param for the included file
include '../api/v1/leagues/table.php';
$table_json = ob_get_clean();
$table = json_decode($table_json);

$league_model = new League();
$league_info = $league_model->getById($league_id);

$pageTitle = ($league_info->name ?? 'League') . ' Table';
include_once 'includes/header.php';
?>

<h1><?php echo htmlspecialchars($league_info->name ?? 'League'); ?> Standings</h1>
<a href="fixtures.php?league_id=<?php echo $league_id; ?>">View Fixtures</a>

<table class="styled-table">
    <thead>
        <tr>
            <th>Pos</th>
            <th>Club</th>
            <th>P</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 ($table as $index => $row): ?>
            <tr>
                <td><?php echo $index + 1; ?></td>
                <td class="team-name"><img src="/smart_football/uploads/club_logos/<?php echo htmlspecialchars($row->logo ?? 'default.png'); ?>" class="table-logo"> <?php echo htmlspecialchars($row->team_name); ?></td>
                <td><?php echo $row->played; ?></td>
                <td><?php echo $row->wins; ?></td>
                <td><?php echo $row->draws; ?></td>
                <td><?php echo $row->losses; ?></td>
                <td><?php echo $row->goals_for; ?></td>
                <td><?php echo $row->goals_against; ?></td>
                <td><?php echo $row->goals_for - $row->goals_against; ?></td>
                <td><strong><?php echo $row->points; ?></strong></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<?php include_once 'includes/footer.php'; ?>