<?php
session_start();
ini_set('display_errors', 0);
error_reporting(0);
require_once 'config.php';
require_once 'functions.php';

requireLogin();
$user = getConnectedUser($pdo);
if (!$user) { header("Location: index.php"); exit; }
$userId = (int)$user['id'];

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

// --- DÉTECTER LES COLONNES DISPONIBLES (une seule fois) ---
try {
    $uCols = $pdo->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_COLUMN);
} catch (Exception $e) { $uCols = []; }
$hasRoleStatus   = in_array('role_status',   $uCols);
$hasLastActivity = in_array('last_activity', $uCols);
$extraU = ($hasRoleStatus   ? ', u.role_status'   : '') .
          ($hasLastActivity ? ', u.last_activity'  : '');

// --- ENVOYER UN MESSAGE ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_pm'])) {
    $receiverId = (int)$_POST['receiver_id'];
    $content    = trim(htmlspecialchars($_POST['content'] ?? ''));
    if (!$receiverId || empty($content)) {
        $error = "Destinataire et message requis.";
    } elseif ($receiverId === $userId) {
        $error = "Tu ne peux pas t'envoyer un message à toi-même.";
    } else {
        // Vérifier limite PM selon grade
        $tierKeyM = match($user['tier']??'free') {'premium_plus'=>'premplus','premium'=>'premium','admin'=>'admin',default=>'free'};
        $defPM = match($tierKeyM){'admin'=>9999,'premplus'=>500,'premium'=>100,default=>20};
        try {
            $rPM = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key=?");
            $rPM->execute(['limit_pm_'.$tierKeyM]);
            $vPM = $rPM->fetchColumn();
            $maxPM = (int)($vPM !== false ? $vPM : $defPM);
        } catch(Exception $e) { $maxPM = $defPM; }
        $sentToday = (int)$pdo->query("SELECT COUNT(*) FROM private_messages WHERE sender_id={$userId} AND created_at >= CURDATE()")->fetchColumn();
        if (!isAdmin($user) && $sentToday >= $maxPM) {
            $error = "Limite de {$maxPM} message(s) privé(s) par jour atteinte pour votre forfait.";
        } else {
        $pdo->prepare("INSERT INTO private_messages (sender_id, receiver_id, content) VALUES (?,?,?)")
            ->execute([$userId, $receiverId, $content]);
        addNotification($pdo, $receiverId, "  Nouveau message de {$user['username']}", "messages.php?with={$userId}");
        addInteractionPoints($pdo, $userId, 'message');
        $msg = "Message envoyé !";
        } // fin else limite PM
    }
}

// --- MARQUER LU ---
$withId = (int)($_GET['with'] ?? 0);
if ($withId) {
    $pdo->prepare("UPDATE private_messages SET is_read=1 WHERE receiver_id=? AND sender_id=?")
        ->execute([$userId, $withId]);
}

