<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

if (!isset($_SESSION['user_id']) || (int)$_SESSION['user_id'] === 0) {
    http_response_code(403); exit("Non autorisé");
}

$circleId = (int)($_GET['id'] ?? 0);
if (!$circleId) { http_response_code(400); exit("ID invalide"); }

$userId = (int)$_SESSION['user_id'];

// Admin peut changer vers n'importe quel cercle
$user = getConnectedUser($pdo);
if (isAdmin($user)) {
    $_SESSION['circle_id'] = $circleId;
    echo "ok"; exit;
}

// Membre : vérifier appartenance
$stmt = $pdo->prepare("SELECT id FROM circle_members WHERE circle_id = ? AND user_id = ?");
$stmt->execute([$circleId, $userId]);

if ($stmt->fetch()) {
    $_SESSION['circle_id'] = $circleId;
    echo "ok";
} else {
    http_response_code(403);
    echo "Non membre de ce cercle";
}
?>
