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

$circleId    = (int)($_SESSION['circle_id'] ?? 1);
$currentUser = (int)($_SESSION['user_id'] ?? 0);

// Mettre à jour last_activity en temps réel (appelé toutes les ~5sec par le chat)
if ($currentUser > 0) {
    try { $pdo->prepare("UPDATE users SET last_activity=NOW() WHERE id=?")->execute([$currentUser]); }
    catch (Exception $e) {}
}

// Vérifier si admin ou oracle (peut supprimer les messages)
$canDelete = false;
if ($currentUser > 0) {
    try {
        $adminChk = $pdo->prepare("SELECT admin, tier FROM users WHERE id=?");
        $adminChk->execute([$currentUser]);
        $adminRow = $adminChk->fetch();
        $canDelete = $adminRow && ((int)$adminRow['admin'] === 1 || strtolower($adminRow['tier']) === 'admin');
        if (!$canDelete) {
            $oracleChk = $pdo->prepare("SELECT oracle_id FROM circles WHERE id=?");
            $oracleChk->execute([$circleId]);
            $oracleRow = $oracleChk->fetch();
            $canDelete = $oracleRow && (int)$oracleRow['oracle_id'] === $currentUser;
        }
    } catch (Exception $e) {}
}

// Messages déjà signalés par l'utilisateur courant
$myReports = [];
if ($currentUser > 0) {
    try {
        $rStmt = $pdo->query("SELECT message_id FROM chat_reports WHERE reporter_id = {$currentUser}");
        $myReports = array_column($rStmt->fetchAll(), 'message_id');
    } catch (Exception $e) {}
}

echo "<style>.chat-action-btn{background:none;border:none;cursor:pointer;font-size:0.6rem;padding:0 2px;line-height:1;opacity:0.7;}.chat-action-btn:hover{opacity:1;}</style>";

try {
    $cols = $pdo->query("SHOW COLUMNS FROM messages")->fetchAll(PDO::FETCH_COLUMN);
    $hasIcon    = in_array('icon_emoji', $cols);
    $hasColor   = in_array('text_color', $cols);
    $hasPhoto   = in_array('photo_path', $cols);
    $hasFlag    = in_array('is_flagged', $cols);
    $hasFlagCnt = in_array('flag_count', $cols);

    // Si colonnes manquantes, les ajouter automatiquement
    if (!$hasIcon)    { $pdo->exec("ALTER TABLE messages ADD COLUMN icon_emoji VARCHAR(10) DEFAULT NULL"); $hasIcon=true; }
    if (!$hasColor)   { $pdo->exec("ALTER TABLE messages ADD COLUMN text_color VARCHAR(7) DEFAULT NULL");  $hasColor=true; }
    if (!$hasPhoto)   { $pdo->exec("ALTER TABLE messages ADD COLUMN photo_path VARCHAR(255) DEFAULT NULL"); $hasPhoto=true; }
    if (!$hasFlag)    { $pdo->exec("ALTER TABLE messages ADD COLUMN is_flagged TINYINT(1) DEFAULT 0");     $hasFlag=true; }
    if (!$hasFlagCnt) { $pdo->exec("ALTER TABLE messages ADD COLUMN flag_count INT(11) DEFAULT 0");        $hasFlagCnt=true; }

    $extraCols = '';
    if ($hasIcon)    $extraCols .= ', m.icon_emoji';
    if ($hasColor)   $extraCols .= ', m.text_color';
    if ($hasPhoto)   $extraCols .= ', m.photo_path';
    if ($hasFlag)    $extraCols .= ', m.is_flagged';
    if ($hasFlagCnt) $extraCols .= ', m.flag_count';

    $userCols = $pdo->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_COLUMN);
    $hasTier  = in_array('tier', $userCols);
    $tierSelect = $hasTier ? ', u.tier' : '';

    $sql = "SELECT m.id, m.user_id, m.username, m.content, m.created_at,
                   c.name as circle_name
            {$extraCols} {$tierSelect}
            FROM messages m
            LEFT JOIN users u ON u.id = m.user_id
            LEFT JOIN circles c ON c.id = m.circle_id
            WHERE m.circle_id = ?
            ORDER BY m.id DESC LIMIT 20";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([$circleId]);
    $messages = array_reverse($stmt->fetchAll());

} catch (Exception $e) {
    echo "<div class='text-danger small p-2'>Erreur chat: " . htmlspecialchars($e->getMessage()) . "</div>";
    exit;
}

if (empty($messages)) {
    echo "<div class='text-muted small text-center py-3' style='font-size:0.7rem;'>Aucun message. Soyez le premier !</div>";
    exit;
}

