<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

require_once '../../../core/bootstrap.php';

// Get user from token
$user = new User();
$user_id = $user->getUserIdFromToken();
if (!$user_id) {
    http_response_code(401);
    echo json_encode(['message' => 'Unauthorized']);
    exit();
}

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

$type = $data->type ?? null;
$id = $data->id ?? null;

if (!$type || !$id) {
    http_response_code(400);
    echo json_encode(['message' => 'Type and ID are required.']);
    exit();
}

$followModel = new Follow();
$is_following = false;
$message = '';

if ($type === 'player') {
    $is_following = $followModel->isFollowingPlayer($user_id, $id);
    if ($is_following) {
        $followModel->unfollowPlayer($user_id, $id);
        $message = 'Player unfollowed.';
    } else {
        $followModel->followPlayer($user_id, $id);
        $message = 'Player followed.';
    }
} elseif ($type === 'club') {
    $is_following = $followModel->isFollowingClub($user_id, $id);
    if ($is_following) {
        $followModel->unfollowClub($user_id, $id);
        $message = 'Club unfollowed.';
    } else {
        $followModel->followClub($user_id, $id);
        $message = 'Club followed.';
    }
}

http_response_code(200);
echo json_encode(['message' => $message, 'is_following' => !$is_following]);
?>