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

// DELETE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && verifyCSRF($_POST['csrf_token'] ?? '')) {
    if ($_POST['action'] === 'delete') {
        $id = (int)$_POST['id'];
        // Delete associated images from filesystem
        $imgs = $db->prepare("SELECT image_path FROM property_images WHERE property_id = ?");
        $imgs->execute([$id]);
        foreach ($imgs->fetchAll() as $img) {
            $path = __DIR__ . '/../' . $img['image_path'];
            if (file_exists($path)) @unlink($path);
        }
        $db->prepare("DELETE FROM properties WHERE id = ?")->execute([$id]);
        setFlash('success', 'Propriété supprimée.');
        redirect(SITE_URL . '/admin/properties');
    }
    if ($_POST['action'] === 'toggle_featured') {
        $id = (int)$_POST['id'];
        $db->prepare("UPDATE properties SET featured = NOT featured WHERE id = ?")->execute([$id]);
        redirect(SITE_URL . '/admin/properties');
    }
    if ($_POST['action'] === 'toggle_status') {
        $id = (int)$_POST['id'];
        $db->prepare("UPDATE properties SET publication_status = CASE WHEN publication_status='publie' THEN 'brouillon' ELSE 'publie' END WHERE id = ?")->execute([$id]);
        redirect(SITE_URL . '/admin/properties');
    }
}

// Filters
$where = ['1=1']; $params = [];
if (!empty($_GET['q'])) { $where[] = "(title LIKE ? OR city LIKE ?)"; $q='%'.$_GET['q'].'%'; $params[]=$q; $params[]=$q; }
if (!empty($_GET['type'])) { $where[] = "type = ?"; $params[] = $_GET['type']; }
if (!empty($_GET['status'])) { $where[] = "publication_status = ?"; $params[] = $_GET['status']; }
$whereClause = implode(' AND ', $where);
$properties = $db->prepare("SELECT * FROM properties WHERE $whereClause ORDER BY created_at DESC");
$properties->execute($params);
$properties = $properties->fetchAll();

$pageTitle = 'Gestion des Propriétés'; $activeNav = 'properties';
include __DIR__ . '/layout.php';
?>

<div class="flex justify-between items-center mb-6">
  <!-- Search/Filters -->
  <form method="GET" class="flex gap-3 flex-wrap">
    <input type="text" name="q" value="<?=htmlspecialchars($_GET['q']??'')?>" placeholder="Rechercher..." class="border border-gray-200 px-4 py-2 text-sm font-sans focus:outline-none focus:border-black w-48"/>
    <select name="type" class="border border-gray-200 px-4 py-2 text-sm font-sans focus:outline-none focus:border-black">
      <option value="">Tous types</option>
      <?php foreach(getPropertyTypes() as $v=>$l): ?>
      <option value="<?=$v?>" <?=($_GET['type']??'')===$v?'selected':''?>><?=$l?></option>
      <?php endforeach; ?>
    </select>
    <select name="status" class="border border-gray-200 px-4 py-2 text-sm font-sans focus:outline-none focus:border-black">
      <option value="">Tous statuts</option>
      <option value="publie" <?=($_GET['status']??'')==='publie'?'selected':''?>>Publiés</option>
      <option value="brouillon" <?=($_GET['status']??'')==='brouillon'?'selected':''?>>Brouillons</option>
    </select>
    <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">Filtrer</button>
    <?php if(!empty($_GET['q'])||!empty($_GET['type'])||!empty($_GET['status'])): ?>
    <a href="<?= SITE_URL ?>/admin/properties" class="border border-gray-200 text-xs tracking-[0.1em] uppercase px-4 py-2 font-sans hover:bg-gray-50 transition-colors">Réinitialiser</a>
    <?php endif; ?>
  </form>
  <a href="<?= SITE_URL ?>/admin/property_edit" class="bg-black text-white text-xs tracking-[0.1em] uppercase px-5 py-2.5 font-sans hover:bg-gray-900 transition-colors flex-shrink-0">+ Ajouter</a>
