<?php
/* =============================================================================
 * File   : project_details.php (Soziety XHTML themed, IC Premiere-like layout)
 * Goal   : Project detail page that mimics the referenced theme’s look (excluding
 *          header & footer) while USING your existing header_mobile.php,
 *          footer_mobile.php, DB (config.php / $conn_crm), and project media.
 * Rules  : - MySQLi only (NO PDO)
 *          - DB collation utf8mb4_general_ci
 *          - Use images if available; otherwise show compact highlighted placeholders
 *          - Any required-but-missing text/fields are shown highlighted so you can add later
 * ============================================================================= */

@session_start();
date_default_timezone_set('Asia/Kolkata');

/* ---------- Load auth/bootstrap / config (must use config.php; no PDO) ------ */
$BOOTSTRAP = __DIR__ . '/../../auth_bootstrap.php';
if (file_exists($BOOTSTRAP)) {
    require_once $BOOTSTRAP; // may define $conn_crm / helpers
}
$CFG = __DIR__ . '/../../config.php';
if (file_exists($CFG)) require_once $CFG;

/* ------------------------- Pick mysqli connection --------------------------- */
$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; }

if (!($DB instanceof mysqli)) {
    http_response_code(500);
    echo "DB connection not found. Ensure config.php defines \$conn (MySQLi).";
    exit;
}

/* ---------------------------- 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 fetch_one($DB,$sql){ $res=@mysqli_query($DB,$sql); if($res){ $row=mysqli_fetch_assoc($res); @mysqli_free_result($res); return $row?:null; } return null; }
function fetch_all($DB,$sql){ $out=[]; $res=@mysqli_query($DB,$sql); if($res){ while($r=mysqli_fetch_assoc($res)){ $out[]=$r; } @mysqli_free_result($res); } return $out; }
function table_exists($DB,$name){
    $name = trim((string)$name);
    if (strpos($name,'.')!==false) { // qualified
        $res = @mysqli_query($DB, "SELECT 1 FROM {$name} LIMIT 1");
        if ($res) { @mysqli_free_result($res); return true; }
        return false;
    }
    $nameEsc = mysqli_real_escape_string($DB,$name);
    $res=@mysqli_query($DB,"SHOW TABLES LIKE '{$nameEsc}'");
    $ok=($res && mysqli_num_rows($res)>0); if($res) @mysqli_free_result($res);
    return $ok;
}
function col_exists($DB,$table,$col){
    $colEsc = mysqli_real_escape_string($DB,(string)$col);
    if (strpos($table,'.')!==false) { $res=@mysqli_query($DB,"SHOW COLUMNS FROM {$table} LIKE '{$colEsc}'"); }
    else { $tEsc = mysqli_real_escape_string($DB,$table); $res=@mysqli_query($DB,"SHOW COLUMNS FROM `{$tEsc}` LIKE '{$colEsc}'"); }
    $ok = ($res && mysqli_num_rows($res)>0); if($res) @mysqli_free_result($res);
    return $ok;
}
function try_use_db($DB,$dbname){
    $dbname = trim($dbname,'` ');
    @mysqli_query($DB,"USE `{$dbname}`");
}
function first_non_empty_in_row($row, $keys){
    foreach ($keys as $k){ if (isset($row[$k]) && trim((string)$row[$k])!=='') return trim((string)$row[$k]); }
    return '';
}
function format_date_human($val){
    if (!$val) return '';
    $ts = strtotime($val); if(!$ts) return '';
    return date('M d, Y', $ts);
}

/* --------------------------------- Inputs ---------------------------------- */
$id = isset($_GET['id']) ? trim((string)$_GET['id']) : '';
if ($id==='') { http_response_code(400); echo "Missing id"; exit; }
$safeId = mysqli_real_escape_string($DB,$id);

/* ----------------------- Resolve projects + media tables -------------------- */
$PROJECTS_TABLE = null;
$MEDIA_TABLE    = null;

