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

requireLogin();
$user   = getConnectedUser($pdo);
$userId = (int)$user['id'];

// Paramètres de recherche
$search   = trim($_GET['q']      ?? '');
$circleFilter = (int)($_GET['circle'] ?? 0);
$page     = max(1, (int)($_GET['page'] ?? 1));
$perPage  = 30;
$offset   = ($page - 1) * $perPage;

// Mes cercles
try {
    $myCircles = $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
    ");
    $myCircles->execute([$userId]);
    $circles = $myCircles->fetchAll();
} catch (Exception $e) { $circles = []; }

// Construire la requête
$where  = "WHERE 1=1";
$params = [];

// Filtrer par cercles accessibles
if ($circleFilter > 0) {
    $where   .= " AND m.circle_id = ?";
    $params[] = $circleFilter;
} else {
    $circleIds = array_column($circles, 'id');
    if (!empty($circleIds)) {
        $in = implode(',', array_fill(0, count($circleIds), '?'));
        $where .= " AND m.circle_id IN ({$in})";
        $params = array_merge($params, $circleIds);
    }
}

if ($search) {
    $where   .= " AND m.content LIKE ?";
    $params[] = "%{$search}%";
}

// Compter total
try {
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM messages m {$where}");
    $countStmt->execute($params);
    $total = (int)$countStmt->fetchColumn();
    $totalPages = ceil($total / $perPage);
} catch (Exception $e) { $total = 0; $totalPages = 1; }

// Charger les messages
try {
    $params[] = $perPage;
    $params[] = $offset;
    $msgStmt = $pdo->prepare("
        SELECT m.id, m.content, m.created_at, m.username, m.user_id,
               c.name as circle_name
        FROM messages m
        LEFT JOIN circles c ON c.id = m.circle_id
        {$where}
        ORDER BY m.id DESC
        LIMIT ? OFFSET ?
    ");
    $msgStmt->execute($params);
    $messages = $msgStmt->fetchAll();
} catch (Exception $e) { $messages = []; }

include 'header.php';
?>

<div class="container mt-4 px-4">
    <div class="d-flex align-items-center gap-3 mb-3 flex-wrap">
        <a href="index.php" class="btn btn-outline-secondary btn-sm">&larr; Retour</a>
        <h5 class="text-info fw-bold mb-0">Historique du chat</h5>
        <span class="text-muted small"><?= number_format($total) ?> message<?= $total > 1 ? 's' : '' ?></span>
    </div>

    <!-- Filtres -->
    <form method="GET" class="row g-2 mb-3">
        <div class="col-md-5">
            <input type="text" name="q" class="form-control form-control-sm bg-dark text-white border-secondary"
                   placeholder="Rechercher dans les messages..." value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-4">
            <select name="circle" class="form-select form-select-sm bg-dark text-white border-secondary">
                <option value="0">Tous mes cercles</option>
                <?php foreach ($circles as $c): ?>
                <option value="<?= $c['id'] ?>" <?= $c['id'] == $circleFilter ? 'selected' : '' ?>>
                    <?= htmlspecialchars($c['name']) ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-3 d-flex gap-2">
            <button type="submit" class="btn btn-info btn-sm fw-bold flex-grow-1">Rechercher</button>
            <?php if ($search || $circleFilter): ?>
            <a href="chat_history.php" class="btn btn-outline-secondary btn-sm">Effacer</a>
            <?php endif; ?>
        </div>
    </form>

    <!-- Messages -->
    <div class="card bg-dark border-secondary shadow">
        <?php if (empty($messages)): ?>
        <div class="text-center text-muted py-4">Aucun message trouvé.</div>
        <?php else: ?>
        <div class="table-responsive">
            <table class="table table-dark table-hover table-sm small mb-0">
                <thead>
                    <tr>
                        <th style="width:120px;">Date</th>
                        <th style="width:100px;">Membre</th>
                        <th style="width:100px;">Cercle</th>
                        <th>Message</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($messages as $msg): ?>
                <tr>
                    <td class="text-muted" style="font-size:0.65rem;"><?= date('d M Y H:i', strtotime($msg['created_at'])) ?></td>
                    <td>
                        <span class="<?= $msg['user_id'] == $userId ? 'text-warning' : 'text-info' ?>" style="font-size:0.72rem;">
                            <?= htmlspecialchars($msg['username']) ?>
                        </span>
                    </td>
                    <td><span class="badge bg-dark border border-info text-info" style="font-size:0.55rem;"><?= htmlspecialchars($msg['circle_name'] ?? '-') ?></span></td>
                    <td style="font-size:0.75rem;">
                        <?php
                        $content = htmlspecialchars($msg['content']);
                        if ($search) {
                            $content = preg_replace('/(' . preg_quote(htmlspecialchars($search), '/') . ')/i',
                                '<mark style="background:#ffc107;color:#000;border-radius:2px;">$1</mark>', $content);
                        }
                        echo $content;
                        ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
        <div class="p-2 d-flex justify-content-center gap-1 border-top border-secondary flex-wrap">
            <?php for ($p = 1; $p <= min($totalPages, 10); $p++): ?>
            <a href="?q=<?= urlencode($search) ?>&circle=<?= $circleFilter ?>&page=<?= $p ?>"
               class="btn btn-xs <?= $p == $page ? 'btn-info' : 'btn-outline-secondary' ?> py-0"
               style="font-size:0.65rem;"><?= $p ?></a>
            <?php endfor; ?>
            <?php if ($totalPages > 10): ?>
            <span class="text-muted small align-self-center">... <?= $totalPages ?> pages</span>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <?php endif; ?>
    </div>
</div>

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