<?php
/* =============================================================================
 * File   : home.php
 * Goal   : Homepage where BOTH "Exclusive Property" and "Featured Property"
 *          sections pull cards from DB (projects.project_tag).
 *          - project_tag = 'Exclusive' -> Exclusive section
 *          - project_tag = 'Featured'  -> Featured section
 *          Hero search forwards to listings with ?exclusive=1 / ?featured=1 & q=
 *          Thumbnails are 309x261 via CSS crop; equal-height cards.
 * Stack  : Core PHP + MySQLi (NO PDO). DB link from config.php
 * Charset: utf8mb4 / COLLATE=utf8mb4_general_ci
 * ============================================================================= */

@session_start();

/* ------------------------- Centralized config ------------------------- */
$cfgs = [ __DIR__.'/config.php', __DIR__.'/../config.php', __DIR__.'/../../config.php' ];
$cfgFound = false;
foreach ($cfgs as $c) { if (file_exists($c)) { require_once $c; $cfgFound = true; break; } }
if (!$cfgFound) { http_response_code(500); die('config.php not found'); }

/* -------------------------- Pick a mysqli link ------------------------ */
$DB = null;
if (isset($conn_crm)        && $conn_crm instanceof mysqli)        $DB = $conn_crm;
elseif (isset($conn_crmplus) && $conn_crmplus instanceof mysqli)   $DB = $conn_crmplus;
elseif (isset($conn)         && $conn instanceof mysqli)           $DB = $conn;
elseif (isset($conn_sa)      && $conn_sa instanceof mysqli)        $DB = $conn_sa;
if (!$DB instanceof mysqli) { http_response_code(500); exit('DB connection not found'); }

/* ---------------------- Charset / Collation -------------------------- */
@mysqli_set_charset($DB, 'utf8mb4');
@mysqli_query($DB, "SET NAMES 'utf8mb4'");
@mysqli_query($DB, "SET collation_connection='utf8mb4_general_ci'");

/* ---------------------------- Helpers -------------------------------- */
if (!function_exists('h')) { function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); } }
function q($s){ global $DB; return mysqli_real_escape_string($DB,(string)$s); }
function base_url(){
  if (!empty($GLOBALS['baseUrl'])) return rtrim($GLOBALS['baseUrl'],'/');
  $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') ? 'https' : 'http';
  $host  = $_SERVER['HTTP_HOST'] ?? ($_SERVER['SERVER_NAME'] ?? 'localhost');
  $dir   = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? '/'),'/');
  return rtrim("$proto://$host$dir",'/');
}
function table_exists($name){ global $DB; $name = q($name); $r = @mysqli_query($DB,"SHOW TABLES LIKE '{$name}'"); $ok = ($r && mysqli_num_rows($r)>0); if($r) @mysqli_free_result($r); return $ok; }
function col_exists($tbl,$col){ global $DB; $tbl = q($tbl); $col = q($col); $r = @mysqli_query($DB,"SHOW COLUMNS FROM `{$tbl}` LIKE '{$col}'"); $ok = ($r && mysqli_num_rows($r)>0); if($r) @mysqli_free_result($r); return $ok; }
function full_url_from($path){
  $p = trim((string)$path);
  if ($p === '') return $p;
  if (preg_match('~^https?://~i', $p)) return $p;
  if ($p[0] === '/') return $p;             // absolute web-root path
  return base_url().'/'.$p;                 // relative -> absolute
}
function inr_format($num){
  $n = (float)$num;
  if ($n >= 10000000) return '₹ '.round($n/10000000,2).' Cr';
  if ($n >= 100000)   return '₹ '.round($n/100000,2).' L';
  return '₹ '.number_format($n, 0);
}

/* ------------------- Resolve Projects / Media tables ------------------ */
$PROJECTS_TABLE = null;
foreach (['projects','project','tbl_projects','pp_projects'] as $t) {
  if (table_exists($t)) { $PROJECTS_TABLE = $t; break; }
}
$MEDIA_TABLE = table_exists('project_media') ? 'project_media' : null;
if (!$PROJECTS_TABLE) { http_response_code(500); exit('Projects table not found.'); }

/* ------------------------------ Paths --------------------------------- */
$base_dir   = __DIR__ . '/Base';
$static_url = '/mobile/assets';

