<?php
$pageTitle = "Tableau de bord";
require_once __DIR__ . '/header.php';

// Stats
try {
    $db = getDB();

    $totalMessages = $db->query("SELECT COUNT(*) FROM messages")->fetchColumn();
    $unreadMessages = $db->query("SELECT COUNT(*) FROM messages WHERE is_read = 0")->fetchColumn();
    $todayMessages = $db->query("SELECT COUNT(*) FROM messages WHERE DATE(created_at) = CURDATE()")->fetchColumn();
    $emailsSent = $db->query("SELECT COUNT(*) FROM email_logs WHERE status = 'sent'")->fetchColumn();

    // Recent messages
    $recentMessages = $db->query("SELECT * FROM messages ORDER BY created_at DESC LIMIT 5")->fetchAll();

    // Recent sent emails
    $recentSent = $db->query("SELECT * FROM email_logs ORDER BY sent_at DESC LIMIT 5")->fetchAll();

} catch (Exception $e) {
    $totalMessages = $unreadMessages = $todayMessages = $emailsSent = 0;
    $recentMessages = $recentSent = [];
}
?>

<div class="page-header">
    <div class="page-header-left">
        <div class="page-eyebrow">— Bienvenue</div>
        <h1 class="page-title">Bonjour, <span class="italic"><?= escape(explode(' ', $currentUser['full_name'])[1] ?? $currentUser['full_name']) ?></span></h1>
        <p class="page-subtitle">Voici un aperçu de votre activité aujourd'hui</p>
    </div>
    <a href="compose.php" class="btn btn-or">
        <i class="fas fa-pen"></i>
        <span>Nouveau message</span>
    </a>
</div>

<!-- STATS -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-card-icon"><i class="fas fa-inbox"></i></div>
        <div class="stat-card-label">Messages totaux</div>
        <div class="stat-card-value"><?= $totalMessages ?></div>
        <div class="stat-card-trend">via formulaire de contact</div>
    </div>

    <div class="stat-card">
        <div class="stat-card-icon"><i class="fas fa-envelope-open-text"></i></div>
        <div class="stat-card-label">Non lus</div>
        <div class="stat-card-value"><?= $unreadMessages ?></div>
        <div class="stat-card-trend">en attente de lecture</div>
    </div>

    <div class="stat-card">
        <div class="stat-card-icon"><i class="fas fa-calendar-day"></i></div>
        <div class="stat-card-label">Aujourd'hui</div>
        <div class="stat-card-value"><?= $todayMessages ?></div>
        <div class="stat-card-trend">nouveaux messages</div>
    </div>

    <div class="stat-card">
        <div class="stat-card-icon"><i class="fas fa-paper-plane"></i></div>
        <div class="stat-card-label">Envoyés</div>
        <div class="stat-card-value"><?= $emailsSent ?></div>
        <div class="stat-card-trend">depuis le tableau de bord</div>
    </div>
</div>

<!-- RECENT MESSAGES -->
<div class="card">
    <div class="card-header">
        <h2 class="card-title">Messages récents</h2>
        <a href="messages.php" class="card-link">Voir tous <i class="fas fa-arrow-right"></i></a>
    </div>

    <?php if (empty($recentMessages)): ?>
        <div class="empty-state">
            <i class="fas fa-inbox"></i>
            <h3>Aucun message</h3>
            <p>Les nouveaux messages du formulaire apparaîtront ici</p>
        </div>
    <?php else: ?>
        <div class="message-list" style="background: transparent; border: none;">
            <?php foreach ($recentMessages as $msg): ?>
                <a href="message-view.php?id=<?= $msg['id'] ?>" class="message-row <?= !$msg['is_read'] ? 'unread' : '' ?>" style="background: <?= !$msg['is_read'] ? 'rgba(201,169,97,0.08)' : 'var(--cream)' ?>; margin-bottom: 8px;">
                    <span class="message-star <?= $msg['is_starred'] ? 'active' : '' ?>">
                        <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, 60)) ?>...</span>
                    </div>
                    <div class="message-date"><?= timeAgo($msg['created_at']) ?></div>
                    <div class="message-actions"><i class="fas fa-chevron-right"></i></div>
                </a>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<!-- INFO CARD -->
<div class="card" style="background: var(--noir); color: var(--cream);">
    <div class="card-header" style="border-bottom-color: rgba(201,169,97,0.2);">
        <h2 class="card-title" style="color: var(--cream);">À propos</h2>
    </div>
    <div style="font-family: var(--serif); font-size: 17px; line-height: 1.7; color: var(--gris-light);">
        <p style="margin-bottom: 15px;"><strong style="color: var(--or); font-style: italic;">Espace personnel sécurisé</strong> — Cet espace vous permet de consulter les messages reçus via le formulaire de contact de votre site et de communiquer directement avec vos clients depuis votre boîte email professionnelle.</p>
        <p>Toutes les données sont chiffrées et stockées de manière sécurisée. Votre boîte email <strong style="color: var(--or);">contact@hichamboucharebavocat.ma</strong> est synchronisée en temps réel.</p>
    </div>
    <div style="display: flex; gap: 25px; margin-top: 25px; padding-top: 20px; border-top: 1px solid rgba(201,169,97,0.15); flex-wrap: wrap;">
        <div style="font-size: 13px; color: var(--gris-light);">
            <i class="fas fa-shield-alt" style="color: var(--or); margin-right: 8px;"></i> Connexion sécurisée
        </div>
        <div style="font-size: 13px; color: var(--gris-light);">
            <i class="fas fa-clock" style="color: var(--or); margin-right: 8px;"></i> Dernière connexion : <?= $currentUser['last_login'] ? formatDate($currentUser['last_login']) : 'Première fois' ?>
        </div>
    </div>
</div>

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