<?php
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;
}

// ======================================
// 2) Connexion DB
// ======================================
try {
  $pdo = new PDO(
    "mysql:host=localhost;dbname=tostrlgj_mariage_db;charset=utf8mb4",
    'tostrlgj_voldy',
    'Voldy25@Ilus',
    [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]
  );
} catch (PDOException $e) {
  die("Erreur DB : " . $e->getMessage());
}

// ======================================
// 3) Actions check-in / uncheck-in
// ======================================
if (isset($_GET['action'], $_GET['id'])) {
  $id = (int) $_GET['id'];
  if ($id > 0) {
    if ($_GET['action'] === 'validate') {
      $stmt = $pdo->prepare("UPDATE invites SET status = 1 WHERE id = ?");
      $stmt->execute([$id]);
    } elseif ($_GET['action'] === 'invalidate') {
      $stmt = $pdo->prepare("UPDATE invites SET status = 0 WHERE id = ?");
      $stmt->execute([$id]);
    }
  }
  header('Location: admin_dashboard.php');
  exit;
}

// ======================================
// 4) Export CSV
// ======================================
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=invitations.csv');

  $output = fopen('php://output', 'w');
  fputcsv($output, ['ID', 'Type', 'Nom complet', 'Conjoint', 'Email', 'Téléphone', 'Code', 'Table', 'Validée', 'Créée le']);

  $sqlExport = "SELECT * FROM invites ORDER BY date_created DESC";
  foreach ($pdo->query($sqlExport) as $row) {
    fputcsv($output, [
      $row['id'],
      ucfirst($row['type_invitation']),
      $row['titre1'] . ' ' . $row['nom'],
      $row['type_invitation'] === 'couple' ? ($row['titre2'] . ' ' . $row['nom2']) : '-',
      $row['email'],
      $row['telephone'],
      $row['code_invitation'],
      $row['table_num'],
      !empty($row['status']) ? 'Oui' : 'Non',
      $row['date_created'],
    ]);
  }
  fclose($output);
  exit;
}

// ======================================
// 5) Stats
// ======================================
$statsStmt = $pdo->query("SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as confirmed,
    SUM(CASE WHEN type_invitation = 'couple' THEN 1 ELSE 0 END) as couples
FROM invites");
$stats = $statsStmt->fetch();

// === ACTIONS EN MASSE ===
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && !empty($_POST['ids'])) {
    $ids = array_map('intval', $_POST['ids']); // Sécurité
    $placeholders = str_repeat('?,', count($ids) - 1) . '?';

    if ($_POST['action'] === 'confirm_bulk') {
        $pdo->prepare("UPDATE invites SET status = 1 WHERE id IN ($placeholders)")->execute($ids);
        // Message de succès (optionnel)
    } elseif ($_POST['action'] === 'whatsapp_bulk') {
        $_SESSION['whatsapp_bulk_ids'] = $ids;
        header('Location: admin_whatsapp_bulk.php');
        exit;
    }
    // Redirige pour éviter re-soumission
    header('Location: ' . $_SERVER['PHP_SELF'] . (isset($_GET['filter']) ? '?filter=' . $_GET['filter'] : ''));
    exit;
}

// === PAGINATION + FILTRES ===
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 30;
$offset = ($page - 1) * $limit;

$filter = $_GET['filter'] ?? 'all';
$where = '';
switch ($filter) {
  case 'confirmed':
    $where = "WHERE status = 1";
    break;
  case 'pending':
    $where = "WHERE (status != 1 OR status IS NULL)";
    break;
  case 'couple':
    $where = "WHERE type_invitation = 'couple'";
    break;
  case 'single':
    $where = "WHERE type_invitation = 'single'";
    break;
}

// Stats
$stats = $pdo->query("SELECT COUNT(*) as total, SUM(CASE WHEN status=1 THEN 1 ELSE 0 END) as confirmed, SUM(CASE WHEN type_invitation='couple' THEN 1 ELSE 0 END) as couples FROM invites")->fetch();

// Données
$stmt = $pdo->prepare("SELECT * FROM invites $where ORDER BY id DESC LIMIT $limit OFFSET $offset");
$stmt->execute();
$invitations = $stmt->fetchAll();

$total = $pdo->prepare("SELECT COUNT(*) FROM invites $where");
$total->execute();
$totalPages = ceil($total->fetchColumn() / $limit);