/* -------------------------- Shared Navbar ----------------------------- */
ob_start();
include "$base_dir/navbar.php";
$navlink_content = ob_get_clean();
$page  = 'nav';
$fpage = 'foot';

/* ---------------------- Project -> Images helper ---------------------- */
function project_images_db_only($project_id, $limit = 3){
  global $DB, $MEDIA_TABLE, $PROJECTS_TABLE;
  $images = [];

  if ($MEDIA_TABLE) {
    $urlCol    = col_exists($MEDIA_TABLE,'url') ? 'url' : (col_exists($MEDIA_TABLE,'file_url') ? 'file_url' : null);
    $sortCol   = col_exists($MEDIA_TABLE,'sort_order') ? 'sort_order' : (col_exists($MEDIA_TABLE,'id') ? 'id' : null);
    $isActCond = col_exists($MEDIA_TABLE,'is_active') ? 'COALESCE(is_active,1)=1 AND ' : '';
    $hasType   = col_exists($MEDIA_TABLE,'media_type');
    if ($urlCol) {
      $pid = (int)$project_id;
      $where = "{$isActCond} project_id={$pid}";
      if ($hasType) { $where .= " AND LOWER(media_type)='image'"; }
      $orderSql = $sortCol ? (' ORDER BY '.($sortCol==='sort_order' ? "$sortCol ASC" : "$sortCol DESC")) : '';
      $limitSql = ' LIMIT '.(int)$limit;

      $sql = "SELECT {$urlCol} AS file_url FROM `{$MEDIA_TABLE}` WHERE {$where}{$orderSql}{$limitSql}";
      if ($rs = mysqli_query($DB,$sql)) {
        while($r = mysqli_fetch_assoc($rs)) {
          if (!empty($r['file_url'])) $images[] = full_url_from($r['file_url']);
        }
        @mysqli_free_result($rs);
      }
    }
  }

  // Fallback to projects.cover_image (still DB)
  if (count($images) < $limit && col_exists($PROJECTS_TABLE,'cover_image')) {
    $pid = (int)$project_id;
    $r2  = mysqli_query($DB,"SELECT cover_image FROM `{$PROJECTS_TABLE}` WHERE id={$pid} LIMIT 1");
    if ($r2 && mysqli_num_rows($r2)) {
      $row = mysqli_fetch_assoc($r2);
      if (!empty($row['cover_image'])) $images[] = full_url_from($row['cover_image']);
    }
    if ($r2) @mysqli_free_result($r2);
  }

  $images = array_values(array_unique(array_filter($images)));
  return array_slice($images, 0, $limit);
}

/* ------------------- Project -> Text/labels helpers ------------------- */
function project_price_text($row){
  if (!empty($row['price_text'])) return $row['price_text'];
  $min = isset($row['price_min']) ? (float)$row['price_min'] : null;
  $max = isset($row['price_max']) ? (float)($row['price_max'] ?? 0) : null;
  if ($min && $max && $max >= $min) return inr_format($min).' - '.inr_format($max);
  if ($min) return inr_format($min);
  return 'Price on request';
}
function project_location_text($row){
  $parts = [];
  foreach (['address','city','state'] as $c) { if (!empty($row[$c])) $parts[] = trim($row[$c]); }
  return $parts ? implode(', ', $parts) : 'Location not specified';
}
function project_config_text($row){
  if (!empty($row['configuration'])) return $row['configuration'];
  if (!empty($row['bedrooms']))     return (int)$row['bedrooms'].' BHK';
  return '—';
}
function project_area_text($row){
  if (!empty($row['area_sqft'])) {
    $u = !empty($row['area_unit']) ? $row['area_unit'] : 'SQFT';
    return (float)$row['area_sqft'].' '.$u;
  }
  return '—';
}

