<?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
// =====================
$message = '';
$isSuccess = false;

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 DB : " . $e->getMessage());
}

// =====================
// 3) Générateur de code unique
// =====================
function generateCode($length = 5)
{
    return strtoupper(substr(bin2hex(random_bytes($length)), 0, $length));
}

// =====================
// 4) Traitement formulaire
// =====================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type       = $_POST['type_invitation'] ?? '';
    $titre1     = trim($_POST['titre1'] ?? '');
    $nom        = trim($_POST['nom'] ?? '');
    $email      = trim($_POST['email'] ?? '');
    $telephone  = trim($_POST['telephone'] ?? '');
    $table_num  = intval($_POST['table_num'] ?? 0);

    // Conjoint (optionnel)
    $titre2     = trim($_POST['titre2'] ?? '');
    $nom2       = trim($_POST['nom2'] ?? '');

    // =====================
    // 4a) Validation
    // =====================
    if ($nom === '' || !filter_var($email, FILTER_VALIDATE_EMAIL) || $telephone === '' || $table_num <= 0) {
        $message = "Merci de remplir tous les champs obligatoires correctement.";
    } else {
        // Nettoyage du téléphone (garder que les chiffres)
        $telephone = preg_replace('/\D/', '', $telephone);

        // Si type = single → pas besoin de conjoint
        if ($type === 'single') {
            $titre2 = null;
            $nom2   = null;
        }

        // =====================
        // 4b) Vérification existence
        // =====================
        $stmt = $pdo->prepare("SELECT * FROM invites WHERE telephone = ?");
        $stmt->execute([$telephone]);
        $existingInvite = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existingInvite) {
            // =====================
            // 4c) Mise à jour si existe déjà
            // =====================
            $updateStmt = $pdo->prepare("
                UPDATE invites 
                SET type_invitation = ?, titre1 = ?, nom = ?, titre2 = ?, nom2 = ?, 
                    table_num = ?, email = ? 
                WHERE telephone = ?
            ");
            $updateStmt->execute([$type, $titre1, $nom, $titre2, $nom2, $table_num, $email, $telephone]);

            $message = "✅ Invité mis à jour avec succès !<br>Code invitation : <strong>" . htmlspecialchars($existingInvite['code_invitation']) . "</strong>";
            $isSuccess = true;
        } else {
            // =====================
            // 4d) Génération code unique
            // =====================
            do {
                $code_invitation = generateCode(5);
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM invites WHERE code_invitation = ?");
                $stmt->execute([$code_invitation]);
                $count = $stmt->fetchColumn();
            } while ($count > 0);

            // =====================
            // 4e) Insertion nouvel invité
            // =====================
            $insertStmt = $pdo->prepare("
                INSERT INTO invites 
                (type_invitation, titre1, nom, titre2, nom2, email, telephone, table_num, code_invitation, status, qr_code) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'Est invité', '')
            ");
            $insertStmt->execute([$type, $titre1, $nom, $titre2, $nom2, $email, $telephone, $table_num, $code_invitation]);

            $message = "✅ Invité ajouté avec succès !<br>Code invitation : <strong>" . htmlspecialchars($code_invitation) . "</strong>";
            $isSuccess = true;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajouter une invitation - 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">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Montserrat', sans-serif;
            background: linear-gradient(135deg, #f5f5f2 0%, #e8e6e1 100%);
            color: #2c2c2c;
            min-height: 100vh;
            padding: 2rem;
        }

        .container {
            max-width: 700px;
            margin: 0 auto;
        }

        .back-button {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            color: #d4a574;
            text-decoration: none;
            font-weight: 600;
            margin-bottom: 2rem;
            transition: all 0.3s ease;
        }

        .back-button:hover {
            color: #8b6f47;
            transform: translateX(-5px);
        }

        .form-card {
            background: white;
            border-radius: 15px;
            padding: 2.5rem;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
        }

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

        .form-subtitle {
            color: #999;
            margin-bottom: 2rem;
            font-size: 0.95rem;
        }

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

        .form-section:last-child {
            border-bottom: none;
        }

        .section-title {
            font-family: 'Playfair Display', serif;
            font-size: 1.3rem;
            color: #d4a574;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            display: block;
            font-weight: 600;
            color: #2c2c2c;
            margin-bottom: 0.7rem;
            font-size: 0.95rem;
        }

        .form-control,
        .form-select {
            width: 100%;
            padding: 0.875rem 1rem;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-family: 'Montserrat', sans-serif;
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }

        .form-control:focus,
        .form-select:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
        }

        .form-control::placeholder {
            color: #ccc;
        }

        .type-selector {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .type-option {
            position: relative;
        }

        .type-option input[type="radio"] {
            display: none;
        }

        .type-label {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            padding: 1rem;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 600;
            background: white;
        }

        .type-option input[type="radio"]:checked + .type-label {
            border-color: #d4a574;
            background: rgba(212, 165, 116, 0.1);
            color: #d4a574;
        }

        .guest-fields {
            background: #f9f9f7;
            padding: 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
        }

        .guest-title {
            display: flex;
            gap: 1rem;
            margin-bottom: 1rem;
            align-items: center;
        }

        .title-radio {
            display: flex;
            gap: 1rem;
        }

        .radio-group {
            display: flex;
            gap: 1.5rem;
            align-items: center;
            margin-bottom: 1rem;
        }

        .radio-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .radio-item input[type="radio"] {
            cursor: pointer;
            width: 18px;
            height: 18px;
            accent-color: #d4a574;
        }

        .radio-item label {
            cursor: pointer;
            font-weight: 500;
            margin: 0;
        }

        .hidden-section {
            display: none;
        }

        .hidden-section.show {
            display: block;
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .submit-button {
            width: 100%;
            padding: 1rem;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }

        .submit-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 30px rgba(212, 165, 116, 0.3);
        }

        .submit-button:active {
            transform: translateY(0);
        }

        @media (max-width: 768px) {
            body {
                padding: 1rem;
            }

            .form-card {
                padding: 1.5rem;
            }

            .form-title {
                font-size: 1.5rem;
            }

            .type-selector {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <a href="admin_dashboard.php" class="back-button">
            <i class="fas fa-arrow-left"></i> Retour au Dashboard
        </a>

        <div class="form-card">
            <h1 class="form-title">
                <i class="fas fa-user-plus"></i> Ajouter une Invitation
            </h1>
            <p class="form-subtitle">Complétez les informations pour ajouter un nouvel invité</p>

            <form method="POST" action="admin_add_invite.php">
                <!-- Type d'invité -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="fas fa-users"></i> Type d'invitation
                    </div>

                    <div class="type-selector">
                        <div class="type-option">
                            <input type="radio" id="single" name="type_invitation" value="single" checked>
                            <label for="single" class="type-label">
                                <i class="fas fa-user"></i> Célibataire
                            </label>
                        </div>
                        <div class="type-option">
                            <input type="radio" id="couple" name="type_invitation" value="couple">
                            <label for="couple" class="type-label">
                                <i class="fas fa-heart"></i> Couple
                            </label>
                        </div>
                    </div>
                </div>

                <!-- Invité 1 -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="fas fa-user"></i> Premier invité
                    </div>

                    <div class="guest-fields">
                        <div class="radio-group">
                            <div class="radio-item">
                                <input type="radio" id="mr1" name="titre1" value="Mr" checked>
                                <label for="mr1">Mr</label>
                            </div>
                            <div class="radio-item">
                                <input type="radio" id="mme1" name="titre1" value="Mme">
                                <label for="mme1">Mme</label>
                            </div>
                            <div class="radio-item">
                                <input type="radio" id="mlle1" name="titre1" value="Mlle">
                                <label for="mlle1">Mlle</label>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="nom" class="form-label">Nom complet *</label>
                            <input type="text" id="nom" name="nom" class="form-control" placeholder="Ex: Jean Dupont" required>
                        </div>

                        <div class="form-group">
                            <label for="email" class="form-label">Email</label>
                            <input type="text" id="email" name="email" class="form-control" placeholder="exemple@email.com">
                        </div>

                        <div class="form-group">
                            <label for="telephone" class="form-label">Téléphone *</label>
                            <input type="tel" id="telephone" name="telephone" class="form-control" placeholder="+225 01 23 45 67 89" required>
                        </div>
                    </div>
                </div>

                <!-- Invité 2 (couple) -->
                <div class="form-section hidden-section" id="coupleSection">
                    <div class="section-title">
                        <i class="fas fa-heart"></i> Conjoint(e)
                    </div>

                    <div class="guest-fields">
                        <div class="radio-group">
                            <div class="radio-item">
                                <input type="radio" id="mr2" name="titre2" value="Mr">
                                <label for="mr2">Mr</label>
                            </div>
                            <div class="radio-item">
                                <input type="radio" id="mme2" name="titre2" value="Mme" checked>
                                <label for="mme2">Mme</label>
                            </div>
                            <div class="radio-item">
                                <input type="radio" id="mlle2" name="titre2" value="Mlle">
                                <label for="mlle2">Mlle</label>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="nom2" class="form-label">Nom complet du conjoint(e)</label>
                            <input type="text" id="nom2" name="nom2" class="form-control" placeholder="Ex: Marie Dupont">
                        </div>
                    </div>
                </div>

                <!-- Détails du mariage -->
                <div class="form-section">
                    <div class="section-title">
                        <i class="fas fa-ring"></i> Détails du mariage
                    </div>

                    <div class="form-group">
                        <label for="table_num" class="form-label">Numéro de table *</label>
                        <input type="number" id="table_num" name="table_num" class="form-control" placeholder="Ex: 5" min="1" required>
                    </div>
                </div>

                <button type="submit" class="submit-button">
                    <i class="fas fa-check"></i> Ajouter l'invité
                </button>
            </form>
        </div>
    </div>

    <script>
        // Toggle couple section
        const typeInputs = document.querySelectorAll('input[name="type_invitation"]');
        const coupleSection = document.getElementById('coupleSection');
        const nom2Input = document.getElementById('nom2');

        typeInputs.forEach(input => {
            input.addEventListener('change', function() {
                if (this.value === 'couple') {
                    coupleSection.classList.add('show');
                } else {
                    coupleSection.classList.remove('show');
                    nom2Input.value = '';
                    document.querySelectorAll('input[name="titre2"]').forEach(r => r.checked = false);
                }
            });
        });
    </script>

    <?php if (isset($message) && $message): ?>
    <script>
        Swal.fire({
            icon: <?= $isSuccess ? "'success'" : "'error'" ?>,
            title: <?= $isSuccess ? "'Succès ! ✅'" : "'Erreur ❌'" ?>,
            html: <?= json_encode($message) ?>,
            confirmButtonColor: '<?= $isSuccess ? "#d4a574" : "#dc3545" ?>',
            confirmButtonText: <?= $isSuccess ? "'Retour au dashboard'" : "'OK'" ?>,
            allowOutsideClick: false
        }).then((result) => {
            if (<?= $isSuccess ? 'true' : 'false' ?>) {
                window.location.href = 'admin_dashboard.php';
            }
        });
    </script>
    <?php endif; ?>

</body>
</html>