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

$statusFilter = $_GET['status'] ?? ''; // 'vente', 'location' or empty for all

// Featured Properties for Hero Slider
try {
    $sqlFeatured = "SELECT * FROM properties WHERE featured = 1 AND publication_status = 'publie'";
    $paramsFeatured = [];
    if ($statusFilter) {
        $sqlFeatured .= " AND status = ?";
        $paramsFeatured[] = $statusFilter;
    }
    $sqlFeatured .= " ORDER BY id DESC LIMIT 5";
    $stmtFeatured = $db->prepare($sqlFeatured);
    $stmtFeatured->execute($paramsFeatured);
    $featuredSlides = $stmtFeatured->fetchAll();
} catch (Exception $e) {
    $featuredSlides = [];
}

// Filtered Properties List
$where = ["publication_status = 'publie'"]; 
$params = [];

if ($statusFilter) {
    $where[] = "status = ?";
    $params[] = $statusFilter;
}

if (!empty($_GET['q'])) { 
    $where[] = "(title LIKE ? OR city LIKE ? OR address LIKE ? OR description LIKE ?)"; 
    $q = '%' . $_GET['q'] . '%'; 
    $params[] = $q; $params[] = $q; $params[] = $q; $params[] = $q; 
}
if (!empty($_GET['type'])) { $where[] = "type = ?"; $params[] = $_GET['type']; }
if (!empty($_GET['city'])) { $where[] = "city = ?"; $params[] = $_GET['city']; }
if (!empty($_GET['min_price'])) { $where[] = "price >= ?"; $params[] = $_GET['min_price']; }
if (!empty($_GET['max_price'])) { $where[] = "price <= ?"; $params[] = $_GET['max_price']; }

$whereClause = "WHERE " . implode(" AND ", $where);
$sort = $_GET['sort'] ?? 'newest';
$orderBy = match($sort) { 
    'price_asc' => 'ORDER BY price ASC',
    'price_desc' => 'ORDER BY price DESC',
    'surface' => 'ORDER BY surface DESC', 
    default => 'ORDER BY created_at DESC' 
};

$stmt = $db->prepare("SELECT * FROM properties $whereClause $orderBy"); 
$stmt->execute($params);
$properties = $stmt->fetchAll();

$cities = getCities(); 
$types = getPropertyTypes();

$headerStyle = 'transparent'; 
$currentPage = 'buy';
?>
<!DOCTYPE html>
<html lang="fr" class="scroll-smooth">
<head>
  <?= renderHead('Nos Propriétés D\'Exception à Sidi Rahal Casablanca', 'Découvrez l\'ensemble de nos villas, appartements, duplex et penthouses d\'exception à la vente et à la location à Sidi Rahal Casablanca.') ?>
</head>
<body class="bg-offwhite text-dark font-sans">
<?php include __DIR__ . '/../components/header.php'; ?>

<!-- PAGE HEADER / BIG TITLE SECTION FIRST -->
<section class="pt-32 pb-12 bg-black text-white text-center border-b border-gray-800">
  <div class="max-w-4xl mx-auto px-6 reveal-scale">
    <p class="text-[11px] tracking-[0.35em] uppercase text-gold font-sans font-semibold mb-3">PORTFEUILLE EXCLUSIF</p>
    <h1 class="font-serif text-4xl sm:text-6xl font-light tracking-tight mb-4 text-[#D4C7A3]">Nos Propriétés D'Exception</h1>
    <div class="w-16 h-px bg-gold mx-auto mb-4"></div>
    <p class="text-sm sm:text-base text-gray-300 font-sans font-light max-w-xl mx-auto">
      Découvrez l'ensemble de nos villas, appartements, duplex et penthouses d'exception à Sidi Rahal Casablanca.
    </p>
  </div>
</section>