/* -------------- Fetch projects by project_tag (DB-only images) -------- */
function fetch_projects_by_tag($tag, $limit=0){
  global $DB, $PROJECTS_TABLE;
  $w = [];
  if (col_exists($PROJECTS_TABLE,'is_active'))     $w[] = "COALESCE(is_active,1)=1";
  if (col_exists($PROJECTS_TABLE,'project_tag'))   $w[] = "LOWER(project_tag)=LOWER('".q($tag)."')";
  $where = $w ? ('WHERE '.implode(' AND ', $w)) : '';

  $order = 'ORDER BY ';
  if (col_exists($PROJECTS_TABLE,'sort_order')) $order .= 'sort_order ASC, ';
  if (col_exists($PROJECTS_TABLE,'created_at')) $order .= 'created_at DESC, ';
  $order .= 'id DESC';

  $limitSql = ((int)$limit > 0) ? (' LIMIT '.(int)$limit) : '';

  $sql = "SELECT * FROM `{$PROJECTS_TABLE}` {$where} {$order}{$limitSql}";
  $out = [];
  if ($rs = mysqli_query($DB,$sql)) {
    while($r = mysqli_fetch_assoc($rs)) {
      $imgs = project_images_db_only((int)$r['id'], 3);
      if (count($imgs) > 0) {
        $r['_images'] = $imgs;
        $out[] = $r;
      }
    }
    @mysqli_free_result($rs);
  }
  return $out;
}

/* ========================== HERO + CONTENT START ======================= */
ob_start();
?>
<!-- ============================ Hero Banner  Start ================================== -->
<style>
/* === 309 x 261 THUMBNAILS for both Exclusive & Featured ===
   - We crop visually (object-fit: cover) to avoid any compression/blur.
   - Every card's image box is identical so grid aligns perfectly.
*/
.thumb-309x261 {
  width: 259px;        /* fixed thumbnail viewport width */
  height: 211px;       /* fixed thumbnail viewport height */
  overflow: hidden;
  border-radius: .5rem;
  margin: 0 auto;      /* center inside fluid columns */
}
.thumb-309x261 img {
  width: 100%;
  height: 100%;
  object-fit: cover;   /* crop without distortion */
  display: block;
}

@media (max-width: 767px) {
  .featured-swiper-wrapper {overflow-x: auto;scroll-snap-type: x mandatory;-webkit-overflow-scrolling: touch;scrollbar-width: none;-ms-overflow-style: none;}
  .featured-swiper-wrapper .row.list-layout {display: flex !important;flex-wrap: nowrap !important;}
  .featured-swiper-wrapper .row.list-layout > div {flex: 0 0 100%;max-width: 100%;scroll-snap-align: start;}
  .featured-swiper-wrapper::-webkit-scrollbar { display: none;}
}
@media (min-width: 768px) and (max-width: 991px) {
  .featured-swiper-wrapper {overflow-x: auto; scroll-snap-type: x mandatory;-webkit-overflow-scrolling: touch;scrollbar-width: none;-ms-overflow-style: none;}
  .featured-swiper-wrapper .row.list-layout {display: flex !important;flex-wrap: nowrap !important;}
  .featured-swiper-wrapper .row.list-layout > div {flex: 0 0 50%; max-width: 50%; scroll-snap-align: start;}
  .featured-swiper-wrapper::-webkit-scrollbar {display: none;}
}
</style>

