<?php
$pageTitle = 'All Fantasy Teams';
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();
}

// --- Instantiate Models ---
$fantasyModel = new Fantasy();

$teams = $fantasyModel->getAllTeamsWithDetails();
?>

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

<div class="page-content">
    <div class="matches-header">
        <h1>All Fantasy Teams</h1>
    </div>

    <!-- Display any success or error messages -->
    <?php if (isset($_GET['status'])): ?>
        <div class="status-message <?php echo $_GET['status'] === 'success' ? 'success' : 'error'; ?>">
            <?php
            if ($_GET['status'] === 'success') {
                echo 'Fantasy team deleted successfully!';
            } else {
                echo 'An error occurred while deleting the team.';
            } ?>
        </div>
    <?php endif; ?>
    <div class="dashboard-section">
        <div class="table-wrapper">
            <table class="styled-table">
                <thead>
                    <tr>
                        <th>Team Name</th>
                        <th>Manager (User)</th>
                        <th>Season</th>
                        <th>Total Points</th>
                        <th>GW Points</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($teams as $team): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($team->team_name); ?></td>
                            <td><?php echo htmlspecialchars($team->manager_name); ?> (<?php echo htmlspecialchars($team->username); ?>)</td>
                            <td><?php echo htmlspecialchars($team->season); ?></td>
                            <td><?php echo $team->total_points; ?></td>
                            <td><?php echo $team->gameweek_points; ?></td>
                            <td>
                                <form action="fantasy_team_delete_process.php" method="POST" onsubmit="return confirm('Are you sure you want to permanently delete this team and all its data?');" style="display:inline;">
                                    <input type="hidden" name="team_id" value="<?php echo $team->id; ?>">
                                    <button type="submit" class="btn-sm btn-danger">Delete</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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