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

requireLogin();
$user   = getConnectedUser($pdo);
$userId = (int)$user['id'];

$msg = ''; $error = '';

// Limite selon forfait
$tierLimits = ['free' => 1, 'premium' => 5, 'premium_plus' => 20, 'admin' => 999];
$maxCircles = $tierLimits[$user['tier'] ?? 'free'] ?? 1;
if (isAdmin($user)) $maxCircles = 999;

// Compter les cercles dont l'user est créateur
$myCount = (int)$pdo->prepare("SELECT COUNT(*) FROM circles WHERE creator_id = ?")->execute([$userId])
    ? $pdo->query("SELECT COUNT(*) FROM circles WHERE creator_id = {$userId}")->fetchColumn()
    : 0;

// Créer un cercle
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_circle'])) {
    $name = trim(htmlspecialchars($_POST['circle_name'] ?? ''));

    if (empty($name)) {
        $error = "Le nom du cercle est requis.";
    } elseif ($myCount >= $maxCircles) {
        $error = "Tu as atteint la limite de cercles pour ton forfait ({$maxCircles} max). Passe à un forfait supérieur !";
    } else {
        // Générer un code unique
        do {
            $code = strtoupper(substr(md5(uniqid(rand(), true)), 0, 8));
            $chk  = $pdo->prepare("SELECT id FROM circles WHERE invite_code = ?");
            $chk->execute([$code]);
        } while ($chk->fetch());

        try {
            // v1.7 — colonnes groupe privé
            try { $pdo->exec("ALTER TABLE circles ADD COLUMN IF NOT EXISTS group_type ENUM('famille','ecole','entreprise') DEFAULT NULL"); } catch(Exception $e){}
            try { $pdo->exec("ALTER TABLE circles ADD COLUMN IF NOT EXISTS is_isolated TINYINT(1) DEFAULT 0"); } catch(Exception $e){}

            $groupType  = in_array($_POST['group_type'] ?? '', ['famille','ecole','entreprise']) ? $_POST['group_type'] : null;
            $isIsolated = ($groupType && isset($_POST['is_isolated'])) ? 1 : 0;

            $pdo->prepare("INSERT INTO circles (name, creator_id, invite_code, oracle_id, status, group_type, is_isolated) VALUES (?, ?, ?, ?, 'active', ?, ?)")
                ->execute([$name, $userId, $code, $userId, $groupType, $isIsolated]);
            $newId = $pdo->lastInsertId();

            // Ajouter le créateur comme membre
            $pdo->prepare("INSERT INTO circle_members (circle_id, user_id) VALUES (?, ?)")->execute([$newId, $userId]);

            // Changer le cercle actif
            $_SESSION['circle_id'] = $newId;

            $msg = "Cercle \"{$name}\" créé ! Code : {$code}";
            $myCount++;
        } catch (Exception $e) { $error = "Erreur : " . $e->getMessage(); }
    }
}

