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

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

// Sélection du cercle via GET ou session
if (isset($_GET['circle_id'])) {
    $circleId = (int)$_GET['circle_id'];
    $_SESSION['circle_id'] = $circleId;
} else {
    $circleId = (int)($_SESSION['circle_id'] ?? 1);
}

// Table demandes
try { $pdo->exec("CREATE TABLE IF NOT EXISTS circle_join_requests (
    id INT AUTO_INCREMENT PRIMARY KEY,
    circle_id INT NOT NULL,
    user_id INT NOT NULL,
    status ENUM('pending','approved','refused') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    reviewed_at TIMESTAMP NULL,
    UNIQUE KEY uniq_req (circle_id, user_id)
)"); } catch(Exception $e) {}

// Approuver / refuser une demande
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['review_request'])) {
    $reqId     = (int)($_POST['request_id'] ?? 0);
    $reqCircle = (int)($_POST['req_circle_id'] ?? 0);
    $action    = $_POST['review_action'] ?? '';
    if ($reqId && in_array($action, ['approved','refused'])) {
        $req = $pdo->prepare("SELECT * FROM circle_join_requests WHERE id=? AND circle_id=?");
        $req->execute([$reqId, $reqCircle]);
        $reqRow = $req->fetch();
        if ($reqRow) {
            $pdo->prepare("UPDATE circle_join_requests SET status=?, reviewed_at=NOW() WHERE id=?")
                ->execute([$action, $reqId]);
            $cnStmt = $pdo->prepare("SELECT name FROM circles WHERE id=?");
            $cnStmt->execute([$reqCircle]); $cn = $cnStmt->fetchColumn();
            if ($action === 'approved') {
                try { $pdo->prepare("INSERT IGNORE INTO circle_members (circle_id,user_id) VALUES (?,?)")
                    ->execute([$reqCircle, $reqRow['user_id']]); } catch(Exception $e) {}
                addNotification($pdo, $reqRow['user_id'], "✅ Ta demande pour rejoindre "$cn" a été approuvée !", "index.php");
                $msg = "Demande approuvée — membre ajouté.";
            } else {
                addNotification($pdo, $reqRow['user_id'], "❌ Ta demande pour rejoindre "$cn" a été refusée.", "index.php");
                $msg = "Demande refusée.";
            }
        }
    }
}

$isAdminUser  = isAdmin($user);
$isOracleUser = isOracle($user, $circleId, $pdo);
// Permettre aussi au créateur du cercle
$isCreator = false;
try {
    $crs = $pdo->prepare("SELECT creator_id FROM circles WHERE id=?");
    $crs->execute([$circleId]);
    $crow = $crs->fetch();
    $isCreator = ($crow && (int)$crow['creator_id'] === $userId);
} catch(Exception $e) {}
if (!$isAdminUser && !$isOracleUser && !$isCreator) { header("Location: index.php"); exit; }

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

