<?php
session_start();

if (!isset($_SESSION['admin_id'])) {
  header("Location: admin_login.php");
  exit;
}

if (
  !isset($_SESSION['user_agent'], $_SESSION['ip']) ||
  $_SESSION['user_agent'] !== ($_SERVER['HTTP_USER_AGENT'] ?? '') ||
  $_SESSION['ip'] !== ($_SERVER['REMOTE_ADDR'] ?? '')
) {
  session_destroy();
  header("Location: admin_login.php");
  exit;
}

if (empty($_SESSION['admin_logged_in'])) {
  header('Location: admin_login.php');
  exit;
}

// 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());
}

$message = '';
$erreur = '';

// Récupérer l'ID de l'invité à modifier
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
  $erreur = "ID invité invalide.";
} else {
  $id = (int)$_GET['id'];

  // Récupérer les données actuelles
  $stmt = $pdo->prepare("SELECT * FROM invites WHERE id = ?");
  $stmt->execute([$id]);
  $invité = $stmt->fetch();

  if (!$invité) {
    $erreur = "Invité non trouvé.";
  }
}

// Traitement du formulaire
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['modifier'])) {
  $type = $_POST['type_invitation'] ?? '';
  $titre1 = trim($_POST['titre1'] ?? '');
  $nom = trim($_POST['nom'] ?? '');
  $titre2 = trim($_POST['titre2'] ?? '');
  $nom2 = trim($_POST['nom2'] ?? '');
  $email = trim($_POST['email'] ?? '');
  $telephone = trim($_POST['telephone'] ?? '');
  $table_num = trim($_POST['table_num'] ?? '');
  $status = (int)($_POST['status'] ?? 0);

  if (empty($titre1) || empty($nom) || empty($telephone)) {
    $erreur = "Les champs Nom complet et Téléphone sont obligatoires.";
  } else {
    try {
      $sql = "UPDATE invites SET type_invitation = ?, titre1 = ?, nom = ?, titre2 = ?, nom2 = ?, email = ?, telephone = ?, table_num = ?, status = ? WHERE id = ?";
      $stmt = $pdo->prepare($sql);
      $stmt->execute([$type, $titre1, $nom, $titre2, $nom2, $email, $telephone, $table_num, $status, $id]);
      $message = "Invité mis à jour avec succès !";
      // Rafraîchir les données
      $stmt = $pdo->prepare("SELECT * FROM invites WHERE id = ?");
      $stmt->execute([$id]);
      $invité = $stmt->fetch();
    } catch (PDOException $e) {
      $erreur = "Erreur lors de la mise à jour : " . $e->getMessage();
    }
  }
}
?>
<!DOCTYPE html>
<html lang="fr">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Modifier Invité - Admin</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);
    }

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

    .form-label {
      font-weight: 600;
      color: #d4a574;
    }

    .btn-submit {
      background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
      color: white;
      padding: 0.75rem 2rem;
      border-radius: 8px;
      font-weight: 600;
      transition: all 0.3s ease;
    }

    .btn-submit:hover {
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(212, 165, 116, 0.3);
    }

    .alert {
      border-radius: 10px;
    }
  </style>
</head>

<body>
  <!-- Navbar -->
  <nav class="navbar navbar-dark bg-dark shadow-sm">
    <div class="container-fluid">
      <a class="navbar-brand" href="admin_dashboard.php">
        <i class="fas fa-heart"></i> Aaron & Princillia
      </a>
      <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">
    <div class="row justify-content-center">
      <div class="col-12 col-lg-8">
        <div class="card-modifier">
          <h2 class="text-center mb-4">
            <i class="fas fa-user-edit"></i> Modifier un Invité
          </h2>

          <?php if ($erreur): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($erreur) ?></div>
          <?php endif; ?>

          <?php if ($message): ?>
            <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
          <?php endif; ?>

          <?php if ($invité): ?>
            <form method="POST">
              <div class="row">
                <div class="col-md-6 mb-3">
                  <label class="form-label">Type d'invitation</label>
                  <select name="type_invitation" class="form-select" required>
                    <option value="single" <?= $invité['type_invitation'] === 'single' ? 'selected' : '' ?>>Célibataire</option>
                    <option value="couple" <?= $invité['type_invitation'] === 'couple' ? 'selected' : '' ?>>Couple</option>
                  </select>
                </div>
                <div class="col-md-6 mb-3">
                  <label class="form-label">Statut</label>
                  <select name="status" class="form-select">
                    <option value="0" <?= !$invité['status'] ? 'selected' : '' ?>>En attente</option>
                    <option value="1" <?= $invité['status'] ? 'selected' : '' ?>>Confirmé</option>
                  </select>
                </div>
              </div>

              <div class="row">
                <div class="col-md-6 mb-3">
                  <label class="form-label">Titre 1</label>
                  <input type="text" name="titre1" class="form-control" value="<?= htmlspecialchars($invité['titre1'] ?? '') ?>" required>
                </div>
                <div class="col-md-6 mb-3">
                  <label class="form-label">Nom complet</label>
                  <input type="text" name="nom" class="form-control" value="<?= htmlspecialchars($invité['nom'] ?? '') ?>" required>
                </div>
              </div>

              <div class="row">
                <div class="col-md-6 mb-3">
                  <label class="form-label">Titre 2 (Conjoint)</label>
                  <input type="text" name="titre2" class="form-control" value="<?= htmlspecialchars($invité['titre2'] ?? '') ?>">
                </div>
                <div class="col-md-6 mb-3">
                  <label class="form-label">Nom conjoint(e)</label>
                  <input type="text" name="nom2" class="form-control" value="<?= htmlspecialchars($invité['nom2'] ?? '') ?>">
                </div>
              </div>

              <div class="row">
                <div class="col-md-6 mb-3">
                  <label class="form-label">Email</label>
                  <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($invité['email'] ?? '') ?>">
                </div>
                <div class="col-md-6 mb-3">
                  <label class="form-label">Téléphone</label>
                  <input type="text" name="telephone" class="form-control" value="<?= htmlspecialchars($invité['telephone'] ?? '') ?>" required>
                </div>
              </div>

              <div class="mb-3">
                <label class="form-label">Numéro de table</label>
                <input type="text" name="table_num" class="form-control" value="<?= htmlspecialchars($invité['table_num'] ?? '') ?>">
              </div>

              <div class="d-flex justify-content-between">
                <a href="admin_dashboard.php" class="btn btn-secondary">
                  <i class="fas fa-arrow-left"></i> Retour
                </a>
                <button type="submit" name="modifier" class="btn btn-submit">
                  <i class="fas fa-save"></i> Sauvegarder
                </button>
              </div>
            </form>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <!-- Bootstrap JS -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>