<?php
/* =============================================================================
 * File   : property_detail.php  (Resido detail page + Microsite Share)
 * What   : Project detail, theme-safe amenities, login-aware share popup,
 *          microsite saving & visit tracking
 * DB     : Core PHP + MySQLi (NO PDO). Uses whatever mysqli link is present
 * Params : ?id=<project id>  OR  ?title=<slug-or-title>  OR  ?slug=<slug>
 * ============================================================================= */

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

/* ------------------------- 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); 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 - check config.php'); }

/* ------------------------- 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 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 normalize_title($s){ $s=strtolower(trim((string)$s)); $s=preg_replace('/[_-]+/',' ',$s); $s=preg_replace('/\s+/', ' ', $s); $s=str_replace('&','and',$s); return trim($s); }
function base_url(){ $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 star_icons($rating){ $rating=max(0,min(5,(float)$rating)); $full=(int)floor($rating); $half=($rating-$full>=0.5)?1:0; $empty=5-$full-$half; $h=''; for($i=0;$i<$full;$i++) $h.='<i class="fa fa-star filled"></i>'; if($half) $h.='<i class="fa fa-star-half filled"></i>'; for($i=0;$i<$empty;$i++) $h.='<i class="fa fa-star"></i>'; return $h; }

/* ------------------------ Resolve table names ------------------------- */
$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;
$AMEN_M  = table_exists('property_ameneties') ? 'property_ameneties' : null;
$AMEN_P  = table_exists('project_ameneties')  ? 'project_ameneties'  : null;

/* ----------------------------- Users fetch ---------------------------- */
/* Try to locate the `users` table on any known connection */
function users_conn(){
  foreach (['conn_sa','conn_crm','conn','conn_crmplus'] as $n) {
    if (!empty($GLOBALS[$n]) && $GLOBALS[$n] instanceof mysqli) {
      $c = $GLOBALS[$n];
      $r = @mysqli_query($c, "SHOW TABLES LIKE 'users'");
      if ($r && mysqli_num_rows($r)>0) { @mysqli_free_result($r); return $c; }
    }
  }
  return null;
}
function current_user(){
  $U = users_conn(); if(!$U) return null;
  $uid = (int)($_SESSION['user_id1'] ?? 0);
  $email = trim((string)($_SESSION['user_email'] ?? ''));
  $row = null;
  if ($uid>0) {
    $rs = @mysqli_query($U, "SELECT * FROM `users` WHERE id={$uid} LIMIT 1");
    if ($rs && mysqli_num_rows($rs)) $row = mysqli_fetch_assoc($rs);
  }
  if (!$row && $email!=='') {
    $e = mysqli_real_escape_string($U,$email);
    $rs = @mysqli_query($U, "SELECT * FROM `users` WHERE email='{$e}' LIMIT 1");
    if ($rs && mysqli_num_rows($rs)) $row = mysqli_fetch_assoc($rs);
  }
  return $row ?: null;
}
$USER = current_user();

/* ----------------------------- Input --------------------------------- */
$projectId   = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$titleParam  = isset($_GET['title']) ? (string)$_GET['title'] : '';
$slugParam   = isset($_GET['slug'])  ? (string)$_GET['slug']  : '';
$lookupKey   = trim($titleParam !== '' ? $titleParam : $slugParam);

/* ------------------------- Fetch the project -------------------------- */
$project = null;
if ($projectId > 0) {
  $sql = "SELECT * FROM `{$PROJECTS}` WHERE id=? ".(col_exists($PROJECTS,'is_active')?'AND COALESCE(is_active,1)=1 ':'')."LIMIT 1";
  if ($st = mysqli_prepare($DB,$sql)) { mysqli_stmt_bind_param($st,'i',$projectId); mysqli_stmt_execute($st);
    $rs = mysqli_stmt_get_result($st); if ($rs && mysqli_num_rows($rs)) { $project = mysqli_fetch_assoc($rs); } if ($rs) @mysqli_free_result($rs); mysqli_stmt_close($st);
  }
} elseif ($lookupKey !== '') {
  $needle = normalize_title($lookupKey);
  $sql = "SELECT * FROM `{$PROJECTS}` 
          WHERE (LOWER(REPLACE(REPLACE(REPLACE(title,'_',' '),'-',' '),'  ',' ')) = ?
                 OR LOWER(REPLACE(REPLACE(REPLACE(project_name,'_',' '),'-',' '),'  ',' ')) = ?)"
          .(col_exists($PROJECTS,'is_active')?' AND COALESCE(is_active,1)=1 ':'')
          ."LIMIT 1";
  if ($st = mysqli_prepare($DB,$sql)) { mysqli_stmt_bind_param($st,'ss',$needle,$needle); mysqli_stmt_execute($st);
    $rs = mysqli_stmt_get_result($st); if ($rs && mysqli_num_rows($rs)) { $project = mysqli_fetch_assoc($rs); } if ($rs) @mysqli_free_result($rs); mysqli_stmt_close($st);
  }
} else { http_response_code(400); exit('Missing id or title/slug'); }
if (!$project) { http_response_code(404); exit('Project not found'); }