// --- CONVERSATIONS (liste) ---
try {
    $convStmt = $pdo->prepare("
        SELECT u.id, u.username, u.tier {$extraU},
               COUNT(CASE WHEN pm.is_read=0 AND pm.receiver_id=? THEN 1 END) as unread,
               MAX(pm.created_at) as last_msg,
               (SELECT content FROM private_messages
                WHERE (sender_id=? AND receiver_id=u.id) OR (sender_id=u.id AND receiver_id=?)
                ORDER BY id DESC LIMIT 1) as last_content
        FROM users u
        JOIN private_messages pm ON (pm.sender_id=u.id AND pm.receiver_id=?)
                                 OR (pm.sender_id=? AND pm.receiver_id=u.id)
        WHERE u.id != ?
        GROUP BY u.id, u.username, u.tier {$extraU}
        ORDER BY last_msg DESC
    ");
    $convStmt->execute([$userId, $userId, $userId, $userId, $userId, $userId]);
    $conversations = $convStmt->fetchAll();
} catch (Exception $e) { $conversations = []; }

// --- MESSAGES AVEC UN USER ---
$thread = [];
if ($withId) {
    try {
        $tStmt = $pdo->prepare("
            SELECT pm.*, u.username as sender_name, u.tier
            FROM private_messages pm
            JOIN users u ON u.id = pm.sender_id
            WHERE (pm.sender_id=? AND pm.receiver_id=?) OR (pm.sender_id=? AND pm.receiver_id=?)
            ORDER BY pm.id ASC
        ");
        $tStmt->execute([$userId, $withId, $withId, $userId]);
        $thread = $tStmt->fetchAll();

        // Infos du destinataire
        $withColsSelect = "id, username, tier" .
                          ($hasRoleStatus   ? ', role_status'  : '') .
                          ($hasLastActivity ? ', last_activity' : '');
        $withStmt = $pdo->prepare("SELECT {$withColsSelect} FROM users WHERE id=?");
        $withStmt->execute([$withId]);
        $withUser = $withStmt->fetch();
    } catch (Exception $e) { $thread = []; }
}

// --- CHERCHER UN USER ---
$search = trim($_GET['search'] ?? '');
$searchResults = [];
if ($search) {
    $sStmt = $pdo->prepare("SELECT id, username, tier FROM users WHERE username LIKE ? AND id != ? LIMIT 10");
    $sStmt->execute(["%$search%", $userId]);
    $searchResults = $sStmt->fetchAll();
}

// Total non lus
try {
    $stmtUnread = $pdo->prepare("SELECT COUNT(*) FROM private_messages WHERE receiver_id=? AND is_read=0");
    $stmtUnread->execute([$userId]);
    $totalUnread = (int)$stmtUnread->fetchColumn();
} catch (Exception $e) { $totalUnread = 0; }

include 'header.php';
?>

<style>
.conv-item { cursor:pointer; padding:8px 10px; border-bottom:1px solid #1a1a1a; transition:0.15s; }
.conv-item:hover, .conv-item.active { background:#1a1a2e; }
.msg-bubble { max-width:75%; padding:6px 10px; border-radius:8px; margin-bottom:6px; font-size:0.8rem; line-height:1.4; }
.msg-me    { background:#1a3a5c; color:#e0e0e0; margin-left:auto; border-bottom-right-radius:2px; }
.msg-other { background:#1a1a1a; color:#e0e0e0; border-bottom-left-radius:2px; }
.msg-time  { font-size:0.58rem; color:#666; margin-top:2px; }
</style>

<div class="container-fluid px-3" style="height:calc(100vh - 60px);overflow:hidden;padding-bottom:2rem!important;">
    <a href="index.php" class="btn btn-outline-secondary btn-sm mb-3">&larr; Dashboard</a>
    <div class="row g-0" style="height:100%;">

        <!-- COLONNE GAUCHE : conversations + recherche -->
        <div class="col-md-3 col-lg-2" style="border-right:1px solid #222;height:100%;overflow-y:auto;">
            <div class="p-2 border-bottom border-secondary">
                <h6 class="text-primary fw-bold mb-2" style="font-size:0.8rem;">
                     MESSAGERIE
                    <?php if ($totalUnread > 0): ?>
                        <span class="badge bg-danger ms-1" style="font-size:0.6rem;"><?= $totalUnread ?></span>
                    <?php endif; ?>
                </h6>
                <form method="GET" class="d-flex gap-1">
                    <input type="text" name="search" class="form-control form-control-sm bg-dark text-white border-secondary"
                           placeholder=" Chercher un membre..." value="<?= htmlspecialchars($search) ?>">
                    <button class="btn btn-primary btn-sm py-0">→</button>
                </form>
            </div>

            <!-- Résultats de recherche -->
            <?php if (!empty($searchResults)): ?>
            <div class="p-1 border-bottom border-secondary bg-dark">
                <small class="text-muted px-2" style="font-size:0.65rem;">RÉSULTATS</small>
                <?php foreach ($searchResults as $sr): ?>
                <a href="messages.php?with=<?= $sr['id'] ?>" class="d-block conv-item text-decoration-none">
                    <span class="text-white" style="font-size:0.75rem;"><?= htmlspecialchars($sr['username']) ?></span>
                    <span class="badge bg-secondary ms-1" style="font-size:0.5rem;"><?= $sr['tier'] ?></span>
                </a>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <!-- Liste conversations -->
            <div style="overflow-y:auto;height:calc(82vh - 80px);">
                <?php if (empty($conversations) && !$search): ?>
                    <div class="text-muted text-center p-3" style="font-size:0.7rem;">
                        Aucune conversation.<br>Cherche un membre pour commencer.
                    </div>
                <?php endif; ?>
                <?php foreach ($conversations as $c):
                    $lastAct = $hasLastActivity ? strtotime($c['last_activity'] ?? '2000-01-01') : 0;
                    $online  = (time() - $lastAct) < 300;
                    $dotColor = $online ? '#28a745' : '#555';
                ?>
                <a href="messages.php?with=<?= $c['id'] ?>" class="d-block conv-item text-decoration-none <?= $withId==$c['id']?'active':'' ?>">
                    <div class="d-flex align-items-center gap-1">
                        <span style="width:7px;height:7px;border-radius:50%;background:<?= $dotColor ?>;flex-shrink:0;"></span>
                        <span class="text-white fw-bold" style="font-size:0.75rem;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                            <?= htmlspecialchars($c['username']) ?>
                        </span>
                        <?php if ($c['unread'] > 0): ?>
                            <span class="badge bg-danger" style="font-size:0.55rem;"><?= $c['unread'] ?></span>
                        <?php endif; ?>
                    </div>
                    <?php if (!empty($c['last_content'])): ?>
                    <div class="text-muted" style="font-size:0.62rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-left:12px;">
                        <?= htmlspecialchars(mb_substr($c['last_content'],0,35)) ?>
                    </div>
                    <?php endif; ?>
                </a>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- COLONNE DROITE : thread ou accueil -->
        <div class="col-md-9 col-lg-10 d-flex flex-column" style="height:100%;overflow:hidden;">

            <?php if ($withId && !empty($withUser)): ?>
            <!-- Header conversation -->
            <div class="p-2 px-3 border-bottom border-secondary d-flex align-items-center gap-2" style="background:#0d0d0d;">
                <?php
                $lastAct = $hasLastActivity ? strtotime($withUser['last_activity'] ?? '2000-01-01') : 0;
                $online  = (time() - $lastAct) < 300;
                $dotColor = $online ? '#28a745' : '#555';
                $tierColor = match($withUser['tier']??'free') { 'premium'=>'text-warning','premium_plus'=>'text-info','admin'=>'text-danger', default=>'text-secondary' };
                ?>
                <span style="width:9px;height:9px;border-radius:50%;background:<?= $dotColor ?>;"></span>
                <h6 class="mb-0 text-white fw-bold"><?= htmlspecialchars($withUser['username']) ?></h6>
                <span class="<?= $tierColor ?> small"><?= strtoupper($withUser['tier']??'FREE') ?></span>
                <span class="text-muted ms-auto" style="font-size:0.65rem;"><?= $online ? 'En ligne' : 'Hors ligne' ?></span>
            </div>

            <!-- Messages -->
            <div id="thread-box" class="flex-grow-1 p-3" style="overflow-y:auto;background:#080808;min-height:0;">
                <?php if (empty($thread)): ?>
                    <div class="text-center text-muted py-5" style="font-size:0.75rem;">Début de la conversation. Envoie un message !</div>
                <?php endif; ?>
                <?php foreach ($thread as $pm):
                    $isMe = (int)$pm['sender_id'] === $userId;
                    $timeStr = date('d M H:i', strtotime($pm['created_at']));
                ?>
                <div class="d-flex flex-column <?= $isMe ? 'align-items-end' : 'align-items-start' ?> mb-2">
                    <?php if (!$isMe): ?>
                        <small class="text-muted mb-1" style="font-size:0.6rem;"><?= htmlspecialchars($pm['sender_name']) ?></small>
                    <?php endif; ?>
                    <div class="msg-bubble <?= $isMe ? 'msg-me' : 'msg-other' ?>">
                        <?= nl2br(htmlspecialchars($pm['content'])) ?>
                    </div>
                    <div class="msg-time <?= $isMe ? 'text-end' : '' ?>"><?= $timeStr ?></div>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- Zone saisie -->
            <div class="p-2 border-top border-secondary bg-dark">
                <div id="pm-feedback"></div>
                <div class="d-flex gap-2">
                    <textarea id="pm-content" class="form-control form-control-sm bg-dark text-white border-secondary"
                              rows="2" placeholder="Ton message..."
                              onkeydown="if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();sendPM();}"></textarea>
                    <button onclick="sendPM()" class="btn btn-primary px-3">
                        <i class="fa-solid fa-paper-plane"></i>
                    </button>
                </div>
                <small class="text-muted" style="font-size:0.6rem;">Entrée pour envoyer · Maj+Entrée pour nouvelle ligne</small>
            </div>

            <?php else: ?>
            <!-- Accueil messagerie -->
            <div class="flex-grow-1 d-flex align-items-center justify-content-center flex-column text-muted">
                <div style="font-size:3rem;"></div>
                <h6 class="mt-2">Messagerie privée</h6>
                <p class="small">Sélectionne une conversation ou cherche un membre.</p>
                <?php if ($msg): ?><div class="alert alert-success small py-1"><?= $msg ?></div><?php endif; ?>
                <?php if ($error): ?><div class="alert alert-danger small py-1"><?= $error ?></div><?php endif; ?>
            </div>
            <?php endif; ?>

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

<script>
const WITH_ID   = <?= (int)$withId ?>;
const MY_ID     = <?= (int)$userId ?>;
let lastMsgId   = <?= !empty($thread) ? (int)end($thread)['id'] : 0 ?>;

// Scroll initial
const tb = document.getElementById('thread-box');
if (tb) tb.scrollTop = tb.scrollHeight;

// Envoyer un message via AJAX
function sendPM() {
    const txt = document.getElementById('pm-content');
    if (!txt || !txt.value.trim()) return;
    const content = txt.value.trim();
    txt.value = '';
    txt.disabled = true;

    const fd = new FormData();
    fd.append('send_pm', '1');
    fd.append('receiver_id', WITH_ID);
    fd.append('content', content);

    fetch('messages.php?with=' + WITH_ID, { method:'POST', body: fd })
        .then(() => {
            txt.disabled = false;
            txt.focus();
            loadNewMessages();
        })
        .catch(() => { txt.disabled = false; });
}

// Charger les nouveaux messages AJAX
function loadNewMessages() {
    if (!WITH_ID) return;
    fetch('fetch_pm.php?with=' + WITH_ID + '&after=' + lastMsgId)
        .then(r => r.json())
        .then(msgs => {
            if (!msgs || !msgs.length) return;
            const tb = document.getElementById('thread-box');
            const wasAtBottom = tb.scrollHeight - tb.scrollTop <= tb.clientHeight + 50;
            msgs.forEach(pm => {
                const isMe = parseInt(pm.sender_id) === MY_ID;
                const div = document.createElement('div');
                div.className = 'd-flex flex-column mb-2 ' + (isMe ? 'align-items-end' : 'align-items-start');
                div.innerHTML = (!isMe ? `<small class="text-muted mb-1" style="font-size:0.6rem;">${pm.sender_name}</small>` : '') +
                    `<div class="msg-bubble ${isMe ? 'msg-me' : 'msg-other'}">${pm.content.replace(/\n/g,'<br>')}</div>
                     <div class="msg-time ${isMe ? 'text-end' : ''}">${pm.created_at}</div>`;
                tb.appendChild(div);
                lastMsgId = Math.max(lastMsgId, parseInt(pm.id));
            });
            if (wasAtBottom) tb.scrollTop = tb.scrollHeight;
        })
        .catch(() => {});
}

// Auto-refresh toutes les 3 secondes
if (WITH_ID) setInterval(loadNewMessages, 3000);
</script>

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