<?php
/* ============================================================================
 * property-sidebar.php (theme-compatible, safe for PHP 8+)
 * - No duplicate helper/DB definitions (guards added)
 * - Uses current GET to preserve selections
 * ========================================================================== */

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

/* ---------- Helpers (guarded) ---------- */
if (!function_exists('h')) {
  function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
}
if (!function_exists('ieq')) {
  function ieq($a,$b){ return strcasecmp((string)$a,(string)$b)===0; }
}
if (!function_exists('q')) {
  function q($s){ global $DB; return ($DB instanceof mysqli) ? mysqli_real_escape_string($DB,(string)$s) : (string)$s; }
}
if (!function_exists('table_exists')) {
  function table_exists($name){
    global $DB; if(!$DB instanceof mysqli) return false;
    $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;
  }
}
if (!function_exists('col_exists')) {
  function col_exists($tbl,$col){
    global $DB; if(!$DB instanceof mysqli) return false;
    $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;
  }
}

/* ---------- DB link (only if not already set by parent page) ---------- */
if (!isset($DB) || !($DB instanceof mysqli)) {
  // pick from known globals first
  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; }
  // try config only if still not found
  if (!($DB instanceof mysqli)) {
    $cfgs = [
      __DIR__.'/../../../config.php',
      __DIR__.'/../../config.php',
      __DIR__.'/../config.php',
      __DIR__.'/config.php'
    ];
    foreach ($cfgs as $c) { if (file_exists($c)) { require_once $c; break; } }
    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) {
  @mysqli_set_charset($DB,'utf8mb4');
  @mysqli_query($DB,"SET NAMES 'utf8mb4'");
  @mysqli_query($DB,"SET collation_connection='utf8mb4_general_ci'");
}

/* ---------- Resolve projects table ---------- */
$PROJECTS=null;
foreach(['projects','project','tbl_projects','pp_projects'] as $t){
  if (table_exists($t)) { $PROJECTS=$t; break; }
}
if (!$PROJECTS) { /* quiet fail in component */ }

/* ---------- Current selections (GET) ---------- */
$g = fn($k,$d='') => (isset($_GET[$k]) ? (is_array($_GET[$k]) ? $_GET[$k] : trim((string)$_GET[$k])) : $d);
$qtext    = $g('q');
$selCity  = $g('city');
$selType  = $g('type');
$selList  = $g('listing'); // Sell / Rent
$selTag   = $g('tag');     // project_tag
$bMin     = $g('beds_min') !== '' ? (int)$g('beds_min') : '';
$bMax     = $g('beds_max') !== '' ? (int)$g('beds_max') : '';
$pMin     = $g('pmin') !== '' ? (float)$g('pmin') : '';
$pMax     = $g('pmax') !== '' ? (float)$g('pmax') : '';
$amenSel  = $g('amenities', []); if(!is_array($amenSel)) $amenSel = [];

/* ---------- Fetch filter lists (only if DB ready) ---------- */
$cities=$types=$tags=[]; $amenities=[];
if ($DB instanceof mysqli && $PROJECTS) {
  if (col_exists($PROJECTS,'city')) {
    if ($rs=@mysqli_query($DB,"SELECT DISTINCT city FROM `{$PROJECTS}` WHERE COALESCE(city,'')<>'' ORDER BY city")){
      while($r=mysqli_fetch_assoc($rs)){ $cities[]=$r['city']; } mysqli_free_result($rs);
    }
  }
  if (col_exists($PROJECTS,'property_type')) {
    if ($rs=@mysqli_query($DB,"SELECT DISTINCT property_type FROM `{$PROJECTS}` WHERE COALESCE(property_type,'')<>'' ORDER BY property_type")){
      while($r=mysqli_fetch_assoc($rs)){ $types[]=$r['property_type']; } mysqli_free_result($rs);
    }
  }
  if (col_exists($PROJECTS,'project_tag')) {
    if ($rs=@mysqli_query($DB,"SELECT DISTINCT project_tag FROM `{$PROJECTS}` WHERE COALESCE(project_tag,'')<>'' ORDER BY project_tag")){
      while($r=mysqli_fetch_assoc($rs)){ $tags[]=$r['project_tag']; } mysqli_free_result($rs);
    }
  }
  if (table_exists('property_ameneties')) {
    if ($rs=@mysqli_query($DB,"SELECT id, amenity_name FROM property_ameneties WHERE COALESCE(is_active,1)=1 ORDER BY sort_order, amenity_name")){
      while($r=mysqli_fetch_assoc($rs)){ $amenities[]=$r; } mysqli_free_result($rs);
    }
  }
}

