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

requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

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

// ── Modification du tier d'un membre ─────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_tier'])) {
    $targetId  = (int)$_POST['target_id'];
    $newTier   = in_array($_POST['tier'], ['free','premium','premium_plus']) ? $_POST['tier'] : 'free';
    $newAdmin  = isset($_POST['is_admin']) ? 1 : 0;
    $newRenewal = !empty($_POST['renewal_date']) ? $_POST['renewal_date'] : null;
    try {
        $pdo->prepare("UPDATE users SET tier=?, admin=?, renewal_date=? WHERE id=?")
            ->execute([$newTier, $newAdmin, $newRenewal, $targetId]);
        $msg = "Droits mis à jour pour le membre #{$targetId}.";
        addNotification($pdo, $targetId, "Vos droits d'accès ont été mis à jour par un administrateur.", "index.php");
    } catch (Exception $e) {
        $error = "Erreur: " . $e->getMessage();
    }
}

// ── Chargement des membres ────────────────────────────────────
$search = trim($_GET['q'] ?? '');
$filterTier = $_GET['tier'] ?? '';
$sql = "SELECT id, username, email, tier, admin, wallet_points, points, renewal_date, last_activity
        FROM users WHERE 1=1";
$params = [];
if ($search) {
    $sql .= " AND (username LIKE ? OR email LIKE ?)";
    $params[] = "%$search%"; $params[] = "%$search%";
}
if ($filterTier) {
    $sql .= " AND tier = ?";
    $params[] = $filterTier;
}
$sql .= " ORDER BY admin DESC, FIELD(tier,'premium_plus','premium','free'), username ASC";
try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $members = $stmt->fetchAll();
} catch (Exception $e) { $members = []; }

