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

// --- Instantiate Models ---
$playerModel = new Player();
$teamModel = new Team();

// --- Security Check ---
$manager_id = $_SESSION['user_id'];
$team = $teamModel->getTeamByManagerId($manager_id);
$player = $playerModel->getPlayerDetailsById($player_id);

// Ensure player exists and belongs to the manager's team
if (!$player || !$team || $player->team_id != $team->id) {
    header('Location: my_team.php?error=access_denied');
    exit();
}

// --- Collect and Sanitize Input ---
$updateData = [
    'squad_number' => filter_input(INPUT_POST, 'squad_number', FILTER_VALIDATE_INT),
    'position' => filter_input(INPUT_POST, 'position', FILTER_SANITIZE_STRING),
    'height_cm' => filter_input(INPUT_POST, 'height_cm', FILTER_VALIDATE_INT),
    'weight_kg' => filter_input(INPUT_POST, 'weight_kg', FILTER_VALIDATE_INT),
    'date_of_birth' => filter_input(INPUT_POST, 'date_of_birth', FILTER_SANITIZE_STRING),
    'nationality' => filter_input(INPUT_POST, 'nationality', FILTER_SANITIZE_STRING),
    'preferred_foot' => filter_input(INPUT_POST, 'preferred_foot', FILTER_SANITIZE_STRING)
];

$redirect_to = $_POST['redirect_to'] ?? "edit_player.php?id=$player_id";
$separator = (parse_url($redirect_to, PHP_URL_QUERY) == NULL) ? '?' : '&';

// Attempt update
if ($playerModel->updatePlayerDetails($player_id, $updateData)) {
    header("Location: {$redirect_to}{$separator}status=success");
} else {
    header("Location: {$redirect_to}{$separator}error=update_failed");
}
exit();