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

header('Content-Type: text/html; charset=utf-8');

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

// Simuler exactement fetch_messages.php
$canDelete = false;
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) {}

$myReports = [];
try {
    $rStmt = $pdo->query("SELECT message_id FROM chat_reports WHERE reporter_id = {$currentUser}");
    $myReports = array_column($rStmt->fetchAll(), 'message_id');
} catch (Exception $e) {}

// Charger derniers messages
$stmt = $pdo->prepare("SELECT m.id, m.user_id, m.username, m.content FROM messages m WHERE m.circle_id=? ORDER BY m.id DESC LIMIT 3");
$stmt->execute([$circleId]);
$msgs = array_reverse($stmt->fetchAll());

echo "<style>.chat-action-btn{background:none;border:none;cursor:pointer;font-size:0.8rem;padding:0 4px;}</style>";
echo "<p>canDelete=$canDelete, currentUser=$currentUser</p>";

foreach ($msgs as $msg) {
    $msgId = $msg['id'];
    echo "<div style='display:flex;align-items:center;gap:4px;border-bottom:1px solid #333;padding:4px;'>";
    echo "<span style='color:#0dcaf0;'>" . htmlspecialchars($msg['username']) . "</span>";
    echo "<span>" . htmlspecialchars($msg['content']) . "</span>";
    echo "<span style='margin-left:auto;display:flex;gap:2px;'>";

    // Flag (pas pour ses propres messages)
    if ($currentUser && $msg['user_id'] != $currentUser) {
        $reported = in_array($msgId, $myReports);
        if ($reported) {
            echo "<button class='chat-action-btn' style='color:#28a745;'>&#10003;</button>";
        } else {
            echo "<button class='chat-action-btn' data-report='{$msgId}' style='color:#555;'>&#9873;</button>";
        }
    }

    // Supprimer (admin/oracle - tous les messages)
    if ($canDelete) {
        echo "<button class='chat-action-btn' style='color:#dc3545;' title='Supprimer #{$msgId}'>&#128465;</button>";
    }

    echo "</span></div>";
}
?>
