<?php
/* ============================================================================
 * File   : listings-list-with-sidebar.php
 * Goal   : Property List (with sidebar) driven from `projects` table
 * Notes  : PHP 8.2-safe, real filters (incl. Featured/Exclusive) + pagination
 * ========================================================================== */

if (session_status() === PHP_SESSION_NONE) { session_start(); }
date_default_timezone_set('Asia/Kolkata');

/* ---- Load 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); exit('config.php not found'); }

/* ---- Pick 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'); }

@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 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 ieq($a,$b){ return strcasecmp((string)$a,(string)$b)===0; }
function rupee_label($n){ $n=(float)$n; if($n>=10000000) return "Rs. ".round($n/10000000,2)." Crore"; if($n>=100000) return "Rs. ".round($n/100000,2)." Lacs"; return '₹ '.number_format($n); }
function addr_line($row){ $parts=[]; foreach(['location','city','region','address'] as $k){ $v=isset($row[$k])?trim((string)$row[$k]):''; if($v!=='') $parts[]=$v; } $parts=array_unique($parts); return $parts?implode(', ',array_slice($parts,0,2)) : ''; }
function pick_image($row,$mediaRows){ foreach($mediaRows as $m){ $u=trim((string)$m['u']); if($u!=='') return $u; } foreach(['cover_image','image','thumbnail'] as $c){ if(isset($row[$c]) && trim((string)$row[$c])!=='') return trim((string)$row[$c]); } return '/brocrm/assets/img/p-1.jpg'; }
function build_qs($extra=[]){ $cur=$_GET; foreach($extra as $k=>$v){ if($v===null){ unset($cur[$k]); } else { $cur[$k]=$v; } } $pairs=[]; foreach($cur as $k=>$v){ if(is_array($v)){ foreach($v as $vv){ $pairs[] = urlencode($k.'[]').'='.urlencode($vv); } } else { $pairs[] = urlencode($k).'='.urlencode($v); } } return $pairs?('?'.implode('&',$pairs)) : ''; }

/* ---- Resolve table(s) ---- */
$PROJECTS=null; foreach(['projects','project','tbl_projects','pp_projects'] as $t){ if(table_exists($t)){ $PROJECTS=$t; break; } }
if (!$PROJECTS) { http_response_code(500); exit('Table `projects` not found'); }
$MEDIA = table_exists('project_media') ? 'project_media' : null;
$mediaUrlCol = $MEDIA ? (col_exists($MEDIA,'url')?'url':(col_exists($MEDIA,'file_url')?'file_url':null)) : null;
$mediaTypeCol= $MEDIA && col_exists($MEDIA,'media_type') ? 'media_type' : null;
$mediaSortCol= $MEDIA && col_exists($MEDIA,'sort_order') ? 'sort_order' : 'id';

/* ---- Inputs (filters, pagination, sorting) ---- */
$perPageOptions=[6,12,24,48];
$perPage=(int)($_GET['per_page'] ?? 12); if(!in_array($perPage,$perPageOptions,true)) $perPage=12;
$page=max(1,(int)($_GET['page'] ?? 1)); $offset=($page-1)*$perPage;

$sortSel=(string)($_GET['sort'] ?? '');

$g = fn($k,$d='') => isset($_GET[$k]) ? (is_array($_GET[$k])?$_GET[$k]:trim((string)$_GET[$k])) : $d;
$qtext   = $g('q');
$fltCity = $g('city');
$fltType = $g('type');
$fltList = $g('listing');

/* TAGS:
 * New: ?exclusive=1 / ?featured=1
 * Legacy (optional): ?tag=Exclusive|Featured
 */
$tagFlags = [];
if (!empty($_GET['exclusive']) && $_GET['exclusive'] === '1') $tagFlags[] = 'exclusive';
if (!empty($_GET['featured'])  && $_GET['featured']  === '1') $tagFlags[] = 'featured';
$legacyTag = $g('tag');
if ($legacyTag!=='') $tagFlags[] = strtolower($legacyTag);

$minBeds = (int)($g('beds_min')!==''?$g('beds_min'):0);
$maxBeds = (int)($g('beds_max')!==''?$g('beds_max'):0);
$priceMin= $g('pmin')!=='' ? (float)$g('pmin') : null;
$priceMax= $g('pmax')!=='' ? (float)$g('pmax') : null;
$amenSel = $g('amenities', []); // array of amenity ids