/* ------------------------ Microsite tables (ensure) ------------------- */
@mysqli_query($DB, "CREATE TABLE IF NOT EXISTS `project_share_links` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `project_id` INT UNSIGNED NOT NULL,
  `user_id` INT UNSIGNED DEFAULT NULL,
  `token` VARCHAR(255) NOT NULL,
  `agent_name` VARCHAR(150) DEFAULT NULL,
  `agent_phone` VARCHAR(50)  DEFAULT NULL,
  `agent_email` VARCHAR(150) DEFAULT NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `visits` INT UNSIGNED NOT NULL DEFAULT 0,
  `leads`  INT UNSIGNED NOT NULL DEFAULT 0,
  `last_visit_at` DATETIME DEFAULT NULL,
  `last_lead_at`  DATETIME DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniq_token` (`token`),
  KEY `idx_project_user` (`project_id`,`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");

@mysqli_query($DB, "CREATE TABLE IF NOT EXISTS `project_share_visits` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `token` VARCHAR(255) NOT NULL,
  `project_id` INT UNSIGNED NOT NULL,
  `ip_hash` CHAR(64) DEFAULT NULL,
  `ua_hash` CHAR(64) DEFAULT NULL,
  `referrer` VARCHAR(255) DEFAULT NULL,
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_token` (`token`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");

/* -------------------------- AJAX handlers ----------------------------- */
if (isset($_POST['ajax']) && $_POST['ajax']==='save_share_link') {
  header('Content-Type: application/json');
  $token  = trim((string)($_POST['token'] ?? ''));
  $pname  = trim((string)($_POST['agent_name'] ?? ''));
  $pphone = trim((string)($_POST['agent_phone'] ?? ''));
  $pemail = trim((string)($_POST['agent_email'] ?? ''));
  if ($token===''){ echo json_encode(['ok'=>false,'msg'=>'Missing token']); exit; }
  $uid = (int)($_SESSION['user_id1'] ?? 0);
  $pid = (int)$project['id'];
  $sql = "INSERT INTO `project_share_links` (`project_id`,`user_id`,`token`,`agent_name`,`agent_phone`,`agent_email`)
          VALUES (".$pid.", ".($uid?:'NULL').", '".q($token)."', ".($pname!==''?"'".q($pname)."'":"NULL").", ".($pphone!==''?"'".q($pphone)."'":"NULL").", ".($pemail!==''?"'".q($pemail)."'":"NULL").")
          ON DUPLICATE KEY UPDATE agent_name=VALUES(agent_name), agent_phone=VALUES(agent_phone), agent_email=VALUES(agent_email)";
  $ok = @mysqli_query($DB,$sql);
  echo json_encode(['ok'=>(bool)$ok,'id'=>$ok?mysqli_insert_id($DB):0,'err'=>$ok?null:mysqli_error($DB)]);
  exit;
}

if (isset($_POST['ajax']) && $_POST['ajax']==='track_visit') {
  header('Content-Type: application/json');
  $token = trim((string)($_POST['token'] ?? '')); $pid=(int)$project['id'];
  if ($token!==''){
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $ip_hash = hash('sha256', $ip);
    $ua_hash = hash('sha256', $ua);
    @mysqli_query($DB, "INSERT INTO `project_share_visits` (`token`,`project_id`,`ip_hash`,`ua_hash`,`referrer`)
                        VALUES ('".q($token)."', {$pid}, '".q($ip_hash)."', '".q($ua_hash)."', '".q(substr((string)($_SERVER['HTTP_REFERER']??''),0,250))."')");
    @mysqli_query($DB, "UPDATE `project_share_links` SET visits=visits+1, last_visit_at=NOW() WHERE token='".q($token)."' AND project_id={$pid} LIMIT 1");
  }
  echo json_encode(['ok'=>true]); exit;
}

/* ----------------------- Values & labels ------------------------------ */
function val($row,$k,$d=''){ return (isset($row[$k]) && $row[$k]!=='' && $row[$k]!==null) ? $row[$k] : $d; }

$title        = val($project,'title', val($project,'project_name','Untitled Project'));
$city         = val($project,'city','');            $region       = val($project,'region','');
$location     = val($project,'location','');        $address      = val($project,'address','');
$propertyType = val($project,'property_type','');   $description  = val($project,'description','');
$projTag      = val($project,'project_tag','');     $isFeatured   = (int)val($project,'is_featured',0) === 1 || strtolower($projTag)==='featured';
$listingType  = ucfirst(strtolower(val($project,'listing_type','Sell'))); // Sell/Rent
$priceText    = val($project,'price_text','');      $priceMin   = trim((string)val($project,'price_min',''));
$priceMax     = trim((string)val($project,'price_max',''));
$bedroomsRaw  = val($project,'bedrooms','');        $bathrooms  = val($project,'bathrooms','');
$floors       = val($project,'floors','');          $areaSqft   = val($project,'area_sqft','');
$areaUnit     = val($project,'area_unit','ft2');    $config     = val($project,'configuration','');
$carpetArea   = val($project,'carpet_area','');     $websiteUrl = val($project,'website_url','');
$lat          = val($project,'lat','');             $lng        = val($project,'lng','');
$propertyVideo= val($project,'property_video','');  $featuresJSON = val($project,'features_json','');

$addrLineParts = array_filter([($address ?: $location), $city, $region], fn($x)=> !!$x);
$addrLine = implode(', ', array_unique($addrLineParts));
$priceLabel = $priceText!=='' ? $priceText : (($priceMin!=='' && $priceMax!=='') ? ('₹ '.number_format((float)$priceMin).' - ₹ '.number_format((float)$priceMax)) : (($priceMin!=='') ? '₹ '.number_format((float)$priceMin) : ''));
$bedroomsLabel = ''; if ($bedroomsRaw!==''){ $b=(int)$bedroomsRaw; $map=[1=>'01 Bedrooms',2=>'02 Bedrooms',3=>'03 Bedrooms',4=>'04 Bedrooms',5=>'05 Bedrooms',6=>'06+ Bedrooms']; $bedroomsLabel=$map[$b]??(string)$bedroomsRaw; }

/* --------------------------- Media (gallery/floor) -------------------- */
$gallery=[]; $floorsMedia=[];
if ($MEDIA){
  $urlCol = col_exists($MEDIA,'url')?'url':(col_exists($MEDIA,'file_url')?'file_url':null);
  $typeCol= col_exists($MEDIA,'media_type')?'media_type':null;
  $titleCol= col_exists($MEDIA,'title')?'title':null;
  $sortCol= col_exists($MEDIA,'sort_order')?'sort_order':'id';
  $isActSql = col_exists($MEDIA,'is_active') ? 'AND COALESCE(is_active,1)=1' : '';
  if($urlCol){
    $q="SELECT {$urlCol} AS u FROM `{$MEDIA}` WHERE project_id=? {$isActSql} ".($typeCol?"AND LOWER({$typeCol})='image'":'')." ORDER BY {$sortCol},id";
    if($st=mysqli_prepare($DB,$q)){ mysqli_stmt_bind_param($st,'i',$project['id']); mysqli_stmt_execute($st); $rs=mysqli_stmt_get_result($st);
      while($rs && ($r=mysqli_fetch_assoc($rs))){ $u=trim((string)$r['u']); if($u!=='') $gallery[]=$u; } if($rs) @mysqli_free_result($rs); mysqli_stmt_close($st);
    }
    if($typeCol){
      $q="SELECT {$urlCol} AS u".($titleCol?(",{$titleCol} AS t"):'')." FROM `{$MEDIA}` WHERE project_id=? {$isActSql} AND LOWER({$typeCol})='floor' ORDER BY {$sortCol},id";
      if($st=mysqli_prepare($DB,$q)){ mysqli_stmt_bind_param($st,'i',$project['id']); mysqli_stmt_execute($st); $rs=mysqli_stmt_get_result($st);
        while($rs && ($r=mysqli_fetch_assoc($rs))){ $u=trim((string)$r['u']); if($u!=='') $floorsMedia[]=['title'=>trim((string)($r['t']??'Floor Plan')),'url'=>$u]; }
        if($rs) @mysqli_free_result($rs); mysqli_stmt_close($st);
      }
    }
  }
}
if(empty($gallery)){
  foreach(['cover_image','image','thumbnail'] as $c){ if(col_exists($PROJECTS,$c)){ $u=trim((string)$project[$c]??''); if($u!=='') $gallery[]=$u; } }
}

/* --------------------------- Amenities -------------------------------- */
$amenityList=[];
if ($AMEN_P && $AMEN_M){
  $sql="SELECT m.amenity_name FROM `{$AMEN_P}` p JOIN `{$AMEN_M}` m ON m.id=p.amenity_id WHERE p.project_id=? AND COALESCE(m.is_active,1)=1 ORDER BY m.sort_order,m.amenity_name";
  if($st=mysqli_prepare($DB,$sql)){ mysqli_stmt_bind_param($st,'i',$project['id']); mysqli_stmt_execute($st); $rs=mysqli_stmt_get_result($st);
    while($rs && ($r=mysqli_fetch_assoc($rs))){ $n=trim((string)$r['amenity_name']); if($n!=='') $amenityList[]=$n; } if($rs) @mysqli_free_result($rs); mysqli_stmt_close($st);
  }
}
if(empty($amenityList) && col_exists($PROJECTS,'amenities')){ $csv=trim((string)$project['amenities']); if($csv!=='') $amenityList=array_values(array_filter(array_map('trim',explode(',',$csv)))); }

/* --------------------------- Nearby (features_json) ------------------- */
$nearbySchools=$nearbyFood=[];
if($featuresJSON!==''){ $fx=json_decode($featuresJSON,true); if(isset($fx['nearby']['schools']) && is_array($fx['nearby']['schools'])) $nearbySchools=$fx['nearby']['schools']; if(isset($fx['nearby']['food']) && is_array($fx['nearby']['food'])) $nearbyFood=$fx['nearby']['food']; }

/* ---------------------- Paths / base layout includes ------------------ */
$base_dir   = __DIR__ . '/Base';
$static_url = '/brocrm/assets';

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

/* --------------------------- HERO + PAGE ------------------------------ */
ob_start();
?>
<style>
/* Remove theme's missing-icon toggles to stop □ squares on headers */
.property_block_wrap .property_block_wrap_header:after,
.property_block_wrap .property_block_title:after { content:none !important; display:none !important; }
/* Amenity bullets (SVG) */
.amenity-li { display:flex; align-items:center; gap:.5rem; padding:.25rem 0; }
.amenity-li svg { flex:0 0 18px; }
</style>

<!-- ============================ Hero Banner  Start================================== -->
<div class="featured_slick_gallery gray">
  <div class="featured_slick_gallery-slide">
    <?php if (!empty($gallery)): foreach ($gallery as $u): ?>
      <div class="featured_slick_padd"><a href="<?php echo h($u); ?>" class="mfp-gallery"><img src="<?php echo h($u); ?>" class="img-fluid mx-auto" alt="<?php echo h($title); ?>" /></a></div>
    <?php endforeach; else: ?>
      <div class="featured_slick_padd"><a href="<?php echo $static_url; ?>/img/p-1.jpg" class="mfp-gallery"><img src="<?php echo $static_url; ?>/img/p-1.jpg" class="img-fluid mx-auto" alt="" /></a></div>
      <div class="featured_slick_padd"><a href="<?php echo $static_url; ?>/img/p-2.jpg" class="mfp-gallery"><img src="<?php echo $static_url; ?>/img/p-2.jpg" class="img-fluid mx-auto" alt="" /></a></div>
    <?php endif; ?>
  </div>
  <?php if (!empty($gallery)): ?><!--<a href="JavaScript:Void(0);" class="btn-view-pic">View photos</a>--><?php endif; ?>
</div>
<!-- ============================ Hero Banner End ================================== -->

<!-- ============================ Property Detail Start ================================== -->
<section class="gray-simple">
  <div class="container">
    <div class="row">
      
      <!-- property main detail -->
      <div class="col-lg-8 col-md-12 col-sm-12">
        <div class="property_block_wrap style-2 p-4">
          <div class="prt-detail-title-desc">
            <div class="d-flex flex-wrap gap-2">
              <?php
                $ltxt = ($listingType==='Rent')?'For Rent':'For Sell';
                $lcls = ($listingType==='Rent')?'bg-success':'bg-danger';
              ?>
              <span class="label text-light <?php echo $lcls; ?>"><?php echo h($ltxt); ?></span>
              <?php if ($propertyType!==''): ?><span class="label text-light bg-secondary"><?php echo h($propertyType); ?></span><?php endif; ?>
              <?php if ($isFeatured): ?><span class="label text-dark bg-warning">Featured</span><?php endif; ?>
              <?php if (!$isFeatured && $projTag!==''): ?><span class="label text-light bg-info"><?php echo h($projTag); ?></span><?php endif; ?>
            </div>
            <h3 class="mt-3"><?php echo h($title); ?></h3>
            <?php if ($addrLine!==''): ?><span><i class="lni-map-marker"></i> <?php echo h($addrLine); ?></span><?php endif; ?>
            <?php if ($priceLabel!==''): ?><h3 class="prt-price-fix text-primary mt-2"><?php echo h($priceLabel); ?></h3><?php endif; ?>

            <div class="list-fx-features">
              <?php if ($bedroomsLabel!==''): ?>
                <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 h($bedroomsLabel); ?></div>
              <?php endif; ?>
              <?php if ($bathrooms!==''): ?>
                <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 h((int)$bathrooms); ?> Bath</div>
              <?php endif; ?>
              <?php if ($areaSqft!==''): ?>
                <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 h((int)$areaSqft).' '.h($areaUnit); ?></div>
              <?php endif; ?>
            </div>
          </div>
        </div>

        <!-- Detail & Features -->
        <?php
          $details = [];
          if($bedroomsLabel!=='') $details['Bedrooms'] = $bedroomsLabel;
          if($bathrooms!=='')    $details['Bathrooms'] = (int)$bathrooms.' Bath';
          if($floors!=='')       $details['Floors']    = (int)$floors;
          if($areaSqft!=='')     $details['Areas']     = (int)$areaSqft.' '.$areaUnit;
          if($carpetArea!=='')   $details['Carpet Area']= $carpetArea;
          if($config!=='')       $details['Configuration']= $config;
          if($propertyType!=='') $details['Property Type']= $propertyType;
          if(col_exists($PROJECTS,'is_active')) $details['Status'] = ((string)val($project,'is_active','1')==='1'?'Active':'Inactive');
        ?>
        <?php if (!empty($details)): ?>
        <div class="property_block_wrap style-2 mt-3 p-4">
          <div class="property_block_wrap_header"><h4 class="property_block_title">Detail &amp; Features</h4></div>
          <div class="block-body">
            <div class="row">
              <?php foreach ($details as $k=>$v): ?>
                <div class="col-md-6 mb-2"><strong><?php echo h($k); ?>:</strong> <?php echo h($v); ?></div>
              <?php endforeach; ?>
            </div>
          </div>
        </div>
        <?php endif; ?>

        <!-- Description -->
        <?php if (trim($description)!==''): ?>
        <div class="property_block_wrap style-2 mt-3 p-4">
          <div class="property_block_wrap_header"><h4 class="property_block_title">Description</h4></div>
          <div class="block-body"><p class="mb-0"><?php echo nl2br(h($description)); ?></p></div>
        </div>
        <?php endif; ?>

        <!-- Amenities (theme-safe: SVG, no icon font) -->
        <?php if (!empty($amenityList)): ?>
        <div class="property_block_wrap style-2 mt-3 p-4">
          <div class="property_block_wrap_header"><h4 class="property_block_title">Amenities</h4></div>
          <div class="block-body">
            <div class="row">
              <?php foreach ($amenityList as $am): ?>
                <div class="col-md-4 col-6 amenity-li">
                  <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path d="M9 16.2l-3.5-3.5-1.4 1.4L9 19 20.3 7.7l-1.4-1.4z"></path></svg>
                  <span><?php echo h($am); ?></span>
                </div>
              <?php endforeach; ?>
            </div>
          </div>
        </div>
        <?php endif; ?>

        <!-- Property Video -->
        <?php if ($propertyVideo!==''): ?>
        <div class="property_block_wrap style-2 mt-3 p-4">
          <div class="property_block_wrap_header"><h4 class="property_block_title">Property Video</h4></div>
          <div class="block-body">
            <?php
              $pv=strtolower($propertyVideo);
              if(strpos($pv,'youtube.com')!==false || strpos($pv,'youtu.be')!==false){
                $vid=''; if(preg_match('~(?:v=|be/)([A-Za-z0-9_-]{6,})~',$propertyVideo,$m)) $vid=$m[1];
                echo $vid?('<div class="ratio ratio-16x9"><iframe src="https://www.youtube.com/embed/'.h($vid).'" allowfullscreen loading="lazy"></iframe></div>'):'<a class="btn btn-outline-primary" target="_blank" href="'.h($propertyVideo).'">Watch Video</a>';
              }elseif(strpos($pv,'vimeo.com')!==false){
                if(preg_match('~vimeo\.com/(\d+)~',$propertyVideo,$m)) echo '<div class="ratio ratio-16x9"><iframe src="https://player.vimeo.com/video/'.h($m[1]).'" allowfullscreen loading="lazy"></iframe></div>';
                else echo '<a class="btn btn-outline-primary" target="_blank" href="'.h($propertyVideo).'">Watch Video</a>';
              }else{
                echo '<video controls style="width:100%;border-radius:8px;border:1px solid #eee"><source src="'.h($propertyVideo).'"></video>';
              }
            ?>
          </div>
        </div>
        <?php endif; ?>

        <!-- Floor Plans -->
        <?php if (!empty($floorsMedia)): ?>
        <div class="property_block_wrap style-2 mt-3 p-4">
          <div class="property_block_wrap_header"><h4 class="property_block_title">Floor Plan</h4></div>
          <div class="block-body">
            <div class="row g-3">
              <?php foreach ($floorsMedia as $fl): ?>
                <div class="col-md-6">
                  <div class="card shadow-sm border">
                    <img src="<?php echo h($fl['url']); ?>" class="card-img-top" alt="<?php echo h($fl['title']); ?>" style="height:220px;object-fit:cover;">
                    <div class="card-body py-2"><div class="fw-medium"><?php echo h($fl['title']); ?></div></div>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          </div>
        </div>
        <?php endif; ?>

        <!-- Location -->
        <?php if (($lat!=='' && $lng!=='') || $addrLine!==''): ?>
        <div class="property_block_wrap style-2 mt-3 p-4">
          <div class="property_block_wrap_header"><h4 class="property_block_title">Location</h4></div>
          <div class="block-body">
            <?php if ($lat!=='' && $lng!==''): ?>
              <div class="ratio ratio-16x9">
                <iframe src="https://www.google.com/maps?q=<?php echo h($lat); ?>,<?php echo h($lng); ?>&z=15&output=embed" allowfullscreen loading="lazy"></iframe>
              </div>
            <?php elseif ($addrLine!==''): ?>
              <div class="ratio ratio-16x9">
                <iframe src="https://www.google.com/maps?q=<?php echo h(urlencode($addrLine)); ?>&z=15&output=embed" allowfullscreen loading="lazy"></iframe>
              </div>
            <?php endif; ?>
            <?php if ($addrLine!==''): ?><div class="mt-2"><i class="fa-solid fa-location-dot me-1"></i><?php echo h($addrLine); ?></div><?php endif; ?>
          </div>
        </div>
        <?php endif; ?>

        <!-- Gallery (grid) -->
        <?php if (!empty($gallery)): ?>
        <div class="property_block_wrap style-2 mt-3 p-4">
          <div class="property_block_wrap_header"><h4 class="property_block_title">Gallery</h4></div>
          <div class="block-body">
            <div class="row g-3">
              <?php foreach ($gallery as $u): ?>
                <div class="col-md-4 col-6">
                  <a href="<?php echo h($u); ?>" class="mfp-gallery d-block"><img src="<?php echo h($u); ?>" class="img-fluid rounded-3" style="height:180px;object-fit:cover;width:100%" alt=""></a>
                </div>
              <?php endforeach; ?>
            </div>
          </div>
        </div>
        <?php endif; ?>

        <!-- Nearby -->
        <?php if (!empty($nearbySchools) || !empty($nearbyFood)): ?>
        <div class="property_block_wrap style-2 mt-3 p-4">
          <div class="property_block_wrap_header"><h4 class="property_block_title">Nearby</h4></div>
          <div class="block-body">
            <?php if (!empty($nearbySchools)): ?>
              <div class="nearby-wrap mb-3">
                <div class="nearby_header">
                  <div class="nearby_header_first"><h5>Schools Around</h5></div>
                  <div class="nearby_header_last"><div class="nearby_powerd">Powerd by <img src="<?php echo $static_url; ?>/img/edu.png" class="img-fluid" alt="" /></div></div>
                </div>
                <div class="neary_section_list">
                  <?php foreach ($nearbySchools as $s): $n=trim((string)($s['name']??'')); if($n==='') continue; $dist=trim((string)($s['distance']??'')); $rat=(float)($s['rating']??0); $rev=(int)($s['reviews']??0); ?>
                  <div class="neary_section">
                    <div class="neary_section_first"><h4 class="nearby_place_title"><?php echo h($n); ?><?php if($dist!==''): ?><small>(<?php echo h($dist); ?> mi)</small><?php endif; ?></h4></div>
                    <div class="neary_section_last"><div class="nearby_place_rate"><?php echo star_icons($rat); ?></div><small class="reviews-count">(<?php echo number_format($rev); ?> Reviews)</small></div>
                  </div>
                  <?php endforeach; ?>
                </div>
              </div>
            <?php endif; ?>

            <?php if (!empty($nearbyFood)): ?>
              <div class="nearby-wrap">
                <div class="nearby_header">
                  <div class="nearby_header_first"><h5>Food Around</h5></div>
                  <div class="nearby_header_last"><div class="nearby_powerd">Powerd by <img src="<?php echo $static_url; ?>/img/food.png" class="img-fluid" alt="" /></div></div>
                </div>
                <div class="neary_section_list">
                  <?php foreach ($nearbyFood as $s): $n=trim((string)($s['name']??'')); if($n==='') continue; $dist=trim((string)($s['distance']??'')); $rat=(float)($s['rating']??0); $rev=(int)($s['reviews']??0); ?>
                  <div class="neary_section">
                    <div class="neary_section_first"><h4 class="nearby_place_title"><?php echo h($n); ?><?php if($dist!==''): ?><small>(<?php echo h($dist); ?> mi)</small><?php endif; ?></h4></div>
                    <div class="neary_section_last"><div class="nearby_place_rate"><?php echo star_icons($rat); ?></div><small class="reviews-count">(<?php echo number_format($rev); ?> Reviews)</small></div>
                  </div>
                  <?php endforeach; ?>
                </div>
              </div>
            <?php endif; ?>
          </div>
        </div>
        <?php endif; ?>

      </div>

      <!-- property Sidebar -->
      <div class="col-lg-4 col-md-12 col-sm-12">
        <div class="like_share_wrap b-0">
          <ul class="like_share_list">
            <li><a href="javascript:void(0)" id="openShareModal" class="btn btn-likes" title="Share"><i class="fas fa-share"></i>Share</a></li>
            <li><a href="javascript:void(0)" class="btn btn-likes" id="saveBtn" title="Save"><i class="fas fa-heart"></i>Save</a></li>
          </ul>
        </div>

        <div id="micrositeBannerAnchor"></div>

        <div class="property-sidebar side_stiky">
          <div class="sider_blocks_wrap p-3 border rounded-3 bg-white">
            <?php if ($priceLabel!==''): ?>
              <div class="side-booking-foot d-flex align-items-center justify-content-between">
                <span class="sb-header-left">Asking Price</span>
                <h3 class="price text-primary mb-0"><?php echo h($priceLabel); ?></h3>
              </div>
              <hr>
            <?php endif; ?>

            <div class="d-grid gap-2">
              <a href="#enquire" class="btn btn-primary fw-medium">Enquire Now</a>
              <a href="#visit" class="btn btn-outline-primary fw-medium">Schedule a Site Visit</a>
              <?php if ($websiteUrl!==''): ?>
                <a href="<?php echo h($websiteUrl); ?>" target="_blank" rel="nofollow noopener" class="btn btn-light fw-medium">Official Project Website</a>
              <?php endif; ?>
            </div>

            <?php if ($priceMin!==''): 
              $p = (float)$priceMin; $rate = 8.5/1200; $n=240; $emi = $p*$rate*pow(1+$rate,$n)/(pow(1+$rate,$n)-1);
            ?>
              <div class="mt-3">
                <div class="small text-muted mb-1">Approx. EMI (20 yrs @ 8.5%)</div>
                <div class="h5 mb-0">₹ <?php echo number_format((float)$emi); ?>/mo</div>
              </div>
            <?php endif; ?>

            <hr>
            <form id="enquire" class="mt-2" action="lead_submit.php" method="post">
              <input type="hidden" name="project_id" value="<?php echo (int)$project['id']; ?>">
              <input type="hidden" name="agent_token" id="agent_token" value="">
              <input type="hidden" name="source_url" value="<?php echo h((isset($_SERVER['REQUEST_SCHEME'])?$_SERVER['REQUEST_SCHEME']:'http').'://'.($_SERVER['HTTP_HOST']??'').($_SERVER['REQUEST_URI']??'')); ?>">
              <div class="mb-2"><label class="form-label">Name</label><input name="name" type="text" class="form-control" placeholder="Your name" required></div>
              <div class="mb-2"><label class="form-label">Phone</label><input name="phone" type="text" class="form-control" placeholder="Phone number" required></div>
              <div class="mb-2"><label class="form-label">Email</label><input name="email" type="email" class="form-control" placeholder="Email"></div>
              <div class="mb-2"><label class="form-label">Message</label><textarea name="message" class="form-control" rows="3">I'm interested in <?php echo h($title); ?>. Please contact me.</textarea></div>
              <button class="btn btn-primary w-100" type="submit">Request Call Back</button>
            </form>
          </div>
        </div>
      </div>

    </div>
  </div>
</section>
<!-- ============================ Property Detail End ================================== -->

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

<!-- Microsite Share Modal -->
<div id="shareModal" class="modal" tabindex="-1" style="display:none">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title">Create Agent Microsite Link</h6>
        <button type="button" class="btn-close" aria-label="Close" onclick="hideShareModal()"></button>
      </div>
      <div class="modal-body">
        <?php if ($USER): ?>
          <div class="alert alert-info py-2">Sharing as <strong><?php echo h(trim(($USER['first_name']??'').' '.($USER['last_name']??''))); ?></strong>
            <?php if(!empty($USER['phone'])) echo ' • '.h($USER['phone']); ?>
            <?php if(!empty($USER['email'])) echo ' • '.h($USER['email']); ?>
          </div>
          <input type="hidden" id="agName"  value="<?php echo h(trim(($USER['first_name']??'').' '.($USER['last_name']??''))); ?>">
          <input type="hidden" id="agPhone" value="<?php echo h($USER['phone'] ?? ''); ?>">
          <input type="hidden" id="agEmail" value="<?php echo h($USER['email'] ?? ''); ?>">
          <button class="btn btn-primary mb-3" type="button" id="btnGenerate">Generate Link</button>
        <?php else: ?>
          <div class="alert alert-warning">Please log in to generate your microsite link.</div>
        <?php endif; ?>

        <div id="linkWrap" class="d-none">
          <label class="form-label">Your microsite URL</label>
          <div class="input-group">
            <input type="text" class="form-control" id="agLink" readonly>
            <button class="btn btn-outline-secondary" type="button" id="btnCopy">Copy</button>
            <button class="btn btn-outline-primary" type="button" id="btnNativeShare">Share</button>
          </div>
          <small class="text-muted d-block mt-1">
            Enquiries from this link will be auto-assigned to you.
          </small>
        </div>
      </div>
    </div>
  </div>
</div>

<script>
/* ---------- Minimal modal show/hide ---------- */
const shareModal = document.getElementById('shareModal');
const openShare = document.getElementById('openShareModal');
if (openShare) openShare.addEventListener('click', ()=>{ shareModal.style.display='block'; shareModal.classList.add('show'); });
function hideShareModal(){ shareModal.classList.remove('show'); shareModal.style.display='none'; }

/* ---------- base64url helpers ---------- */
function b64uEncode(str){return btoa(unescape(encodeURIComponent(str))).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');}
function b64uDecode(str){str=str.replace(/-/g,'+').replace(/_/g,'/'); return decodeURIComponent(escape(atob(str)));}

/* ---------- Build & save microsite link ---------- */
const linkWrap = document.getElementById('linkWrap');
const agLink   = document.getElementById('agLink');

function generateTokenPayload(){
  const n = (document.getElementById('agName')?.value||'').trim();
  const p = (document.getElementById('agPhone')?.value||'').trim();
  const e = (document.getElementById('agEmail')?.value||'').trim();
  const payload = JSON.stringify({n, p, e, t: Date.now()});
  return { token: b64uEncode(payload), agent_name:n, agent_phone:p, agent_email:e };
}

function showLinkAndSave(){
  const g = generateTokenPayload();
  const url = new URL(window.location.href);
  url.searchParams.set('id', '<?php echo (int)$project['id']; ?>'); // canonical id
  url.searchParams.set('ag', g.token);
  agLink.value = url.toString();
  linkWrap.classList.remove('d-none');

  // save in DB
  const form = new URLSearchParams();
  form.append('ajax','save_share_link');
  form.append('token', g.token);
  form.append('agent_name', g.agent_name);
  form.append('agent_phone', g.agent_phone);
  form.append('agent_email', g.agent_email);
  fetch(location.href, {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:form.toString()})
    .then(r=>r.json()).then(j=>{ if(!j.ok){ console.warn('Save failed', j); } });
}

document.getElementById('btnGenerate')?.addEventListener('click', showLinkAndSave);
document.getElementById('btnCopy')?.addEventListener('click', async ()=>{ await navigator.clipboard.writeText(agLink.value); alert('Link copied'); });
document.getElementById('btnNativeShare')?.addEventListener('click', async ()=>{ if(navigator.share){ try{ await navigator.share({title:document.title,url:agLink.value}); }catch(e){} } else { await navigator.clipboard.writeText(agLink.value); alert('Link copied'); }});

/* ---------- If arriving via microsite, banner + hidden token + visit track ---------- */
function readMicrositeToken(){
  const usp = new URLSearchParams(location.search);
  const ag = usp.get('ag'); if(!ag) return null;
  try { return {raw:ag, data: JSON.parse(b64uDecode(ag))}; } catch(e){ return {raw:ag, data:null}; }
}
const _ag = readMicrositeToken();
if (_ag){
  // Banner
  const host = document.getElementById('micrositeBannerAnchor');
  const bar = document.createElement('div');
  bar.className = 'mb-3';
  const nm = (_ag.data && _ag.data.n) ? _ag.data.n : 'Agent';
  const ph = (_ag.data && _ag.data.p) ? _ag.data.p : '';
  bar.innerHTML = '<div class="p-2 rounded-3" style="background:#fff3cd;border:1px solid #ffe69c;">' +
                  '<strong>Presented by:</strong> ' + nm + (ph?(' &nbsp;•&nbsp; <a href="tel:'+ph+'">'+ph+'</a>'):'') + '</div>';
  host.appendChild(bar);

  // token in enquiry form
  const tokField = document.getElementById('agent_token'); if (tokField) tokField.value = _ag.raw;

  // track visit
  const form=new URLSearchParams(); form.append('ajax','track_visit'); form.append('token', _ag.raw);
  fetch(location.href, { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:form.toString() }).catch(()=>{});
}

/* ---------- Save (dummy favorite button) ---------- */
document.getElementById('saveBtn')?.addEventListener('click', ()=>{ alert('Saved to favorites (demo).'); });
</script>
<?php
$hero_content = ob_get_clean();

/* ---------------------------- Render base ----------------------------- */
$base_tpl = "$base_dir/style/base.php";
if (file_exists($base_tpl)) {
  include $base_tpl;   // expects $navlink_content, $hero_content
} else {
  ?><!doctype html>
  <html lang="en">
  <head>
    <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?php echo h($title); ?></title>
    <link rel="stylesheet" href="<?php echo h($static_url); ?>/css/styles.css">
  </head>
  <body><?php echo $hero_content; ?></body>
  </html><?php
}
