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

// Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRF($_POST['csrf_token'] ?? '')) {
    // Update RDV status
    if (!empty($_POST['update_status'])) {
        $db->prepare("UPDATE rdv_requests SET status = ? WHERE id = ?")
           ->execute([sanitize($_POST['status']), (int)$_POST['id']]);
        setFlash('success','Statut mis à jour.');
    }
    // Save slot setting
    if (!empty($_POST['save_settings'])) {
        foreach(['matin','apres_midi','soir'] as $c) {
            $db->prepare("UPDATE rdv_settings SET heure_debut=?, heure_fin=?, intervalle_minutes=?, actif=? WHERE creneau=?")
               ->execute([$_POST[$c.'_debut']??'08:00', $_POST[$c.'_fin']??'12:00', (int)($_POST[$c.'_interval']??30), !empty($_POST[$c.'_actif'])?1:0, $c]);
        }
        setFlash('success','Paramètres de créneaux mis à jour.');
    }
    // Add blackout
    if (!empty($_POST['add_blackout'])) {
        $db->prepare("INSERT INTO rdv_blackouts (date_debut, date_fin, motif) VALUES (?,?,?)")
           ->execute([$_POST['date_debut'], $_POST['date_fin'], sanitize($_POST['motif']??'')]);
        setFlash('success','Période d\'indisponibilité ajoutée.');
    }
    // Delete blackout
    if (!empty($_POST['delete_blackout'])) {
        $db->prepare("DELETE FROM rdv_blackouts WHERE id = ?")->execute([(int)$_POST['blackout_id']]);
        setFlash('success','Période supprimée.');
    }
    redirect(SITE_URL . '/admin/rdv.php');
}

// Load data
$rdvs = $db->query("SELECT * FROM rdv_requests ORDER BY date_rdv DESC, heure DESC")->fetchAll();
$settings = $db->query("SELECT * FROM rdv_settings ORDER BY FIELD(creneau,'matin','apres_midi','soir')")->fetchAll();
$blackouts = $db->query("SELECT * FROM rdv_blackouts ORDER BY date_debut DESC LIMIT 20")->fetchAll();

// Group RDVs by date for calendar
$rdvByDate = [];
foreach ($rdvs as $r) { $rdvByDate[$r['date_rdv']][] = $r; }

$pageTitle = 'Gestion des Rendez-vous'; $activeNav = 'rdv';
include __DIR__ . '/layout.php';
?>

<!-- Tabs -->
<div class="flex gap-1 mb-8 border-b border-gray-200">
  <button onclick="showTab('agenda')" id="tab-agenda" class="tab-btn px-5 py-2.5 text-sm font-sans border-b-2 border-black">Agenda</button>
  <button onclick="showTab('settings')" id="tab-settings" class="tab-btn px-5 py-2.5 text-sm font-sans border-b-2 border-transparent text-gray-400 hover:text-black transition-colors">Créneaux</button>
  <button onclick="showTab('blackouts')" id="tab-blackouts" class="tab-btn px-5 py-2.5 text-sm font-sans border-b-2 border-transparent text-gray-400 hover:text-black transition-colors">Indisponibilités</button>
</div>

