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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRF($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'] ?? '';

    // Add Zone
    if ($action === 'add_zone') {
        $name = sanitize($_POST['name_zone'] ?? '');
        if ($name) {
            $db->prepare("INSERT IGNORE INTO zones (name, slug, ordre) VALUES (?,?,?)")
               ->execute([$name, slugify($name), $db->query("SELECT COALESCE(MAX(ordre),0)+1 FROM zones")->fetchColumn()]);
            setFlash('success', "Zone \"$name\" ajoutée.");
        }
    }
    // Delete Zone
    if ($action === 'delete_zone') {
        $db->prepare("DELETE FROM zones WHERE id = ?")->execute([(int)$_POST['zone_id']]);
        setFlash('success', 'Zone supprimée.');
    }
    // Reorder zones
    if ($action === 'reorder_zones' && !empty($_POST['ordre'])) {
        foreach ($_POST['ordre'] as $id => $ord) {
            $db->prepare("UPDATE zones SET ordre = ? WHERE id = ?")->execute([(int)$ord, (int)$id]);
        }
        setFlash('success', 'Ordre mis à jour.');
    }
    // Add Type
    if ($action === 'add_type') {
        $name = sanitize($_POST['name_type'] ?? '');
        if ($name) {
            $db->prepare("INSERT IGNORE INTO property_types (name, slug, ordre) VALUES (?,?,?)")
               ->execute([$name, slugify($name), $db->query("SELECT COALESCE(MAX(ordre),0)+1 FROM property_types")->fetchColumn()]);
            setFlash('success', "Type \"$name\" ajouté.");
        }
    }
    // Delete Type
    if ($action === 'delete_type') {
        $db->prepare("DELETE FROM property_types WHERE id = ?")->execute([(int)$_POST['type_id']]);
        setFlash('success', 'Type supprimé.');
    }

    redirect(SITE_URL . '/admin/taxonomies');
}

$zones = $db->query("SELECT * FROM zones ORDER BY ordre ASC")->fetchAll();
$types = $db->query("SELECT * FROM property_types ORDER BY ordre ASC")->fetchAll();

$pageTitle = 'Zones & Types de bien'; $activeNav = 'taxonomies';
include __DIR__ . '/layout.php';
?>

<div class="grid md:grid-cols-2 gap-8">
  <!-- ZONES -->
  <div>
    <div class="bg-white border border-gray-200 mb-4">
      <div class="p-5 border-b border-gray-100"><h2 class="font-serif text-lg font-light text-black">Zones</h2></div>
      <ul id="zones-list" class="divide-y divide-gray-50">
        <?php foreach($zones as $z): ?>
        <li class="flex items-center justify-between px-5 py-3">
          <span class="text-sm font-sans text-black"><?=htmlspecialchars($z['name'])?></span>
          <form method="POST" class="inline">
            <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
            <input type="hidden" name="action" value="delete_zone"/>
            <input type="hidden" name="zone_id" value="<?=$z['id']?>"/>
            <button type="submit" class="text-xs text-red-400 hover:text-red-600 font-sans" onclick="return confirm('Supprimer cette zone ?')">Supprimer</button>
          </form>
        </li>
        <?php endforeach; ?>
        <?php if(empty($zones)): ?>
        <li class="px-5 py-6 text-sm text-gray-400 font-sans text-center">Aucune zone.</li>
        <?php endif; ?>
      </ul>
    </div>
    <!-- Add Zone -->
    <form method="POST" class="flex gap-2">
      <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
      <input type="hidden" name="action" value="add_zone"/>
      <input type="text" name="name_zone" placeholder="Nouvelle zone..." required class="flex-1 border border-gray-200 px-4 py-2 text-sm font-sans focus:outline-none focus:border-black"/>
      <button type="submit" class="bg-black text-white text-xs tracking-[0.1em] uppercase px-4 py-2 font-sans hover:bg-gray-900 transition-colors">Ajouter</button>
    </form>
    <p class="text-xs text-gray-400 font-sans mt-2">Les zones alimentent la barre de recherche et les formulaires d'estimation/RDV.</p>
  </div>

  <!-- TYPES -->
  <div>
    <div class="bg-white border border-gray-200 mb-4">
      <div class="p-5 border-b border-gray-100"><h2 class="font-serif text-lg font-light text-black">Types de bien</h2></div>
      <ul class="divide-y divide-gray-50">
        <?php foreach($types as $t): ?>
        <li class="flex items-center justify-between px-5 py-3">
          <span class="text-sm font-sans text-black"><?=htmlspecialchars($t['name'])?> <span class="text-xs text-gray-400 ml-2">(<?=htmlspecialchars($t['slug'])?>)</span></span>
          <form method="POST" class="inline">
            <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
            <input type="hidden" name="action" value="delete_type"/>
            <input type="hidden" name="type_id" value="<?=$t['id']?>"/>
            <button type="submit" class="text-xs text-red-400 hover:text-red-600 font-sans" onclick="return confirm('Supprimer ce type ?')">Supprimer</button>
          </form>
        </li>
        <?php endforeach; ?>
        <?php if(empty($types)): ?>
        <li class="px-5 py-6 text-sm text-gray-400 font-sans text-center">Aucun type.</li>
        <?php endif; ?>
      </ul>
    </div>
    <!-- Add Type -->
    <form method="POST" class="flex gap-2">
      <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
      <input type="hidden" name="action" value="add_type"/>
      <input type="text" name="name_type" placeholder="Nouveau type de bien..." required class="flex-1 border border-gray-200 px-4 py-2 text-sm font-sans focus:outline-none focus:border-black"/>
      <button type="submit" class="bg-black text-white text-xs tracking-[0.1em] uppercase px-4 py-2 font-sans hover:bg-gray-900 transition-colors">Ajouter</button>
    </form>
    <p class="text-xs text-gray-400 font-sans mt-2">Les types de bien alimentent dynamiquement la recherche et les filtres de propriétés.</p>
  </div>
</div>

<?php include __DIR__ . '/layout_footer.php'; ?>