/* ---- Build WHERE ---- */
$where=[];
if (col_exists($PROJECTS,'is_active')) $where[]="COALESCE(`is_active`,1)=1";
if ($qtext!==''){
  $q = q('%'.$qtext.'%');
  $where[]="(title LIKE '{$q}' OR project_name LIKE '{$q}' OR city LIKE '{$q}' OR location LIKE '{$q}' OR region LIKE '{$q}' OR address LIKE '{$q}')";
}
if ($fltCity!=='')  $where[]="LOWER(city)=LOWER('".q($fltCity)."')";
if ($fltType!=='')  $where[]="LOWER(property_type)=LOWER('".q($fltType)."')";
if ($fltList!=='')  $where[]="LOWER(listing_type)=LOWER('".q($fltList)."')";

/* Tag WHERE (IN for multiple) */
$tagFlags = array_values(array_unique(array_filter(array_map('trim',$tagFlags))));
if ($tagFlags){
  $esc = array_map(fn($t)=>"'".q(strtolower($t))."'", $tagFlags);
  $where[] = "LOWER(TRIM(project_tag)) IN (".implode(',',$esc).")";
}

if ($minBeds>0 && col_exists($PROJECTS,'bedrooms')) $where[]="(COALESCE(bedrooms,0)+0) >= ".(int)$minBeds;
if ($maxBeds>0 && col_exists($PROJECTS,'bedrooms')) $where[]="(COALESCE(bedrooms,0)+0) <= ".(int)$maxBeds;
if ($priceMin!==null && col_exists($PROJECTS,'price_min')) $where[]="(COALESCE(NULLIF(price_min,''),0)+0) >= ".(float)$priceMin;
if ($priceMax!==null && col_exists($PROJECTS,'price_min')) $where[]="(COALESCE(NULLIF(price_min,''),0)+0) <= ".(float)$priceMax;

/* Amenities filter (ANY match) via EXISTS */
$amenFilterSQL='';
if (!empty($amenSel) && table_exists('project_ameneties')) {
  $ids = array_values(array_unique(array_map('intval',(array)$amenSel)));
  if ($ids){
    $amenList = implode(',', $ids);
    $amenFilterSQL = " AND EXISTS (SELECT 1 FROM project_ameneties pa WHERE pa.project_id = {$PROJECTS}.id AND pa.amenity_id IN ({$amenList}))";
  }
}

$whereSQL = $where ? ('WHERE '.implode(' AND ',$where)) : '';

/* ---- Sorting ---- */
if ($sortSel==='1'){ $orderSQL="ORDER BY COALESCE(NULLIF(price_min,''),0)+0 ASC, id DESC";
}elseif ($sortSel==='2'){ $orderSQL="ORDER BY COALESCE(NULLIF(price_min,''),0)+0 DESC, id DESC";
}elseif ($sortSel==='3'){ $orderSQL="ORDER BY COALESCE(is_featured,0) DESC, id DESC";
}else{ $orderSQL="ORDER BY id DESC"; }

/* ---- Count ---- */
$totalRows=0;
if ($res=@mysqli_query($DB,"SELECT COUNT(*) c FROM `{$PROJECTS}` {$whereSQL}{$amenFilterSQL}")){
  $r=mysqli_fetch_assoc($res); $totalRows=(int)$r['c']; mysqli_free_result($res);
}
$totalPages=max(1,(int)ceil($totalRows/$perPage));

/* ---- Fetch rows ---- */
$sql="SELECT * FROM `{$PROJECTS}` {$whereSQL} {$amenFilterSQL} {$orderSQL} LIMIT {$perPage} OFFSET {$offset}";
$rows=[]; $ids=[];
if ($res=@mysqli_query($DB,$sql)){
  while($r=mysqli_fetch_assoc($res)){ $rows[]=$r; $ids[]=(int)$r['id']; }
  mysqli_free_result($res);
}