/* prefer current selected DB */
foreach (['projects','project','tbl_projects','pp_projects'] as $t){
    if (table_exists($DB,$t)) { $PROJECTS_TABLE = $t; break; }
}
if (!$PROJECTS_TABLE) {
    try_use_db($DB,'broriserin_broriserin');
    foreach (['projects','project','tbl_projects','pp_projects'] as $t){
        if (table_exists($DB,$t)) { $PROJECTS_TABLE = $t; break; }
    }
}
if (!$PROJECTS_TABLE) {
    $fq = '`broriserin_broriserin`.`projects`';
    if (table_exists($DB,$fq)) $PROJECTS_TABLE = $fq;
}
if (!$PROJECTS_TABLE) { http_response_code(500); echo "Projects table not found or not accessible."; exit; }

/* Media (gallery / docs / floorplans) from project_media if present */
if (table_exists($DB,'project_media'))         $MEDIA_TABLE='project_media';
elseif (table_exists($DB,'`broriserin_broriserin`.`project_media`')) $MEDIA_TABLE='`broriserin_broriserin`.`project_media`';

/* --------------------- Column detection & data fetch ------------------------ */
$HAS = function($c) use($DB,$PROJECTS_TABLE){ return col_exists($DB,$PROJECTS_TABLE,$c); };

$C = [
    'id'        => $HAS('id') ? 'id' : ( $HAS('project_id') ? 'project_id' : 'id' ),
    'title'     => $HAS('title') ? 'title' : ( $HAS('name') ? 'name' : ( $HAS('project_name') ? 'project_name' : 'title' )),
    'address'   => $HAS('address') ? 'address' : ( $HAS('location') ? 'location' : null ),
    'city'      => $HAS('city') ? 'city' : null,
    'state'     => $HAS('state') ? 'state' : null,
    'country'   => $HAS('country') ? 'country' : null,
    'price_min' => $HAS('price_min') ? 'price_min' : null,
    'price_txt' => $HAS('price_text') ? 'price_text' : ( $HAS('price_label') ? 'price_label' : null ),
    'image'     => $HAS('cover_image') ? 'cover_image' : ( $HAS('image') ? 'image' : ( $HAS('thumbnail') ? 'thumbnail' : null )),
    'conf'      => $HAS('configuration') ? 'configuration' : null,
    'area'      => $HAS('carpet_area') ? 'carpet_area' : ( $HAS('area') ? 'area' : null ),
    'type'      => $HAS('type') ? 'type' : ( $HAS('property_type') ? 'property_type' : null ),
    'beds'      => $HAS('bedrooms') ? 'bedrooms' : null,
    'baths'     => $HAS('bathrooms') ? 'bathrooms' : null,
    'floors'    => $HAS('floors') ? 'floors' : null,
    'amen'      => $HAS('amenities') ? 'amenities' : null,
    'lat'       => $HAS('lat') ? 'lat' : null,
    'lng'       => $HAS('lng') ? 'lng' : null,
    'posted'    => $HAS('created_at') ? 'created_at' : ( $HAS('created_on') ? 'created_on' : ( $HAS('publish_date') ? 'publish_date' : ( $HAS('updated_at') ? 'updated_at' : null )))
];

/* Fetch row */
$idCol = $C['id'];
$proj  = fetch_one($DB,"SELECT * FROM {$PROJECTS_TABLE} WHERE `{$idCol}`='{$safeId}' LIMIT 1");
if (!$proj) { http_response_code(404); echo "Project not found"; exit; }

/* ----------------------------- Derived fields ------------------------------- */
$title = $proj[$C['title']] ?? 'Project';
$addressBits = [];
foreach (['address','city','state','country'] as $k){
    $col = $C[$k] ?? null;
    if ($col && !empty($proj[$col])) $addressBits[] = trim((string)$proj[$col]);
}
$fullAddress = implode(', ', array_unique(array_filter($addressBits)));
$postedOn    = format_date_human( $C['posted'] ? ($proj[$C['posted']] ?? '') : '' );

