<?php
session_start();
require_once 'config.php';
require_once 'functions.php';
if (!isset($_SESSION['user_id'])) { http_response_code(403); exit; }
$userId   = (int)$_SESSION['user_id'];
$circleId = (int)($_GET['id'] ?? $_SESSION['circle_id'] ?? 0);
if (!$circleId) { echo '<p class="text-danger small text-center py-3">Cercle invalide.</p>'; exit; }

// Vérifier appartenance
try {
    $chk = $pdo->prepare("SELECT id FROM circle_members WHERE circle_id=? AND user_id=?");
    $chk->execute([$circleId, $userId]);
    if (!$chk->fetch()) { echo '<p class="text-danger small text-center py-3">Accès refusé.</p>'; exit; }
    $cInfo = $pdo->prepare("SELECT name FROM circles WHERE id=?");
    $cInfo->execute([$circleId]); $circle = $cInfo->fetch();
} catch (Exception $e) { echo '<p class="text-danger small text-center py-3">Erreur.</p>'; exit; }

// Envoyer message (POST)
if ($_SERVER['REQUEST_METHOD']==='POST' && !empty($_POST['msg'])) {
    $msg  = trim(htmlspecialchars($_POST['msg']));
    $icon = trim($_POST['icon'] ?? '');
    if ($msg) {
        try {
            $pdo->prepare("INSERT INTO messages (user_id,circle_id,content,icon_emoji) VALUES (?,?,?,?)")
                ->execute([$userId,$circleId,$msg,$icon?:null]);
        } catch (Exception $e) {
            try { $pdo->prepare("INSERT INTO messages (user_id,circle_id,content) VALUES (?,?,?)")->execute([$userId,$circleId,$msg]); }
            catch (Exception $e2) {}
        }
    }
    exit;
}

// Charger les cercles de l'user pour le sélecteur
try {
    $ucW = $pdo->prepare("SELECT c.id,c.name FROM circles c JOIN circle_members cm ON cm.circle_id=c.id WHERE cm.user_id=? ORDER BY c.name ASC");
    $ucW->execute([$userId]); $userCirclesWall = $ucW->fetchAll();
} catch (Exception $e) { $userCirclesWall = []; }

