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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: teams.php');
    exit();
}

$action = $_POST['action'] ?? '';
$teamModel = new Team();
$clubManagerModel = new ClubManager();

// Verify club ownership
$club = $clubManagerModel->getClubByManagerId($_SESSION['user_id']);
if (!$club) {
    header('Location: teams.php?status=error&error=no_club');
    exit();
}

try {
    if ($action === 'create') {
        $data = [
            'name' => trim($_POST['name']),
            'club_id' => $club->id,
            'manager_id' => !empty($_POST['manager_id']) ? $_POST['manager_id'] : null
        ];

        if ($teamModel->create($data)) {
            header('Location: teams.php?status=success');
        } else {
            header('Location: teams.php?status=error&error=create_failed');
        }

    } elseif ($action === 'update') {
        $data = [
            'id' => $_POST['team_id'],
            'name' => trim($_POST['name']),
            'club_id' => $club->id, // Ensure it stays in the same club
            'manager_id' => !empty($_POST['manager_id']) ? $_POST['manager_id'] : null
        ];

        if ($teamModel->update($data)) {
            header('Location: teams.php?status=success');
        } else {
            header('Location: teams.php?status=error&error=update_failed');
        }

    } elseif ($action === 'delete') {
        $team_id = $_POST['team_id'];
        // Add extra check if needed to ensure team belongs to club before deleting
        if ($teamModel->delete($team_id)) {
            header('Location: teams.php?status=success');
        } else {
            header('Location: teams.php?status=error&error=delete_failed');
        }
    } else {
        header('Location: teams.php');
    }
} catch (Exception $e) {
    header('Location: teams.php?status=error&error=' . urlencode($e->getMessage()));
}
exit();
?>