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

// --- Authentication Check ---
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// --- Role Check ---
// Explicitly allow commissioners to access this page
$allowed_roles = ['admin', 'super_admin', 'super_fantasy_manager', 'commissioner'];
if (!in_array($_SESSION['user_role'], $allowed_roles)) {
    // Access Denied
    header('Location: index.php');
    exit();
}

$pageTitle = 'Process Fantasy Points';
include 'includes/header.php';

$fixtureModel = new Fixture();
$fantasyModel = class_exists('Fantasy') ? new Fantasy() : null;

// Determine relevant gameweek (default to the latest finished one)
$league_id = 1; // Default league context
$latest_finished_gameweek = $fixtureModel->getLatestFinishedGameweek($league_id);
$gameweek_to_process = $latest_finished_gameweek ? $latest_finished_gameweek : 1;

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $gw = filter_input(INPUT_POST, 'gameweek', FILTER_VALIDATE_INT);
    
    if ($gw) {
        try {
            if ($fantasyModel && method_exists($fantasyModel, 'calculateGameweekPoints')) {
                $fantasyModel->calculateGameweekPoints($gw);
                $message = "Fantasy points for Gameweek $gw have been processed successfully.";
                $messageType = 'success';
            } else {
                // Fallback if the method isn't implemented yet
                $message = "Simulation: Points processed for Gameweek $gw. (Fantasy model method pending)";
                $messageType = 'info';
            }
        } catch (Exception $e) {
            $message = "Error processing points: " . $e->getMessage();
            $messageType = 'error';
        }
    }
}
?>

<div class="page-content">
    <div class="matches-header">
        <h1>Process Fantasy Points</h1>
    </div>

    <?php if ($message): ?>
        <div class="status-message <?php echo $messageType; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <div class="dashboard-section">
        <p>Use this tool to calculate and update fantasy points for all players and teams for a specific gameweek.</p>
        <p><strong>Note:</strong> This should usually be done after all matches in the gameweek have finished.</p>

        <form action="admin_gameweek_process.php" method="POST" class="styled-form" style="max-width: 400px; margin-top: 20px;">
            <div class="form-group">
                <label for="gameweek">Select Gameweek</label>
                <select name="gameweek" id="gameweek" required>
                    <?php for ($i = 1; $i <= 38; $i++): ?>
                        <option value="<?php echo $i; ?>" <?php echo ($i == $gameweek_to_process) ? 'selected' : ''; ?>>Gameweek <?php echo $i; ?></option>
                    <?php endfor; ?>
                </select>
            </div>
            <button type="submit" class="btn" onclick="return confirm('Are you sure you want to process points for this gameweek? This may overwrite existing points.')">Process Points</button>
        </form>
    </div>
</div>

<style>
.status-message { padding: 15px; border-radius: 8px; margin-bottom: 20px; }
.status-message.success { background: #d4edda; color: #155724; }
.status-message.error { background: #f8d7da; color: #721c24; }
.status-message.info { background: #d1ecf1; color: #0c5460; }
</style>

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