<?php
require_once __DIR__ . '/../includes/config.php';
$db = getDB();

$success = false; 
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRF($_POST['csrf_token'] ?? '')) {
        $error = "Session expirée. Veuillez réessayer.";
    } else {
        $nom = sanitize($_POST['nom'] ?? '');
        $email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
        $phone = sanitize($_POST['phone'] ?? '');
        $message = sanitize($_POST['message'] ?? '');
        $profil_je_suis = sanitize($_POST['profil_je_suis'] ?? '');
        $profil_je_le_suis = sanitize($_POST['profil_je_le_suis'] ?? '');
        $property_id = !empty($_POST['property_id']) ? (int)$_POST['property_id'] : null;

        if (!$nom || !$email || !$message) {
            $error = "Veuillez remplir tous les champs obligatoires (*).";
        } else {
            $stmt = $db->prepare("INSERT INTO contact_messages (nom, email, phone, message, profil_je_suis, profil_je_le_suis, property_id) VALUES (?,?,?,?,?,?,?)");
            if ($stmt->execute([$nom, $email, $phone, $message, $profil_je_suis, $profil_je_le_suis, $property_id])) {
                $success = true;

                sendNotificationEmail('contact_notification', [
                    'nom' => $nom,
                    'email' => $email,
                    'profil' => $profil_je_suis . ($profil_je_le_suis ? ' / ' . $profil_je_le_suis : ''),
                    'message' => $message,
                ]);
            } else {
                $error = "Une erreur est survenue lors de l'envoi du message.";
            }
        }
    }
}

$prop = null;
if (!empty($_GET['property_id'])) {
    $stmt = $db->prepare("SELECT id, title FROM properties WHERE id = ?");
    $stmt->execute([$_GET['property_id']]);
    $prop = $stmt->fetch();
}

$headerStyle = 'transparent'; 
$currentPage = 'contact';
?>
<!DOCTYPE html>
<html lang="fr" class="scroll-smooth">
<head>
  <?= renderHead('Contactez AJOUAMAI IMMO-BUSINESS — Dar Bouazza', 'Contactez Hind Ajouamai et l\'équipe AJOUAMAI IMMO-BUSINESS pour vos projets immobiliers.') ?>
</head>
<body class="bg-offwhite text-dark font-sans">
<?php include __DIR__ . '/../components/header.php'; ?>

<!-- HERO BANNER -->
<section class="relative h-[55vh] min-h-[450px] flex items-center justify-center overflow-hidden bg-black text-white">
  <img src="<?= SITE_URL ?>/assets/img/project-2.jpg" data-parallax-speed="0.2" class="parallax-bg absolute inset-0 w-full h-[120%] object-cover opacity-60" alt="Contact AJOUAMAI IMMO-BUSINESS"/>
  <div class="absolute inset-0 bg-gradient-to-t from-black via-black/40 to-black/60"></div>
  
  <div class="relative z-10 text-center px-6 max-w-4xl mx-auto reveal-scale">
    <p class="text-[11px] tracking-[0.35em] uppercase font-sans mb-4 text-gold font-medium">À VOTRE ÉCOUTE</p>
    <h1 class="font-serif text-4xl sm:text-6xl font-light tracking-tight mb-4">Contactez Notre Équipe</h1>
    <div class="w-16 h-px bg-gold mx-auto mb-4"></div>
    <p class="text-sm font-sans text-gray-300 font-light max-w-lg mx-auto">
      Un accompagnement réactif et personnalisé pour concrétiser vos ambitions immobilières.
    </p>
  </div>
</section>

