<?php
// Set headers for JSON response
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');

// Bootstrap the application
require_once '../../../core/bootstrap.php';

// Protect this action
require_once '../middleware/validate_token.php';

// Instantiate models
$fantasyTeam = new FantasyTeam();
$fantasySquad = new FantasySquad();
$player = new Player();

// Get raw posted data
$data = json_decode(file_get_contents("php://input"));

// --- Validation ---
$errors = [];
if (empty($data->fantasy_team_id) || !is_numeric($data->fantasy_team_id)) {
    $errors[] = 'A numeric fantasy_team_id is required.';
}
if (empty($data->player_ids) || !is_array($data->player_ids)) {
    $errors[] = 'An array of player_ids is required.';
}
if (isset($data->player_ids) && is_array($data->player_ids) && count($data->player_ids) !== 15) {
    $errors[] = 'You must select exactly 15 players for your squad.';
}

if (!empty($errors)) {
    http_response_code(400); // Bad Request
    echo json_encode(['errors' => $errors]);
    exit();
}

// --- Authorization & Further Validation ---

// 1. Find the fantasy team
$team = $fantasyTeam->findById($data->fantasy_team_id);
if (!$team) {
    http_response_code(404); // Not Found
    echo json_encode(['message' => 'Fantasy team not found.']);
    exit();
}

// 2. Check if the logged-in user owns this fantasy team
if ($team->user_id != $authenticated_user_data->id) {
    http_response_code(403); // Forbidden
    echo json_encode(['message' => 'Access Denied. You do not own this fantasy team.']);
    exit();
}

// --- Advanced Squad Validation ---
$squadPlayers = $player->getDetailsForSquad($data->player_ids);

if (count($squadPlayers) !== 15) {
    http_response_code(400);
    echo json_encode(['message' => 'One or more selected player IDs are invalid.']);
    exit();
}

$totalCost = 0;
$positions = ['Goalkeeper' => 0, 'Defender' => 0, 'Midfielder' => 0, 'Forward' => 0];
$clubs = [];

foreach ($squadPlayers as $p) {
    $totalCost += (float)$p->price;
    if (isset($positions[$p->position])) {
        $positions[$p->position]++;
    }
    if (!isset($clubs[$p->club_id])) {
        $clubs[$p->club_id] = 0;
    }
    $clubs[$p->club_id]++;
}

// 1. Check budget
if ($totalCost > 100.0) {
    http_response_code(400);
    echo json_encode(['message' => "Squad cost ($" . number_format($totalCost, 1) . "m) exceeds the $100.0m budget."]);
    exit();
}

// 2. Check position constraints
if ($positions['Goalkeeper'] !== 2 || $positions['Defender'] !== 5 || $positions['Midfielder'] !== 5 || $positions['Forward'] !== 3) {
    http_response_code(400);
    echo json_encode(['message' => 'Invalid squad structure. You must select 2 Goalkeepers, 5 Defenders, 5 Midfielders, and 3 Forwards.']);
    exit();
}

// 3. Check club constraints
foreach ($clubs as $club_id => $count) {
    if ($count > 3) {
        http_response_code(400);
        echo json_encode(['message' => 'You cannot select more than 3 players from the same club.']);
        exit();
    }
}

$currentGameweek = 1; // This would typically come from a global settings table

if ($fantasySquad->setSquad($data->fantasy_team_id, $data->player_ids, $currentGameweek)) {
    http_response_code(200); // OK
    echo json_encode(['message' => 'Squad selected successfully.']);
} else {
    http_response_code(500);
    echo json_encode(['message' => 'An error occurred while selecting the squad.']);
}
?>