/* ---------- Selected labels ---------- */
$lblWhere = $selCity!=='' ? $selCity : 'Anywhere';
$lblType  = $selType!=='' ? $selType : 'Any Type';
$lblBeds  = ($bMin!=='' || $bMax!=='') ? (($bMin!==''?$bMin:'Any').' - '.($bMax!==''?$bMax:'Any')) : 'Any';
$lblPrice = ($pMin!=='' || $pMax!=='') ? ( ($pMin!==''?'₹'.number_format((float)$pMin):'Any').' - '.($pMax!==''?'₹'.number_format((float)$pMax):'Any') ) : 'Any';
$lblMood  = ($selList!=='' || $selTag!=='') ? trim(($selList?:'Any').' '.($selTag?('· '.$selTag):'')) : 'Any';
$action   = (string)($_SERVER['PHP_SELF'] ?? '');

/* ---------- Keep other GET params ---------- */
if (!function_exists('keep_get_hidden')) {
  function keep_get_hidden($skip=['q','city','type','listing','tag','beds_min','beds_max','pmin','pmax','amenities']){
    foreach($_GET as $k=>$v){
      if(in_array($k,$skip,true)) 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).'">'; }
    }
  }
}
?>

<!-- property Sidebar -->
<div class="col-lg-4 col-md-12 col-sm-12">
  <div class="simple-sidebar sm-sidebar property-sidebar" id="filter_search" style="left:0;">

    <div class="search-sidebar_header">
      <h4 class="ssh_heading">Close Filter</h4>
      <button type="button" onclick="closeFilterSearch()" class="w3-bar-item w3-button w3-large">
        <i class="fa-regular fa-circle-xmark fs-5 text-muted-2"></i>
      </button>
    </div>

    <div class="sidebar-widgets">
      <form method="get" action="<?php echo h($action); ?>" class="search-inner p-0">
        <?php keep_get_hidden(); ?>

        <div class="filter-search-box">
          <div class="form-group">
            <div class="position-relative">
              <input type="text" name="q" value="<?php echo h($qtext); ?>" class="form-control rounded-3 ps-5" placeholder="Search by space name…">
              <div class="position-absolute top-50 start-0 translate-middle-y ms-2">
                <span class="svg-icon text-primary svg-icon-2hx">
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect opacity="0.5" x="17.0365" y="15.1223" width="8.15546" height="2" rx="1" transform="rotate(45 17.0365 15.1223)" fill="currentColor"/>
                    <path d="M11 19C6.55556 19 3 15.4444 3 11C3 6.55556 6.55556 3 11 3C15.4444 3 19 6.55556 19 11C19 15.4444 15.4444 19 11 19ZM11 5C7.53333 5 5 7.53333 5 11C5 14.4667 7.53333 17 11 17C14.4667 17 17 14.4667 17 11C17 7.53333 14.4667 5 11 5Z" fill="currentColor"/>
                  </svg>
                </span>
              </div>
            </div>
          </div>
        </div>