<div class="image-bottom hero-banner bg-primary-dark" style="background:url(<?php echo $static_url; ?>/img/banner-bg2.jpg) no-repeat;" data-overlay="0">
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-lg-9 col-md-11 col-sm-12">
        <div class="inner-banner-text text-center">
          <h2 class="mb-1"><span class="font-normal">Ready. Set. Sold</span></h2>
          <div class="fs-5 fw-light px-xl-4 px-lg-4 text-white">Explore handpicked homes and investment properties — verified, affordable, and ready for you.</div>
        </div>

        <!-- HERO SEARCH: sends to grid-layout-with-sidebar.php with exclusive/featured + q -->
        <form class="full-search-2 eclip-search italian-search hero-search-radius shadow-hard"
              id="heroSearchForm" method="get" action="grid-layout-with-sidebar.php">
          <div class="hero-search-content">
            <div class="row">
              <!-- Exclusive / Featured -->
              <div class="col-lg-3 col-md-4 col-sm-12 b-r">
                <div class="form-group">
                  <div class="choose-propert-type">
                    <ul>
                      <li>
                        <div class="form-check">
                          <input class="form-check-input" type="radio" id="optExclusive" name="tagopt" value="exclusive">
                          <label class="form-check-label" for="optExclusive">Exclusive</label>
                        </div>
                      </li>
                      <li>
                        <div class="form-check">
                          <input class="form-check-input" type="radio" id="optFeatured" name="tagopt" value="featured" checked>
                          <label class="form-check-label" for="optFeatured">Featured</label>
                        </div>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>

              <!-- Search by text/location -->
              <div class="col-lg-7 col-md-5 col-sm-12 p-md-0 elio">
                <div class="form-group border-start borders">
                  <div class="position-relative">
                    <input type="text" name="q" id="heroQuery" class="form-control border-0 ps-5" placeholder="Search by city, location or project">
                    <div class="position-absolute top-50 start-0 translate-middle-y ms-2">
                      <span class="svg-icon text-primary svg-icon-2hx">
                        <svg width="25" height="25" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path opacity="0.3" d="M18.0624 15.3453L13.1624 20.7453C12.5624 21.4453 11.5624 21.4453 10.9624 20.7453L6.06242 15.3453C4.56242 13.6453 3.76242 11.4453 4.06242 8.94534C4.56242 5.34534 7.46242 2.44534 11.0624 2.04534C15.8624 1.54534 19.9624 5.24534 19.9624 9.94534C20.0624 12.0453 19.2624 13.9453 18.0624 15.3453Z" fill="currentColor"/>
                          <path d="M12.0624 13.0453C13.7193 13.0453 15.0624 11.7022 15.0624 10.0453C15.0624 8.38849 13.7193 7.04535 12.0624 7.04535C10.4056 7.04535 9.06241 8.38849 9.06241 10.0453C9.06241 11.7022 10.4056 13.0453 12.0624 13.0453Z" fill="currentColor"/>
                        </svg>
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Submit -->
              <div class="col-lg-2 col-md-3 col-sm-12">
                <div class="form-group">
                  <button type="submit" class="btn btn-dark full-width">Search</button>
                </div>
              </div>
            </div><!-- /row -->
          </div>

          <!-- These are set by JS right before submit to match your filter API -->
          <input type="hidden" name="exclusive" id="heroExclusive" value="">
          <input type="hidden" name="featured"  id="heroFeatured"  value="1">
        </form>
      </div>
    </div>
  </div>
</div>
<!-- ============================ Hero Banner End ================================== -->

<!-- ============================ Explore Top Places Start ================================== -->
<section>
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-lg-7 col-md-10 text-center">
        <div class="sec-heading center">
          <h2>Explore Properties in Best Places</h2>
          <p>Discover handpicked properties across the most sought-after locations for your dream lifestyle.</p>
        </div>
      </div>
    </div>

    <div class="row justify-content-center row-cols-xl-5 row-cols-lg-4 row-cols-md-3 row-cols-sm-2 row-cols-1 g-2 g-lg-4">
      <?php include "$base_dir/Components/Home/best-places.php"; ?>
    </div>
  </div>
</section>
<!-- ============================ Explore Top Places End ================================== -->
<?php
/* -------------------- Fetch DB data for both sections ------------------- */
$exclusiveProjects = fetch_projects_by_tag('Exclusive', 0);
$featuredProjects  = fetch_projects_by_tag('Featured', 0);