/* ---- Preload image per project ---- */
$mediaMap=[];
if ($MEDIA && $mediaUrlCol && $ids){
  $idList=implode(',', array_map('intval',$ids));
  $typeFilter = $mediaTypeCol ? "AND (LOWER({$mediaTypeCol})='image' OR {$mediaTypeCol} IS NULL)" : "";
  $q="SELECT project_id AS pid, {$mediaUrlCol} AS u FROM `{$MEDIA}` WHERE project_id IN ({$idList}) {$typeFilter} ORDER BY {$mediaSortCol}, id";
  if ($mres=@mysqli_query($DB,$q)){
    while($m=mysqli_fetch_assoc($mres)){ $pid=(int)$m['pid']; if(!isset($mediaMap[$pid])) $mediaMap[$pid]=[]; if(trim((string)$m['u'])!=='') $mediaMap[$pid][]=['u'=>$m['u']]; }
    mysqli_free_result($mres);
  }
}

/* ---- Base chrome ---- */
$base_dir   = __DIR__ . '/Base';
$static_url = '/brocrm/assets';
ob_start(); @include "$base_dir/navbar.php"; $navlink_content=ob_get_clean(); $page='nav'; $fpage='foot';

/* ---- View ---- */
ob_start();
?>
<!-- ============================ Page Title Start================================== -->
<div class="page-title">
  <div class="container">
    <div class="row">
      <div class="col-lg-12 col-md-12">
        <h2 class="ipt-title">Property List</h2>
        <span class="ipn-subtitle">Property List With Sidebar</span>
      </div>
    </div>
  </div>
</div>
<!-- ============================ Page Title End ================================== -->

