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

// Route the request based on the HTTP method
switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        handleGet($club);
        break;
    case 'POST':
        handlePost($club);
        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 clubs in a league.
 * This is a public endpoint.
 */
function handleGet($club) {
    // Get league_id from query string
    $league_id = filter_input(INPUT_GET, 'league_id', FILTER_VALIDATE_INT);

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

    $result = $club->getAllByLeague($league_id);
    http_response_code(200);
    echo json_encode($result);
}

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

    // Check user role
    $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 club.']);
        exit();
    }

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

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

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

    $clubData = [
        'name' => htmlspecialchars(strip_tags($data->name)),
        'stadium' => !empty($data->stadium) ? htmlspecialchars(strip_tags($data->stadium)) : 'N/A',
        'league_id' => $data->league_id
    ];

    $newClubId = $club->create($clubData);

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