<!-- HERO SECTION: AUTOMATIC SLIDER FOR HOTTEST PROPERTIES (AFTER BIG TITLE) -->
<section class="relative h-[65vh] min-h-[500px] bg-black text-white overflow-hidden">
  <?php if (!empty($featuredSlides)): ?>
    <div class="swiper swiper-featured-properties w-full h-full">
      <div class="swiper-wrapper">
        <?php foreach ($featuredSlides as $slide): 
          $slideImg = resolveAssetUrl(getPrimaryImage($slide['id']));
          $slideType = getPropertyTypes()[$slide['type']] ?? ucfirst($slide['type']);
          $slideStatusLabel = $slide['status'] === 'location' ? 'Location' : 'Vente';
        ?>
          <div class="swiper-slide relative w-full h-full">
            <img src="<?= htmlspecialchars($slideImg) ?>" class="w-full h-full object-cover opacity-75" alt="<?= htmlspecialchars($slide['title']) ?>" />
            <div class="absolute inset-0 bg-gradient-to-t from-black via-black/30 to-black/50"></div>
            
            <div class="absolute bottom-12 left-0 right-0 max-w-7xl mx-auto px-6 z-10">
              <div class="flex items-center gap-3 mb-4">
                <span class="bg-gold text-white text-[10px] tracking-[0.25em] uppercase font-sans px-3 py-1.5 font-semibold">
                  SÉLECTION D'EXCEPTION · <?= htmlspecialchars($slideType) ?>
                </span>
                <span class="bg-white/20 backdrop-blur-md text-white text-[10px] tracking-[0.2em] uppercase font-sans px-3 py-1.5 font-medium border border-white/30">
                  <?= $slideStatusLabel ?>
                </span>
              </div>
              
              <h2 class="font-serif text-3xl sm:text-5xl md:text-6xl font-light text-white mb-3 max-w-3xl leading-tight">
                <?= htmlspecialchars($slide['title']) ?>
              </h2>
              
              <p class="text-gray-300 font-sans text-sm sm:text-base font-light mb-6 flex items-center gap-4">
                <span>📍 <?= htmlspecialchars($slide['city']) ?></span>
                <span>•</span>
                <span class="text-gold font-medium"><?= htmlspecialchars($slide['price_label'] ?: formatPrice($slide['price'])) ?></span>
              </p>

              <a href="<?= SITE_URL ?>/pages/property/<?= htmlspecialchars($slide['slug']) ?>" class="btn-lemonde-consultation inline-flex">
                <span>Découvrir la propriété</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>
              </a>
            </div>
          </div>
        <?php endforeach; ?>
      </div>

      <!-- Navigation Arrows -->
      <div class="absolute bottom-12 right-6 z-20 hidden md:flex items-center gap-2">
        <div class="swiper-button-prev-custom rounded-full cursor-pointer">←</div>
        <div class="swiper-button-next-custom rounded-full cursor-pointer">→</div>
      </div>

      <!-- Swiper Pagination Dots -->
      <div class="swiper-pagination !bottom-4"></div>
    </div>
  <?php else: ?>
    <!-- Fallback static hero -->
    <div class="w-full h-full relative flex items-center justify-center text-center px-6">
      <img src="<?= SITE_URL ?>/assets/img/home.jpeg" class="absolute inset-0 w-full h-full object-cover opacity-60" alt="Propriétés 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 max-w-3xl">
        <p class="text-[11px] tracking-[0.3em] uppercase text-gold mb-3 font-medium">PORTFOLIO EXCLUSIF AJOUAMAI IMMO-BUSINESS</p>
        <h2 class="font-serif text-4xl sm:text-5xl font-light text-white mb-4">Découvrez nos biens</h2>
        <p class="text-gray-300 font-sans font-light text-sm sm:text-base">Sélection rigoureuse de biens prestigieux à la vente et à la location à Sidi Rahal Casablanca.</p>
      </div>
    </div>
  <?php endif; ?>
</section>