// Charger tous les cercles où l'user est oracle ou admin
try {
    if ($isAdminUser) {
        $allCircles = $pdo->query("SELECT id, name FROM circles ORDER BY name ASC")->fetchAll();
    } else {
        $allCirclesStmt = $pdo->prepare("
            SELECT c.id, c.name FROM circles c
            JOIN circle_members cm ON cm.circle_id = c.id
            WHERE cm.user_id = ? AND (c.oracle_id = ? OR c.creator_id = ?)
            ORDER BY c.name ASC
        ");
        $allCirclesStmt->execute([$userId, $userId, $userId]);
        $allCircles = $allCirclesStmt->fetchAll();
    }
} catch (Exception $e) { $allCircles = []; }

$circleStmt = $pdo->prepare("SELECT * FROM circles WHERE id = ?");
$circleStmt->execute([$circleId]);
$circle = $circleStmt->fetch();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (isset($_POST['remove_member'])) {
        $targetId = (int)$_POST['member_id'];
        if ($targetId !== $userId) {
            $pdo->prepare("DELETE FROM circle_members WHERE circle_id = ? AND user_id = ?")->execute([$circleId, $targetId]);
            addNotification($pdo, $targetId, "Tu as ete retire du cercle " . ($circle['name'] ?? '') . ".", "index.php");
            $msg = "Membre retire.";
        }
    }

    if (isset($_POST['set_oracle']) && $isAdminUser) {
        $targetId = (int)$_POST['member_id'];
        $pdo->prepare("UPDATE circles SET oracle_id = ? WHERE id = ?")->execute([$targetId, $circleId]);
        $msg = "Oracle mis a jour.";
    }

    if (isset($_POST['invite_member'])) {
        $invName = trim($_POST['invite_username'] ?? '');
        $invStmt = $pdo->prepare("SELECT id, username FROM users WHERE username = ?");
        $invStmt->execute([$invName]);
        $invUser = $invStmt->fetch();

        if (!$invUser) {
            $error = "Membre introuvable : " . htmlspecialchars($invName);
        } else {
            $chk = $pdo->prepare("SELECT id FROM circle_members WHERE circle_id = ? AND user_id = ?");
            $chk->execute([$circleId, $invUser['id']]);
            if ($chk->fetch()) {
                $error = htmlspecialchars($invUser['username']) . " est deja dans ce cercle.";
            } else {
                $code    = $circle['invite_code'] ?? '';
                $joinUrl = "gestion_cercle.php?join_circle={$circleId}&code={$code}";
                addNotification($pdo, $invUser['id'],
                    $user['username'] . " t'invite dans le cercle \"" . ($circle['name']??'') . "\". Clique pour rejoindre !",
                    $joinUrl);
                $msg = "Invitation envoyee a " . htmlspecialchars($invUser['username']) . " !";
            }
        }
    }
}

// Rejoindre via lien
if (isset($_GET['join_circle']) && isset($_GET['code'])) {
    $jcId   = (int)$_GET['join_circle'];
    $jcCode = trim($_GET['code']);
    $jcStmt = $pdo->prepare("SELECT id, name, invite_code FROM circles WHERE id = ?");
    $jcStmt->execute([$jcId]);
    $jcCircle = $jcStmt->fetch();
    if ($jcCircle && $jcCircle['invite_code'] === $jcCode) {
        $chk = $pdo->prepare("SELECT id FROM circle_members WHERE circle_id = ? AND user_id = ?");
        $chk->execute([$jcId, $userId]);
        if (!$chk->fetch()) {
            $pdo->prepare("INSERT INTO circle_members (circle_id, user_id) VALUES (?, ?)")->execute([$jcId, $userId]);
            $msg = "Tu as rejoint " . htmlspecialchars($jcCircle['name']) . " !";
        }
    }
}