// ======================================
// 6) Liste initiale
// ======================================
$stmt = $pdo->query("SELECT * FROM invites ORDER BY id DESC LIMIT 30 OFFSET 0");
$invitations = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Admin Dashboard - Aaron & Princillia</title>
  <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700;900&family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body {
      font-family: 'Montserrat', sans-serif;
      background: linear-gradient(135deg, #f5f5f2 0%, #e8e6e1 100%);
      color: #2c2c2c;
      min-height: 100vh;
    }

    .navbar-brand {
      font-family: 'Playfair Display', serif;
      font-size: 1.8rem;
      font-weight: 700;
      background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }

    .admin-name {
      font-weight: 600;
      color: #d4a574;
    }

    .btn-logout {
      background: #dc3545;
      color: white;
      padding: 0.5rem 1.5rem;
      border-radius: 8px;
      text-decoration: none;
      transition: all 0.3s ease;
      border: none;
      cursor: pointer;
    }

    .btn-logout:hover {
      background: #c82333;
      transform: translateY(-2px);
    }

    .header-title {
      font-family: 'Playfair Display', serif;
      font-size: 2.5rem;
      color: #2c2c2c;
      margin-bottom: 2rem;
    }

    .stat-card {
      background: white;
      border-radius: 15px;
      padding: 2rem;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
      text-align: center;
      transition: transform 0.3s ease;
    }

    .stat-card:hover {
      transform: translateY(-5px);
    }

    .stat-icon {
      font-size: 2.5rem;
      color: #d4a574;
      margin-bottom: 1rem;
    }

    .stat-number {
      font-family: 'Playfair Display', serif;
      font-size: 2.5rem;
      font-weight: 900;
      color: #2c2c2c;
    }

    .stat-label {
      color: #999;
      font-size: 0.95rem;
      margin-top: 0.5rem;
      text-transform: uppercase;
      letter-spacing: 1px;
    }

    .search-box {
      background: white;
      border-radius: 15px;
      padding: 1.5rem;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
    }

    .search-input {
      width: 100%;
      padding: 1rem;
      border: 2px solid #eee;
      border-radius: 8px;
      font-size: 1rem;
      transition: border 0.3s ease;
    }

    .search-input:focus {
      outline: none;
      border-color: #d4a574;
    }

    .search-help {
      font-size: 0.85rem;
      color: #999;
      margin-top: 0.5rem;
    }

    .table-container {
      background: white;
      border-radius: 15px;
      overflow: hidden;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
    }

    thead th {
      background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
      color: white;
      padding: 1.5rem;
      text-align: left;
      font-weight: 600;
    }

    tbody tr {
      border-bottom: 1px solid #eee;
      transition: background 0.2s ease;
    }

    tbody tr:hover {
      background: #f9f9f7;
    }

    tbody td {
      padding: 1.2rem 1.5rem;
    }

    .badge {
      display: inline-block;
      padding: 0.5rem 1rem;
      border-radius: 50px;
      font-size: 0.85rem;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }

    .badge-couple {
      background: rgba(40, 167, 69, 0.1);
      color: #28a745;
    }

    .badge-single {
      background: rgba(23, 162, 184, 0.1);
      color: #17a2b8;
    }

    .badge-confirmed {
      background: rgba(40, 167, 69, 0.1);
      color: #28a745;
    }

    .badge-pending {
      background: rgba(108, 117, 125, 0.1);
      color: #6c757d;
    }

    .action-buttons {
      display: flex;
      gap: 0.5rem;
      flex-wrap: wrap;
    }

    .btn-sm {
      padding: 0.5rem 0.75rem;
      font-size: 0.85rem;
    }

    .btn-warning {
      background: #ffc107;
      color: #2c2c2c;
    }

    .btn-warning:hover {
      background: #e0a800;
    }

    .btn-info {
      background: #17a2b8;
      color: white;
    }

    .btn-info:hover {
      background: #138496;
    }

    .btn-edit {
      background: #007bff;
      color: white;
    }

    .btn-edit:hover {
      background: #0056b3;
    }

    .btn-view {
      background: #d4a574;
      color: white;
    }

    .btn-view:hover {
      background: #8b6f47;
    }

    .modal-content {
      border-radius: 15px;
      box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    }

    .modal-header {
      background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
      color: white;
      border-radius: 15px 15px 0 0;
    }

    .modal-title {
      font-family: 'Playfair Display', serif;
      font-size: 1.8rem;
      font-weight: 700;
    }

    .detail-group {
      margin-bottom: 2rem;
      padding-bottom: 2rem;
      border-bottom: 2px solid #f0f0f0;
    }

    .detail-group:last-child {
      border-bottom: none;
    }

    .detail-label {
      font-weight: 600;
      color: #d4a574;
      text-transform: uppercase;
      font-size: 0.85rem;
      letter-spacing: 1px;
      margin-bottom: 0.5rem;
    }

    .detail-value {
      font-size: 1.1rem;
      color: #2c2c2c;
    }

    .empty-state {
      text-align: center;
      padding: 3rem;
      color: #999;
    }

    .empty-icon {
      font-size: 3rem;
      color: #ddd;
      margin-bottom: 1rem;
    }

    @media (max-width: 768px) {
      .header-title {
        font-size: 1.8rem;
      }

      .stat-number {
        font-size: 2rem;
      }

      .action-buttons {
        flex-direction: column;
      }

      .btn-sm {
        width: 100%;
        justify-content: center;
      }

      .table-responsive .table td,
      .table-responsive .table th {
        white-space: nowrap;
      }
    }
  </style>
</head>

<body>
  <!-- Navbar -->
  <nav class="navbar navbar-dark bg-dark shadow-sm">
    <div class="container-fluid">
      <div class="navbar-brand">
        <i class="fas fa-heart"></i> Aaron & Princillia
      </div>
      <div class="d-flex align-items-center gap-3">
        <span class="admin-name"><i class="fas fa-user-shield"></i> <?= htmlspecialchars($_SESSION['admin_username'] ?? 'Admin'); ?></span>
        <a href="admin_logout.php" class="btn btn-danger">
          <i class="fas fa-sign-out-alt"></i> Déconnexion
        </a>
      </div>
    </div>
  </nav>

  <!-- Main Container -->
  <div class="container-fluid py-4">
    <!-- Header -->
    <div class="dashboard-header text-center mb-4">
      <h1 class="header-title">
        <i class="fas fa-clipboard-list"></i> Gestion des Invitations
      </h1>
    </div>

    <!-- Stats Cards -->
    <div class="row g-4 mb-4">
      <div class="col-12 col-sm-6 col-md-4">
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-users"></i></div>
          <div class="stat-number"><?= $stats['total'] ?? 0 ?></div>
          <div class="stat-label">Invitations totales</div>
        </div>
      </div>
      <div class="col-12 col-sm-6 col-md-4">
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
          <div class="stat-number"><?= $stats['confirmed'] ?? 0 ?></div>
          <div class="stat-label">Confirmées</div>
        </div>
      </div>
      <div class="col-12 col-sm-6 col-md-4">
        <div class="stat-card">
          <div class="stat-icon"><i class="fas fa-heart"></i></div>
          <div class="stat-number"><?= $stats['couples'] ?? 0 ?></div>
          <div class="stat-label">Couples</div>
        </div>
      </div>
    </div>

    <!-- Actions Bar -->
    <div class="row mb-4">
      <div class="col-12">
        <div class="d-flex flex-wrap gap-2">
          <a href="admin_dashboard.php?export=csv" class="btn btn-primary">
            <i class="fas fa-download"></i> Exporter CSV
          </a>
          <a href="admin_add_invite.php" class="btn btn-success">
            <i class="fas fa-user-plus"></i> Ajouter un invité
          </a>
          <a href="admin_stats.php" class="btn btn-outline-dark">
            📊 Voir les statistiques
          </a>
          <a href="admin_caroussel.php" class="btn btn-info">
            <i class="fas fa-images"></i> Gérer les photos
          </a>
          <a href="admin_messages.php" class="btn btn-warning">
            <i class="fas fa-envelope"></i> Gérer les messages
          </a>
          <a href="admin_location.php" class="btn btn-secondary">📍 Gérer le lieu
          </a>
        </div>
      </div>
    </div>

    <!-- Filtres -->
    <div class="row mb-4">
      <div class="col-12">
        <div class="btn-group" role="group">
          <a href="?filter=all&page=1" class="btn btn-outline-<?= $filter === 'all' ? 'dark active' : 'secondary' ?>">Tous</a>
          <a href="?filter=confirmed&page=1" class="btn btn-outline-<?= $filter === 'confirmed' ? 'success active' : 'secondary' ?>">✅ Confirmés</a>
          <a href="?filter=pending&page=1" class="btn btn-outline-<?= $filter === 'pending' ? 'warning active' : 'secondary' ?>">⏳ En attente</a>
          <a href="?filter=couple&page=1" class="btn btn-outline-<?= $filter === 'couple' ? 'primary active' : 'secondary' ?>">💑 Couples</a>
          <a href="?filter=single&page=1" class="btn btn-outline-<?= $filter === 'single' ? 'info active' : 'secondary' ?>">👤 Célibataires</a>
        </div>
      </div>
    </div>

    <!-- Search Box -->
    <div class="row mb-4">
      <div class="col-12">
        <div class="search-box">
          <input type="text"
            id="searchInput"
            class="search-input form-control"
            placeholder="🔍 Rechercher par nom, conjoint, email, téléphone ou code invitation..."
            autocomplete="off">
          <p class="search-help">La recherche se lance automatiquement à partir de 2 caractères.</p>
        </div>
      </div>
    </div>

    <!-- Table -->
    <div class="row">
  <div class="col-12">
    <div class="table-container">
      <div class="table-responsive">
        <!-- 🔑 UN SEUL formulaire, qui englobe TOUT -->
        <form method="POST">
          <table class="table mb-0">
            <thead>
              <tr>
                <!-- ✅ Nouvelle colonne pour la case "Sélectionner tout" -->
                <th><input type="checkbox" id="select-all"></th>
                <th>Type</th>
                <th>Nom complet</th>
                <th>Conjoint</th>
                <th>Téléphone</th>
                <th>Code</th>
                <th>Table</th>
                <th>Statut</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody id="inviteTableBody">
              <?php if (empty($invitations)): ?>
                <tr>
                  <td colspan="9"> <!-- ⚠️ 9 colonnes maintenant (1 de plus) -->
                    <div class="empty-state">
                      <div class="empty-icon"><i class="fas fa-inbox"></i></div>
                      <p>Aucune invitation trouvée.</p>
                    </div>
                  </td>
                </tr>
              <?php else: ?>
                <?php foreach ($invitations as $inv): ?>
                  <tr data-id="<?= $inv['id'] ?>">
                    <!-- ✅ Case à cocher dans sa propre colonne -->
                    <td><input type="checkbox" name="ids[]" value="<?= $inv['id'] ?>"></td>
                    <td>
                      <span class="badge <?= ($inv['type_invitation'] === 'couple') ? 'bg-success' : 'bg-info' ?>">
                        <?= ucfirst($inv['type_invitation']) ?>
                      </span>
                    </td>
                    <td><?= htmlspecialchars(($inv['titre1'] ?? '') . ' ' . $inv['nom']) ?></td>
                    <td>
                      <?php if ($inv['type_invitation'] === 'couple' && !empty($inv['nom2'])): ?>
                        <?= htmlspecialchars(($inv['titre2'] ?? '') . ' ' . $inv['nom2']) ?>
                      <?php else: ?>
                        <span style="color: #999;">—</span>
                      <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($inv['telephone']) ?></td>
                    <td>
                      <code style="background: #f0f0f0; padding: 0.25rem 0.5rem; border-radius: 4px;">
                        <?= htmlspecialchars($inv['code_invitation']) ?>
                      </code>
                    </td>
                    <td><?= htmlspecialchars($inv['table_num'] ?? '—') ?></td>
                    <td>
                      <span class="badge <?= !empty($inv['status']) ? 'bg-success' : 'bg-secondary' ?>">
                        <?= !empty($inv['status']) ? '✓ Confirmée' : '⏳ En attente' ?>
                      </span>
                    </td>
                    <td>
                      <div class="action-buttons">
                        <?php if (!empty($inv['status'])): ?>
                          <a class="btn btn-sm btn-warning" href="admin_dashboard.php?action=invalidate&id=<?= $inv['id'] ?>">
                            <i class="fas fa-times"></i> Annuler
                          </a>
                        <?php else: ?>
                          <a class="btn btn-sm btn-success" href="admin_dashboard.php?action=validate&id=<?= $inv['id'] ?>">
                            <i class="fas fa-check"></i> Valider
                          </a>
                        <?php endif; ?>
                        <button class="btn btn-sm btn-view" onclick="openDetailsModal(<?= htmlspecialchars(json_encode($inv)) ?>)">
                          <i class="fas fa-eye"></i> Voir
                        </button>
                        <button class="btn btn-sm" style="background: #25D366; color: white;" onclick="sendWhatsApp('<?= htmlspecialchars($inv['telephone']) ?>', '<?= htmlspecialchars($inv['code_invitation']) ?>', '<?= htmlspecialchars(($inv['titre1'] ?? '') . ' ' . $inv['nom']) ?>')">
                          <i class="fab fa-whatsapp"></i> WhatsApp
                        </button>
                        <button class="btn btn-sm" style="background: #6c757d; color: white;" onclick="copyInviteLink('<?= htmlspecialchars($inv['code_invitation']) ?>')">
                          <i class="fas fa-link"></i> Copier lien
                        </button>
                        <a class="btn btn-sm btn-edit" href="admin_modifier.php?id=<?= $inv['id'] ?>">
                          <i class="fas fa-edit"></i> Modifier
                        </a>
                      </div>
                    </td>
                  </tr>
                <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>

          <!-- ✅ Actions + pagination EN DEHORS du tableau, mais DANS le formulaire -->
          <div class="d-flex flex-wrap justify-content-between align-items-center mt-3">
            <div>
              <select name="action" class="form-select d-inline" style="width:auto;">
                <option value="">Actions groupées</option>
                <option value="confirm_bulk">✅ Confirmer sélection</option>
                <option value="whatsapp_bulk">📲 WhatsApp sélection</option>
              </select>
              <button type="submit" class="btn btn-outline-dark" onclick="return confirm('Appliquer l\'action ?')">
                Appliquer
              </button>
            </div>

            <!-- Pagination (optionnellement dans le formulaire, mais pas obligé) -->
            <nav>
              <ul class="pagination mb-0">
                <?php if ($page > 1): ?>
                  <li class="page-item"><a class="page-link" href="?filter=<?= $filter ?>&page=<?= $page - 1 ?>">Précédent</a></li>
                <?php endif; ?>
                <li class="page-item active"><span class="page-link">Page <?= $page ?> / <?= $totalPages ?></span></li>
                <?php if ($page < $totalPages): ?>
                  <li class="page-item"><a class="page-link" href="?filter=<?= $filter ?>&page=<?= $page + 1 ?>">Suivant</a></li>
                <?php endif; ?>
              </ul>
            </nav>
          </div>
        </form> <!-- 🔚 Fermeture du formulaire -->
      </div>
    </div>
  </div>
</div>
  </div>

  <!-- Modal Details -->
  <div id="detailsModal" class="modal fade" tabindex="-1">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">
        <div class="modal-header">
          <h2 class="modal-title">Détails de l'invité</h2>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
        </div>
        <div class="modal-body" id="modalBodyContent">
          <!-- Content will be inserted here -->
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fermer</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Bootstrap JS -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // WhatsApp Function
    function sendWhatsApp(phone, code, name) {
      const cleanPhone = phone.replace(/[^\d]/g, '');
      const whatsappPhone = cleanPhone.startsWith('225') ? cleanPhone : cleanPhone;
      const message = `Bonjour ${name},\n\n
Nous avons le plaisir de vous inviter à notre *Mariage Coutumier*, qui aura lieu !\n\n
Date : *20 Décembre 2025* dans la Salle SPLENDEUR.
Votre code d'invitation: *${code}*\n\n
Veuillez utiliser ce code pour confirmer votre présence à cette célébration au lien ci-dessous.
Merci!
Pour les couples invités, une seule personne peut répondre pour deux, en indiquant 2 personnes avec vos coordonnées.
Au plaisir de vous compter parmi nous.
            
*Aaron & Princillia*
https://bit.ly/43ED9ki`;
      const encodedMessage = encodeURIComponent(message);
      const whatsappUrl = `https://wa.me/${whatsappPhone}?text=${encodedMessage}`;
      window.open(whatsappUrl, '_blank');
    }

    // Copy Invite Link Function
    function copyInviteLink(code) {
      const inviteUrl = `${window.location.origin}/aaronandprincillia/essaye_confirm_invit.php?code=${code}`;
      navigator.clipboard.writeText(inviteUrl).then(() => {
        showNotification('✅ Lien copié dans le presse-papiers !', 'success');
      }).catch(() => {
        const textarea = document.createElement('textarea');
        textarea.value = inviteUrl;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        showNotification('✅ Lien copié dans le presse-papiers !', 'success');
      });
    }

    // Notification Function
    function showNotification(message, type) {
      const notification = document.createElement('div');
      notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: ${type === 'success' ? '#28a745' : '#dc3545'};
                color: white;
                padding: 1rem 1.5rem;
                border-radius: 8px;
                box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
                z-index: 2000;
                animation: slideInRight 0.3s ease;
                font-weight: 600;
            `;
      notification.textContent = message;
      document.body.appendChild(notification);
      setTimeout(() => {
        notification.remove();
      }, 3000);
    }

    // Modal Functions
    function openDetailsModal(data) {
      const content = `
                <div class="detail-group">
                    <div class="detail-label">👤 Information personnelle</div>
                    <div class="row">
                        <div class="col-12 col-md-6">
                            <div class="detail-label">Nom</div>
                            <div class="detail-value">${escapeHtml(data.titre1 || '')} ${escapeHtml(data.nom)}</div>
                        </div>
                        <div class="col-12 col-md-6">
                            <div class="detail-label">Type</div>
                            <div class="detail-value">${data.type_invitation === 'couple' ? '💑 Couple' : '👤 Célibataire'}</div>
                        </div>
                    </div>
                </div>

                ${data.type_invitation === 'couple' ? `
                <div class="detail-group">
                    <div class="detail-label">💑 Conjoint(e)</div>
                    <div class="detail-value">${escapeHtml(data.titre2 || '')} ${escapeHtml(data.nom2 || '')}</div>
                </div>
                ` : ''}

                <div class="detail-group">
                    <div class="detail-label">📞 Contact</div>
                    <div class="row">
                        <div class="col-12 col-md-6">
                            <div class="detail-label">Téléphone</div>
                            <div class="detail-value"><a href="tel:${escapeHtml(data.telephone)}">${escapeHtml(data.telephone)}</a></div>
                        </div>
                        <div class="col-12 col-md-6">
                            <div class="detail-label">Email</div>
                            <div class="detail-value"><a href="mailto:${escapeHtml(data.email)}">${escapeHtml(data.email)}</a></div>
                        </div>
                    </div>
                </div>

                <div class="detail-group">
                    <div class="detail-label">🎫 Invitation</div>
                    <div class="row">
                        <div class="col-12 col-md-6">
                            <div class="detail-label">Code</div>
                            <div class="detail-value"><code class="bg-light p-2 rounded">${escapeHtml(data.code_invitation)}</code></div>
                        </div>
                        <div class="col-12 col-md-6">
                            <div class="detail-label">Table</div>
                            <div class="detail-value">${escapeHtml(data.table_num || '—')}</div>
                        </div>
                    </div>
                </div>

                <div class="detail-group">
                    <div class="detail-label">✅ Statut</div>
                    <div class="detail-value">
                        <span class="badge ${data.status ? 'bg-success' : 'bg-secondary'}">
                            ${data.status ? '✓ Confirmation reçue' : '⏳ En attente de confirmation'}
                        </span>
                    </div>
                </div>

                <div class="detail-group">
                    <div class="detail-label">📅 Date d'inscription</div>
                    <div class="detail-value">${escapeHtml(data.date_created)}</div>
                </div>
            `;
      document.getElementById('modalBodyContent').innerHTML = content;
      const modal = new bootstrap.Modal(document.getElementById('detailsModal'));
      modal.show();
    }

    function escapeHtml(text) {
      const map = {
        '&': '&amp;',
        '<': '<',
        '>': '>',
        '"': '&quot;',
        "'": '&#039;'
      };
      return text.replace(/[&<>"']/g, m => map[m]);
    }

    // Search functionality
    document.addEventListener("DOMContentLoaded", function() {
      const searchInput = document.getElementById("searchInput");
      const tableBody = document.getElementById("inviteTableBody");
      const originalTable = tableBody.innerHTML;

      function fetchAndRender(query) {
        fetch("dashboard_search_invit.php?q=" + encodeURIComponent(query), {
            credentials: "same-origin"
          })
          .then(res => res.text())
          .then(html => {
            tableBody.innerHTML = html;
          })
          .catch(() => {
            tableBody.innerHTML = '<tr><td colspan="8" class="text-center text-danger">Erreur lors de la recherche.</td></tr>';
          });
      }

      searchInput.addEventListener("input", function() {
        const q = this.value.trim();

        if (q === "") {
          tableBody.innerHTML = originalTable;
          return;
        }
        if (q.length >= 2) {
          fetchAndRender(q);
        }
      });
    });
  </script>
  <script>
  document.getElementById('select-all').addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('input[name="ids[]"]');
    checkboxes.forEach(cb => cb.checked = this.checked);
  });
</script>
</body>

</html>