<!-- Tab: Agenda -->
<div id="tab-content-agenda">
  <div class="bg-white border border-gray-200">
    <div class="p-5 border-b border-gray-100 flex justify-between items-center">
      <h2 class="font-serif text-lg font-light text-black">Liste des RDV</h2>
      <span class="text-xs text-gray-400 font-sans"><?=count($rdvs)?> RDV au total</span>
    </div>
    <table class="w-full admin-table">
      <thead class="border-b border-gray-100"><tr>
        <th>Client</th><th>Date & Heure</th><th>Créneau</th><th>Recherche bien</th><th>Statut</th><th></th>
      </tr></thead>
      <tbody>
        <?php if(empty($rdvs)): ?>
        <tr><td colspan="6" class="text-center py-12 text-gray-400">Aucun RDV enregistré.</td></tr>
        <?php endif; ?>
        <?php foreach($rdvs as $r): ?>
        <tr>
          <td>
            <div class="font-medium text-black"><?=htmlspecialchars($r['prenom'].' '.$r['nom'])?></div>
            <div class="text-xs text-gray-400"><?=htmlspecialchars($r['email'])?></div>
            <div class="text-xs text-gray-400"><?=htmlspecialchars($r['indicatif'].' '.$r['mobile'])?></div>
          </td>
          <td>
            <div class="font-medium"><?=date('d/m/Y',strtotime($r['date_rdv']))?></div>
            <div class="text-xs text-gray-400"><?=htmlspecialchars(substr($r['heure'],0,5))?></div>
          </td>
          <td class="text-xs capitalize text-gray-600"><?=str_replace('_',' ',$r['creneau'])?></td>
          <td>
            <?php if($r['recherche_bien']): ?>
              <span class="text-[9px] tracking-[0.1em] uppercase px-2 py-0.5 bg-black text-white">Oui</span>
            <?php else: ?>
              <span class="text-xs text-gray-400">Non</span>
            <?php endif; ?>
          </td>
          <td>
            <form method="POST" class="flex gap-1">
              <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
              <input type="hidden" name="id" value="<?=$r['id']?>"/>
              <select name="status" class="border border-gray-200 text-[10px] font-sans px-2 py-1 focus:outline-none">
                <?php foreach(['en_attente','confirme','annule','realise'] as $s): ?>
                <option value="<?=$s?>" <?=$r['status']===$s?'selected':''?>><?=ucfirst(str_replace('_',' ',$s))?></option>
                <?php endforeach; ?>
              </select>
              <button type="submit" name="update_status" class="bg-black text-white text-[10px] px-2 py-1 font-sans">OK</button>
            </form>
          </td>
          <td>
            <?php if($r['recherche_bien'] && $r['criteres_recherche']): ?>
            <?php $c = json_decode($r['criteres_recherche'],true); ?>
            <div class="text-[10px] text-gray-400 font-sans">
              <?=htmlspecialchars($c['zone']??'')?>
              <?=htmlspecialchars($c['type_bien']??'')?>
              <?=htmlspecialchars($c['budget']??'')?>
            </div>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Tab: Settings -->
<div id="tab-content-settings" class="hidden">
  <form method="POST" class="bg-white border border-gray-200 p-8 max-w-2xl">
    <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
    <h2 class="font-serif text-xl font-light text-black mb-6">Configuration des créneaux</h2>
    <?php
    $settingsMap = [];
    foreach($settings as $s) $settingsMap[$s['creneau']] = $s;
    $creneaux = ['matin'=>'Matin','apres_midi'=>'Après-midi','soir'=>'Soir'];
    foreach($creneaux as $key=>$label):
      $s = $settingsMap[$key] ?? ['heure_debut'=>'08:00','heure_fin'=>'12:00','intervalle_minutes'=>30,'actif'=>1];
    ?>
    <div class="border border-gray-100 p-6 mb-4">
      <div class="flex items-center justify-between mb-4">
        <h3 class="font-serif text-lg font-light text-black"><?=$label?></h3>
        <label class="flex items-center gap-2 cursor-pointer">
          <input type="checkbox" name="<?=$key?>_actif" <?=$s['actif']?'checked':''?> class="w-4 h-4 accent-black"/>
          <span class="text-sm font-sans">Actif</span>
        </label>
      </div>
      <div class="grid grid-cols-3 gap-4">
        <div>
          <label class="text-[10px] tracking-[0.15em] uppercase text-gray-400 font-sans block mb-1">Début</label>
          <input type="time" name="<?=$key?>_debut" value="<?=htmlspecialchars(substr($s['heure_debut'],0,5))?>" class="input-underline"/>
        </div>
        <div>
          <label class="text-[10px] tracking-[0.15em] uppercase text-gray-400 font-sans block mb-1">Fin</label>
          <input type="time" name="<?=$key?>_fin" value="<?=htmlspecialchars(substr($s['heure_fin'],0,5))?>" class="input-underline"/>
        </div>
        <div>
          <label class="text-[10px] tracking-[0.15em] uppercase text-gray-400 font-sans block mb-1">Intervalle (min)</label>
          <input type="number" name="<?=$key?>_interval" value="<?=(int)$s['intervalle_minutes']?>" min="15" max="120" step="15" class="input-underline"/>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
    <button type="submit" name="save_settings" class="bg-black text-white text-xs tracking-[0.15em] uppercase px-6 py-3 font-sans hover:bg-gray-900 transition-colors">Enregistrer</button>
  </form>