<!-- MAIN CONTACT SECTION -->
<section class="py-24 bg-white">
  <div class="max-w-7xl mx-auto px-6 grid lg:grid-cols-12 gap-16">
    
    <!-- LEFT: FORM -->
    <div class="lg:col-span-7 reveal-left bg-offwhite p-10 sm:p-14 border border-gray-200/80 shadow-lg">
      
      <div class="mb-10 border-b border-gray-200 pb-4">
        <p class="text-[10px] tracking-[0.3em] uppercase text-gold font-sans font-semibold mb-1">FORMULAIRE DE CONTACT</p>
        <h2 class="font-serif text-3xl font-light text-black">Envoyez-nous un message</h2>
      </div>

      <?php if($success): ?>
        <div class="bg-emerald-900/10 border border-emerald-700/30 p-6 mb-8 text-center text-emerald-900 font-sans text-sm">
          ✓ Votre message a été transmis avec succès. Notre équipe vous recontactera sous 24h.
        </div>
      <?php endif; ?>

      <?php if($error): ?>
        <div class="bg-rose-900/10 border border-rose-700/30 p-6 mb-8 text-center text-rose-900 font-sans text-sm">
          <?= htmlspecialchars($error) ?>
        </div>
      <?php endif; ?>

      <?php if($prop): ?>
        <div class="border-l-2 border-gold p-4 mb-8 bg-white text-xs font-sans text-gray-700">
          <span class="text-gold font-semibold uppercase tracking-wider block mb-1">Demande concernant la propriété :</span>
          <strong><?= htmlspecialchars($prop['title']) ?></strong>
        </div>
      <?php endif; ?>

      <form method="POST" id="contact-form" class="space-y-8" novalidate>
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(generateCSRF()) ?>"/>
        <?php if($prop): ?><input type="hidden" name="property_id" value="<?= $prop['id'] ?>"/><?php endif; ?>

        <!-- Sélecteur : "Je suis" -->
        <div>
          <label class="block text-xs tracking-[0.2em] uppercase font-sans text-black font-medium mb-3">Je suis *</label>
          <div class="grid grid-cols-3 gap-3">
            <?php foreach(['Propriétaire', 'Acheteur', 'Locataire'] as $prof): ?>
            <label class="cursor-pointer">
              <input type="radio" name="profil_je_suis" value="<?= $prof ?>" class="peer hidden" checked/>
              <div class="border border-gray-300 bg-white text-center py-3 text-xs tracking-wider uppercase font-sans peer-checked:bg-black peer-checked:text-white peer-checked:border-black transition-all hover:border-black">
                <?= $prof ?>
              </div>
            </label>
            <?php endforeach; ?>
          </div>
        </div>

        <!-- Nom complet -->
        <div>
          <label class="block text-xs tracking-[0.2em] uppercase font-sans text-black font-medium mb-2">Nom & Prénom *</label>
          <input type="text" name="nom" required class="input-underline" placeholder="Votre nom complet"/>
        </div>

        <!-- Email & Téléphone -->
        <div class="grid sm:grid-cols-2 gap-8">
          <div>
            <label class="block text-xs tracking-[0.2em] uppercase font-sans text-black font-medium mb-2">Adresse Email *</label>
            <input type="email" name="email" required class="input-underline" placeholder="votre@email.com"/>
          </div>
          <div>
            <label class="block text-xs tracking-[0.2em] uppercase font-sans text-black font-medium mb-2">Téléphone</label>
            <input type="tel" name="phone" class="input-underline" placeholder="+212 6 XX XX XX XX"/>
          </div>
        </div>

        <!-- Message -->
        <div>
          <label class="block text-xs tracking-[0.2em] uppercase font-sans text-black font-medium mb-2">Votre Message *</label>
          <textarea name="message" rows="5" required class="input-underline resize-none" placeholder="Précisez votre demande ou projet immobilier..."></textarea>
        </div>

        <!-- Sélecteur 2 : Profil d'investissement -->
        <div>
          <label class="block text-xs tracking-[0.2em] uppercase font-sans text-black font-medium mb-3">Mon projet concerne</label>
          <div class="grid grid-cols-2 sm:grid-cols-4 gap-2">
            <?php foreach(['Investissement', 'Résidence principale', 'Résidence secondaire', 'Conseil'] as $prof2): ?>
            <label class="cursor-pointer">
              <input type="radio" name="profil_je_le_suis" value="<?= $prof2 ?>" class="peer hidden"/>
              <div class="border border-gray-300 bg-white text-center py-2.5 text-[11px] font-sans peer-checked:bg-gold peer-checked:text-white peer-checked:border-gold transition-all hover:border-gold">
                <?= $prof2 ?>
              </div>
            </label>
            <?php endforeach; ?>
          </div>
        </div>

        <!-- Submit Button -->
        <button type="submit" class="btn-lemonde-consultation w-full">
          <span>Envoyer mon message</span>
          <svg class="w-4 h-4 ml-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M17.25 8.25L21 12m0 0l-3.75 3.75M21 12H3"/></svg>
        </button>
      </form>

    </div>

    <!-- RIGHT: DIRECT DIRECTORY INFO & FAST ACTION CARDS -->
    <div class="lg:col-span-5 reveal-right space-y-8 flex flex-col justify-between">
      
      <div class="bg-offwhite p-10 border border-gray-200/80 space-y-8">
        <div>
          <p class="text-[10px] tracking-[0.3em] uppercase text-gold font-sans font-semibold mb-2">AGENCE DIRECTE</p>
          <h3 class="font-serif text-2xl font-light text-black">AJOUAMAI IMMO-BUSINESS</h3>
          <p class="text-xs text-gray-500 font-sans mt-1">Sidi Rahal Casablanca</p>
        </div>

        <div class="space-y-6 pt-6 border-t border-gray-200 text-xs font-sans">
          <div class="flex items-start gap-4">
            <div class="w-8 h-8 bg-black text-gold flex items-center justify-center flex-shrink-0">📞</div>
            <div>
              <span class="text-gray-400 uppercase tracking-widest text-[9px] block mb-1">Téléphone & WhatsApp</span>
              <p class="text-dark font-medium"><?= htmlspecialchars(getSetting('agency_phone', '+212 600-000000')) ?></p>
            </div>
          </div>

          <div class="flex items-start gap-4">
            <div class="w-8 h-8 bg-black text-gold flex items-center justify-center flex-shrink-0">✉️</div>
            <div>
              <span class="text-gray-400 uppercase tracking-widest text-[9px] block mb-1">Courrier Électronique</span>
              <p class="text-dark font-medium"><?= htmlspecialchars(getSetting('notification_email', 'contact@aib-immobilier.ma')) ?></p>
            </div>
          </div>
        </div>
      </div>

      <!-- ESTIMATION CARD -->
      <div class="bg-black text-white p-8 border border-gold/30">
        <p class="text-[10px] tracking-[0.3em] uppercase text-gold font-sans font-semibold mb-2">ESTIMATION SUR MESURE</p>
        <h3 class="font-serif text-2xl font-light mb-3">Faire estimer mon bien</h3>
        <p class="text-xs text-gray-400 font-sans mb-6 leading-relaxed">Évaluation objective, rapide et confidentielle sous 48h par Hind Ajouamai.</p>
        <a href="<?= SITE_URL ?>/pages/estimation" class="btn-gold-outline inline-flex w-full text-center justify-center">
          Demander une estimation →
        </a>
      </div>

      <!-- RDV CARD -->
      <div class="bg-offwhite p-8 border border-gray-200">
        <p class="text-[10px] tracking-[0.3em] uppercase text-gray-400 font-sans font-semibold mb-2">PRISE DE RENDEZ-VOUS</p>
        <h3 class="font-serif text-2xl font-light text-black mb-3">Réserver une consultation</h3>
        <p class="text-xs text-gray-500 font-sans mb-6 leading-relaxed">Discutons de votre projet immobilier autour d'un échange personnalisé.</p>
        <a href="<?= SITE_URL ?>/pages/rdv" class="block text-center border border-black text-black text-xs tracking-[0.2em] uppercase py-3.5 hover:bg-black hover:text-white transition-all font-sans font-medium">
          Choisir un créneau →
        </a>
      </div>

    </div>

  </div>
</section>

<?php include __DIR__ . '/../components/footer.php'; ?>
<script src="<?= SITE_URL ?>/assets/js/app.js"></script>
</body>
</html>