foreach ($messages as $msg) {
    $tier       = $msg['tier'] ?? 'free';
    $isFlagged  = (int)($msg['is_flagged'] ?? 0);
    $flagCount  = (int)($msg['flag_count'] ?? 0);
    $icon       = $msg['icon_emoji'] ?? '';
    $textColor  = $msg['text_color'] ?? null;
    $photoPath  = $msg['photo_path'] ?? null;
    $time       = date('H:i', strtotime($msg['created_at']));
    $name       = htmlspecialchars($msg['username'] ?? 'Inconnu');
    $content    = htmlspecialchars(filterBadWords($msg['content'] ?? '', $pdo));
    $circleName = !empty($msg['circle_name']) ? htmlspecialchars($msg['circle_name']) : '';
    $msgId      = (int)$msg['id'];
    $isOracle   = ($msg['user_id'] == 0);

    // Couleur du nom selon tier
    if ($isOracle)              $nameStyle = 'color:#ff6600;font-weight:bold;';
    elseif ($tier==='admin')    $nameStyle = 'color:#dc3545;font-weight:bold;';
    elseif ($tier==='premium_plus') $nameStyle = 'color:#ffc107;font-weight:bold;';
    elseif ($tier==='premium')  $nameStyle = 'color:#0dcaf0;font-weight:bold;';
    else                        $nameStyle = 'color:#6c757d;';

    // Style si flaggé
    $msgBg = $isFlagged ? 'background:rgba(255,100,0,0.15);border-left:3px solid #ff6600;padding-left:4px;border-radius:3px;' : '';

    // Style texte personnalisé (premium+)
    $contentStyle = $textColor ? "color:{$textColor};" : 'color:#e0e0e0;';

    echo "<div class='chat-msg' style='border-bottom:1px solid #111;padding:2px 0 3px;{$msgBg}font-size:0.75rem;' id='msg-{$msgId}'>";

    // LIGNE 1 : heure + icône + nom + cercle + boutons
    echo "<div style='display:flex;align-items:center;gap:3px;flex-wrap:nowrap;'>";
    echo "<span style='font-size:0.58rem;color:#555;flex-shrink:0;'>{$time}</span>";
    if ($icon) echo "<span style='font-size:0.85rem;line-height:1;flex-shrink:0;'>{$icon}</span>";
    echo "<span style='{$nameStyle}font-size:0.72rem;flex-shrink:0;'>{$name}</span>";
    // Badge grade au lieu du nom de cercle
    $tierBadgeMap = [
        'admin'        => ['ADMIN',    '#dc3545', 'rgba(220,53,69,0.15)'],
        'premium_plus' => ['PREM+',    '#ffc107', 'rgba(255,193,7,0.12)'],
        'premium'      => ['PREMIUM',  '#4d90fe', 'rgba(13,110,253,0.12)'],
        'free'         => ['',         '',        ''],
    ];
    $tierBadge = $tierBadgeMap[$tier] ?? ['','',''];
    if ($tierBadge[0] && !$isOracle) {
        echo "<span style='font-size:0.5rem;background:{$tierBadge[2]};color:{$tierBadge[1]};border:1px solid {$tierBadge[1]};border-radius:4px;padding:0 4px;flex-shrink:0;font-weight:700;letter-spacing:0.5px;'>{$tierBadge[0]}</span>";
    }
    echo "<span style='margin-left:auto;display:flex;gap:2px;align-items:center;flex-shrink:0;'>";
    if ($currentUser && $msg['user_id'] != $currentUser) {
        $iHaveReported = in_array($msgId, $myReports);
        if ($iHaveReported) {
            echo "<button id='flag-{$msgId}' data-reported='1' class='chat-action-btn' style='color:#28a745;cursor:default;font-size:0.65rem;' title='Signalé'>ok</button>";
        } else {
            echo "<button onclick='reportMsg({$msgId})' id='flag-{$msgId}' data-report='{$msgId}' class='chat-action-btn' style='color:#666;font-size:0.7rem;' title='Signaler'>[!]</button>";
        }
    }
    if ($canDelete) {
        echo "<button onclick='deleteMsg({$msgId})' id='del-{$msgId}' class='chat-action-btn' style='color:#666;font-size:0.65rem;' title='Supprimer'>[x]</button>";
    }
    echo "</span></div>";

    // LIGNE 2 : contenu (seulement si non vide)
    if ($content) {
        echo "<div style='{$contentStyle}font-size:0.74rem;line-height:1.35;padding-left:2px;'>{$content}</div>";
    }
    if ($photoPath && file_exists(__DIR__.'/'.$photoPath)) {
        echo "<img src='" . htmlspecialchars($photoPath) . "' style='max-width:140px;max-height:90px;object-fit:contain;border-radius:3px;margin-top:2px;cursor:pointer;border:1px solid #333;display:block;' onclick=\"openLightbox('" . htmlspecialchars($photoPath) . "','Message de {$name}')\">";
    }
    if ($isFlagged) {
        echo "<div style='font-size:0.55rem;color:#ff6600;'>[!] Signale</div>";
    }

    echo "</div>";
}
?>