<!-- Exclusive / Featured toggles -->
<div class="position-relative d-flex flex-xl-row flex-column align-items-center">
  <!-- Exclusive -->
  <div class="verifyd-prt-block flex-fill full-width my-1 me-1">
    <div class="d-flex align-items-center justify-content-between border rounded-3 px-2 py-3">
      <div class="eliok-cliops d-flex align-items-center">
        <span class="svg-icon text-success 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="M20.5543 4.37824L12.1798 2.02473C12.0626 1.99176 11.9376 1.99176 11.8203 2.02473L3.44572 4.37824C3.18118 4.45258 3 4.6807 3 4.93945V13.569C3 14.6914 3.48509 15.8404 4.4417 16.984C5.17231 17.8575 6.18314 18.7345 7.446 19.5909C9.56752 21.0295 11.6566 21.912 11.7445 21.9488C11.8258 21.9829 11.9129 22 12.0001 22C12.0872 22 12.1744 21.983 12.2557 21.9488C12.3435 21.912 14.4326 21.0295 16.5541 19.5909C17.8169 18.7345 18.8277 17.8575 19.5584 16.984C20.515 15.8404 21 14.6914 21 13.569V4.93945C21 4.6807 20.8189 4.45258 20.5543 4.37824Z" fill="currentColor"/>
          </svg>
        </span>
        <span class="text-muted-2 fw-medium ms-1">Exclusive</span>
      </div>
      <div class="form-check form-switch">
        <input class="form-check-input" type="checkbox" role="switch" id="exSwitch">
      </div>
    </div>
  </div>

  <!-- Featured -->
  <div class="super-agt-block flex-fill full-width my-1 ms-1">
    <div class="d-flex align-items-center justify-content-between border rounded-3 px-2 py-3">
      <div class="eliok-cliops d-flex align-items-center">
        <span class="svg-icon text-warning svg-icon-2hx">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
            <path d="M12 2l2.9 6.2 6.8.6-5 4.4 1.5 6.7L12 16.9 5.7 20l1.5-6.7-5-4.4 6.8-.6L12 2z" fill="currentColor"/>
          </svg>
        </span>
        <span class="text-muted-2 fw-medium ms-1">Featured</span>
      </div>
      <div class="form-check form-switch">
        <input class="form-check-input" type="checkbox" role="switch" id="featSwitch">
      </div>
    </div>
  </div>
</div>