<!-- STICKY FILTER BAR -->
<div class="sticky top-20 z-30 bg-white/95 backdrop-blur-md border-b border-gray-200 py-5 shadow-xs">
  <div class="max-w-7xl mx-auto px-6">
    <form method="GET" class="flex flex-wrap items-center justify-between gap-4">
      
      <!-- Transaction Status Filter Tabs (Toutes / Acheter / Louer) -->
      <div class="w-full md:w-auto flex items-center gap-2 border-b md:border-b-0 border-gray-200 pb-3 md:pb-0">
        <a href="?<?= http_build_query(array_merge($_GET, ['status' => ''])) ?>" class="px-4 py-2 text-xs tracking-[0.2em] uppercase font-sans border transition-all <?= empty($statusFilter) ? 'bg-black text-white border-black font-semibold' : 'border-gray-200 text-gray-600 hover:border-black' ?>">
          Toutes
        </a>
        <a href="?<?= http_build_query(array_merge($_GET, ['status' => 'vente'])) ?>" class="px-4 py-2 text-xs tracking-[0.2em] uppercase font-sans border transition-all <?= $statusFilter === 'vente' ? 'bg-black text-white border-black font-semibold' : 'border-gray-200 text-gray-600 hover:border-black' ?>">
          À Vendre
        </a>
        <a href="?<?= http_build_query(array_merge($_GET, ['status' => 'location'])) ?>" class="px-4 py-2 text-xs tracking-[0.2em] uppercase font-sans border transition-all <?= $statusFilter === 'location' ? 'bg-black text-white border-black font-semibold' : 'border-gray-200 text-gray-600 hover:border-black' ?>">
          À Louer
        </a>
      </div>

      <input type="hidden" name="status" value="<?= htmlspecialchars($statusFilter) ?>"/>

      <div class="flex-1 min-w-[200px]">
        <input type="text" name="q" value="<?= htmlspecialchars($_GET['q'] ?? '') ?>" placeholder="Rechercher par mot clé, résidence..." class="input-underline text-xs sm:text-sm"/>
      </div>

      <div class="flex-1 min-w-[160px]">
        <select name="type" class="select-underline text-xs sm:text-sm">
          <option value="">Tous les Types</option>
          <?php foreach($types as $v => $l): ?>
            <option value="<?= $v ?>" <?= ($_GET['type'] ?? '') === $v ? 'selected' : '' ?>><?= $l ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="flex-1 min-w-[160px]">
        <select name="city" class="select-underline text-xs sm:text-sm">
          <option value="">Toutes les Villes</option>
          <?php foreach($cities as $c): ?>
            <option value="<?= htmlspecialchars($c) ?>" <?= ($_GET['city'] ?? '') === $c ? 'selected' : '' ?>><?= htmlspecialchars($c) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="flex-1 min-w-[160px]">
        <select name="sort" class="select-underline text-xs sm:text-sm">
          <option value="newest" <?= $sort === 'newest' ? 'selected' : '' ?>>Plus Récents</option>
          <option value="price_asc" <?= $sort === 'price_asc' ? 'selected' : '' ?>>Prix Croissant</option>
          <option value="price_desc" <?= $sort === 'price_desc' ? 'selected' : '' ?>>Prix Décroissant</option>
          <option value="surface" <?= $sort === 'surface' ? 'selected' : '' ?>>Surface Décroissante</option>
        </select>
      </div>

      <button type="submit" class="bg-black text-white text-xs tracking-[0.2em] uppercase px-8 py-3.5 hover:bg-gold transition-colors font-sans font-medium">
        Filtrer
      </button>

      <?php if (!empty($_GET['q']) || !empty($_GET['type']) || !empty($_GET['city']) || !empty($_GET['status'])): ?>
        <a href="<?= SITE_URL ?>/pages/properties" class="text-xs text-gray-500 hover:text-black underline font-sans">
          Effacer
        </a>
      <?php endif; ?>

    </form>
  </div>
</div>

<!-- RESULTS LISTING SECTION -->
<section class="py-20 bg-offwhite">
  <div class="max-w-7xl mx-auto px-6">
    
    <div class="flex items-center justify-between mb-12 border-b border-gray-200/80 pb-4">
      <p class="text-xs tracking-[0.2em] uppercase font-sans text-gray-500">
        <span class="text-black font-semibold text-sm"><?= count($properties) ?></span> propriété(s) disponible(s)
      </p>
      <span class="text-xs text-gold font-sans uppercase tracking-widest hidden sm:inline">AJOUAMAI IMMO-BUSINESS · Sidi Rahal Casablanca</span>
    </div>

    <?php if (empty($properties)): ?>
      <div class="text-center py-24 border border-gray-200 bg-white max-w-2xl mx-auto shadow-xs">
        <svg class="w-12 h-12 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/></svg>
        <p class="font-serif text-2xl font-light text-black mb-2">Aucune propriété ne correspond à votre recherche</p>
        <p class="text-xs text-gray-500 mb-8 font-sans">Ajustez vos filtres ou contactez-nous pour une recherche personnalisée.</p>
        <a href="<?= SITE_URL ?>/pages/properties" class="btn-lemonde-consultation inline-flex">Réinitialiser les filtres</a>
      </div>
    <?php else: ?>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10">
        <?php foreach ($properties as $prop):
          $img = getPrimaryImage($prop['id']); 
          $specs = [];
          if ($prop['surface']) $specs[] = $prop['surface'] . ' m²';
          if ($prop['bedrooms']) $specs[] = $prop['bedrooms'] . ' ch';
          if ($prop['bathrooms']) $specs[] = $prop['bathrooms'] . ' sdb';
          
          $cardPhoto = $img;
          $cardTitle = $prop['title'];
          $cardLocation = $prop['city'];
          $cardSurface = $prop['surface'];
          $cardBedrooms = $prop['bedrooms'];
          $cardBathrooms = $prop['bathrooms'];
          $cardSpecs = implode(' · ', $specs);
          $cardPrice = $prop['price_label'] ?: formatPrice($prop['price']);
          $cardBadge = getPropertyStatuses()[$prop['status']] ?? 'À vendre';
          $cardType = getPropertyTypes()[$prop['type']] ?? ucfirst($prop['type']);
          $cardLink = SITE_URL . '/pages/property/' . htmlspecialchars($prop['slug']);
        ?>
          <div class="reveal">
            <?php include __DIR__ . '/../components/property-card.php'; ?>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

  </div>
</section>

<?php include __DIR__ . '/../components/footer.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>
<script src="<?= SITE_URL ?>/assets/js/app.js"></script>
</body>
</html>