$priceText   = '';
if ($C['price_txt'] && !empty($proj[$C['price_txt']])){
    $priceText = (string)$proj[$C['price_txt']];
} elseif ($C['price_min'] && is_numeric($proj[$C['price_min']] ?? null)) {
    $priceText = 'Rs. '.number_format((float)$proj[$C['price_min']]).' onwards';
} else {
    $priceText = ''; // will render as “Contact” style when empty
}

$typeText = $C['type'] && !empty($proj[$C['type']]) ? (string)$proj[$C['type']] : '';

/* Images & categorized media (image/doc/floor) */
$images = [];
$floors = []; // floor plans
$docs   = [];

if (!empty($C['image']) && !empty($proj[$C['image']])) {
    $images[] = ['title'=>$title,'url'=>$proj[$C['image']]];
}
if ($MEDIA_TABLE){
    $rows = fetch_all($DB,"SELECT * FROM {$MEDIA_TABLE} WHERE project_id='{$safeId}' AND COALESCE(is_active,1)=1 ORDER BY sort_order,id");
    foreach($rows as $r){
        $mt = strtolower(trim((string)($r['media_type'] ?? 'image')));
        $url= trim((string)($r['url'] ?? ''));
        $ttl= trim((string)($r['title'] ?? ''));
        if (!$url) continue;
        if ($mt==='image')        $images[] = ['title'=>$ttl?:'Image', 'url'=>$url];
        elseif ($mt==='doc')      $docs[]   = ['title'=>$ttl?:'Document', 'url'=>$url];
        elseif ($mt==='floor')    $floors[] = ['title'=>$ttl?:'Floor Plan', 'url'=>$url, 'desc'=>$r['description']??''];
        else                      $images[] = ['title'=>$ttl?:ucfirst($mt), 'url'=>$url];
    }
}

/* Amenities list (comma/pipe separated) */
$amenities = [];
if (!empty($C['amen']) && !empty($proj[$C['amen']])) {
    $amenities = array_filter(array_map('trim', preg_split('/[|,]/',(string)$proj[$C['amen']])));
}

/* Meta numbers */
$beds   = $C['beds']   ? (string)($proj[$C['beds']]   ?? '') : '';
$baths  = $C['baths']  ? (string)($proj[$C['baths']]  ?? '') : '';
$fcount = $C['floors'] ? (string)($proj[$C['floors']] ?? '') : '';
$area   = $C['area']   ? (string)($proj[$C['area']]   ?? '') : '';

/* --------------------------------- SEO -------------------------------------- */
$host   = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on'?'https':'http').'://'.($_SERVER['HTTP_HOST'] ?? 'localhost');
$path   = $_SERVER['SCRIPT_NAME'] ?? '/mobile/projects_mobile/project_details.php';
$PAGE_CANONICAL = $host.$path.('?id='.urlencode($id));

$PAGE_TITLE = $title.' • Project Details';
$PAGE_DESC  = ($priceText?$priceText.' • ':'').($fullAddress?$fullAddress.' • ':'').'Explore photos, overview, amenities, floor plans, and location.';
$OG_IMAGE   = (!empty($images) ? $images[0]['url'] : '');

/* ------------------------------ Theme assets base --------------------------- */
$BASE  = defined('BASE_URL') ? rtrim(BASE_URL,'/').'/' : '/';
$ASSET = $BASE . 'mobile/';
$ACTIVE_FOOTER = 'projects'; // for footer highlight
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo h($PAGE_TITLE); ?></title>
<meta name="description" content="<?php echo h($PAGE_DESC); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=5">
<link rel="canonical" href="<?php echo h($PAGE_CANONICAL); ?>">
<meta name="robots" content="index,follow">
<meta property="og:title" content="<?php echo h($PAGE_TITLE); ?>">
<meta property="og:description" content="<?php echo h($PAGE_DESC); ?>">
<meta property="og:type" content="article">
<?php if($OG_IMAGE){ ?><meta property="og:image" content="<?php echo h($OG_IMAGE); ?>"><?php } ?>
<meta property="og:url" content="<?php echo h($PAGE_CANONICAL); ?>">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="<?php echo h($PAGE_TITLE); ?>">
<meta name="twitter:description" content="<?php echo h($PAGE_DESC); ?>">
<?php if($OG_IMAGE){ ?><meta name="twitter:image" content="<?php echo h($OG_IMAGE); ?>"><?php } ?>