<script>
(function () {
  const params = new URLSearchParams(location.search);
  const ex = document.getElementById('exSwitch');
  const ft = document.getElementById('featSwitch');

  // reflect current URL
  ex.checked = params.get('exclusive') === '1';
  ft.checked = params.get('featured')  === '1';

  function apply() {
    const u = new URL(location.href);
    ex.checked ? u.searchParams.set('exclusive', '1') : u.searchParams.delete('exclusive');
    ft.checked ? u.searchParams.set('featured',  '1') : u.searchParams.delete('featured');
    location.href = u.toString();
  }
  ex.addEventListener('change', apply);
  ft.addEventListener('change', apply);
})();
</script>

        <div class="filter_wraps">

          <!-- Where -->
          <div class="single_search_boxed">
            <div class="widget-boxed-header">
              <h4>
                <a href="#where" data-bs-toggle="collapse" aria-expanded="<?php echo $selCity!==''?'true':'false'; ?>" role="button" class="<?php echo $selCity!==''?'':'collapsed'; ?>">
                  Where<span class="selected"><?php echo h($lblWhere); ?></span>
                </a>
              </h4>
            </div>
            <div class="widget-boxed-body collapse <?php echo $selCity!==''?'show':''; ?>" id="where" data-parent="#where">
              <div class="side-list no-border">
                <div class="single_filter_card">
                  <div class="card-body pt-0">
                    <div class="inner_widget_link">
                      <ul class="no-ul-list filter-list">
                        <?php if ($cities): foreach($cities as $c): $id='city-'.md5($c); ?>
                          <li>
                            <input id="<?php echo $id; ?>" class="checkbox-custom" name="city" type="radio" value="<?php echo h($c); ?>" <?php echo ieq($selCity,$c)?'checked':''; ?>>
                            <label for="<?php echo $id; ?>" class="checkbox-custom-label"><?php echo h($c); ?></label>
                          </li>
                        <?php endforeach; else: ?>
                          <li class="text-muted">No cities found</li>
                        <?php endif; ?>
                        <li class="mt-2"><a href="javascript:void(0)" onclick="document.querySelectorAll('input[name=city]').forEach(el=>el.checked=false)">Clear</a></li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Property Types -->
          <div class="single_search_boxed">
            <div class="widget-boxed-header">
              <h4>
                <a href="#fptype" data-bs-toggle="collapse" aria-expanded="<?php echo $selType!==''?'true':'false'; ?>" role="button" class="<?php echo $selType!==''?'':'collapsed'; ?>">
                  Property Types<span class="selected"><?php echo h($lblType); ?></span>
                </a>
              </h4>
            </div>
            <div class="widget-boxed-body collapse <?php echo $selType!==''?'show':''; ?>" id="fptype" data-parent="#fptype">
              <div class="side-list no-border">
                <div class="single_filter_card">
                  <div class="card-body pt-0">
                    <div class="inner_widget_link">
                      <ul class="no-ul-list filter-list">
                        <?php if ($types): foreach($types as $t): $id='ptype-'.md5($t); ?>
                          <li>
                            <input id="<?php echo $id; ?>" class="checkbox-custom" name="type" type="radio" value="<?php echo h($t); ?>" <?php echo ieq($selType,$t)?'checked':''; ?>>
                            <label for="<?php echo $id; ?>" class="checkbox-custom-label"><?php echo h($t); ?></label>
                          </li>
                        <?php endforeach; else: ?>
                          <li class="text-muted">No property types</li>
                        <?php endif; ?>
                        <li class="mt-2"><a href="javascript:void(0)" onclick="document.querySelectorAll('input[name=type]').forEach(el=>el.checked=false)">Clear</a></li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Bedrooms -->
          <div class="single_search_boxed">
            <div class="widget-boxed-header">
              <h4>
                <a href="#fbedrooms" data-bs-toggle="collapse" aria-expanded="<?php echo ($bMin!==''||$bMax!=='')?'true':'false'; ?>" role="button" class="<?php echo ($bMin!==''||$bMax!=='')?'':'collapsed'; ?>">
                  Bedrooms<span class="selected"><?php echo h($lblBeds); ?></span>
                </a>
              </h4>
            </div>
            <div class="widget-boxed-body collapse <?php echo ($bMin!==''||$bMax!=='')?'show':''; ?>" id="fbedrooms" data-parent="#fbedrooms">
              <div class="side-list no-border">
                <div class="single_filter_card">
                  <div class="card-body pt-0">
                    <div class="row g-2">
                      <div class="col-6">
                        <label class="form-label small">Min</label>
                        <select class="form-control" name="beds_min">
                          <option value="">Any</option>
                          <?php for($i=1;$i<=6;$i++): ?>
                            <option value="<?php echo $i; ?>" <?php echo ($bMin!=='' && (int)$bMin===$i)?'selected':''; ?>><?php echo $i; ?>+</option>
                          <?php endfor; ?>
                        </select>
                      </div>
                      <div class="col-6">
                        <label class="form-label small">Max</label>
                        <select class="form-control" name="beds_max">
                          <option value="">Any</option>
                          <?php for($i=1;$i<=6;$i++): ?>
                            <option value="<?php echo $i; ?>" <?php echo ($bMax!=='' && (int)$bMax===$i)?'selected':''; ?>><?php echo $i; ?>+</option>
                          <?php endfor; ?>
                        </select>
                      </div>
                    </div>
                    <div class="mt-2"><a href="javascript:void(0)" onclick="document.querySelector('[name=beds_min]').value='';document.querySelector('[name=beds_max]').value=''">Clear</a></div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Price Range -->
          <div class="single_search_boxed">
            <div class="widget-boxed-header">
              <h4>
                <a href="#fprice" data-bs-toggle="collapse" aria-expanded="<?php echo ($pMin!==''||$pMax!=='')?'true':'false'; ?>" role="button" class="<?php echo ($pMin!==''||$pMax!=='')?'':'collapsed'; ?>">
                  Price Range<span class="selected"><?php echo h($lblPrice); ?></span>
                </a>
              </h4>
            </div>
            <div class="widget-boxed-body collapse <?php echo ($pMin!==''||$pMax!=='')?'show':''; ?>" id="fprice" data-parent="#fprice">
              <div class="side-list no-border">
                <div class="single_filter_card">
                  <div class="card-body pt-0">
                    <div class="row g-2">
                      <div class="col-6">
                        <label class="form-label small">Min (₹)</label>
                        <input type="number" class="form-control" name="pmin" value="<?php echo h($pMin); ?>" placeholder="e.g. 5000000">
                      </div>
                      <div class="col-6">
                        <label class="form-label small">Max (₹)</label>
                        <input type="number" class="form-control" name="pmax" value="<?php echo h($pMax); ?>" placeholder="e.g. 15000000">
                      </div>
                    </div>
                    <div class="mt-2"><a href="javascript:void(0)" onclick="document.querySelector('[name=pmin]').value='';document.querySelector('[name=pmax]').value=''">Clear</a></div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Mood (Listing Type + Tag) -->
          <div class="single_search_boxed">
            <div class="widget-boxed-header">
              <h4>
                <a href="#mood" data-bs-toggle="collapse" aria-expanded="<?php echo ($selList!==''||$selTag!=='')?'true':'false'; ?>" role="button" class="<?php echo ($selList!==''||$selTag!=='')?'':'collapsed'; ?>">
                  Mood<span class="selected"><?php echo h($lblMood); ?></span>
                </a>
              </h4>
            </div>
            <div class="widget-boxed-body collapse <?php echo ($selList!==''||$selTag!=='')?'show':''; ?>" id="mood" data-parent="#mood">
              <div class="side-list no-border">
                <div class="single_filter_card">
                  <div class="card-body pt-0">
                    <div class="inner_widget_link">
                      <ul class="no-ul-list filter-list">
                        <li class="mb-2"><strong class="small text-muted">Listing Type</strong></li>
                        <?php foreach (['Sell','Rent'] as $lt): $id='list-'.strtolower($lt); ?>
                          <li>
                            <input id="<?php echo $id; ?>" class="checkbox-custom" name="listing" type="radio" value="<?php echo $lt; ?>" <?php echo ieq($selList,$lt)?'checked':''; ?>>
                            <label for="<?php echo $id; ?>" class="checkbox-custom-label"><?php echo $lt; ?></label>
                          </li>
                        <?php endforeach; ?>
                        <li class="mt-2"><a href="javascript:void(0)" onclick="document.querySelectorAll('input[name=listing]').forEach(el=>el.checked=false)">Clear</a></li>

                        <li class="mt-3 mb-2"><strong class="small text-muted">Project Tag</strong></li>
                        <?php if ($tags): foreach($tags as $tg): $id='tag-'.md5($tg); ?>
                          <li>
                            <input id="<?php echo $id; ?>" class="checkbox-custom" name="tag" type="radio" value="<?php echo h($tg); ?>" <?php echo ieq($selTag,$tg)?'checked':''; ?>>
                            <label for="<?php echo $id; ?>" class="checkbox-custom-label"><?php echo h($tg); ?></label>
                          </li>
                        <?php endforeach; else: ?>
                          <li class="text-muted">No tags</li>
                        <?php endif; ?>
                        <li class="mt-2"><a href="javascript:void(0)" onclick="document.querySelectorAll('input[name=tag]').forEach(el=>el.checked=false)">Clear</a></li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Amenities -->
          <div class="single_search_boxed">
            <div class="widget-boxed-header">
              <h4>
                <a href="#ameneties" data-bs-toggle="collapse" aria-expanded="<?php echo !empty($amenSel)?'true':'false'; ?>" role="button" class="<?php echo !empty($amenSel)?'':'collapsed'; ?>">
                  Ameneties<span class="selected"><?php echo !empty($amenSel)?(count($amenSel).' Selected'):'Any'; ?></span>
                </a>
              </h4>
            </div>
            <div class="widget-boxed-body collapse <?php echo !empty($amenSel)?'show':''; ?>" id="ameneties" data-parent="#ameneties">
              <div class="side-list no-border">
                <div class="single_filter_card">
                  <div class="card-body pt-0">
                    <div class="inner_widget_link">
                      <ul class="no-ul-list filter-list">
                        <?php if ($amenities): foreach($amenities as $am):
                          $id='am-'.(int)$am['id']; $checked = in_array((int)$am['id'], array_map('intval',$amenSel), true); ?>
                          <li>
                            <input id="<?php echo $id; ?>" class="checkbox-custom" name="amenities[]" type="checkbox" value="<?php echo (int)$am['id']; ?>" <?php echo $checked?'checked':''; ?>>
                            <label for="<?php echo $id; ?>" class="checkbox-custom-label"><?php echo h($am['amenity_name']); ?></label>
                          </li>
                        <?php endforeach; else: ?>
                          <li class="text-muted">No amenities</li>
                        <?php endif; ?>
                        <?php if ($amenities): ?>
                          <li class="mt-2"><a href="javascript:void(0)" onclick="document.querySelectorAll('input[name^=amenities]').forEach(el=>el.checked=false)">Clear</a></li>
                        <?php endif; ?>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>

        <div class="form-group filter_button">
          <button type="submit" class="btn btn btn-primary rounded full-width">Show Results</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
// Fallbacks if not defined elsewhere
if (typeof openFilterSearch !== 'function') {
  window.openFilterSearch = function(){
    var el=document.getElementById('filter_search');
    if(!el) return; el.style.display = (getComputedStyle(el).display==='none') ? 'block' : 'none';
  };
}
if (typeof closeFilterSearch !== 'function') {
  window.closeFilterSearch = function(){
    var el=document.getElementById('filter_search');
    if(!el) return; el.style.display='none';
  };
}
</script>