// Charger les messages
try {
    $msgs = $pdo->prepare("
        SELECT m.id, m.content, m.icon_emoji, m.created_at, m.is_flagged,
               u.id as uid, u.username, u.tier
        FROM messages m JOIN users u ON u.id=m.user_id
        WHERE m.circle_id=?
        ORDER BY m.id DESC LIMIT 60
    ");
    $msgs->execute([$circleId]);
    $messages = array_reverse($msgs->fetchAll());
} catch (Exception $e) { $messages = []; }

// Charger icônes dispo
try {
    $user = $pdo->prepare("SELECT tier,interaction_points FROM users WHERE id=?");
    $user->execute([$userId]); $uData = $user->fetch();
    $tier = $uData['tier'] ?? 'free'; $interPts = (int)($uData['interaction_points'] ?? 0);
    $tierLevel = match($tier) { 'admin'=>4,'premium_plus'=>3,'premium'=>2,default=>1 };
    $tierMap   = ['free'=>1,'premium'=>2,'premium_plus'=>3,'admin'=>4];
    $iconsStmt = $pdo->query("SELECT emoji,label,required_tier,required_points FROM chat_icons WHERE is_active=1 ORDER BY sort_order ASC");
    $allIcons  = array_filter($iconsStmt->fetchAll(), fn($i) => ($tierMap[$i['required_tier']]??1) <= $tierLevel && $interPts >= (int)$i['required_points']);
} catch (Exception $e) { $allIcons = []; }
?>
<style>
.wall-msg{padding:4px 6px;border-bottom:1px solid #0d0d0d;font-size:0.75rem;display:flex;align-items:baseline;gap:4px;}
.wall-msg:hover{background:rgba(255,255,255,0.02);}
.wall-icon-grid{display:flex;flex-wrap:wrap;gap:4px;padding:6px;background:#0a0a14;border:1px solid #1a1a2a;border-radius:6px;margin-bottom:6px;max-height:100px;overflow-y:auto;}
.wall-icon-btn{font-size:1.1rem;cursor:pointer;padding:2px 4px;border-radius:3px;border:none;background:none;transition:background 0.1s;}
.wall-icon-btn:hover{background:rgba(255,255,255,0.1);}
</style>

<div style="display:flex;flex-direction:column;height:100%;min-height:0;">

    <!-- En-tête: nom cercle + sélecteur + plein écran -->
    <div style="flex-shrink:0;padding-bottom:7px;border-bottom:1px solid #1a1a2a;margin-bottom:7px;">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:<?=count($userCirclesWall)>1?'5':'0'?>px;">
            <span style="font-size:0.7rem;color:#fd7e14;font-weight:700;letter-spacing:1px;">
                💬 <?=htmlspecialchars($circle['name']??'MUR')?>
            </span>
            <button onclick="wallOpenFullscreen()" style="background:none;border:none;color:#888;font-size:0.6rem;cursor:pointer;padding:0;">Plein écran ↗</button>
        </div>
        <?php if (count($userCirclesWall) > 1): ?>
        <div style="display:flex;gap:4px;flex-wrap:wrap;margin-top:3px;">
            <?php foreach ($userCirclesWall as $cw):
                $cwAct = (int)$cw['id'] === $circleId; ?>
            <button onclick="<?=$cwAct?'void(0)':'wallSwitchCircle('.(int)$cw['id'].')'?>"
                    style="background:<?=$cwAct?'rgba(253,126,20,0.2)':'rgba(255,255,255,0.04)'?>;
                           border:1px solid <?=$cwAct?'#fd7e14':'#333'?>;
                           color:<?=$cwAct?'#fd7e14':'#aaa'?>;
                           border-radius:4px;padding:2px 8px;font-size:0.6rem;font-weight:700;
                           cursor:<?=$cwAct?'default':'pointer'?>;">
                <?=$cwAct?'● ':''?><?=htmlspecialchars($cw['name'])?>
            </button>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

    <!-- Messages -->
    <div id="wall-msgs" style="flex:1;overflow-y:auto;margin-bottom:7px;min-height:0;">
        <?php if(empty($messages)): ?>
        <div style="text-align:center;padding:20px;color:#888;font-size:0.72rem;">Aucun message — Soyez le premier !</div>
        <?php else: foreach($messages as $m):
            $tc = match($m['tier']??'free'){'admin'=>'#dc3545','premium_plus'=>'#ffc107','premium'=>'#4d90fe',default=>'#6c757d'};
            $time = date('d/m H:i', strtotime($m['created_at']));
            $icon = $m['icon_emoji'] ?? '';
            $isMe = (int)$m['uid'] === $userId;
        ?>
        <div class="wall-msg" id="wmsg-<?=$m['id']?>">
            <span style="font-size:0.56rem;color:#888;flex-shrink:0;"><?=$time?></span>
            <?php if($icon): ?><span style="font-size:0.9rem;line-height:1;"><?=htmlspecialchars($icon)?></span><?php endif; ?>
            <span style="color:<?=$tc?>;font-weight:700;flex-shrink:0;"><?=htmlspecialchars($m['username']??'')?></span>
            <span style="color:#ddd;flex:1;word-break:break-word;"><?=htmlspecialchars($m['content']??'')?></span>
            <?php if($isMe): ?>
            <button onclick="wallDeleteMsg(<?=$m['id']?>)" title="Supprimer" style="background:none;border:none;color:#888;font-size:0.6rem;cursor:pointer;padding:0 2px;flex-shrink:0;line-height:1;">[x]</button>
            <?php endif; ?>
        </div>
        <?php endforeach; endif; ?>
    </div>

    <!-- Icônes picker (caché par défaut) -->
    <?php if (!empty($allIcons)): ?>
    <div id="wall-icon-picker" style="display:none;flex-shrink:0;">
        <div class="wall-icon-grid">
        <?php foreach($allIcons as $ic): ?>
            <button class="wall-icon-btn" title="<?=htmlspecialchars($ic['label']??'')?>"
                    onclick="wallSelectIcon('<?=htmlspecialchars($ic['emoji'])?>', this)">
                <?=htmlspecialchars($ic['emoji'])?>
            </button>
        <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Zone de saisie -->
    <div style="flex-shrink:0;display:flex;gap:5px;align-items:center;">
        <!-- Bouton icône -->
        <?php if (!empty($allIcons)): ?>
        <button id="wall-icon-btn" onclick="wallTogglePicker()"
                style="background:none;border:1px solid #333;color:#888;border-radius:5px;padding:4px 7px;font-size:0.75rem;cursor:pointer;flex-shrink:0;min-width:34px;"
                title="Choisir une icône">😊</button>
        <?php endif; ?>
        <!-- Icône sélectionnée -->
        <span id="wall-icon-selected" data-emoji="" style="display:none;font-size:1rem;cursor:pointer;flex-shrink:0;" onclick="wallClearIcon()" title="Cliquer pour retirer">😀</span>

        <!-- Input message -->
        <input id="wall-input" type="text" placeholder="Message au cercle..." maxlength="500" autocomplete="off"
               class="form-control form-control-sm bg-dark text-white border-secondary"
               style="font-size:0.72rem;flex:1;"
               onkeydown="if(event.key==='Enter'&&!event.shiftKey){wallSend();event.preventDefault();}">

        <!-- Envoyer -->
        <button onclick="wallSend()"
                style="background:rgba(40,167,69,0.2);border:1px solid #28a745;color:#777;border-radius:5px;padding:5px 12px;font-size:0.7rem;font-weight:700;cursor:pointer;flex-shrink:0;">
            <i class="fa-solid fa-paper-plane fa-xs"></i>
        </button>
    </div>
</div>

<script>
// Fonctions icônes (locales au wall modal)
function wallSelectIcon(emoji, btn) {
    const sel = document.getElementById('wall-icon-selected');
    const wallBtn = document.getElementById('wall-icon-btn');
    if (sel) { sel.textContent = emoji; sel.dataset.emoji = emoji; sel.style.display = 'inline'; }
    document.getElementById('wall-icon-picker').style.display = 'none';
}
function wallClearIcon() {
    const sel = document.getElementById('wall-icon-selected');
    if (sel) { sel.textContent = ''; sel.dataset.emoji = ''; sel.style.display = 'none'; }
}
function wallTogglePicker() {
    const p = document.getElementById('wall-icon-picker');
    if (p) p.style.display = p.style.display === 'none' ? 'block' : 'none';
}
function wallDeleteMsg(id) {
    if (!confirm('Supprimer ce message ?')) return;
    fetch('fetch_messages.php?delete_id=' + id, {method:'GET'})
        .then(() => { const el = document.getElementById('wmsg-'+id); if(el) el.remove(); });
}
// Scroll en bas au chargement
const _wm = document.getElementById('wall-msgs');
if (_wm) _wm.scrollTop = _wm.scrollHeight;
</script>