<link rel="stylesheet" href="<?php echo h($ASSET.'assets/vendor/bootstrap/css/bootstrap.min.css'); ?>">
<link rel="stylesheet" href="<?php echo h($ASSET.'assets/css/style.css'); ?>">
<link rel="shortcut icon" href="<?php echo h($ASSET.'assets/images/favicon.png'); ?>" type="image/png">
<meta name="theme-color" content="#ffffff">

<style>
:root{
    --primary-color:#db1d23;
    --hover-color:#cd380f;
    --text-color:#161e2d;
    --muted:#6c757d;
    --chip:#f1f3f5;
    --highlight:#e91e63;
}

body.theme-dark :root{ --chip:rgba(255,255,255,.06); }

/* ====== Gallery (flat-gallery-single like) ====== */
.flat-gallery-single{ display:grid; grid-template-columns:2fr 1fr; grid-template-rows:auto auto auto; gap:10px; }
.flat-gallery-single .box-img{ position:relative; border-radius:14px; overflow:hidden; background:#f7f7f7; min-height:180px; }
.flat-gallery-single .item1{ grid-column:1/2; grid-row:1/3; min-height:320px; }
.flat-gallery-single .item-2{ grid-column:2/3; grid-row:1/2; min-height:155px;}
.flat-gallery-single .item-3{ grid-column:2/3; grid-row:2/3; min-height:155px;}
.flat-gallery-single .item-4, .flat-gallery-single .item-5 { display:none; } /* keep layout light on mobile */
.flat-gallery-single img{ width:100%; height:100%; object-fit:cover; display:block; }
.flat-gallery-single .box-btn{ position:absolute; right:10px; bottom:10px; }
.tf-btn.primary{ background:var(--primary-color); color:#fff; border:none; border-radius:10px; padding:.5rem .9rem; font-weight:600; }

/* ====== Property header (title/price/meta) ====== */
.flat-property-detail{ margin-top:14px; }
.header-property-detail .flag-tag{ background:var(--primary-color); color:#fff; border-radius:999px; padding:.25rem .6rem; font-size:.8rem; font-weight:700; }
.header-property-detail .title{ margin:6px 0 0 0; font-weight:700;}
.header-property-detail .box-price h4{ margin:0; color:var(--primary-color); }
.header-property-detail .meta{ display:flex; flex-wrap:wrap; gap:14px; padding:0; margin:10px 0 0 0; list-style:none; color:var(--muted);}
.header-property-detail .meta .meta-item{ display:flex; gap:8px; align-items:center; font-size:.95rem; color:var(--muted); margin:0; }

/* ====== Cards / sections ====== */
.single-property-element{ background:#fff; border:1px solid #eee; border-radius:14px; padding:16px; margin:14px 0; }
.single-property-element .title{ margin-bottom:10px; }
.single-detail p{ margin-bottom:.7rem; line-height:1.55; }

/* ====== Overview grid ====== */
.info-box{ display:grid; grid-template-columns:repeat(2,1fr); gap:12px; }
@media (min-width: 992px){ .info-box{ grid-template-columns:repeat(3,1fr);} }
.info-box .item{ display:flex; gap:12px; align-items:center; background:var(--chip); border-radius:12px; padding:10px; }
.info-box .label{ color:var(--muted); font-size:.85rem; display:block; }
.info-box .content span:last-child{ font-weight:600; }

/* ====== Features list ====== */
.box-feature ul{ display:grid; grid-template-columns:repeat(2,1fr); gap:10px; padding:0; list-style:none; margin:0; }
.box-feature li{ display:flex; gap:10px; align-items:center; border:1px dashed #e7e7e7; border-radius:10px; padding:8px 10px; }

/* ====== Map ====== */
#map-embed{ width:100%; min-height:320px; border:0; border-radius:12px; }

/* ====== Sidebar contact ====== */
.widget-sidebar{ position:sticky; top:70px; }
.single-property-contact{ border:1px solid #eee; border-radius:14px; padding:16px; }
.single-property-contact .title{ margin-bottom:12px; }
.single-property-contact .info-item{ display:block; color:var(--text-color); text-decoration:none; }
.single-property-contact .tf-btn{ width:100%; }

/* ====== Share ====== */
.property-share-social{ display:flex; gap:8px; align-items:center; margin:16px 0; }
.property-share-social .list-social{ display:flex; gap:8px; padding:0; margin:0; list-style:none; }
.box-icon{ display:inline-flex; width:40px; height:40px; border-radius:999px; align-items:center; justify-content:center; background:var(--chip); }

/* ====== Highlight for required-but-missing ====== */
.missing{ color:var(--highlight); font-weight:700; }

/* ====== Utility ====== */
.small-muted{ color:var(--muted); font-size:.9rem; }
</style>
</head>
<body>

<?php
/* Header + Sidebar (use your existing components exactly as-is) */
$H = __DIR__ . '/../../header_mobile.php';
$S = __DIR__ . '/../../sidebar_mobile.php';
if (file_exists($H)) require $H;
if (file_exists($S)) require $S;
?>

<main class="page-content container pt-3 pb-5">

  <!-- ====== GALLERY ====== -->
  <?php if (!empty($images)): ?>
    <section class="flat-gallery-single">
      <div class="item1 box-img">
        <img src="<?php echo h($images[0]['url']); ?>" alt="<?php echo h($title); ?>">
        <?php if (count($images) > 1): ?>
          <div class="box-btn">
            <a class="tf-btn primary" href="<?php echo h($images[0]['url']); ?>" target="_blank" rel="noopener">View Photos (<?php echo count($images); ?>)</a>
          </div>
        <?php endif; ?>
      </div>

      <?php
      /* show up to 2 thumbs in right column for compact layout */
      $thumbs = array_slice($images, 1, 2);
      $slot = 2;
      foreach ($thumbs as $im){
          echo '<a class="item-'.$slot.' box-img" href="'.h($im['url']).'" target="_blank" rel="noopener">';
          echo '<img src="'.h($im['url']).'" alt="'.h($title).'">';
          echo '</a>';
          $slot++;
      }
      ?>
    </section>
  <?php else: ?>
    <section class="single-property-element">
      <div class="small-muted">Photos</div>
      <div class="missing">No photos uploaded yet — add cover_image / project_media (media_type = image)</div>
    </section>
  <?php endif; ?>

  <!-- ====== HEADER (title / badge / price / meta) ====== -->
  <section class="flat-property-detail">
    <div class="single-property-element header-property-detail">
      <div class="content-top d-flex justify-content-between align-items-center">
        <div class="box-name">
          <span class="flag-tag">Selling</span>
          <h4 class="title"><?php echo h($title); ?></h4>
        </div>
        <div class="box-price d-flex align-items-center">
          <h4><?php echo $priceText ? h($priceText) : 'Contact'; ?></h4>
        </div>
      </div>

      <div class="content-bottom d-flex justify-content-between align-items-start flex-wrap">
        <div class="info-box" style="display:block">
          <ul class="meta">
            <li class="meta-item">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M4 7a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"></path><path d="M16 3v4"></path><path d="M8 3v4"></path><path d="M4 11h16"></path></svg>
              <?php echo $postedOn ? h($postedOn) : '<span class="missing">Posted date</span>'; ?>
            </li>
            <li class="meta-item">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0"></path><path d="M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0z"></path></svg>
              <?php echo $fullAddress ? h($fullAddress) : '<span class="missing">Location</span>'; ?>
            </li>
          </ul>
        </div>

        <ul class="icon-box" style="list-style:none; display:flex; gap:8px; margin:6px 0 0 0;">
          <li><button type="button" class="box-icon" title="Save"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M19.5 12.572l-7.5 7.428l-7.5 -7.428a5 5 0 1 1 7.5 -6.566a5 5 0 1 1 7.5 6.572"></path></svg></button></li>
          <li><a class="box-icon" title="Share" href="javascript:void(0)" onclick="shareIt()"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M4 12v.01"></path><path d="M12 20v.01"></path><path d="M20 12v.01"></path><path d="M7 12h10"></path><path d="M12 7l5 5l-5 5"></path></svg></a></li>
        </ul>
      </div>
    </div>
  </section>

  <!-- ====== DESCRIPTION ====== -->
  <section class="single-property-element">
    <div class="h6 title fw-7">Description</div>
    <div class="body-2 text-variant-1">
      <div class="ck-content single-detail">
        <?php
          $desc = first_non_empty_in_row($proj, ['description','detailed_description','short_description','about','project_description']);
          if ($desc) {
              echo '<p>'.nl2br(h($desc)).'</p>';
          } else {
              echo '<p class="missing">No description available — add a description column (e.g., description) to show here.</p>';
          }
        ?>
      </div>
    </div>
  </section>

  <!-- ====== OVERVIEW ====== -->
  <section class="single-property-element">
    <div class="h6 title fw-7">Overview</div>
    <div class="row row-cols-2 row-cols-lg-3 g-3 g-lg-4 info-box">
      <div class="col item">
        <div class="content">
          <span class="label">Property ID:</span>
          <span><?php echo h($proj[$C['id']]); ?></span>
        </div>
      </div>
      <div class="col item">
        <div class="content">
          <span class="label">Type:</span>
          <span><?php echo $typeText ? h($typeText) : '<span class="missing">Type</span>'; ?></span>
        </div>
      </div>
      <div class="col item">
        <div class="content">
          <span class="label">Bedrooms:</span>
          <span><?php echo $beds!=='' ? h($beds) : '<span class="missing">Beds</span>'; ?></span>
        </div>
      </div>
      <div class="col item">
        <div class="content">
          <span class="label">Bathrooms:</span>
          <span><?php echo $baths!=='' ? h($baths) : '<span class="missing">Baths</span>'; ?></span>
        </div>
      </div>
      <div class="col item">
        <div class="content">
          <span class="label">Floors:</span>
          <span><?php echo $fcount!=='' ? h($fcount) : '<span class="missing">Floors</span>'; ?></span>
        </div>
      </div>
      <div class="col item">
        <div class="content">
          <span class="label">Square:</span>
          <span><?php echo $area!=='' ? h($area) : '<span class="missing">Area</span>'; ?></span>
        </div>
      </div>
      <div class="col item">
        <div class="content">
          <span class="label">Price:</span>
          <span><?php echo $priceText ? h($priceText) : 'Contact'; ?></span>
        </div>
      </div>
    </div>
  </section>

  <!-- ====== FEATURES / AMENITIES ====== -->
  <section class="single-property-element">
    <div class="h6 title fw-7">Amenities and features</div>
    <div class="box-feature">
      <ul>
        <?php
          if ($amenities) {
              foreach ($amenities as $a) {
                  echo '<li class="feature-item">'.h($a).'</li>';
              }
          } else {
              // Show a few suggested placeholders highlighted so you can fill later
              $suggest = ['Parking','Swimming pool','Balcony','Garden','Security','Fitness center','Air Conditioning','Laundry Room','Spa & Massage'];
              foreach ($suggest as $s) {
                  echo '<li class="feature-item"><span class="missing">'.h($s).'</span></li>';
              }
          }
        ?>
      </ul>
    </div>
  </section>

  <!-- ====== LOCATION (Map) ====== -->
  <section class="single-property-element">
    <div class="h6 title fw-7">Location</div>
    <?php
      $hasGeo = (!empty($C['lat']) && !empty($C['lng']) && !empty($proj[$C['lat']]) && !empty($proj[$C['lng']]));
      if ($hasGeo) {
          $lat = urlencode((string)$proj[$C['lat']]);
          $lng = urlencode((string)$proj[$C['lng']]);
          $gmq = $lat.','.$lng;
          $gmurl = 'https://www.google.com/maps?q='.$gmq;
          // Use simple Google Maps embed (no extra libs)
          echo '<iframe id="map-embed" loading="lazy" allowfullscreen src="https://maps.google.com/maps?q='.$gmq.'&z=14&output=embed"></iframe>';
          echo '<ul class="info-map" style="list-style:none; padding-left:0; margin-top:10px;"><li><div class="fw-7">Address</div><a class="mt-2 d-inline-block" target="_blank" rel="noopener" href="'.h($gmurl).'">'.($fullAddress? h($fullAddress) : h($gmq)).'</a></li></ul>';
      } else {
          echo '<div class="missing">No geo coordinates — add lat/lng columns to enable the map.</div>';
      }
    ?>
  </section>

  <!-- ====== FLOOR PLANS ====== -->
  <section class="single-property-element">
    <div class="h6 title fw-7">Floor plans</div>
    <?php if ($floors): ?>
      <ul class="list-unstyled" id="floor-list">
        <?php foreach ($floors as $i=>$fp): ?>
          <li class="mb-3">
            <div class="fw-semibold"><?php echo h($fp['title']); ?></div>
            <?php if (!empty($fp['desc'])): ?>
              <div class="small-muted mb-2"><?php echo h($fp['desc']); ?></div>
            <?php endif; ?>
            <div class="box-img" style="border-radius:12px; overflow:hidden; border:1px solid #eee;">
              <img src="<?php echo h($fp['url']); ?>" alt="<?php echo h($fp['title']); ?>" style="width:100%; height:auto;">
            </div>
          </li>
        <?php endforeach; ?>
      </ul>
    <?php else: ?>
      <div class="missing">No floor plans — add rows in project_media with media_type = <strong>floor</strong>.</div>
    <?php endif; ?>
  </section>

  <!-- ====== SHARE ====== -->
  <section class="wrapper-onepage">
    <div class="property-share-social">
      <span>Share:</span>
      <ul class="list-social">
        <li><a class="box-icon" title="Facebook" target="_blank" href="https://www.facebook.com/sharer.php?u=<?php echo urlencode($PAGE_CANONICAL); ?>"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M7 10v4h3v7h4v-7h3l1 -4h-4v-2a1 1 0 0 1 1 -1h3v-4h-3a5 5 0 0 0 -5 5v2h-3"></path></svg></a></li>
        <li><a class="box-icon" title="X" target="_blank" href="https://x.com/intent/tweet?url=<?php echo urlencode($PAGE_CANONICAL); ?>&text=<?php echo urlencode($title); ?>"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M4 4l11.733 16h4.267l-11.733 -16z"></path><path d="M4 20l6.768 -6.768m2.46 -2.46l6.772 -6.772"></path></svg></a></li>
        <li><a class="box-icon" title="LinkedIn" target="_blank" href="https://www.linkedin.com/sharing/share-offsite/?url=<?php echo urlencode($PAGE_CANONICAL); ?>"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"></path><path d="M8 11l0 5"></path><path d="M8 8l0 .01"></path><path d="M12 16l0 -5"></path><path d="M16 16v-3a2 2 0 0 0 -4 0"></path></svg></a></li>
        <li><a class="box-icon" title="WhatsApp" target="_blank" href="https://api.whatsapp.com/send?text=<?php echo urlencode($title.' '.$PAGE_CANONICAL); ?>"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M3 21l1.65 -3.8a9 9 0 1 1 3.4 2.9l-5.05 .9"></path><path d="M9 10a.5 .5 0 0 0 1 0v-1a.5 .5 0 0 0 -1 0v1a5 5 0 0 0 5 5h1a.5 .5 0 0 0 0 -1h-1a.5 .5 0 0 0 0 1"></path></svg></a></li>
        <li><a class="box-icon" title="Email" target="_blank" href="mailto:?subject=<?php echo urlencode($title); ?>&body=<?php echo urlencode($PAGE_CANONICAL); ?>"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M3 7a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10z"></path><path d="M3 7l9 6l9 -6"></path></svg></a></li>
      </ul>
    </div>
  </section>

  <!-- ====== SIDEBAR (Contact Agency) ====== -->
  <div class="row">
    <div class="col-lg-8"></div>
    <div class="col-lg-4">
      <div class="widget-sidebar">
        <div class="widget-box single-property-contact bg-surface">
          <div class="h6 title fw-7">Contact Us</div>
          <?php
            $phone = first_non_empty_in_row($proj, ['phone','mobile','contact','contact_phone']);
            $email = first_non_empty_in_row($proj, ['email','contact_email']);
          ?>
          <div class="box-avatar d-flex align-items-center gap-3 mb-3">
            <div class="avatar avt-100 round" style="width:64px;height:64px;border-radius:999px;overflow:hidden;background:#f3f3f3;">
              <img src="<?php echo h($ASSET.'favicon.png'); ?>" alt="Agency" style="width:100%;height:100%;object-fit:contain;">
            </div>
            <div class="info">
              <div class="text-1 name fw-semibold">Broriser</div>
              <a class="info-item" href="<?php echo $phone ? 'tel:'.preg_replace('/\s+/', '', $phone) : 'javascript:void(0)'; ?>">
                <?php echo $phone ? h($phone) : '<span class="missing">Phone</span>'; ?>
              </a>
              <a class="info-item" href="<?php echo $email ? 'mailto:'.h($email) : 'javascript:void(0)'; ?>">
                <?php echo $email ? h($email) : '<span class="missing">Email</span>'; ?>
              </a>
            </div>
          </div>

          <form class="contact-form" method="post" action="javascript:void(0)" onsubmit="alert('Demo only. Hook this to your handler.');">
            <div class="mb-2">
              <label class="form-label">Name</label>
              <input type="text" class="form-control" placeholder="Your name" required>
            </div>
            <div class="mb-2">
              <label class="form-label">Phone</label>
              <input type="text" class="form-control" placeholder="Ex 0123456789" required>
            </div>
            <div class="mb-2">
              <label class="form-label">Email</label>
              <input type="email" class="form-control" placeholder="email@example.com" required>
            </div>
            <div class="mb-3">
              <label class="form-label">Message</label>
              <textarea class="form-control" rows="3" placeholder="Enter your message..." required></textarea>
            </div>
            <button class="tf-btn primary" type="submit">Send Message</button>
          </form>
        </div>
      </div>
    </div>
  </div>

</main>

<?php
/* Footer (use exactly your existing component) */
$F = __DIR__ . '/../../footer_mobile.php';
if (file_exists($F)) require $F;
?>

<script src="<?php echo h($ASSET.'assets/vendor/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
<script>
function shareIt(){
  try {
    if (navigator.share) {
      navigator.share({title: <?php echo json_encode($title); ?>, url: <?php echo json_encode($PAGE_CANONICAL); ?>});
      return;
    }
  } catch(e){}
  alert('Share this link:\\n<?php echo h($PAGE_CANONICAL); ?>');
}
</script>
</body>
</html>
