<?php
$pageTitle = 'Edit Team';
include_once 'includes/header.php';

$teamModel = new Team();
$clubModel = new Club();
$userModel = new User();
$error = '';

$team_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$team_id) {
    header('Location: manage_teams.php');
    exit();
}

$team = $teamModel->findById($team_id);
if (!$team) {
    header('Location: manage_teams.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $club_id = filter_input(INPUT_POST, 'club_id', FILTER_VALIDATE_INT);
    $manager_id = filter_input(INPUT_POST, 'manager_id', FILTER_VALIDATE_INT);

    if (empty($name) || empty($club_id)) {
        $error = 'Team name and club are required.';
    } else {
        $teamData = [
            'id' => $team_id,
            'name' => $name,
            'club_id' => $club_id,
            'manager_id' => $manager_id ?: null
        ];
        if ($teamModel->update($teamData)) {
            $_SESSION['flash_message'] = "Team '{$name}' updated successfully!";
            header('Location: manage_teams.php');
            exit();
        } else {
            $error = 'Failed to update team.';
        }
    }
}

$all_clubs = $clubModel->getAllForAdmin();
$potential_managers = $userModel->getPotentialManagers(['team_manager', 'admin', 'super_admin']);
include_once 'includes/sidebar.php';
?>

<h1>Edit Team: <?php echo htmlspecialchars($team->name); ?></h1>

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

<div class="form-container">
    <form action="edit_team.php?id=<?php echo $team_id; ?>" method="POST">
        <div class="form-group"><label for="name">Team Name</label><input type="text" name="name" id="name" value="<?php echo htmlspecialchars($team->name); ?>" required></div>
        <div class="form-group">
            <label for="club_id">Club</label>
            <select name="club_id" id="club_id" required>
                <?php foreach ($all_clubs as $club): ?>
                    <option value="<?php echo $club->id; ?>" <?php echo ($club->id == $team->club_id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($club->name); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label for="manager_id">Team Manager (Coach)</label>
            <select name="manager_id" id="manager_id">
                <option value="">-- Unassigned --</option>
                <?php foreach ($potential_managers as $manager): ?><option value="<?php echo $manager->id; ?>" <?php echo ($manager->id == $team->manager_id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($manager->first_name . ' ' . $manager->last_name); ?></option><?php endforeach; ?>
            </select>
        </div>
        <button type="submit" class="btn">Update Team</button>
    </form>
</div>

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