$membersStmt = $pdo->prepare("
    SELECT u.id, u.username, u.tier, u.last_activity, cm.joined_at,
           CASE WHEN c.oracle_id = u.id THEN 1 ELSE 0 END as is_oracle
    FROM circle_members cm
    JOIN users u ON u.id = cm.user_id
    JOIN circles c ON c.id = cm.circle_id
    WHERE cm.circle_id = ?
    ORDER BY is_oracle DESC, cm.joined_at ASC
");
$membersStmt->execute([$circleId]);
$members = $membersStmt->fetchAll();

$searchInvite  = trim($_GET['search'] ?? '');
$searchResults = [];
if ($searchInvite) {
    $sStmt = $pdo->prepare("SELECT id, username FROM users WHERE username LIKE ? AND id NOT IN (SELECT user_id FROM circle_members WHERE circle_id = ?) LIMIT 8");
    $sStmt->execute(["%$searchInvite%", $circleId]);
    $searchResults = $sStmt->fetchAll();
}

include 'header.php';
?>

<div class="container mt-4 px-4">
    <div class="d-flex align-items-center gap-3 mb-3 flex-wrap">
        <h5 class="text-info fw-bold mb-0">Gestion du cercle</h5>
        <?php if (count($allCircles) > 1): ?>
        <form method="GET" class="d-flex align-items-center gap-2">
            <select name="circle_id" class="form-select form-select-sm bg-dark text-white border-info"
                    style="max-width:220px;" onchange="this.form.submit()">
                <?php foreach ($allCircles as $ac): ?>
                <option value="<?= $ac['id'] ?>" <?= $ac['id'] == $circleId ? 'selected' : '' ?>>
                    <?= htmlspecialchars($ac['name']) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </form>
        <?php endif; ?>
        <span class="text-muted small">— <?= htmlspecialchars($circle['name'] ?? '') ?></span>
    </div>
    <p class="text-muted small mb-3">Gérer les membres, invitations et accès du cercle.</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; ?>

    <div class="row g-3">
        <div class="col-md-7">
            <div class="card bg-dark border-info shadow">
                <div class="card-header py-2">
                    <span class="text-info fw-bold small">Membres (<?= count($members) ?>)</span>
                </div>
                <div class="table-responsive">
                    <table class="table table-dark table-sm small mb-0">
                        <thead><tr><th>Membre</th><th>Grade</th><th>Rejoint</th><th>Role</th><th></th></tr></thead>
                        <tbody>
                        <?php foreach ($members as $m):
                            $tc = match($m['tier']??'free') { 'admin'=>'text-danger','premium_plus'=>'text-warning','premium'=>'text-info',default=>'text-muted' };
                            $online = (time() - strtotime($m['last_activity']??'2000-01-01')) < 300;
                        ?>
                        <tr>
                            <td>
                                <span style="width:7px;height:7px;border-radius:50%;display:inline-block;background:<?= $online?'#28a745':'#555' ?>;margin-right:4px;"></span>
                                <span class="text-white"><?= htmlspecialchars($m['username']) ?></span>
                            </td>
                            <td><span class="<?= $tc ?>"><?= strtoupper($m['tier']??'FREE') ?></span></td>
                            <td class="text-muted" style="font-size:0.65rem;"><?= date('d M Y', strtotime($m['joined_at'])) ?></td>
                            <td>
                                <?php if ($m['is_oracle']): ?>
                                    <span class="badge bg-warning text-dark" style="font-size:0.6rem;">Oracle</span>
                                <?php else: ?>
                                    <span class="text-muted" style="font-size:0.65rem;">Membre</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-end">
                                <div class="d-flex gap-1 justify-content-end">
                                    <?php if ($isAdminUser && !$m['is_oracle']): ?>
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="member_id" value="<?= $m['id'] ?>">
                                        <button type="submit" name="set_oracle" class="btn btn-xs btn-outline-warning py-0" onclick="return confirm('Nommer Oracle ?')">Oracle</button>
                                    </form>
                                    <?php endif; ?>
                                    <?php if ($m['id'] !== $userId): ?>
                                    <form method="POST" class="d-inline">
                                        <input type="hidden" name="member_id" value="<?= $m['id'] ?>">
                                        <button type="submit" name="remove_member" class="btn btn-xs btn-outline-danger py-0" onclick="return confirm('Retirer ce membre ?')">Retirer</button>
                                    </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-md-5">
            <div class="card bg-dark border-success shadow mb-3">
                <div class="card-header py-2 text-success fw-bold small">Inviter un membre</div>
                <div class="card-body">
                    <form method="GET" class="d-flex gap-2 mb-2">
                        <input type="text" name="search" class="form-control form-control-sm bg-dark text-white border-secondary"
                               placeholder="Chercher..." value="<?= htmlspecialchars($searchInvite) ?>">
                        <button class="btn btn-sm btn-outline-info flex-shrink-0">OK</button>
                    </form>
                    <?php foreach ($searchResults as $sr): ?>
                    <div class="d-flex justify-content-between align-items-center py-1 border-bottom border-secondary">
                        <span class="text-white" style="font-size:0.78rem;"><?= htmlspecialchars($sr['username']) ?></span>
                        <form method="POST" class="d-inline">
                            <input type="hidden" name="invite_username" value="<?= htmlspecialchars($sr['username']) ?>">
                            <button type="submit" name="invite_member" class="btn btn-xs btn-outline-success py-0">Inviter</button>
                        </form>
                    </div>
                    <?php endforeach; ?>
                    <form method="POST" class="mt-2">
                        <div class="input-group input-group-sm">
                            <input type="text" name="invite_username" class="form-control bg-dark text-white border-secondary" placeholder="Nom exact..." required>
                            <button type="submit" name="invite_member" class="btn btn-success">Inviter</button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="card bg-dark border-secondary shadow">
                <div class="card-header py-2 text-info fw-bold small">Code d'invitation</div>
                <div class="card-body py-2">
                    <div class="input-group input-group-sm">
                        <input type="text" id="gcCode" class="form-control text-info fw-bold text-center bg-dark border-secondary"
                               value="<?= htmlspecialchars($circle['invite_code'] ?? '') ?>" readonly>
                        <button class="btn btn-outline-info"
                                onclick="navigator.clipboard.writeText(document.getElementById('gcCode').value).then(()=>{this.innerText='Copie !';setTimeout(()=>this.innerText='Copier',2000)})">Copier</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Charger les demandes en attente pour ce cercle
$pendingRequests = [];
try {
    $prStmt = $pdo->prepare("
        SELECT cjr.*, u.username, u.points
        FROM circle_join_requests cjr
        JOIN users u ON u.id = cjr.user_id
        WHERE cjr.circle_id = ? AND cjr.status = 'pending'
        ORDER BY cjr.created_at ASC
    ");
    $prStmt->execute([$circleId]);
    $pendingRequests = $prStmt->fetchAll();
} catch(Exception $e) {}
?>

<?php if (!empty($pendingRequests)): ?>
<div class="container-fluid mb-4" style="max-width:900px;">
    <div class="card bg-dark border-warning shadow">
        <div class="card-header py-2 fw-bold small" style="background:#1a1200;color:#ffc107;letter-spacing:1px;">
            <i class="fa-solid fa-user-clock me-2"></i>
            DEMANDES D'ADHÉSION EN ATTENTE
            <span class="badge bg-warning text-dark ms-2"><?= count($pendingRequests) ?></span>
        </div>
        <div class="card-body p-0">
            <?php foreach ($pendingRequests as $pr): ?>
            <div class="d-flex align-items-center justify-content-between p-3 border-bottom border-secondary">
                <div>
                    <span class="fw-bold text-info" style="font-size:0.8rem;"><?= htmlspecialchars($pr['username']) ?></span>
                    <span class="text-muted ms-2" style="font-size:0.65rem;"><?= (int)$pr['points'] ?> pts</span>
                    <div class="text-muted" style="font-size:0.6rem;">Demande reçue le <?= date('d M Y H:i', strtotime($pr['created_at'])) ?></div>
                </div>
                <div class="d-flex gap-2">
                    <form method="POST">
                        <input type="hidden" name="request_id" value="<?= $pr['id'] ?>">
                        <input type="hidden" name="req_circle_id" value="<?= $pr['circle_id'] ?>">
                        <input type="hidden" name="review_action" value="approved">
                        <button type="submit" name="review_request" class="btn btn-success btn-sm fw-bold" style="font-size:0.65rem;">
                            ✓ Approuver
                        </button>
                    </form>
                    <form method="POST">
                        <input type="hidden" name="request_id" value="<?= $pr['id'] ?>">
                        <input type="hidden" name="req_circle_id" value="<?= $pr['circle_id'] ?>">
                        <input type="hidden" name="review_action" value="refused">
                        <button type="submit" name="review_request" class="btn btn-outline-danger btn-sm" style="font-size:0.65rem;"
                                onclick="return confirm('Refuser cette demande ?')">
                            ✕ Refuser
                        </button>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>
<?php endif; ?>

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