</div>

<!-- Table -->
<div class="bg-white border border-gray-200 overflow-x-auto">
  <table class="w-full admin-table min-w-[600px]">
    <thead class="border-b border-gray-100">
      <tr>
        <th>Propriété</th><th>Type</th><th>Statut</th><th>Prix</th>
        <th class="text-center">Vedette</th><th class="text-center">Publié</th><th class="text-right">Actions</th>
      </tr>
    </thead>
    <tbody>
      <?php if (empty($properties)): ?>
      <tr><td colspan="7" class="text-center py-12 text-gray-400">Aucune propriété trouvée.</td></tr>
      <?php endif; ?>
      <?php foreach ($properties as $prop): ?>
      <tr>
        <td>
          <div class="flex items-center gap-3">
            <img src="<?= htmlspecialchars(getPrimaryImage($prop['id'])) ?>" class="w-12 h-12 object-cover flex-shrink-0 rounded-lg shadow-xs" alt=""/>
            <div>
              <div class="text-sm font-medium text-black line-clamp-1"><?=htmlspecialchars($prop['title'])?></div>
              <div class="text-xs text-gray-400"><?=htmlspecialchars($prop['city'])?></div>
            </div>
          </div>
        </td>
        <td class="capitalize text-gray-600"><?=htmlspecialchars($prop['type'])?></td>
        <td><span class="text-xs"><?= $prop['status'] === 'vente' ? 'Vente' : 'Location' ?></span></td>
        <td class="font-medium"><?=htmlspecialchars($prop['price_label'])?></td>
        <td class="text-center">
          <form method="POST" class="inline">
            <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
            <input type="hidden" name="action" value="toggle_featured"/>
            <input type="hidden" name="id" value="<?=$prop['id']?>"/>
            <button type="submit" class="w-8 h-8 border <?=$prop['featured']?'bg-black border-black':'border-gray-200'?> hover:border-black transition-colors flex items-center justify-center mx-auto">
              <?php if($prop['featured']): ?><svg class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 24 24"><path d="M11.48 3.499a.562.562 0 011.04 0l2.125 5.111a.563.563 0 00.475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 00-.182.557l1.285 5.385a.562.562 0 01-.84.61l-4.725-2.885a.563.563 0 00-.586 0L6.982 20.54a.562.562 0 01-.84-.61l1.285-5.386a.562.562 0 00-.182-.557l-4.204-3.602a.563.563 0 01.321-.988l5.518-.442a.563.563 0 00.475-.345L11.48 3.5z"/></svg>
              <?php endif; ?>
            </button>
          </form>
        </td>
        <td class="text-center">
          <form method="POST" class="inline">
            <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
            <input type="hidden" name="action" value="toggle_status"/>
            <input type="hidden" name="id" value="<?=$prop['id']?>"/>
            <button type="submit" class="text-xs px-2 py-1 border <?=$prop['publication_status']==='publie'?'bg-black text-white border-black':'border-gray-300 text-gray-400'?> hover:border-black transition-colors">
              <?=$prop['publication_status']==='publie'?'Publié':'Brouillon'?>
            </button>
          </form>
        </td>
        <td class="text-right">
          <div class="flex items-center justify-end gap-3">
            <a href="<?= SITE_URL ?>/pages/property/<?=$prop['slug']?>" target="_blank" class="text-xs text-gray-400 hover:text-black transition-colors">Voir</a>
            <a href="<?= SITE_URL ?>/admin/property_edit?id=<?=$prop['id']?>" class="text-xs text-gray-400 hover:text-black transition-colors">Modifier</a>
            <form method="POST" class="inline" onsubmit="return confirm('Supprimer cette propriété ?')">
              <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>
              <input type="hidden" name="action" value="delete"/>
              <input type="hidden" name="id" value="<?=$prop['id']?>"/>
              <button type="submit" class="text-xs text-red-400 hover:text-red-600 transition-colors">Suppr.</button>
            </form>
          </div>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>

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