// Mes cercles
try {
    $myCircles = $pdo->prepare("
        SELECT c.*, cm.joined_at,
               (SELECT COUNT(*) FROM circle_members WHERE circle_id = c.id) as member_count,
               CASE WHEN c.creator_id = ? THEN 1 ELSE 0 END as is_creator
        FROM circles c
        JOIN circle_members cm ON cm.circle_id = c.id AND cm.user_id = ?
        ORDER BY is_creator DESC, c.name ASC
    ");
    $myCircles->execute([$userId, $userId]);
    $circles = $myCircles->fetchAll();
} catch (Exception $e) { $circles = []; }

include 'header.php';
?>

<div class="container mt-4 px-4" style="max-width:700px;">
    <h5 class="text-info fw-bold mb-1">Mes cercles</h5>
    <p class="text-muted small mb-3">
        Forfait <span class="text-warning"><?= strtoupper($user['tier']??'FREE') ?></span> —
        <?= $myCount ?>/<?= $maxCircles === 999 ? 'illimité' : $maxCircles ?> cercles créés
    </p>

    <?php if ($msg):   ?><div class="alert alert-success small py-2"><?= $msg ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger  small py-2"><?= $error ?></div><?php endif; ?>

    <!-- CRÉER UN CERCLE -->
    <?php if ($myCount < $maxCircles): ?>
    <div class="card bg-dark border-success shadow mb-4">
        <div class="card-header py-2 text-success fw-bold small">Créer un nouveau cercle</div>
        <div class="card-body">
            <form method="POST">
                <div class="d-flex gap-2 mb-2">
                    <input type="text" name="circle_name" class="form-control bg-dark text-white border-secondary"
                           placeholder="Nom du cercle..." maxlength="50" required>
                    <button type="submit" name="create_circle" class="btn btn-success fw-bold flex-shrink-0">Créer</button>
                </div>
                <!-- v1.7 — Type de groupe privé -->
                <div class="d-flex gap-2 align-items-center flex-wrap">
                    <select name="group_type" id="groupTypeSelect" onchange="toggleIsolatedOption(this.value)"
                            class="form-select form-select-sm bg-dark text-white border-secondary" style="max-width:200px;font-size:0.68rem;">
                        <option value="">Cercle standard</option>
                        <option value="famille">👨‍👩‍👧 Famille</option>
                        <option value="ecole">🏫 École / Classe</option>
                        <option value="entreprise">🏢 Entreprise / Équipe</option>
                    </select>
                    <div id="isolatedOption" style="display:none;">
                        <div class="form-check form-check-sm mb-0">
                            <input type="checkbox" name="is_isolated" id="isIsolatedCheck" class="form-check-input" value="1" checked>
                            <label class="form-check-label text-warning small" for="isIsolatedCheck" style="font-size:0.65rem;">
                                🔒 Groupe isolé — membres voient seulement ce groupe
                            </label>
                        </div>
                    </div>
                </div>
                <div id="groupTypeInfo" style="display:none;margin-top:6px;font-size:0.6rem;color:#a78bfa;background:rgba(167,139,250,0.08);border:1px solid rgba(167,139,250,0.2);border-radius:5px;padding:6px 10px;">
                    En mode groupe privé, les membres voient seulement les engagements de leur groupe. Les récompenses sont des textes libres (ex: 1h de Xbox) plutôt que des points.
                </div>
            </form>
        </div>
    </div>
<script>
function toggleIsolatedOption(val) {
    document.getElementById('isolatedOption').style.display = val ? 'block' : 'none';
    document.getElementById('groupTypeInfo').style.display = val ? 'block' : 'none';
}
</script>
    <?php else: ?>
    <div class="alert alert-warning small py-2 mb-4">
        Limite atteinte (<?= $maxCircles ?> cercles). <a href="upgrade.php" class="text-warning fw-bold">Passer à un forfait supérieur</a>
    </div>
    <?php endif; ?>

    <!-- LISTE DES CERCLES -->
    <div class="card bg-dark border-secondary shadow">
        <div class="card-header py-2 text-info fw-bold small">Mes cercles (<?= count($circles) ?>)</div>
        <div class="table-responsive">
            <table class="table table-dark table-sm small mb-0">
                <thead><tr><th>Nom</th><th class="text-center">Membres</th><th>Rôle</th><th>Code</th><th></th></tr></thead>
                <tbody>
                <?php foreach ($circles as $c):
                    $isActive = (int)($_SESSION['circle_id'] ?? 1) === (int)$c['id'];
                ?>
                <tr <?= $isActive ? "style='background:#0a1a0a;'" : '' ?>>
                    <td>
                        <?php if ($isActive): ?>
                            <span class="badge bg-success me-1" style="font-size:0.5rem;">ACTIF</span>
                        <?php endif; ?>
                        <span class="text-white"><?= htmlspecialchars($c['name']) ?></span>
                    </td>
                    <td class="text-center text-info"><?= $c['member_count'] ?></td>
                    <td>
                        <?php if ($c['is_creator']): ?>
                            <span class="badge bg-warning text-dark" style="font-size:0.55rem;">Créateur</span>
                        <?php else: ?>
                            <span class="text-muted" style="font-size:0.65rem;">Membre</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if ($c['is_creator'] || isAdmin($user)): ?>
                            <code class="text-info" style="font-size:0.65rem;"><?= htmlspecialchars($c['invite_code']) ?></code>
                        <?php else: ?>
                            <span class="text-muted">—</span>
                        <?php endif; ?>
                    </td>
                    <td class="text-end">
                        <?php if (!$isActive): ?>
                        <a href="set_circle.php?id=<?= $c['id'] ?>" class="btn btn-xs btn-outline-info py-0">Activer</a>
                        <?php endif; ?>
                        <?php if ($c['is_creator'] || isAdmin($user)): ?>
                        <a href="gestion_cercle.php" onclick="<?= $isActive ? '' : "fetch('set_circle.php?id={$c['id']}').then(()=>window.location='gestion_cercle.php');return false;" ?>"
                           class="btn btn-xs btn-outline-secondary py-0 ms-1">Gérer</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($circles)): ?>
                <tr><td colspan="5" class="text-center text-muted py-3">Aucun cercle. Crée-en un !</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
