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

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

// Handle deletion
if (isset($_GET['delete_id'])) {
    $delete_id = filter_input(INPUT_GET, 'delete_id', FILTER_VALIDATE_INT);
    if ($delete_id && $teamModel->delete($delete_id)) {
        $_SESSION['flash_message'] = 'Team deleted successfully!';
    } else {
        // Using flash_error to distinguish from success messages if needed
        $_SESSION['flash_message'] = 'Failed to delete team. It might have associated players or fixtures.';
    }
    header('Location: manage_teams.php');
    exit();
}

// Handle form submission for creating a new team
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_team'])) {
    $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.';
    } elseif ($teamModel->findByNameAndClub($name, $club_id)) {
        $error = "A team with this name already exists for the selected club.";
    } else {
        $db = new Database();
        try {
            $db->beginTransaction();

            $teamId = $teamModel->create(['name' => $name, 'club_id' => $club_id]);

            if ($manager_id) {
                $teamModel->assignManager($teamId, $manager_id);
                // Optionally, ensure the user's role is correct
                $userModel->updateRole($manager_id, 'team_manager');
            }

            $db->commit();
            $_SESSION['flash_message'] = 'Team created successfully!';
            header('Location: manage_teams.php');
            exit();
        } catch (Exception $e) {
            $db->rollBack();
            $error = 'Failed to create team: ' . $e->getMessage();
        }
    }
}

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

$all_clubs = $clubModel->getAllForAdmin(); // Re-use existing method
$potential_managers = $userModel->getPotentialManagers(['team_manager', 'admin', 'super_admin']);
$all_teams = $teamModel->getAllWithDetails();

include_once 'includes/sidebar.php';
?>

<h1>Manage Teams</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; ?>

<!-- Create Team Form -->
<div class="form-container">
    <h2>Create New Team</h2>
    <form action="manage_teams.php" method="POST">
        <div class="form-group"><label for="name">Team Name (e.g., Senior Team, U21s)</label><input type="text" name="name" id="name" required></div>
        <div class="form-group">
            <label for="club_id">Club</label>
            <select name="club_id" id="club_id" required>
                <option value="">-- Select a Club --</option>
                <?php foreach ($all_clubs as $club): ?><option value="<?php echo $club->id; ?>"><?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 htmlspecialchars($manager->first_name . ' ' . $manager->last_name); ?></option><?php endforeach; ?>
            </select>
        </div>
        <button type="submit" name="create_team" class="btn">Create Team</button>
    </form>
</div>

<!-- List of Existing Teams -->
<h2>Existing Teams</h2>
<table class="styled-table">
    <thead><tr><th>ID</th><th>Team Name</th><th>Club</th><th>Manager</th><th>Actions</th></tr></thead>
    <tbody>
        <?php foreach ($all_teams as $team): ?>
            <tr>
                <td><?php echo $team->id; ?></td>
                <td><?php echo htmlspecialchars($team->name); ?></td>
                <td><?php echo htmlspecialchars($team->club_name); ?></td>
                <td><?php echo htmlspecialchars($team->manager_name ?? 'N/A'); ?></td>
                <td class="actions-cell">
                    <a href="edit_team.php?id=<?php echo $team->id; ?>" class="btn-sm btn-edit">Edit</a>
                    <a href="?delete_id=<?php echo $team->id; ?>" class="btn-sm btn-delete" onclick="return confirm('Are you sure you want to delete this team?');">Delete</a>
                </td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

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