<?php
$pageTitle = 'Manage Seasons';
include_once 'includes/header.php';

$season = new Season();
$message = '';
$error = '';

// Handle form submission for creating a new season
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_season'])) {
    $name = trim($_POST['name'] ?? '');

    if (empty($name)) {
        $error = 'Season name is required.';
    } else {
        if ($season->create($name)) {
            $_SESSION['flash_message'] = 'Season created successfully!';
            header('Location: manage_seasons.php');
            exit();
        } else {
            $error = 'Failed to create season. It may already exist.';
        }
    }
}

// Handle deletion
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['delete_id'])) {
    $delete_id = filter_input(INPUT_GET, 'delete_id', FILTER_VALIDATE_INT);
    if ($delete_id && $season->delete($delete_id)) {
        $_SESSION['flash_message'] = 'Season deleted successfully!';
        header('Location: manage_seasons.php');
        exit();
    } else {
        $error = 'Failed to delete season.';
    }
}

// Check for flash messages
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
}

$all_seasons = $season->getAll();

include_once 'includes/sidebar.php';
?>

<h1>Manage Seasons</h1>

<?php if ($message): ?><div class="message success"><?php echo $message; ?></div><?php endif; ?>
<?php if ($error): ?><div class="message error"><?php echo $error; ?></div><?php endif; ?>

<div class="form-container">
    <h2>Create New Season</h2>
    <form action="manage_seasons.php" method="POST">
        <div class="form-group"><label for="name">Season Name (e.g., 2024/2025)</label><input type="text" name="name" id="name" required></div>
        <button type="submit" name="create_season" class="btn">Create Season</button>
    </form>
</div>

<h2>Existing Seasons</h2>
<table class="styled-table">
    <thead><tr><th>ID</th><th>Name</th><th>Actions</th></tr></thead>
    <tbody>
        <?php foreach ($all_seasons as $s): ?>
            <tr>
                <td><?php echo $s->id; ?></td>
                <td><?php echo htmlspecialchars($s->name); ?></td>
                <td><a href="?delete_id=<?php echo $s->id; ?>" onclick="return confirm('Are you sure? Deleting a season might affect associated leagues.')">Delete</a></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

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