<section class="gray-simple">
  <div class="container">

    <div class="row">
      <div class="col-lg-12 col-md-12">
        <div class="filter_search_opt">
          <a href="javascript:void(0);" class="btn btn-dark full-width mb-4" onclick="openFilterSearch()">
            <span class="svg-icon text-light svg-icon-2hx me-2">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M19.0759 3H4.72777C3.95892 3 3.47768 3.83148 3.86067 4.49814L8.56967 12.6949C9.17923 13.7559 9.5 14.9582 9.5 16.1819V19.5072C9.5 20.2189 10.2223 20.7028 10.8805 20.432L13.8805 19.1977C14.2553 19.0435 14.5 18.6783 14.5 18.273V13.8372C14.5 12.8089 14.8171 11.8056 15.408 10.964L19.8943 4.57465C20.3596 3.912 19.8856 3 19.0759 3Z" fill="currentColor"/>
              </svg>
            </span>Open Filter Option
          </a>
        </div>
      </div>
    </div>

    <div class="row">

      <!-- LEFT FILTER SIDEBAR -->
      <?php include "$base_dir/Components/Listings/property-sidebar.php"; ?>

      <div class="col-lg-8 col-md-12 list-layout">

        <div class="row justify-content-center">
          <div class="col-lg-12 col-md-12">
            <div class="item-shorting-box">
              <div class="item-shorting clearfix">
                <?php $showFrom=$totalRows?($offset+1):0; $showTo=min($offset+$perPage,$totalRows); ?>
                <div class="left-column pull-left"><h4 class="fs-6 m-0">Found <?php echo (int)$showFrom; ?>–<?php echo (int)$showTo; ?> of <?php echo (int)$totalRows; ?> Results</h4></div>
              </div>
              <div class="item-shorting-box-right">
                <div class="shorting-by">
                  <form method="get">
                    <?php
                      foreach($_GET as $k=>$v){
                        if($k==='sort') continue;
                        if(is_array($v)){
                          foreach($v as $vv){ echo '<input type="hidden" name="'.h($k).'[]" value="'.h($vv).'">'; }
                        } else {
                          echo '<input type="hidden" name="'.h($k).'" value="'.h($v).'">';
                        }
                      }
                    ?>
                    <select name="sort" id="shorty" class="form-control" onchange="this.form.submit()">
                      <option value=""></option>
                      <option value="1" <?php echo ($sortSel==='1'?'selected':''); ?>>Low Price</option>
                      <option value="2" <?php echo ($sortSel==='2'?'selected':''); ?>>High Price</option>
                      <option value="3" <?php echo ($sortSel==='3'?'selected':''); ?>>Most Popular</option>
                    </select>
                  </form>
                </div>
                <ul class="shorting-list">
                  <li>
                    <a href="grid-layout-with-sidebar.php" class="w-12 h-12">
                      <span class="svg-icon text-muted-2 svg-icon-2hx">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <rect x="2" y="2" width="9" height="9" rx="2" fill="currentColor"/>
                          <rect opacity="0.3" x="13" y="2" width="9" height="9" rx="2" fill="currentColor"/>
                          <rect opacity="0.3" x="13" y="13" width="9" height="9" rx="2" fill="currentColor"/>
                          <rect opacity="0.3" x="2" y="13" width="9" height="9" rx="2" fill="currentColor"/>
                        </svg>
                      </span>
                    </a>
                  </li>
                  <li>
                    <a href="listings-list-with-sidebar.php" class="active w-12 h-12">
                      <span class="svg-icon text-seegreen svg-icon-2hx">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path opacity="0.3" d="M14 10V20C14 20.6 13.6 21 13 21H10C9.4 21 9 20.6 9 20V10C9 9.4 9.4 9 10 9H13C13.6 9 14 9.4 14 10ZM20 9H17C16.4 9 16 9.4 16 10V20C16 20.6 16.4 21 17 21H20C20.6 21 21 20.6 21 20V10C21 9.4 20.6 9 20 9Z" fill="currentColor"/>
                          <path d="M7 10V20C7 20.6 6.6 21 6 21H3C2.4 21 2 20.6 2 20V10C2 9.4 2.4 9 3 9H6C6.6 9 7 9.4 7 10ZM21 6V3C21 2.4 20.6 2 20 2H3C2.4 2 2 2.4 2 3V6C2 6.6 2.4 7 3 7H20C20.6 7 21 6.6 21 6Z" fill="currentColor"/>
                        </svg>
                      </span>
                    </a>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>

        <!-- List Cards -->
        <div class="row justify-content-center g-4">
          <?php if (!$rows): ?>
            <div class="col-12"><div class="alert alert-info">No properties found.</div></div>
          <?php else: foreach ($rows as $r):
            $pid=(int)$r['id'];
            $t=trim((string)($r['title']??$r['project_name']??'Untitled'));
            $img=pick_image($r,$mediaMap[$pid]??[]);
            $addr=addr_line($r);

            $listVal=(string)($r['listing_type']??'');
            $isRent=ieq($listVal,'rent');
            $ltxt=$isRent?'For Rent':'For Sell';
            $lcls=$isRent?'bg-success':'bg-danger';

            $ptype=trim((string)($r['property_type']??''));
            $tag = trim((string)($r['project_tag']??''));   // <- DB tag
            $isFeatured = ieq($tag,'featured') || ((int)($r['is_featured']??0)===1);

            $priceText=trim((string)($r['price_text']??''));
            $pmin=trim((string)($r['price_min']??''));
            $pmax=trim((string)($r['price_max']??''));
            if($priceText!==''){ $priceLabel=$priceText;
            } elseif($pmin!=='' && is_numeric($pmin) && $pmax!=='' && is_numeric($pmax)){ $priceLabel=rupee_label((float)$pmin).' - '.rupee_label((float)$pmax);
            } elseif($pmin!=='' && is_numeric($pmin)){ $priceLabel=rupee_label((float)$pmin);
            } else { $priceLabel=''; }

            $beds=(int)($r['bedrooms']??0);
            $baths=(int)($r['bathrooms']??0);
            $area=(int)($r['area_sqft']??0);
            $aUnit=trim((string)($r['area_unit']??'ft2'));
          ?>
          <div class="col-12">
            <div class="property-listing property-1 d-flex flex-column flex-md-row">

              <a href="property_detail.php?id=<?php echo $pid; ?>" class="property-img flex-shrink-0" style="max-width:360px; position:relative;">
                <img src="<?php echo h($img); ?>" alt="<?php echo h($t); ?>" class="img-fluid" style="height:240px;object-fit:cover;width:100%;">
                <div class="property_status" style="position:absolute; left:10px; bottom:10px;">
                  <span class="label text-light <?php echo $lcls; ?>"><?php echo h($ltxt); ?></span>
                  <?php if ($ptype!==''): ?><span class="label text-light bg-secondary"><?php echo h($ptype); ?></span><?php endif; ?>
                  <?php if ($isFeatured): ?>
                    <span class="label text-dark bg-warning">Featured</span>
                  <?php elseif ($tag!==''): ?>
                    <span class="label text-light bg-info"><?php echo h($tag); /* Exclusive */ ?></span>
                  <?php endif; ?>
                </div>
              </a>

              <div class="property-content ms-md-3 mt-3 mt-md-0">
                <div class="listing-detail-wrapper">
                  <div class="listing-short-detail">
                    <h4 class="listing-name mb-1"><a href="property_detail.php?id=<?php echo $pid; ?>"><?php echo h($t); ?></a></h4>
                    <?php if ($addr!==''): ?><span class="property-location"><i class="lni-map-marker"></i> <?php echo h($addr); ?></span><?php endif; ?>
                  </div>
                  <?php if ($priceLabel!==''): ?>
                    <div class="list-price mt-2"><h5 class="price text-primary m-0"><?php echo h($priceLabel); ?></h5></div>
                  <?php endif; ?>
                </div>

                <div class="price-features-wrapper mt-3">
                  <div class="list-fx-features">
                    <?php if ($beds>0): ?>
                      <div class="listing-card-info-icon"><div class="inc-fleat-icon me-1"><img src="<?php echo $static_url; ?>/img/bed.svg" width="13" alt=""></div><?php echo $beds; ?> Bed</div>
                    <?php endif; ?>
                    <?php if ($baths>0): ?>
                      <div class="listing-card-info-icon"><div class="inc-fleat-icon me-1"><img src="<?php echo $static_url; ?>/img/bathtub.svg" width="13" alt=""></div><?php echo $baths; ?> Bath</div>
                    <?php endif; ?>
                    <?php if ($area>0): ?>
                      <div class="listing-card-info-icon"><div class="inc-fleat-icon me-1"><img src="<?php echo $static_url; ?>/img/move.svg" width="13" alt=""></div><?php echo $area.' '.h($aUnit?:'ft2'); ?></div>
                    <?php endif; ?>
                  </div>
                </div>

                <div class="listing-footer-wrapper mt-3">
                  <a href="property_detail.php?id=<?php echo $pid; ?>" class="btn btn-sm btn-primary">View Details</a>
                </div>
              </div>

            </div>
          </div>
          <?php endforeach; endif; ?>
        </div>

        <!-- Pagination (preserves filters) -->
        <div class="row">
          <div class="col-lg-12 col-md-12 col-sm-12">
            <?php if ($totalPages>1): ?>
            <ul class="pagination p-center">
              <li class="page-item <?php echo $page<=1?'disabled':''; ?>">
                <a class="page-link" href="<?php echo $page>1 ? build_qs(['page'=>$page-1]) : 'javascript:void(0)'; ?>" aria-label="Previous">
                  <i class="fa-solid fa-arrow-left-long"></i>
                </a>
              </li>
              <?php $start=max(1,$page-2); $end=min($totalPages,$page+2); for($p=$start;$p<=$end;$p++): ?>
                <li class="page-item <?php echo $p===$page?'active':''; ?>">
                  <a class="page-link" href="<?php echo build_qs(['page'=>$p]); ?>"><?php echo $p; ?></a>
                </li>
              <?php endfor; ?>
              <li class="page-item <?php echo $page>=$totalPages?'disabled':''; ?>">
                <a class="page-link" href="<?php echo $page<$totalPages ? build_qs(['page'=>$page+1]) : 'javascript:void(0)'; ?>" aria-label="Next">
                  <i class="fa-solid fa-arrow-right-long"></i>
                </a>
              </li>
            </ul>
            <?php endif; ?>
          </div>
        </div>

      </div>
    </div>
  </div>
</section>

<!-- ============================ Call To Action ================================== -->
<section class="bg-primary call-to-act-wrap">
  <div class="container">
    <?php include "$base_dir/Components/Home/estate-agent.php"; ?>
  </div>
</section>

<script>
  function openFilterSearch(){
    var el=document.querySelector('.property-sidebar'); if(!el) return;
    el.style.display = (getComputedStyle(el).display==='none') ? 'block' : 'none';
  }
  // Keep Exclusive/Featured switches (in sidebar) in sync with URL
  (function(){
    const params = new URLSearchParams(location.search);
    const ex = document.getElementById('exSwitch');
    const ft = document.getElementById('featSwitch');
    if (ex) ex.checked = params.get('exclusive') === '1';
    if (ft) ft.checked = params.get('featured')  === '1';
  })();
</script>
<?php
$hero_content = ob_get_clean();

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