<?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 League model
$league = new League();

// Route the request based on the HTTP method
switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        handleGet($league);
        break;
    case 'POST':
        handlePost($league);
        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 leagues.
 * This is a public endpoint.
 */
function handleGet($league) {
    $result = $league->getAll();
    http_response_code(200);
    echo json_encode($result);
}

/**
 * Handles POST request to create a new league.
 * This is a protected endpoint.
 */
function handlePost($league) {
    // Include the JWT validation middleware to protect this action
    require_once '../middleware/validate_token.php';

    // Check if the user has the required role (e.g., admin or league_manager)
    $allowed_roles = ['admin', 'super_admin', 'league_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 league.']);
        exit();
    }

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

    // Basic validation
    if (empty($data->name) || empty($data->country)) {
        http_response_code(400); // Bad Request
        echo json_encode(['message' => 'League name and country are required.']);
        exit();
    }

    $leagueData = [
        'name' => htmlspecialchars(strip_tags($data->name)),
        'country' => htmlspecialchars(strip_tags($data->country)),
        'manager_id' => $authenticated_user_data->id // The creator is assigned as the manager
    ];

    $newLeagueId = $league->create($leagueData);

    if ($newLeagueId) {
        http_response_code(201); // Created
        echo json_encode(['message' => 'League created successfully.', 'league_id' => $newLeagueId]);
    } else {
        http_response_code(500); // Internal Server Error
        echo json_encode(['message' => 'League could not be created.']);
    }
}
?>