<?php
$pageTitle = 'Gameweek Stats';
include 'includes/header.php';

// --- Admin Authentication & Authorization ---
if (!in_array($_SESSION['admin_user_role'] ?? '', ['admin', 'super_admin', 'super_fantasy_manager'])) {
    header('Location: dashboard.php');
    exit();
}

$fantasyPointsModel = new FantasyPoints();

// Get gameweek
$gameweek = filter_input(INPUT_GET, 'gameweek', FILTER_VALIDATE_INT);
if (!$gameweek) {
    $gameweek = 1;
}

$stats = $fantasyPointsModel->getGameweekPlayerStats($gameweek);

include 'includes/sidebar.php';
?>

<div class="page-content">
    <div class="matches-header">
        <h1>Gameweek <?php echo htmlspecialchars($gameweek); ?> Top Performers</h1>
        <form method="GET" action="fantasy_gameweek_stats.php" style="display: flex; align-items: center; gap: 10px;">
            <label for="gameweek" style="margin: 0; font-weight: bold;">Gameweek:</label>
            <input type="number" id="gameweek" name="gameweek" min="1" value="<?php echo htmlspecialchars($gameweek); ?>" style="width: 80px; padding: 5px;">
            <button type="submit" class="btn-sm">View</button>
        </form>
    </div>

    <div class="dashboard-section">
        <div class="table-wrapper">
            <table class="styled-table">
                <thead>
                    <tr>
                        <th>Rank</th>
                        <th>Player</th>
                        <th>Club</th>
                        <th>Position</th>
                        <th>Points</th>
                        <th>Minutes</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($stats)): ?>
                        <tr><td colspan="6" style="text-align:center;">No stats available for this gameweek.</td></tr>
                    <?php else: ?>
                        <?php $rank = 1; foreach ($stats as $player): ?>
                            <tr>
                                <td><?php echo $rank++; ?></td>
                                <td><?php echo htmlspecialchars($player->first_name . ' ' . $player->last_name); ?></td>
                                <td><?php echo htmlspecialchars($player->club_name); ?></td>
                                <td><?php echo htmlspecialchars($player->position); ?></td>
                                <td><strong><?php echo $player->total_points; ?></strong></td>
                                <td><?php echo $player->total_minutes; ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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