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

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

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

$player_id = filter_input(INPUT_POST, 'player_id', FILTER_VALIDATE_INT);

if (!$player_id) {
    header('Location: my_team.php?error=invalid_data');
    exit();
}

$teamModel = new Team();
$team = $teamModel->getTeamByManagerId($_SESSION['user_id']);

if (!$team) {
    header('Location: my_team.php?error=no_team');
    exit();
}

// --- Check Transfer Window / Roster Status ---
$settingModel = new Setting();
$settings = $settingModel->getAll();
$today = date('Y-m-d');
$registration_period_open = !empty($settings['registration_period_open']);
$is_transfer_window_open = ($today >= ($settings['transfer_window_start'] ?? '') && $today <= ($settings['transfer_window_end'] ?? ''));

if (!$is_transfer_window_open && !$registration_period_open) {
    header('Location: my_team.php?error=action_not_allowed');
    exit();
}

$playerModel = new Player();
// Verify player belongs to this team
$player = $playerModel->getPlayerDetailsById($player_id);
if (!$player || $player->team_id != $team->id) {
    header('Location: my_team.php?error=auth_failed');
    exit();
}

// Remove player (set team_id to NULL, role to 'user')
$playerModel->removePlayerFromTeam($player_id);

// Notify all club managers if released during transfer window
if ($is_transfer_window_open) {
    $userModel = new User();
    $notificationModel = new Notification();
    $clubManagers = $userModel->getAllByRole('club_manager');
    foreach ($clubManagers as $manager) {
        $notificationModel->create($manager->id, 'player_released', "Player {$player->first_name} {$player->last_name} has been released by {$team->team_name} and is now a free agent.");
    }
}

header('Location: my_team.php?status=player_removed');
exit();
?>