// ── Droits par fonctionnalité (matrice statique + dynamique) ──
// Format: [label, description, feat_key, free, premium, premium_plus, admin]
// feat_key = clé unique sauvegardée dans admin_config comme droit_<feat_key>_<tier>
$droitsMatrix = [
    ['TABLEAU DE BORD', '', null, null, null, null, null],
    ['Dashboard standard',       'Accès au dashboard, gages, chat',                          'dashboard',        true,  true,  true,  true],
    ['Pastilles de navigation',  'Sections Classements/Chat/Événements/Médias/Amis',         'pastilles',        false, true,  true,  true],
    ['Barre profil compacte',    'Infos profil compactes au-dessus des gages',               'profil_bar',       true,  true,  true,  true],

    ['GAGES', '', null, null, null, null, null],
    ['Créer un gage',            'Lancer un défi à un membre',                               'create_bet',       true,  true,  true,  true],
    ['Gage global (ouvert)',     'Gage visible à tout le site',                              'global_bet',       true,  true,  true,  true],
    ['Mise de jetons sur gage',  'Miser des jetons sur un gage',                             'wallet_bet',       false, true,  true,  true],
    ['Modifier/supprimer gage',  'Propriétaire ou admin seulement',                          'edit_bet',         true,  true,  true,  true],
    ['Voter OUI/NON sur gage',   'Votes sur les gages publics',                              'vote_bet',         true,  true,  true,  true],

    ['CHAT / MUR', '', null, null, null, null, null],
    ['Envoyer des messages',     'Chat dans le cercle actif',                                'chat_send',        true,  true,  true,  true],
    ['Icônes gratuites chat',    'Emojis de base disponibles pour tous',                     'chat_icons_free',  true,  true,  true,  true],
    ['Icônes Premium chat',      'Emojis réservés Premium',                                  'chat_icons_prem',  false, true,  true,  true],
    ['Icônes Premium+ chat',     'Emojis exclusifs Premium+',                                'chat_icons_pp',    false, false, true,  true],
    ['Couleur de texte chat',    'Texte coloré dans le chat',                                'chat_color',       false, false, true,  true],
    ['Photo dans le chat',       'Joindre une photo au message',                             'chat_photo',       false, false, true,  true],

    ['MÉDIAS & PROFIL', '', null, null, null, null, null],
    ['Uploader photo preuve',    'Photo pour valider un gage',                               'upload_proof',     true,  true,  true,  true],
    ['Galerie médias',           'Voir toutes les photos du cercle',                         'gallery',          true,  true,  true,  true],
    ['Personnaliser profil',     'Image de fond, bio, surnom',                               'profile_custom',   true,  true,  true,  true],
    ['Thème visuel perso',       'Choisir un thème parmi ceux de l\'admin',                 'custom_theme',     false, false, true,  true],

    ['SOCIAL', '', null, null, null, null, null],
    ['Messagerie privée',        'MP entre membres',                                         'private_msg',      true,  true,  true,  true],
    ['Système d\'amis',          'Ajouter, accepter, favoris',                               'friends',          true,  true,  true,  true],
    ['Évaluer un membre',        'Note 1-5 étoiles',                                         'rate_user',        true,  true,  true,  true],

    ['JETONS (WALLET)', '', null, null, null, null, null],
    ['Accès au wallet',          'Voir et utiliser ses jetons',                              'wallet_access',    true,  true,  true,  true],
    ['Bonus quotidien jetons',   'Jetons offerts à la connexion',                            'wallet_daily',     true,  true,  true,  true],
    ['Roulement quotidien',      'Spin roue pour bonus aléatoire',                           'wallet_roll',      true,  true,  true,  true],
    ['Boutique jetons',          'Acheter des jetons',                                       'wallet_shop',      true,  true,  true,  true],

    ['CERCLES', '', null, null, null, null, null],
    ['Rejoindre un cercle',      'Via code d\'invitation',                                   'join_circle',      true,  true,  true,  true],
    ['Créer un cercle',          'Créer son propre cercle',                                  'create_circle',    true,  true,  true,  true],
    ['Gérer son cercle',         'Créateur ou Oracle du cercle',                             'manage_circle',    true,  true,  true,  true],
    ['Oracle — voter',           'Voter pour l\'Oracle',                                     'oracle_vote',      true,  true,  true,  true],
    ['Oracle — juger',           'Arbitrer les gages en tant qu\'Oracle',                    'oracle_judge',     false, false, false, true],
    ['Oracle Mailing',           'Envoyer des courriels via SMTP cercle',                    'oracle_mail',      false, false, false, true],
    ['Mur du cercle',            'Chat dédié au cercle',                                     'circle_wall',      true,  true,  true,  true],

    ['ADMIN', '', null, null, null, null, null],
    ['Panneau d\'administration', 'Accès complet au panneau admin',                          'admin_panel',      false, false, false, true],
    ['Gestion des membres',     'Modifier tier, points, wallet',                  false, false, false, true],
    ['Gestion des gages',       'Voir/supprimer tous les gages',                  false, false, false, true],
    ['Gestion des signalements','Traiter les reports',                            false, false, false, true],
    ['Configuration système',   'Modifier les clés admin_config',                 false, false, false, true],
    ['Apparence du site',       'Thème, couleurs, polices',                       false, false, false, true],
    ['Marquise défilante',      'Ajouter/modifier les messages défilants',        false, false, false, true],
    ['Admin boutique',          'is_admin_store — gérer les produits',            false, false, false, true],
];

include 'header.php';
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