/* --------------- Card renderer: EXCLUSIVE (compact card) --------------- */
function render_exclusive_cards($rows){
  foreach ($rows as $row):
    $id       = (int)($row['id'] ?? 0);
    $title    = !empty($row['title']) ? $row['title'] : ('Project #'.$id);
    $location = project_location_text($row);
    $priceTxt = project_price_text($row);
    $config   = project_config_text($row);
    $areaTxt  = project_area_text($row);
    $bedsTxt  = !empty($row['bedrooms']) ? ((int)$row['bedrooms'].' Beds') : '—';
    $imgs     = isset($row['_images']) ? $row['_images'] : [];
    if (count($imgs) === 0) continue;
    $firstImg = $imgs[0];
    $linkSlug = urlencode(str_replace(' ', '-', strtolower($title)));
?>
  <div class="single-slide">
    <div class="property-listing card border rounded-3 card-fixed equal-card">
      <div class="listing-img-wrapper p-2 d-flex justify-content-center">
        <div class="thumb-309x261">
          <a href="property_detail.php?title=<?php echo $linkSlug; ?>">
            <img src="<?php echo h($firstImg); ?>" alt="<?php echo h($title); ?>">
          </a>
        </div>
      </div>

      <div class="listing-caption-wrapper px-3 equal-body">
        <div class="listing-detail-wrapper">
          <div class="listing-short-detail-wrap">
            <div class="listing-short-detail">
              <div class="d-flex align-items-center">
                <span class="label bg-light-danger text-danger d-inline-flex mb-1">Exclusive</span>
                <span class="label bg-light-purple text-purple property-cats ms-2"><?php echo h($row['property_type'] ?? ($row['type'] ?? ($row['category'] ?? 'Apartment'))); ?></span>
              </div>
              <h4 class="listing-name fw-semibold fs-5 mb-2 mt-2">
                <a href="property_detail.php?title=<?php echo $linkSlug; ?>"><?php echo h($title); ?></a>
              </h4>
              <div class="prt-location text-muted-2">
                <i class="fa-solid fa-location-dot me-1"></i><?php echo h($location); ?>
              </div>
            </div>
          </div>
        </div>

        <div class="price-features-wrapper">
          <div class="list-fx-features d-flex align-items-center justify-content-between">
            <div class="listing-card d-flex align-items-center">
              <div class="square--30 text-muted-2 fs-sm circle gray-simple me-2"><i class="fa-solid fa-building-shield fs-sm"></i></div>
              <span class="text-muted-2"><?php echo h($config); ?></span>
            </div>
            <div class="listing-card d-flex align-items-center">
              <div class="square--30 text-muted-2 fs-sm circle gray-simple me-2"><i class="fa-solid fa-bed fs-sm"></i></div>
              <span class="text-muted-2"><?php echo h($bedsTxt); ?></span>
            </div>
            <div class="listing-card d-flex align-items-center">
              <div class="square--30 text-muted-2 fs-sm circle gray-simple me-2"><i class="fa-solid fa-clone fs-sm"></i></div>
              <span class="text-muted-2"><?php echo h($areaTxt); ?></span>
            </div>
          </div>
        </div>

        <div class="listing-detail-footer d-flex align-items-center justify-content-between py-4">
          <div class="listing-short-detail-flex"><h6 class="listing-card-info-price m-0"><?php echo h($priceTxt); ?></h6></div>
          <div class="footer-flex">
            <a href="property-detail.php?id=<?php echo $id; ?>" class="btn btn-sm btn-outline-primary px-3">View</a>
          </div>
        </div>
      </div>
    </div>
  </div>
<?php
  endforeach;
}

