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

$success = false; $error = '';

// Handle slot query (AJAX)
if (isset($_GET['slots']) && isset($_GET['creneau'])) {
    header('Content-Type: application/json');
    $creneau = sanitize($_GET['creneau']);
    $date = sanitize($_GET['date'] ?? '');
    $slots = getAvailableSlots($creneau);
    // Filter out taken slots
    if ($date) {
        $slots = array_filter($slots, function($h) use ($date) {
            return !isSlotTaken($date, $h . ':00');
        });
    }
    echo json_encode(array_values($slots));
    exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRF($_POST['csrf_token'] ?? '')) {
        $error = "Session expirée. Veuillez réessayer.";
    } else {
        $prenom = sanitize($_POST['prenom'] ?? '');
        $nom    = sanitize($_POST['nom'] ?? '');
        $email  = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
        $mobile = sanitize($_POST['mobile'] ?? '');
        $indicatif = sanitize($_POST['indicatif'] ?? '+212');
        $date_rdv  = sanitize($_POST['date_rdv'] ?? '');
        $creneau   = sanitize($_POST['creneau'] ?? '');
        $heure     = sanitize($_POST['heure'] ?? '');
        $recherche = !empty($_POST['recherche_bien']) ? 1 : 0;

        if (!$prenom || !$nom || !$email || !$mobile || !$date_rdv || !$creneau || !$heure) {
            $error = "Veuillez remplir tous les champs obligatoires.";
        } elseif (strtotime($date_rdv) < strtotime(date('Y-m-d'))) {
            $error = "Veuillez choisir une date future.";
        } elseif (isDateBlocked($date_rdv)) {
            $error = "Cette date n'est pas disponible. Veuillez en choisir une autre.";
        } elseif (isSlotTaken($date_rdv, $heure . ':00')) {
            $error = "Ce créneau est déjà pris. Veuillez en choisir un autre.";
        } else {
            $criteres = null;
            if ($recherche && !empty($_POST['criteres'])) {
                $criteres = json_encode([
                    'zone'     => sanitize($_POST['criteres']['zone'] ?? ''),
                    'type_bien'=> sanitize($_POST['criteres']['type_bien'] ?? ''),
                    'budget'   => sanitize($_POST['criteres']['budget'] ?? ''),
                ]);
            }

            $stmt = $db->prepare("INSERT INTO rdv_requests (prenom, nom, email, mobile, indicatif, date_rdv, creneau, heure, recherche_bien, criteres_recherche) VALUES (?,?,?,?,?,?,?,?,?,?)");
            if ($stmt->execute([$prenom, $nom, $email, $mobile, $indicatif, $date_rdv, $creneau, $heure . ':00', $recherche, $criteres])) {
                $success = true;
                $dateFormatted = date('d/m/Y', strtotime($date_rdv));
                // Notify agency
                sendNotificationEmail('rdv_notification_agency', [
                    'prenom'=>$prenom,'nom'=>$nom,'email'=>$email,
                    'mobile'=>$mobile,'indicatif'=>$indicatif,
                    'date'=>$dateFormatted,'heure'=>$heure,
                ]);
                // Confirm to client
                sendNotificationEmail('rdv_confirmation_client', [
                    'prenom'=>$prenom,'date'=>$dateFormatted,'heure'=>$heure,
                ], $email);
                // WhatsApp (if configured)
                sendWhatsAppNotification($indicatif . $mobile, "Bonjour $prenom, votre RDV AJOUAMAI IMMO-BUSINESS est confirmé le $dateFormatted à $heure.");
            } else {
                $error = "Une erreur est survenue. Veuillez réessayer.";
            }
        }
    }
}