</div>

<!-- Tab: Blackouts -->
<div id="tab-content-blackouts" class="hidden">
  <div class="grid md:grid-cols-2 gap-6">
    <!-- Add blackout -->
    <form method="POST" class="bg-white border border-gray-200 p-8">
      <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
      <h2 class="font-serif text-xl font-light text-black mb-6">Ajouter une indisponibilité</h2>
      <div class="space-y-4">
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label class="text-[10px] tracking-[0.15em] uppercase text-gray-400 font-sans block mb-1">Du</label>
            <input type="date" name="date_debut" required min="<?=date('Y-m-d')?>" class="input-underline"/>
          </div>
          <div>
            <label class="text-[10px] tracking-[0.15em] uppercase text-gray-400 font-sans block mb-1">Au</label>
            <input type="date" name="date_fin" required min="<?=date('Y-m-d')?>" class="input-underline"/>
          </div>
        </div>
        <div>
          <label class="text-[10px] tracking-[0.15em] uppercase text-gray-400 font-sans block mb-1">Motif</label>
          <input type="text" name="motif" placeholder="Ex: Vacances, Indisponibilité..." class="input-underline"/>
        </div>
        <button type="submit" name="add_blackout" class="w-full bg-black text-white text-xs tracking-[0.15em] uppercase py-3 font-sans hover:bg-gray-900 transition-colors">Ajouter</button>
      </div>
    </form>
    <!-- List blackouts -->
    <div class="bg-white border border-gray-200">
      <div class="p-5 border-b border-gray-100"><h2 class="font-serif text-lg font-light text-black">Périodes bloquées</h2></div>
      <?php if(empty($blackouts)): ?>
        <p class="p-5 text-sm text-gray-400 font-sans">Aucune indisponibilité.</p>
      <?php else: ?>
      <div class="divide-y divide-gray-50">
        <?php foreach($blackouts as $b): ?>
        <div class="p-4 flex justify-between items-center">
          <div>
            <p class="text-sm font-medium text-black font-sans"><?=date('d/m/Y',strtotime($b['date_debut']))?> → <?=date('d/m/Y',strtotime($b['date_fin']))?></p>
            <?php if($b['motif']): ?><p class="text-xs text-gray-400 font-sans"><?=htmlspecialchars($b['motif'])?></p><?php endif; ?>
          </div>
          <form method="POST" class="inline">
            <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
            <input type="hidden" name="blackout_id" value="<?=$b['id']?>"/>
            <button type="submit" name="delete_blackout" class="text-xs text-red-400 hover:text-red-600 transition-colors font-sans" onclick="return confirm('Supprimer?')">Supprimer</button>
          </form>
        </div>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<?php include __DIR__ . '/layout_footer.php'; ?>
<script>
function showTab(name) {
  ['agenda','settings','blackouts'].forEach(t => {
    document.getElementById('tab-content-' + t).classList.add('hidden');
    document.getElementById('tab-' + t).classList.remove('border-black');
    document.getElementById('tab-' + t).classList.add('border-transparent','text-gray-400');
  });
  document.getElementById('tab-content-' + name).classList.remove('hidden');
  document.getElementById('tab-' + name).classList.add('border-black');
  document.getElementById('tab-' + name).classList.remove('border-transparent','text-gray-400');
}
</script>
