<!-- admin_messages.php -->
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();

// Vérifie si l'admin est bien connecté
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

// 🔒 Optionnel mais recommandé : vérifier l'IP et le User-Agent
// (utile si tu veux bloquer le partage de session)

if (
    ($_SESSION['ip'] ?? '') !== ($_SERVER['REMOTE_ADDR'] ?? '') ||
    ($_SESSION['user_agent'] ?? '') !== ($_SERVER['HTTP_USER_AGENT'] ?? '')
) {
    session_destroy();
    header('Location: admin_login.php?error=session_hijack');
    exit;
}
// 🔌 Connexion BDD
try {
    $pdo = new PDO("mysql:host=localhost;dbname=tostrlgj_mariage_db;charset=utf8mb4", 'tostrlgj_voldy', 'Voldy25@Ilus', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
} catch (Exception $e) {
    die("Erreur de base de données : " . htmlspecialchars($e->getMessage()));
}

// 🛠️ Traitement des actions (approuver/refuser)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && isset($_POST['id'])) {
    $id = (int)$_POST['id'];
    if ($_POST['action'] === 'approve') {
        $pdo->prepare("UPDATE invites SET approved = 1 WHERE id = ?")->execute([$id]);
    } elseif ($_POST['action'] === 'reject') {
        $pdo->prepare("UPDATE invites SET approved = -1 WHERE id = ?")->execute([$id]);
    }
    header('Location: admin_messages.php?msg=' . ($_POST['action'] === 'approve' ? 'approved' : 'rejected'));
    exit;
}

// 📥 Récupérer les messages en attente
$stmt = $pdo->prepare("
    SELECT id, nom, message_maries, status, date_created 
    FROM invites 
    WHERE approved = 0 
      AND message_maries IS NOT NULL 
      AND TRIM(message_maries) != ''
    ORDER BY date_created DESC
");
$stmt->execute();
$pendingMessages = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="fr">
<head="UTF-8">
    <meta charset="UTF-8">
    <title>Modération des Messages</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
    <h1 class="mb-4">📨 Messages à modérer</h1>

    <?php if (isset($_GET['msg'])): ?>
        <div class="alert alert-success">
            Message <?= $_GET['msg'] === 'approved' ? 'approuvé' : 'refusé' ?> avec succès.
        </div>
    <?php endif; ?>

    <?php if (empty($pendingMessages)): ?>
        <div class="alert alert-info">Aucun message en attente de modération.</div>
    <?php else: ?>
        <p><strong><?= count($pendingMessages) ?></strong> message(s) à valider</p>
        <?php foreach ($pendingMessages as $msg): ?>
            <div class="card mb-3">
                <div class="card-body">
                    <h5 class="card-title"><?= htmlspecialchars($msg['nom']) ?></h5>
                    <p class="card-text"><?= nl2br(htmlspecialchars($msg['message_maries'])) ?></p>
                    <small class="text-muted">Statut : <?= htmlspecialchars($msg['status']) ?> • <?= $msg['date_created'] ?></small>
                    <div class="mt-3">
                        <form method="POST" style="display:inline;">
                            <input type="hidden" name="id" value="<?= $msg['id'] ?>">
                            <button type="submit" name="action" value="approve" class="btn btn-success btn-sm">✅ Approuver</button>
                            <button type="submit" name="action" value="reject" class="btn btn-danger btn-sm" onclick="return confirm('Refuser ce message ?')">❌ Refuser</button>
                        </form>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <a href="admin_dashboard.php" class="btn btn-secondary">← Retour au tableau de bord</a>
</div>
</body>
</html>