/* --------------- Card renderer: FEATURED (property-1 layout) ---------- */
function render_featured_cards($rows){
  foreach ($rows as $row):
    $id       = (int)($row['id'] ?? 0);
    $title    = !empty($row['title']) ? $row['title'] : ('Project #'.$id);
    $priceTxt = project_price_text($row);
    $location = project_location_text($row);
    $imgs     = isset($row['_images']) ? $row['_images'] : [];
    if (count($imgs) === 0) continue;
    $firstImg = $imgs[0];
    $linkSlug = urlencode(str_replace(' ', '-', strtolower($title)));
?>
<div class="col-xl-6 col-lg-6 col-md-12 d-flex">
  <div class="property-listing property-1 bg-white p-2 rounded equal-card w-100">
    <div class="listing-img-wrapper d-flex justify-content-center">
      <a href="property_detail.php?title=<?php echo $linkSlug; ?>" class="thumb-309x261">
        <img src="<?php echo h($firstImg); ?>" alt="<?php echo h($title); ?>">
      </a>
    </div>

    <div class="listing-content equal-body">
      <div class="listing-detail-wrapper-box">
        <div class="listing-detail-wrapper d-flex align-items-center justify-content-between">
          <div class="listing-short-detail">
            <span class="label bg-light-danger text-danger d-inline-flex mb-1">Featured</span>
            <h4 class="listing-name mb-1 mt-2">
              <a href="property_detail.php?title=<?php echo $linkSlug; ?>"><?php echo h($title); ?></a>
            </h4>
            <div class="fr-can-rating">
              <i class="fas fa-star fs-xs filled"></i>
              <i class="fas fa-star fs-xs filled"></i>
              <i class="fas fa-star fs-xs filled"></i>
              <i class="fas fa-star fs-xs filled"></i>
              <i class="fas fa-star fs-xs"></i>
              <span class="reviews_text fs-sm text-muted ms-2">(Reviews)</span>
            </div>
          </div>
          <div class="list-price">
            <h6 class="listing-card-info-price text-primary"><?php echo h($priceTxt); ?></h6>
          </div>
        </div>
      </div>

      <div class="price-features-wrapper">
        <div class="list-fx-features d-flex align-items-center justify-content-between mt-3 mb-1">
          <div class="listing-card d-flex align-items-center">
            <div class="square--25 text-muted-2 fs-sm circle gray-simple me-1"><i class="fa-solid fa-building-shield fs-xs"></i></div>
            <span class="text-muted-2 fs-sm"><?php echo h(project_config_text($row)); ?></span>
          </div>
          <div class="listing-card d-flex align-items-center">
            <div class="square--25 text-muted-2 fs-sm circle gray-simple me-1"><i class="fa-solid fa-bed fs-xs"></i></div>
            <span class="text-muted-2 fs-sm"><?php echo !empty($row['bedrooms']) ? (int)$row['bedrooms'].' Beds' : '—'; ?></span>
          </div>
          <div class="listing-card d-flex align-items-center">
            <div class="square--25 text-muted-2 fs-sm circle gray-simple me-1"><i class="fa-solid fa-clone fs-xs"></i></div>
            <span class="text-muted-2 fs-sm"><?php echo h(project_area_text($row)); ?></span>
          </div>
        </div>
      </div>

      <div class="listing-footer-wrapper d-flex align-items-center justify-content-between mt-auto">
        <div class="listing-locate">
          <span class="listing-location text-muted-2">
            <i class="fa-solid fa-location-pin me-1"></i><?php echo h($location); ?>
          </span>
        </div>
        <div class="listing-detail-btn">
          <a href="property_detail.php?title=<?php echo $linkSlug; ?>" class="btn btn-sm px-4 fw-medium btn-primary">View</a>
        </div>
      </div>
    </div>
  </div>
</div>
<?php
  endforeach;
}
?>

<!-- ============================ Exclusive Property ============================ -->
<section>
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-lg-7 col-md-10 text-center">
        <div class="sec-heading center">
          <h2>Exclusive Property</h2>
          <p>Experience unparalleled comfort and elegance with our exclusive property listings.</p>
        </div>
      </div>
    </div>

    <div class="row justify-content-center">
      <div class="col-lg-12 col-md-12">
        <div class="floral-wraps">
          <div class="slide-livok top-arrow">
            <?php
              if (!empty($exclusiveProjects)) { render_exclusive_cards($exclusiveProjects); }
              else { echo '<p class="text-center text-muted py-5">No Exclusive projects found.</p>'; }
            ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>
<div class="clearfix"></div>
<!-- ============================ /Exclusive ============================ -->

<!-- ============================ Featured Property ====================== -->
<section class="bg-light">
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-lg-7 col-md-10 text-center">
        <div class="sec-heading center">
          <h2>Featured Property</h2>
          <p>Explore our top-rated properties carefully chosen for their quality, value, and location.</p>
        </div>
      </div>
    </div>

    <div class="featured-swiper-wrapper">
      <div class="row list-layout">
        <?php
          if (!empty($featuredProjects)) { render_featured_cards($featuredProjects); }
          else { echo '<div class="col-12"><p class="text-center text-muted py-5 m-0">No Featured projects found.</p></div>'; }
        ?>
      </div>
    </div>

    <div class="row">
      <div class="col-lg-12 col-md-12 col-sm-12 text-center mt-4">
        <a href="grid-layout-with-sidebar.php" class="btn btn-primary px-lg-5 rounded">Browse More Properties</a>
      </div>
    </div>
  </div>
</section>

<!-- Top Agents -->
<section class="pt-0">
  <div class="container">
    <div class="row justify-content-start">
      <div class="row justify-content-center">
        <div class="col-lg-7 col-md-10 text-center">
          <div class="sec-heading center">
            <h2>Meet Top Agents</h2>
            <p>Top Agents description line</p>
          </div>
        </div>
      </div>
    </div>
    <div class="row justify-content-center">
      <div class="col-lg-12 col-md-12">
        <div class="floral-wraps">
          <div class="slide-livok top-arrow">
            <?php include "$base_dir/Components/Home/agents1.php"; ?>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- Reviews -->
