<?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';

// Check user role
$allowed_roles = ['team_manager', 'admin', 'super_admin'];
if (!in_array($authenticated_user_data->role, $allowed_roles)) {
    http_response_code(403); // Forbidden
    echo json_encode(['message' => 'Access Denied. Only Team Managers or Admins can submit lineups.']);
    exit();
}

// Instantiate models
$lineup = new Lineup();
$fixture = new Fixture();
$team = new Team();

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

// Validation
$errors = [];
if (empty($data->fixture_id) || !is_numeric($data->fixture_id)) $errors[] = 'A numeric fixture_id is required.';
if (empty($data->team_id) || !is_numeric($data->team_id)) $errors[] = 'A numeric team_id is required.';
if (empty($data->players) || !is_array($data->players)) $errors[] = 'A "players" array is required.';

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

// --- Further Authorization & Validation ---
// Check if fixture exists
$targetFixture = $fixture->findById($data->fixture_id);
if (!$targetFixture) {
    http_response_code(404);
    echo json_encode(['message' => 'Fixture not found.']);
    exit();
}

// Check if the team is part of the fixture
if ($data->team_id != $targetFixture->home_team_id && $data->team_id != $targetFixture->away_team_id) {
    http_response_code(403);
    echo json_encode(['message' => 'This team is not part of the specified fixture.']);
    exit();
}

// Check if the authenticated user is the manager of the team they are submitting for (unless they are an admin)
$targetTeam = $team->findById($data->team_id);
if ($authenticated_user_data->role === 'team_manager' && $authenticated_user_data->id != $targetTeam->manager_id) {
    http_response_code(403);
    echo json_encode(['message' => 'Access Denied. You are not the manager of this team.']);
    exit();
}

// TODO: Add validation to ensure each player in $data->players belongs to the team.

$lineupData = [
    'formation' => $data->formation ?? '4-4-2' // Default formation
];


if ($lineup->submit($data->fixture_id, $data->team_id, $data->players, $lineupData)) {
    http_response_code(201); // Created
    echo json_encode(['message' => 'Lineup submitted successfully.']);
} else {
    http_response_code(500);
    echo json_encode(['message' => 'An error occurred while submitting the lineup.']);
}
?>