<style>
.rights-table th  { font-size:0.62rem; letter-spacing:1px; text-transform:uppercase; padding:8px 10px; white-space:nowrap; }
.rights-table td  { font-size:0.72rem; padding:6px 10px; vertical-align:middle; }
.rights-table tr.section-row td { background:#0d0d1a; color:#0dcaf0; font-size:0.6rem; font-weight:700; letter-spacing:2px; padding:5px 10px; border-top:2px solid #1a1a3a; }
.tier-badge       { font-size:0.55rem; padding:2px 7px; border-radius:10px; font-weight:700; }
.check-yes        { color:#28a745; font-size:0.9rem; }
.check-no         { color:#777; font-size:0.9rem; }
.check-only       { color:#ffc107; font-size:0.75rem; font-weight:bold; }
.member-row:hover { background:#0d0d1a !important; cursor:pointer; }
.tier-select      { background:#111; border:1px solid #333; color:#fff; border-radius:4px; font-size:0.68rem; padding:2px 6px; }
.edit-panel       { display:none; background:#050520; border:1px solid #0dcaf0; border-radius:8px; padding:16px; margin-top:8px; }
</style>

<div class="container-fluid mt-3 mb-5">

    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="admin.php" class="btn btn-outline-secondary btn-sm">
            <i class="fa-solid fa-arrow-left fa-xs me-1"></i>Admin
        </a>
        <h4 class="oracle-text text-info mb-0" style="letter-spacing:2px;">
            <i class="fa-solid fa-shield-halved me-2"></i>GESTION DES DROITS
        </h4>
    </div>

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

    <div class="row g-4">

        <!-- ── COL GAUCHE : Matrice des droits ───────────────── -->
        <div class="col-lg-7">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header d-flex justify-content-between align-items-center py-2" style="background:#050520;border-bottom:1px solid #1a1a3a;">
                    <span class="oracle-text text-info fw-bold" style="font-size:0.78rem; letter-spacing:1px;">
                        <i class="fa-solid fa-table-list me-2"></i>MATRICE DES DROITS
                    </span>
                    <div class="d-flex gap-2">
                        <span class="tier-badge" style="background:rgba(108,117,125,0.2);border:1px solid #555;color:#aaa;">FREE</span>
                        <span class="tier-badge badge-gold">PREMIUM</span>
                        <span class="tier-badge badge-silver">PREMIUM+</span>
                        <span class="tier-badge" style="background:rgba(220,53,69,0.2);border:1px solid #dc3545;color:#dc3545;">ADMIN</span>
                    </div>
                </div>
                <div class="card-body p-0" style="overflow-x:auto;">
                    <table class="table table-dark table-sm mb-0 rights-table">
                        <thead>
                            <tr style="background:#0a0a1a;">
                                <th style="width:35%;">Fonctionnalité</th>
                                <th style="width:25%; color:#888;">Description</th>
                                <th class="text-center" style="color:#aaa;">Free</th>
                                <th class="text-center" style="color:#d4af37;">Prem.</th>
                                <th class="text-center" style="color:#a9a9a9;">Prem+</th>
                                <th class="text-center" style="color:#dc3545;">Admin</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($droitsMatrix as $row):
                            // Ligne de section (séparateur)
                            if ($row[1] === '' && $row[2] === null):
                        ?>
                            <tr class="section-row">
                                <td colspan="6"><i class="fa-solid fa-chevron-right fa-xs me-1"></i><?= $row[0] ?></td>
                            </tr>
                        <?php else:
                            [$label, $desc, $featKey, $free, $prem, $premplus, $admin] = $row;
                            // Utiliser feat_key comme clé si disponible, sinon slug du label
                            $rowKey = $featKey ?? strtolower(preg_replace('/[^a-z0-9]/i','_',$label));
                            // Lire la valeur depuis admin_config si elle a été modifiée
                            foreach (['free','premium','premplus','admin'] as $ti => $tk) {
                                $cfgKey = 'droit_'.$rowKey.'_'.$tk;
                                try {
                                    $cfgVal = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key=?");
                                    $cfgVal->execute([$cfgKey]);
                                    $v = $cfgVal->fetchColumn();
                                    if ($v !== false) {
                                        if ($tk==='free')     $free     = (bool)$v;
                                        if ($tk==='premium')  $prem     = (bool)$v;
                                        if ($tk==='premplus') $premplus = (bool)$v;
                                        if ($tk==='admin')    $admin    = (bool)$v;
                                    }
                                } catch(Exception $e) {}
                            }
                            $icon = fn($v, $tier, $rk) =>
                                '<i class="fa-'.($v?'solid fa-circle-check check-yes':'regular fa-circle check-no').'" '
                                .'data-row="'.$rk.'" data-tier="'.$tier.'" data-val="'.($v?1:0).'" '
                                .'title="Double-cliquer pour modifier" '
                                .'style="cursor:pointer;transition:transform 0.1s;" '
                                .'ondblclick="drToggle(this)"></i>';
                        ?>
                            <tr style="border-bottom:1px solid #111;" id="dr-row-<?= $rowKey ?>">
                                <td class="fw-bold" style="color:#ddd;"><?= htmlspecialchars($label) ?></td>
                                <td style="color:#888; font-size:0.65rem;"><?= htmlspecialchars($desc) ?></td>
                                <td class="text-center"><?= $icon($free,    'free',     $rowKey) ?></td>
                                <td class="text-center"><?= $icon($prem,    'premium',  $rowKey) ?></td>
                                <td class="text-center"><?= $icon($premplus,'premplus', $rowKey) ?></td>
                                <td class="text-center"><?= $icon($admin,   'admin',    $rowKey) ?></td>
                            </tr>
                        <?php endif; endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div class="card-footer py-2 d-flex justify-content-between align-items-center" style="background:#050510;border-top:1px solid #1a1a1a;">
                    <span class="text-muted" style="font-size:0.6rem;">
                        <i class="fa-solid fa-circle-info me-1"></i>
                        Double-cliquer sur une boule pour activer/désactiver un droit. Sauvegarder pour persister.
                    </span>
                    <div>
                        <span id="drChangesCount" style="font-size:0.6rem;color:#ffc107;margin-right:8px;"></span>
                        <button id="drSaveBtn" onclick="drSave()" style="display:none;background:rgba(40,167,69,0.2);border:1px solid #28a745;color:#777;border-radius:5px;padding:4px 12px;font-size:0.68rem;font-weight:700;cursor:pointer;">
                            <i class="fa-solid fa-floppy-disk me-1"></i>Sauvegarder les modifications
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- ── COL DROITE : Gestion membres ──────────────────── -->
        <div class="col-lg-5">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header py-2" style="background:#050520;border-bottom:1px solid #1a1a3a;">
                    <span class="oracle-text text-warning fw-bold" style="font-size:0.78rem; letter-spacing:1px;">
                        <i class="fa-solid fa-users-gear me-2"></i>MODIFIER LES DROITS
                    </span>
                </div>
                <div class="card-body p-2">

                    <!-- Recherche + filtre -->
                    <div class="d-flex gap-2 mb-2">
                        <form method="GET" class="d-flex gap-2 flex-grow-1">
                            <input type="text" name="q" value="<?= htmlspecialchars($search) ?>"
                                   placeholder="Rechercher un membre..."
                                   class="form-control form-control-sm bg-black text-white border-secondary"
                                   style="font-size:0.7rem;">
                            <select name="tier" class="tier-select">
                                <option value="">Tous</option>
                                <option value="free"         <?= $filterTier==='free'?'selected':'' ?>>Free</option>
                                <option value="premium"      <?= $filterTier==='premium'?'selected':'' ?>>Premium</option>
                                <option value="premium_plus" <?= $filterTier==='premium_plus'?'selected':'' ?>>Premium+</option>
                            </select>
                            <button type="submit" class="btn btn-outline-info btn-sm">
                                <i class="fa-solid fa-search fa-xs"></i>
                            </button>
                        </form>
                    </div>

                    <!-- Liste membres -->
                    <div style="max-height:520px; overflow-y:auto;">
                    <?php foreach ($members as $m):
                        $tierColors = ['free'=>'secondary','premium'=>'warning','premium_plus'=>'info'];
                        $tc = $tierColors[$m['tier']] ?? 'secondary';
                        $tierLabel = ['free'=>'Free','premium'=>'Premium','premium_plus'=>'Prem+'];
                        $tl = $tierLabel[$m['tier']] ?? $m['tier'];
                        $isAdm = (int)$m['admin'];
                        $lastAct = strtotime($m['last_activity'] ?? '2000-01-01');
                        $daysAgo = floor((time()-$lastAct)/86400);
                        $actColor = $daysAgo <= 1 ? '#28a745' : ($daysAgo <= 7 ? '#ffc107' : '#555');
                    ?>
                    <div class="member-row rounded mb-1 p-2" style="background:#0a0a0a;border:1px solid #1a1a1a;"
                         onclick="toggleEdit(<?= $m['id'] ?>)">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center gap-2">
                                <!-- Avatar -->
                                <div style="width:28px;height:28px;border-radius:50%;background:#0d6efd;display:flex;align-items:center;justify-content:center;color:#fff;font-size:11px;font-weight:700;flex-shrink:0;">
                                    <?= strtoupper(mb_substr($m['username'],0,1)) ?>
                                </div>
                                <div>
                                    <div style="font-size:0.73rem;color:#ddd;font-weight:600;">
                                        <?= htmlspecialchars($m['username']) ?>
                                        <?php if ($isAdm): ?>
                                            <span class="tier-badge ms-1" style="background:rgba(220,53,69,0.2);border:1px solid #dc3545;color:#dc3545;">ADMIN</span>
                                        <?php endif; ?>
                                    </div>
                                    <div style="font-size:0.58rem;color:#888;"><?= htmlspecialchars($m['email']) ?></div>
                                </div>
                            </div>
                            <div class="d-flex align-items-center gap-2">
                                <span class="badge bg-<?= $tc ?> text-dark" style="font-size:0.55rem;"><?= $tl ?></span>
                                <span style="font-size:0.6rem;color:<?= $actColor ?>;" title="Dernière activité">
                                    <?= $daysAgo <= 0 ? 'Auj.' : $daysAgo.'j' ?>
                                </span>
                                <i class="fa-solid fa-chevron-down text-muted" style="font-size:0.6rem;" id="chevron_<?= $m['id'] ?>"></i>
                            </div>
                        </div>

                        <!-- Panel édition (caché par défaut) -->
                        <div id="edit_<?= $m['id'] ?>" class="edit-panel" onclick="event.stopPropagation()">
                            <form method="POST">
                                <input type="hidden" name="target_id" value="<?= $m['id'] ?>">
                                <div class="row g-2 mb-2">
                                    <div class="col-6">
                                        <label class="small text-muted mb-1" style="font-size:0.62rem;">NIVEAU D'ACCÈS</label>
                                        <select name="tier" class="tier-select w-100">
                                            <option value="free"         <?= $m['tier']==='free'?'selected':'' ?>>Free</option>
                                            <option value="premium"      <?= $m['tier']==='premium'?'selected':'' ?>>Premium</option>
                                            <option value="premium_plus" <?= $m['tier']==='premium_plus'?'selected':'' ?>>Premium+</option>
                                        </select>
                                    </div>
                                    <div class="col-6">
                                        <label class="small text-muted mb-1" style="font-size:0.62rem;">RENOUVELLEMENT</label>
                                        <input type="date" name="renewal_date"
                                               value="<?= htmlspecialchars($m['renewal_date'] ?? '') ?>"
                                               class="form-control form-control-sm bg-black text-white border-secondary"
                                               style="font-size:0.68rem;">
                                    </div>
                                </div>
                                <div class="d-flex gap-3 mb-3">
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="checkbox" name="is_admin" id="adm_<?= $m['id'] ?>"
                                               <?= $isAdm ? 'checked' : '' ?>>
                                        <label class="form-check-label text-danger small" for="adm_<?= $m['id'] ?>" style="font-size:0.68rem;">
                                            <i class="fa-solid fa-shield-halved fa-xs me-1"></i>Administrateur
                                        </label>
                                    </div>
                                </div>
                                <!-- Infos lecture seule -->
                                <div class="d-flex gap-3 mb-3" style="font-size:0.62rem;color:#888;">
                                    <span><i class="fa-solid fa-star fa-xs me-1"></i><?= (int)$m['points'] ?> pts</span>
                                    <span><i class="fa-solid fa-coins fa-xs me-1"></i><?= number_format((int)$m['wallet_points']) ?> jetons</span>
                                </div>
                                <div class="d-flex gap-2">
                                    <button type="submit" name="update_tier"
                                            class="btn btn-sm btn-warning fw-bold flex-grow-1"
                                            style="font-size:0.68rem;">
                                        <i class="fa-solid fa-floppy-disk fa-xs me-1"></i>Enregistrer
                                    </button>
                                    <a href="admin_users.php?edit=<?= $m['id'] ?>"
                                       class="btn btn-sm btn-outline-info"
                                       style="font-size:0.68rem;">
                                        <i class="fa-solid fa-user-pen fa-xs"></i>
                                    </a>
                                </div>
                            </form>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php if (empty($members)): ?>
                        <div class="text-center text-muted py-4" style="font-size:0.72rem;">Aucun membre trouvé</div>
                    <?php endif; ?>
                    </div>

                </div>
            </div>
        </div>

    </div><!-- row -->
</div>

<script>
function toggleEdit(id) {
    const panel   = document.getElementById('edit_' + id);
    const chevron = document.getElementById('chevron_' + id);
    const isOpen  = panel.style.display === 'block';
    document.querySelectorAll('.edit-panel').forEach(p => p.style.display = 'none');
    document.querySelectorAll('[id^="chevron_"]').forEach(c => c.style.transform = '');
    if (!isOpen) {
        panel.style.display   = 'block';
        chevron.style.transform = 'rotate(180deg)';
        chevron.style.transition = 'transform 0.2s';
    }
}

// ── Double-clic toggle droits ──────────────────────────────
let drChanges = {};

function drToggle(el) {
    const val     = el.dataset.val === '1';
    const newVal  = !val;
    const row     = el.dataset.row;
    const tier    = el.dataset.tier;

    // Animer
    el.style.transform = 'scale(1.4)';
    setTimeout(() => el.style.transform = '', 200);

    // Changer l'apparence
    el.dataset.val = newVal ? '1' : '0';
    if (newVal) {
        el.className = 'fa-solid fa-circle-check check-yes';
        el.style.cursor = 'pointer';
    } else {
        el.className = 'fa-regular fa-circle check-no';
    }

    // Stocker le changement
    if (!drChanges[row]) drChanges[row] = {};
    drChanges[row][tier] = newVal;

    // Afficher le bouton sauvegarder
    document.getElementById('drSaveBtn').style.display = 'block';
    document.getElementById('drChangesCount').textContent =
        Object.values(drChanges).reduce((s, o) => s + Object.keys(o).length, 0) + ' changement(s) non sauvegardé(s)';
}

function drSave() {
    if (!Object.keys(drChanges).length) return;
    const btn = document.getElementById('drSaveBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-1"></i>Sauvegarde...';

    fetch('admin_droits_save.php', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify(drChanges)
    })
    .then(r => r.json())
    .then(data => {
        if (data.ok) {
            drChanges = {};
            btn.style.display = 'none';
            btn.disabled = false;
            btn.innerHTML = '<i class="fa-solid fa-floppy-disk me-1"></i>Sauvegarder les modifications';
            // Toast succès
            const t = document.createElement('div');
            t.style.cssText = 'position:fixed;bottom:20px;right:20px;background:#28a745;color:#fff;padding:8px 16px;border-radius:6px;font-size:0.75rem;font-weight:700;z-index:9999;';
            t.textContent = '✅ Droits sauvegardés !';
            document.body.appendChild(t);
            setTimeout(() => t.remove(), 2500);
        } else {
            btn.disabled = false;
            alert('Erreur: ' + (data.error || 'Inconnue'));
        }
    })
    .catch(() => { btn.disabled = false; alert('Erreur réseau'); });
}
</script>

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