<section class="gray-bg">
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-lg-7 col-md-10 text-center">
        <div class="sec-heading center">
          <h2>Good Reviews by Customers</h2>
          <p>Review line</p>
        </div>
      </div>
    </div>
    <div class="row justify-content-center">
      <div class="col-lg-12 col-md-12">
        <div class="smart-textimonials smart-center" id="smart-textimonials">
          <?php include "$base_dir/Components/Home/reviews.php"; ?>
        </div>
      </div>
    </div>
  </div>
</section>

<script>
/* Keep hidden inputs in sync with the radio selection before submit */
(function(){
  const form = document.getElementById('heroSearchForm');
  const ex   = document.getElementById('heroExclusive');
  const ft   = document.getElementById('heroFeatured');

  function syncHidden(){
    const val = (document.querySelector('input[name="tagopt"]:checked')||{}).value || 'featured';
    ex.value = (val === 'exclusive') ? '1' : '';
    ft.value = (val === 'featured')  ? '1' : '';
  }
  document.querySelectorAll('input[name="tagopt"]').forEach(el => {
    el.addEventListener('change', syncHidden);
  });
  form.addEventListener('submit', syncHidden);
  syncHidden(); // set defaults on load
})();
document.addEventListener('DOMContentLoaded', function () {
  const wrapper = document.querySelector('.featured-swiper-wrapper');
  const row = wrapper.querySelector('.row.list-layout');
  if (!wrapper || !row) {
    console.error('Wrapper or row not found');
    return;
  }

  let clonesAdded = false;
  let autoScrollInterval;
  const cloneCount = 2;

  function cloneCards() {
    if (clonesAdded) return;

    const items = Array.from(row.children);
    if (items.length < 2) return;
    for (let i = items.length - cloneCount; i < items.length; i++) {
      const clone = items[i].cloneNode(true);
      row.insertBefore(clone, items[0]);
    }
    for (let i = 0; i < cloneCount; i++) {
      const clone = items[i].cloneNode(true);
      row.appendChild(clone);
    }
    clonesAdded = true;
    setTimeout(() => {
      let offset = 0;
      for (let i = 0; i < cloneCount; i++) {
        const el = row.children[i];
        const style = window.getComputedStyle(el);
        const margin = parseInt(style.marginRight || 0);
        offset += el.offsetWidth + margin;
      }
      wrapper.scrollLeft = offset;
    }, 100);
  }
  function autoScroll() {
    const items = Array.from(row.children);
    if (items.length === 0) return;
    autoScrollInterval = setInterval(() => {
      const firstCard = row.children[0];
      const style = window.getComputedStyle(firstCard);
      const cardWidth = firstCard.offsetWidth + parseInt(style.marginRight || 0);

      wrapper.scrollBy({ left: cardWidth, behavior: 'smooth' });

      setTimeout(() => {
        checkLoop(cardWidth);
      }, 500);
    }, 3000);
  }
  function checkLoop(cardWidth) {
    const scrollLeft = wrapper.scrollLeft;
    const totalCards = row.children.length;
    const visibleCards = totalCards - cloneCount * 2;
    const maxScroll = cardWidth * (visibleCards + cloneCount);

    if (scrollLeft >= maxScroll) {
      wrapper.scrollLeft = cardWidth * cloneCount;
    }
  }

  function stopAutoScroll() {
    clearInterval(autoScrollInterval);
  }

  function setup() {
    if (window.innerWidth <= 991) {
      cloneCards();
      autoScroll();
      wrapper.addEventListener('mouseenter', stopAutoScroll);
      wrapper.addEventListener('touchstart', stopAutoScroll);
      wrapper.addEventListener('mouseleave', autoScroll);
    } else {
      stopAutoScroll();
    }
  }

  window.addEventListener('load', setup);
  window.addEventListener('resize', () => {
    stopAutoScroll();
    clonesAdded = false;
    window.location.reload();
  });
});
</script>
<?php
$hero_content = ob_get_clean();

/* ----------------------------- Render base ----------------------------- */
include "$base_dir/style/base.php";
