<?php
$pageTitle = "Messages du site";
require_once __DIR__ . '/header.php';

// Filter
$filter = $_GET['filter'] ?? 'all';
$search = trim($_GET['search'] ?? '');

// Build query
$where = [];
$params = [];

if ($filter === 'unread') $where[] = "is_read = 0";
elseif ($filter === 'starred') $where[] = "is_starred = 1";
elseif ($filter === 'replied') $where[] = "replied = 1";

if (!empty($search)) {
    $where[] = "(name LIKE ? OR email LIKE ? OR subject LIKE ? OR message LIKE ?)";
    $searchTerm = "%$search%";
    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm, $searchTerm]);
}

$whereSql = !empty($where) ? "WHERE " . implode(' AND ', $where) : '';

try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM messages $whereSql ORDER BY created_at DESC");
    $stmt->execute($params);
    $messages = $stmt->fetchAll();

    $counts = $db->query("
        SELECT
            COUNT(*) as total,
            SUM(CASE WHEN is_read = 0 THEN 1 ELSE 0 END) as unread,
            SUM(CASE WHEN is_starred = 1 THEN 1 ELSE 0 END) as starred,
            SUM(CASE WHEN replied = 1 THEN 1 ELSE 0 END) as replied
        FROM messages
    ")->fetch();
} catch (Exception $e) {
    $messages = [];
    $counts = ['total' => 0, 'unread' => 0, 'starred' => 0, 'replied' => 0];
}
?>

<div class="page-header">
    <div class="page-header-left">
        <div class="page-eyebrow">— Boîte de réception</div>
        <h1 class="page-title">Messages du <span class="italic">site</span></h1>
        <p class="page-subtitle">Demandes de consultation reçues via le formulaire</p>
    </div>
</div>

<!-- FILTERS -->
<div class="filters-bar">
    <form method="GET" style="flex: 1; min-width: 250px; display: flex; gap: 10px;">
        <input type="hidden" name="filter" value="<?= escape($filter) ?>">
        <input type="text" name="search" placeholder="Rechercher dans les messages..." class="search-input" value="<?= escape($search) ?>">
        <button type="submit" class="btn btn-primary" style="padding: 10px 20px;">
            <i class="fas fa-search"></i>
        </button>
    </form>

    <div class="filter-tabs">
        <a href="?filter=all" class="filter-tab <?= $filter === 'all' ? 'active' : '' ?>">Tous (<?= $counts['total'] ?>)</a>
        <a href="?filter=unread" class="filter-tab <?= $filter === 'unread' ? 'active' : '' ?>">Non lus (<?= $counts['unread'] ?>)</a>
        <a href="?filter=starred" class="filter-tab <?= $filter === 'starred' ? 'active' : '' ?>">Importants (<?= $counts['starred'] ?>)</a>
        <a href="?filter=replied" class="filter-tab <?= $filter === 'replied' ? 'active' : '' ?>">Répondus (<?= $counts['replied'] ?>)</a>
    </div>
</div>

<!-- MESSAGES LIST -->
<?php if (empty($messages)): ?>
    <div class="card">
        <div class="empty-state">
            <i class="fas fa-inbox"></i>
            <h3>Aucun message</h3>
            <p>
                <?php if (!empty($search)): ?>
                    Aucun résultat pour "<?= escape($search) ?>"
                <?php else: ?>
                    Les nouveaux messages du formulaire apparaîtront ici
                <?php endif; ?>
            </p>
        </div>
    </div>
<?php else: ?>
    <div class="message-list">
        <?php foreach ($messages as $msg): ?>
            <a href="message-view.php?id=<?= $msg['id'] ?>" class="message-row <?= !$msg['is_read'] ? 'unread' : '' ?>">
                <span class="message-star <?= $msg['is_starred'] ? 'active' : '' ?>" onclick="event.preventDefault(); toggleStar(<?= $msg['id'] ?>, this);">
                    <i class="<?= $msg['is_starred'] ? 'fas' : 'far' ?> fa-star"></i>
                </span>
                <div>
                    <div class="message-from"><?= escape($msg['name']) ?></div>
                    <div class="message-from-email"><?= escape($msg['email']) ?></div>
                </div>
                <div class="message-subject">
                    <?= escape($msg['subject']) ?>
                    <span class="message-subject-preview"> — <?= escape(mb_substr($msg['message'], 0, 80)) ?>...</span>
                </div>
                <div class="message-date">
                    <?= timeAgo($msg['created_at']) ?>
                    <?php if ($msg['replied']): ?>
                        <br><i class="fas fa-reply" style="color: var(--green); font-size: 11px; margin-top: 4px;"></i>
                    <?php endif; ?>
                </div>
                <div class="message-actions"><i class="fas fa-chevron-right"></i></div>
            </a>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<script>
async function toggleStar(id, el) {
    try {
        const response = await fetch('actions.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'action=toggle_star&id=' + id
        });
        const data = await response.json();
        if (data.success) {
            const icon = el.querySelector('i');
            if (data.starred) {
                el.classList.add('active');
                icon.classList.remove('far');
                icon.classList.add('fas');
            } else {
                el.classList.remove('active');
                icon.classList.remove('fas');
                icon.classList.add('far');
            }
        }
    } catch(e) { console.error(e); }
}
</script>

<?php require_once __DIR__ . '/footer.php'; ?>