$introTitle   = getPageContent('rdv', 'intro', 'title', 'Prendre rendez-vous');
$introContent = getPageContent('rdv', 'intro', 'content', '');
$zones = getZones();
$types = getPropertyTypes();
$headerStyle = 'solid'; $currentPage = 'rdv';
?>
<!DOCTYPE html>
<html lang="fr" class="scroll-smooth">
<head>
  <?= renderHead('Prendre Rendez-vous', 'Prenez rendez-vous avec AJOUAMAI IMMO-BUSINESS pour votre projet immobilier à Dar Bouazza.') ?>
  <style>
    .calendar-day { transition: all 0.15s ease; }
    .calendar-day:hover:not(.disabled):not(.empty) { background: #000; color: #fff; }
    .calendar-day.selected { background: #000; color: #fff; }
    .calendar-day.today { border-color: #000; }
    .calendar-day.disabled { opacity: 0.3; cursor: not-allowed; }
    .slot-btn { transition: all 0.15s ease; }
    .slot-btn:hover:not(:disabled) { background: #000; color: #fff; border-color: #000; }
    .slot-btn.selected { background: #000; color: #fff; border-color: #000; }
    .slot-btn:disabled { opacity: 0.3; cursor: not-allowed; }
  </style>
</head>
<body class="bg-[#F5F5F5] text-gray-800 font-sans">
<?php include __DIR__.'/../components/header.php'; ?>

<!-- Intro -->
<section class="pt-32 pb-12 bg-white border-b border-gray-100">
  <div class="max-w-3xl mx-auto px-6 text-center reveal">
    <p class="text-[11px] tracking-[0.25em] uppercase text-gray-400 font-sans mb-4">Prise de RDV</p>
    <h1 class="font-serif text-4xl md:text-5xl font-light text-black mb-6"><?= htmlspecialchars($introTitle) ?></h1>
    <?php if ($introContent): ?>
      <p class="text-gray-500 font-sans leading-relaxed"><?= htmlspecialchars(strip_tags($introContent)) ?></p>
    <?php endif; ?>
  </div>
</section>

<section class="py-16">
  <div class="max-w-3xl mx-auto px-6">

    <?php if($success): ?>
    <div class="bg-white border border-gray-200 p-10 mb-10 text-center reveal">
      <div class="w-16 h-16 border-2 border-black rounded-full flex items-center justify-center mx-auto mb-6">
        <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M5 13l4 4L19 7"/></svg>
      </div>
      <h2 class="font-serif text-3xl font-light text-black mb-3">Rendez-vous confirmé</h2>
      <p class="text-gray-500 font-sans">Un email de confirmation vous a été envoyé. Notre équipe sera ravie de vous accueillir.</p>
    </div>
    <?php endif; ?>
    <?php if($error): ?>
    <div class="bg-gray-50 border border-red-200 p-6 mb-8 reveal">
      <p class="text-sm text-red-700 font-sans"><?= htmlspecialchars($error) ?></p>
    </div>
    <?php endif; ?>

    <form method="POST" id="rdv-form" class="space-y-12 reveal delay-100" novalidate>
      <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(generateCSRF()) ?>"/>
      <input type="hidden" name="date_rdv" id="selected-date-input"/>
      <input type="hidden" name="heure" id="selected-time-input"/>

      <!-- ══════ CALENDRIER ══════ -->
      <div>
        <div class="flex items-center gap-4 mb-6">
          <span class="font-serif text-3xl font-light text-black/20">01</span>
          <h2 class="font-serif text-xl font-light text-black">Choisir une date</h2>
        </div>

        <div class="bg-white border border-gray-200 p-6">
          <!-- Month Navigation -->
          <div class="flex items-center justify-between mb-6">
            <button type="button" id="prev-month" class="p-2 hover:opacity-60 transition-opacity">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M15 19l-7-7 7-7"/></svg>
            </button>
            <h3 id="month-title" class="font-serif text-lg font-light text-black"></h3>
            <button type="button" id="next-month" class="p-2 hover:opacity-60 transition-opacity">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 5l7 7-7 7"/></svg>
            </button>
          </div>
          <!-- Day headers -->
          <div class="grid grid-cols-7 text-center mb-2">
            <?php foreach(['Lu','Ma','Me','Je','Ve','Sa','Di'] as $d): ?>
            <div class="text-[10px] tracking-[0.15em] uppercase text-gray-400 font-sans py-1"><?=$d?></div>
            <?php endforeach; ?>
          </div>
          <!-- Days grid -->
          <div id="calendar-grid" class="grid grid-cols-7 gap-1"></div>
          <!-- Selected date display -->
          <div id="selected-date-display" class="mt-4 text-center text-sm font-sans text-gray-500 hidden">
            Date sélectionnée : <span id="selected-date-text" class="font-medium text-black"></span>
          </div>
        </div>
      </div>

      <!-- ══════ CRÉNEAU ══════ -->
      <div id="creneau-section" class="hidden">
        <div class="flex items-center gap-4 mb-6">
          <span class="font-serif text-3xl font-light text-black/20">02</span>
          <h2 class="font-serif text-xl font-light text-black">Choisir un créneau</h2>
        </div>
        <div class="flex gap-3">
          <?php foreach(['matin'=>'Matin','apres_midi'=>'Après-midi','soir'=>'Soir'] as $v=>$l): ?>
          <label class="cursor-pointer flex-1">
            <input type="radio" name="creneau" value="<?=$v?>" class="peer hidden creneau-radio"/>
            <div class="border border-gray-200 text-center py-3 text-sm font-sans peer-checked:bg-black peer-checked:text-white peer-checked:border-black transition-all hover:border-black"><?=$l?></div>
          </label>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- ══════ HORAIRES ══════ -->
      <div id="horaires-section" class="hidden">
        <div class="flex items-center gap-4 mb-6">
          <span class="font-serif text-3xl font-light text-black/20">03</span>
          <h2 class="font-serif text-xl font-light text-black">Choisir un horaire</h2>
        </div>
        <div id="slots-grid" class="grid grid-cols-4 sm:grid-cols-6 gap-2"></div>
        <div id="slots-loading" class="hidden text-center py-4 text-sm text-gray-400 font-sans">Chargement...</div>
      </div>

      <!-- ══════ COORDONNÉES ══════ -->
      <div id="contact-section" class="hidden">
        <div class="flex items-center gap-4 mb-6">
          <span class="font-serif text-3xl font-light text-black/20">04</span>
          <h2 class="font-serif text-xl font-light text-black">Vos coordonnées</h2>
        </div>
        <div class="space-y-8">
          <div class="grid sm:grid-cols-2 gap-8">
            <div>
              <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Prénom *</label>
              <input type="text" name="prenom" required class="input-underline" placeholder="Votre prénom"/>
            </div>
            <div>
              <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Nom *</label>
              <input type="text" name="nom" required class="input-underline" placeholder="Votre nom"/>
            </div>
          </div>
          <div>
            <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Email *</label>
            <input type="email" name="email" required class="input-underline" placeholder="votre@email.com"/>
          </div>
          <div>
            <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Mobile *</label>
            <div class="flex gap-3 items-end">
              <select name="indicatif" class="select-underline w-32 flex-shrink-0">
                <?php
                $indicatifs = ['+212'=>'🇲🇦 +212','+33'=>'🇫🇷 +33','+1'=>'🇺🇸 +1','+44'=>'🇬🇧 +44','+34'=>'🇪🇸 +34','+39'=>'🇮🇹 +39','+49'=>'🇩🇪 +49','+32'=>'🇧🇪 +32','+41'=>'🇨🇭 +41','+351'=>'🇵🇹 +351','+216'=>'🇹🇳 +216','+213'=>'🇩🇿 +213','+20'=>'🇪🇬 +20'];
                foreach($indicatifs as $code=>$label): ?>
                <option value="<?=$code?>" <?=$code==='+212'?'selected':''?>><?=$label?></option>
                <?php endforeach; ?>
              </select>
              <input type="tel" name="mobile" required class="input-underline flex-1" placeholder="6 XX XX XX XX"/>
            </div>
          </div>
        </div>
      </div>

      <!-- ══════ RECHERCHE DE BIEN ══════ -->
      <div id="recherche-section" class="hidden">
        <div class="bg-[#F5F5F5] p-8">
          <p class="text-sm font-sans text-gray-700 mb-4 font-medium">Êtes-vous aussi à la recherche d'un bien immobilier ?</p>
          <div class="flex gap-3 mb-0" id="recherche-toggle">
            <label class="cursor-pointer">
              <input type="radio" name="recherche_bien" value="1" class="peer hidden"/>
              <div class="border border-gray-300 px-6 py-3 text-sm font-sans peer-checked:bg-black peer-checked:text-white peer-checked:border-black transition-all hover:border-black">Oui</div>
            </label>
            <label class="cursor-pointer">
              <input type="radio" name="recherche_bien" value="0" class="peer hidden"/>
              <div class="border border-gray-300 px-6 py-3 text-sm font-sans peer-checked:bg-black peer-checked:text-white peer-checked:border-black transition-all hover:border-black">Non</div>
            </label>
          </div>
          <!-- Bloc critères -->
          <div id="criteres-bloc" class="hidden mt-6 space-y-4 border-t border-gray-200 pt-6">
            <p class="text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-4">Informations complémentaires</p>
            <div class="grid sm:grid-cols-3 gap-4">
              <div>
                <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Zone souhaitée</label>
                <select name="criteres[zone]" class="select-underline">
                  <option value="">Toutes les zones</option>
                  <?php foreach($zones as $z): ?><option value="<?=htmlspecialchars($z)?>"><?=htmlspecialchars($z)?></option><?php endforeach; ?>
                </select>
              </div>
              <div>
                <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Type de bien</label>
                <select name="criteres[type_bien]" class="select-underline">
                  <option value="">Tous types</option>
                  <?php foreach($types as $slug=>$label): ?><option value="<?=$slug?>"><?=htmlspecialchars($label)?></option><?php endforeach; ?>
                </select>
              </div>
              <div>
                <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Budget (MAD)</label>
                <input type="text" name="criteres[budget]" class="input-underline" placeholder="Ex: 1 500 000"/>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Submit -->
      <div id="submit-section" class="hidden">
        <button type="submit" class="w-full bg-black text-white text-xs tracking-[0.15em] uppercase py-5 hover:bg-gray-900 transition-colors font-sans text-sm">
          Confirmer le rendez-vous
        </button>
      </div>
    </form>
  </div>
</section>

<?php include __DIR__.'/../components/footer.php'; ?>
<script src="<?= SITE_URL ?>/assets/js/app.js"></script>
<script>
(function() {
  const SITE_URL = '<?= SITE_URL ?>';
  let selectedDate = null;
  let selectedTime = null;

  // ── CALENDAR ──────────────────────────────────
  let viewYear = new Date().getFullYear();
  let viewMonth = new Date().getMonth();
  const today = new Date(); today.setHours(0,0,0,0);

  const monthNames = ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'];

  function renderCalendar() {
    document.getElementById('month-title').textContent = monthNames[viewMonth] + ' ' + viewYear;
    const grid = document.getElementById('calendar-grid');
    grid.innerHTML = '';

    const firstDay = new Date(viewYear, viewMonth, 1).getDay();
    const daysInMonth = new Date(viewYear, viewMonth + 1, 0).getDate();
    const startOffset = (firstDay === 0 ? 6 : firstDay - 1); // Monday start

    for (let i = 0; i < startOffset; i++) {
      const empty = document.createElement('div');
      empty.classList.add('calendar-day', 'empty', 'p-2');
      grid.appendChild(empty);
    }

    for (let d = 1; d <= daysInMonth; d++) {
      const dateObj = new Date(viewYear, viewMonth, d);
      const dateStr = `${viewYear}-${String(viewMonth+1).padStart(2,'0')}-${String(d).padStart(2,'0')}`;
      const dayEl = document.createElement('button');
      dayEl.type = 'button';
      dayEl.textContent = d;
      dayEl.classList.add('calendar-day', 'w-full', 'p-2', 'text-sm', 'font-sans', 'border', 'border-transparent', 'text-center');

      const isPast = dateObj < today;
      const isSunday = dateObj.getDay() === 0;
      const isToday = dateObj.getTime() === today.getTime();

      if (isPast || isSunday) {
        dayEl.classList.add('disabled', 'text-gray-300');
        dayEl.disabled = true;
      } else {
        if (isToday) dayEl.classList.add('today', 'border-black');
        if (dateStr === selectedDate) dayEl.classList.add('selected');
        dayEl.addEventListener('click', () => selectDate(dateStr, dayEl));
      }
      grid.appendChild(dayEl);
    }
  }

  function selectDate(dateStr, el) {
    selectedDate = dateStr;
    document.getElementById('selected-date-input').value = dateStr;
    document.querySelectorAll('.calendar-day').forEach(d => d.classList.remove('selected'));
    el.classList.add('selected');
    // Show formatted date
    const parts = dateStr.split('-');
    const formatted = `${parts[2]}/${parts[1]}/${parts[0]}`;
    document.getElementById('selected-date-text').textContent = formatted;
    document.getElementById('selected-date-display').classList.remove('hidden');
    // Show creneau section
    document.getElementById('creneau-section').classList.remove('hidden');
    // Reset time selection
    selectedTime = null;
    document.getElementById('selected-time-input').value = '';
    document.getElementById('horaires-section').classList.add('hidden');
    document.getElementById('contact-section').classList.add('hidden');
    document.getElementById('recherche-section').classList.add('hidden');
    document.getElementById('submit-section').classList.add('hidden');
    document.querySelectorAll('.creneau-radio').forEach(r => r.checked = false);
    document.getElementById('slots-grid').innerHTML = '';
  }

  document.getElementById('prev-month').addEventListener('click', () => {
    viewMonth--; if(viewMonth < 0) { viewMonth = 11; viewYear--; }
    renderCalendar();
  });
  document.getElementById('next-month').addEventListener('click', () => {
    viewMonth++; if(viewMonth > 11) { viewMonth = 0; viewYear++; }
    renderCalendar();
  });

  renderCalendar();

  // ── CRÉNEAU ──────────────────────────────────
  document.querySelectorAll('.creneau-radio').forEach(r => r.addEventListener('change', function() {
    loadSlots(this.value);
  }));

  function loadSlots(creneau) {
    const grid = document.getElementById('slots-grid');
    const loading = document.getElementById('slots-loading');
    grid.innerHTML = ''; loading.classList.remove('hidden');
    document.getElementById('horaires-section').classList.remove('hidden');

    fetch(`${SITE_URL}/pages/rdv?slots=1&creneau=${encodeURIComponent(creneau)}&date=${encodeURIComponent(selectedDate)}`)
      .then(r => r.json())
      .then(slots => {
        loading.classList.add('hidden');
        if (slots.length === 0) {
          grid.innerHTML = '<p class="col-span-6 text-sm text-gray-400 font-sans text-center py-4">Aucun créneau disponible pour ce moment.</p>';
          return;
        }
        slots.forEach(h => {
          const btn = document.createElement('button');
          btn.type = 'button';
          btn.textContent = h;
          btn.classList.add('slot-btn', 'border', 'border-gray-200', 'py-2', 'text-sm', 'font-sans', 'text-center');
          btn.addEventListener('click', () => selectTime(h, btn));
          grid.appendChild(btn);
        });
      })
      .catch(() => { loading.classList.add('hidden'); grid.innerHTML = '<p class="col-span-6 text-sm text-red-400 font-sans text-center py-4">Erreur de chargement.</p>'; });
  }

  function selectTime(h, btn) {
    selectedTime = h;
    document.getElementById('selected-time-input').value = h;
    document.querySelectorAll('.slot-btn').forEach(b => b.classList.remove('selected'));
    btn.classList.add('selected');
    document.getElementById('contact-section').classList.remove('hidden');
    document.getElementById('recherche-section').classList.remove('hidden');
    document.getElementById('submit-section').classList.remove('hidden');
  }

  // ── RECHERCHE BIEN ──────────────────────────────────
  document.querySelectorAll('[name="recherche_bien"]').forEach(r => r.addEventListener('change', function() {
    const bloc = document.getElementById('criteres-bloc');
    if (this.value === '1') bloc.classList.remove('hidden');
    else bloc.classList.add('hidden');
  }));

  // ── VALIDATION ──────────────────────────────────
  document.getElementById('rdv-form').addEventListener('submit', function(e) {
    const errors = [];
    if (!selectedDate) errors.push('Veuillez sélectionner une date.');
    if (!document.querySelector('.creneau-radio:checked')) errors.push('Veuillez choisir un créneau (Matin/Après-midi/Soir).');
    if (!selectedTime) errors.push('Veuillez choisir un horaire.');
    if (!this.querySelector('[name="prenom"]').value.trim()) errors.push('Le prénom est obligatoire.');
    if (!this.querySelector('[name="nom"]').value.trim()) errors.push('Le nom est obligatoire.');
    const email = this.querySelector('[name="email"]').value.trim();
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) errors.push('Email invalide.');
    if (!this.querySelector('[name="mobile"]').value.trim()) errors.push('Le mobile est obligatoire.');

    if (errors.length > 0) { e.preventDefault(); alert(errors.join('\n')); }
  });
})();
</script>
</body></html>
