<?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 = ['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 assign club managers.']);
    exit();
}

// Instantiate models
$clubManager = new ClubManager();
$user = new User();
$club = new Club();
$db = new Database(); // For transaction management

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

// Validation
$errors = [];
if (empty($data->user_id) || !is_numeric($data->user_id)) $errors[] = 'A numeric user_id is required.';
if (empty($data->club_id) || !is_numeric($data->club_id)) $errors[] = 'A numeric club_id is required.';
if (empty($data->role_title)) $errors[] = 'A role_title (e.g., "President") is required.';

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

// --- Further Validation ---
if (!$user->findById($data->user_id)) {
    http_response_code(404);
    echo json_encode(['message' => 'User not found.']);
    exit();
}
if (!$club->findById($data->club_id)) {
    http_response_code(404);
    echo json_encode(['message' => 'Club not found.']);
    exit();
}

// --- Perform assignment within a transaction ---
try {
    $db->beginTransaction();

    // 1. Update the user's role
    $user->updateRole($data->user_id, 'club_manager');

    // 2. Create the assignment in the junction table
    $clubManager->assign($data->user_id, $data->club_id, $data->role_title);

    // If both succeed, commit the changes
    $db->commit();

    http_response_code(200); // OK
    echo json_encode(['message' => 'Club manager assigned successfully.']);

} catch (Exception $e) {
    // If anything fails, roll back all changes
    $db->rollBack();
    http_response_code(500);
    echo json_encode(['message' => 'An error occurred during the assignment process.', 'error' => $e->getMessage()]);
}
?>

