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

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

// Instantiate Team model
$team = new Team();

// Route the request based on the HTTP method
switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        handleGet($team);
        break;
    case 'POST':
        handlePost($team);
        break;
    default:
        // Method Not Allowed
        header('Access-Control-Allow-Methods: GET, POST');
        http_response_code(405);
        echo json_encode(['message' => 'Method Not Allowed']);
        break;
}

/**
 * Handles GET request to fetch all teams in a club.
 * This is a public endpoint.
 */
function handleGet($team) {
    // Get club_id from query string
    $club_id = filter_input(INPUT_GET, 'club_id', FILTER_VALIDATE_INT);

    if (!$club_id) {
        http_response_code(400); // Bad Request
        echo json_encode(['message' => 'A valid integer club_id is required.']);
        exit();
    }

    $result = $team->getAllByClub($club_id);
    http_response_code(200);
    echo json_encode($result);
}

/**
 * Handles POST request to create a new team.
 * This is a protected endpoint for club managers and admins.
 */
function handlePost($team) {
    // Protect this action
    require_once '../middleware/validate_token.php';

    // Check user role
    $allowed_roles = ['admin', 'super_admin', 'club_manager'];
    if (!in_array($authenticated_user_data->role, $allowed_roles)) {
        http_response_code(403); // Forbidden
        echo json_encode(['message' => 'Access Denied. You do not have permission to create a team.']);
        exit();
    }

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

    // Validation
    if (empty($data->name) || empty($data->club_id) || !is_numeric($data->club_id)) {
        http_response_code(400);
        echo json_encode(['message' => 'Team name and a numeric club_id are required.']);
        exit();
    }

    // Check if team name already exists for this club
    if ($team->findByNameAndClub($data->name, $data->club_id)) {
        http_response_code(409); // Conflict
        echo json_encode(['message' => 'A team with this name already exists in this club.']);
        exit();
    }

    $teamData = [
        'name' => htmlspecialchars(strip_tags($data->name)),
        'club_id' => $data->club_id
    ];

    $newTeamId = $team->create($teamData);

    if ($newTeamId) {
        http_response_code(201); // Created
        echo json_encode(['message' => 'Team created successfully.', 'team_id' => $newTeamId]);
    } else {
        http_response_code(500);
        echo json_encode(['message' => 'Team could not be created.']);
    }
}
?>