<?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();
}

$user_id_to_add = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);
$team_id = filter_input(INPUT_POST, 'team_id', FILTER_VALIDATE_INT);

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

// Security check: ensure the current manager owns the team they are adding to.
$teamModel = new Team();
$team = $teamModel->getTeamByManagerId($_SESSION['user_id']);
if (!$team || $team->id != $team_id) {
    header('Location: my_team.php?error=auth_failed');
    exit();
}

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

if (!$is_transfer_window_open && $team->roster_status !== 'draft') {
    header('Location: my_team.php?error=window_closed');
    exit();
}

$db = new Database();

try {
    $db->beginTransaction();

    // Check if player record exists
    $db->query("SELECT user_id FROM players WHERE user_id = :user_id");
    $db->bind(':user_id', $user_id_to_add);
    
    if ($db->single()) {
        $db->query("UPDATE players SET team_id = :team_id WHERE user_id = :user_id");
    } else {
        $db->query("INSERT INTO players (user_id, team_id, position, squad_number) VALUES (:user_id, :team_id, 'Midfielder', 0)");
    }
    $db->bind(':user_id', $user_id_to_add);
    $db->bind(':team_id', $team_id);
    $db->execute();

    // Update user role
    $db->query("UPDATE users SET role = 'player' WHERE id = :user_id");
    $db->bind(':user_id', $user_id_to_add);
    $db->execute();

    $db->commit();

    // Notify the user
    $notificationModel = new Notification();
    $notificationModel->create($user_id_to_add, 'team_join', "You have been added to the team '{$team->name}'. Welcome aboard!");

    header('Location: my_team.php?status=player_added');
} catch (Exception $e) {
    $db->rollBack();
    header('Location: my_team.php?error=assign_failed');
}
exit();
?>