<?php
$pageTitle = 'Process Fantasy Points';
// Use the admin-specific header which has the correct authentication logic.
include 'includes/header.php';

// --- Admin Authentication & Authorization ---
// The main auth check is in header.php. This is a role-specific check.
if (!in_array($_SESSION['admin_user_role'], ['admin', 'super_admin', 'super_fantasy_manager'])) {
    header('Location: dashboard.php');
    exit();
}

$gameweek = filter_input(INPUT_GET, 'gameweek', FILTER_VALIDATE_INT);
$league_id = 1; // Assume Premier League for now

include 'includes/sidebar.php';
?>

<div class="page-content">
    <h1>Processing Fantasy Points</h1>

    <?php if (!$gameweek): ?>
        <p class="message error">Please provide a valid gameweek number in the URL. Example: ?gameweek=1</p>
    <?php else: ?>
        <p>Attempting to process points for Gameweek: <strong><?php echo $gameweek; ?></strong></p>
        <?php
        $fantasyPointsModel = new FantasyPoints();
        $result = $fantasyPointsModel->calculateForGameweek($gameweek, $league_id);

        $message_class = $result['status'] === 'success' ? 'success' : 'error';
        echo "<div class='message {$message_class}'>" . htmlspecialchars($result['message']) . "</div>";
        ?>
    <?php endif; ?>

    <p style="margin-top: 2rem;"><a href="process_fantasy_points.php?gameweek=<?php echo ($gameweek ? $gameweek + 1 : 1); ?>" class="btn">Process Next Gameweek (<?php echo ($gameweek ? $gameweek + 1 : 1); ?>)</a></p>
</div>

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