<?php
// This file will act as our API endpoint to get details for a single club.

// Set the header to output JSON
header('Content-Type: application/json');
// Allow requests from any origin (useful for development, can be restricted in production)
header('Access-Control-Allow-Origin: *');

// Bootstrap the application to get access to models and the database.
require_once '../core/bootstrap.php';

try {
    // 1. Get the Club ID from the request
    $club_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

    // 2. Validate the ID
    if (!$club_id) {
        // If no ID is provided, return a 400 Bad Request error
        http_response_code(400);
        echo json_encode(['error' => 'A valid club ID is required.']);
        exit;
    }

    // 3. Instantiate the necessary models
    $clubModel = new Club();
    $userModel = new User();

    // Check for a logged-in user to see if they are following the club
    $current_user_id = $userModel->getUserIdFromToken();

    // 4. Fetch the club details from the database
    $clubDetails = $clubModel->getClubDetails($club_id, $current_user_id);

    // 5. Check if the club was found
    if ($clubDetails) {
        // If found, return a 200 OK status and the club data
        http_response_code(200);
        echo json_encode($clubDetails);
    } else {
        // If not found, return a 404 Not Found error
        http_response_code(404);
        echo json_encode(['error' => 'Club not found.']);
    }

} catch (Exception $e) {
    // Handle any unexpected errors (e.g., database connection issues)
    http_response_code(500);
    echo json_encode([
        'error' => 'An internal server error occurred.',
        'message' => $e->getMessage() // Optional: for debugging
    ]);
}