<?php
/* =============================================================================
 * File   : home_mobile.php  (unified renderer; Soziety XHTML theme aware)
 * Goal   : ONE file that renders Home for both Mobile + Desktop.
 * Stack  : Core PHP + MySQLi (NO PDO). DB links come from ./config.php
 * Notes  : Integrates Soziety XHTML UI kit assets (xhtml/assets/*)
 * ============================================================================= */

@session_start();
require_once __DIR__ . '/config.php';

/* ------------------------- Choose DB 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; }
if (function_exists('_set_charset_and_collation')) { _set_charset_and_collation($DB); }

/* -------------------- Security + Robots -------------------- */
@header('X-Content-Type-Options: nosniff');
@header('Referrer-Policy: strict-origin-when-cross-origin');
@header('X-Robots-Tag: index, follow');

/* ------------------------ Helpers ------------------------- */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function fetch_all($c,$sql){ $o=[]; if($c && $r=@mysqli_query($c,$sql)){ while($x=mysqli_fetch_assoc($r)){ $o[]=$x; } @mysqli_free_result($r);} return $o; }
function fetch_one($c,$sql){ $row=[]; if($c && ($r=@mysqli_query($c,$sql))){ $row=mysqli_fetch_assoc($r)?:[]; @mysqli_free_result($r);} return $row; }
function tbl_exists($c,$n){ if(!$c) return false; $n=mysqli_real_escape_string($c,$n); $r=@mysqli_query($c,"SHOW TABLES LIKE '{$n}'"); $ok=($r&&mysqli_num_rows($r)>0); if($r) @mysqli_free_result($r); return $ok; }
function col_exists($c,$t,$x){ if(!$c) return false; $t=mysqli_real_escape_string($c,$t); $x=mysqli_real_escape_string($c,$x); $r=@mysqli_query($c,"SHOW COLUMNS FROM `{$t}` LIKE '{$x}'"); $ok=($r&&mysqli_num_rows($r)>0); if($r) @mysqli_free_result($r); return $ok; }
function get_setting($c,$k,$d=null){ if(!$c) return $d; $k=mysqli_real_escape_string($c,$k); $r=@mysqli_query($c,"SELECT setting_val FROM ui_app_settings WHERE setting_key='{$k}' LIMIT 1"); if($r&&($x=mysqli_fetch_assoc($r))){ @mysqli_free_result($r); return $x['setting_val']; } if($r) @mysqli_free_result($r); return $d; }

/* Prefer a local .webp if available (for <picture>) */
function hm_local_webp_or_null($url){
  if(!$url) return null;
  if(strpos($url,'http://')===0 || strpos($url,'https://')===0) return null;
  $p = parse_url($url, PHP_URL_PATH); if(!$p) return null;
  $try = preg_replace('/\.(jpe?g|png)$/i', '.webp', $p);
  if($try!==$p){
    $full = rtrim($_SERVER['DOCUMENT_ROOT']??'','/').$try;
    if(is_file($full)) return $try;
  }
  return null;
}
function hm_picture($url,$alt,$w,$h,$opts=[]){
  $sizes=$opts['sizes']??'100vw';
  $priority=!empty($opts['priority']);
  $loading=$priority?'eager':'lazy';
  $decoding=$priority?'sync':'async';
  $fetch=$priority?'high':'auto';
  $webp=hm_local_webp_or_null($url);
  $wA=$w?' width="'.(int)$w.'"':'';
  $hA=$h?' height="'.(int)$h.'"':'';
  $extra=!empty($opts['extra'])?$opts['extra']:'';
  $html='<picture>';
  if($webp){ $html.='<source type="image/webp" srcset="'.h($webp).'" sizes="'.h($sizes).'">'; }
  $html.='<img src="'.h($url).'" alt="'.h($alt).'" loading="'.$loading.'" decoding="'.$decoding.'" fetchpriority="'.$fetch.'"'.$wA.$hA.' '.$extra.'>';
  $html.='</picture>';
  return $html;
}

/* ----------------------- Theme defaults -------------------- */
$BASE = defined('BASE_URL') ? rtrim(BASE_URL,'/').'/' : ''; // used to build local asset paths
$ASSET_PREFIX = $BASE . 'xhtml/'; // points to uploaded kit
$DEFAULT_THEME = tbl_exists($DB,'ui_app_settings') ? (get_setting($DB,'default_theme','light') ?: 'light') : 'light';
$FORCE_THEME   = tbl_exists($DB,'ui_app_settings') ? (int)(get_setting($DB,'force_theme','0') ?: 0) : 0;

/* Optional tokens (bg/text/primary/line/card/chip…) */
$TOK=[];
if(tbl_exists($DB,'ui_theme_tokens')){
  foreach(fetch_all($DB,"SELECT token,dark_value,light_value FROM ui_theme_tokens") as $r){
    $k=preg_replace('~[^a-z0-9_-]+~i','',strtolower($r['token']??'')); if($k) $TOK[$k]=['light'=>trim((string)($r['light_value']??'')),'dark'=>trim((string)($r['dark_value']??''))];
  }
}
function token_or($key,$light,$dark=null){ global $TOK,$DEFAULT_THEME,$FORCE_THEME; $dark=$dark??$light; $mode=($FORCE_THEME&&$DEFAULT_THEME==='dark')?'dark':'light'; if(isset($TOK[$key])&&($TOK[$key][$mode]??'')) return $TOK[$key][$mode]; return $mode==='dark'?$dark:$light; }

/* ------------------------ Content -------------------------- */
$rows = tbl_exists($DB,'ui_home') ? fetch_all($DB,"SELECT * FROM ui_home WHERE is_active=1 ORDER BY section, sort_order, id") : [];
$banners=[]; $highlights=[]; $quickActions=[]; $opps=[]; $stats=['matches'=>0,'earnings'=>['currency'=>'₹','amount'=>0]]; $network=null; $grid=[]; $events=[];
foreach($rows as $r){
  $sec=strtolower(trim($r['section']));
  if($sec==='banner') $banners[]=$r;
  elseif($sec==='highlight') $highlights[]=$r;
  elseif($sec==='quick_action') $quickActions[]=$r;
  elseif($sec==='opportunity') $opps[]=$r;
  elseif($sec==='stat'){ $sub=strtolower((string)$r['subtype']); if($sub==='matches') $stats['matches']=(int)$r['count_value']; if($sub==='earnings') $stats['earnings']=['currency'=>$r['currency']?:'₹','amount'=>(float)$r['amount']]; }
  elseif($sec==='network'){ if(!$network) $network=$r; }
  elseif($sec==='grid') $grid[]=$r;
  elseif($sec==='event') $events[]=$r;
}

/* ------------------------ Projects (CRM DB) ------------------------- */
$PROJECTS_TABLE=null; foreach(['projects','project','tbl_projects','pp_projects','projects_master'] as $try){ if(tbl_exists($DB,$try)){ $PROJECTS_TABLE=$try; break; } }
$C=[]; if($PROJECTS_TABLE){
  $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')),
    'city'      => $HAS('city')?'city':($HAS('city_id')?'city_id':null),
    'region'    => $HAS('region')?'region':($HAS('region_id')?'region_id':null),
    'location'  => $HAS('location')?'location':($HAS('address')?'address':($HAS('locality_id')?'locality_id':null)),
    'price_min' => $HAS('price_min')?'price_min':($HAS('starting_price')?'starting_price':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)),
    'badges'    => $HAS('badges')?'badges':($HAS('tags')?'tags':null),
    'is_feat'   => $HAS('is_featured')?'is_featured':($HAS('featured')?'featured':null),
    'url'       => $HAS('website_url')?'website_url':null,
  ];
}
$homeProjects=[];
if($PROJECTS_TABLE){
  $where = (!empty($C['is_feat'])) ? "WHERE COALESCE(`{$C['is_feat']}`,0)=1" : '';
  $rowsP = fetch_all($DB,"SELECT * FROM `{$PROJECTS_TABLE}` {$where} ORDER BY 1 DESC LIMIT 24");
  if(!$rowsP) $rowsP = fetch_all($DB,"SELECT * FROM `{$PROJECTS_TABLE}` ORDER BY 1 DESC LIMIT 24");
  foreach($rowsP as $row){
    $title=$row[$C['title']]??'Untitled Project';
    $city =!empty($C['city'])?($row[$C['city']]??''):'';
    $region=!empty($C['region'])?($row[$C['region']]??''):'';
    $loc  =!empty($C['location'])?($row[$C['location']]??''):'';
    $sub=trim(($loc?$loc:'').($city?', '.$city:'').($region?', '.$region:''));
    $price=''; if(!empty($C['price_txt'])&&!empty($row[$C['price_txt']])) $price=$row[$C['price_txt']];
    elseif(!empty($C['price_min'])&&$row[$C['price_min']]!=='') $price='Rs. '.number_format((float)$row[$C['price_min']]).' onwards';
    $img=!empty($C['image'])?($row[$C['image']]??''):($PROJECTS_TABLE==='projects_master' ? (fetch_one($DB,"SELECT url FROM project_media WHERE project_id=".(int)($row[$C['id']]??0)." AND media_type='image' AND is_active=1 ORDER BY sort_order,id LIMIT 1")['url']??'') : '');
    $badges=[]; if(!empty($C['badges'])&&!empty($row[$C['badges']])){ $raw=(string)$row[$C['badges']]; $dec=json_decode($raw,true); $badges=is_array($dec)?array_values(array_filter(array_map('trim',$dec))):array_values(array_filter(array_map('trim',explode(',',$raw)))); }
    $homeProjects[]=['id'=>$row[$C['id']]??'','title'=>$title,'sub'=>$sub,'price'=>$price,'img'=>$img,'badges'=>$badges,'url'=>!empty($C['url'])&&!empty($row[$C['url']])?$row[$C['url']] : ('project_details.php?id='.urlencode($row[$C['id']]??''))];
  }
}

/* ------------------------- SEO ----------------------------- */
$metaTitle='Home • Projects, CRM & Network';
if(!empty($network['title'])) $metaTitle=h($network['title']).' • Home';
$metaDesc ='Explore featured projects, quick CRM actions, matches/earnings, and events.';
if(!empty($network['body'])) $metaDesc=h(strip_tags($network['body']));
$ogImage  = (!empty($banners[0]['image_url'])) ? $banners[0]['image_url'] : (!empty($homeProjects[0]['img']) ? $homeProjects[0]['img'] : '');
$scheme   = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') ? 'https' : 'http';
$host     = $_SERVER['HTTP_HOST'] ?? 'localhost';
$uri      = strtok($_SERVER['REQUEST_URI'] ?? '/home_mobile.php','?');
$canonical= $scheme.'://'.$host.$uri;

/* Header/Footer/Sidebar data */
$hdr_cfg=$hdr_menu=$ftr_menu=$sid_menu=[];
if(tbl_exists($DB,'ui_header_settings')) $hdr_cfg=fetch_one($DB,"SELECT * FROM ui_header_settings WHERE id=1");
if(tbl_exists($DB,'ui_header_menu'))     $hdr_menu=fetch_all($DB,"SELECT * FROM ui_header_menu WHERE is_active=1 ORDER BY sort_order,id");
if(tbl_exists($DB,'ui_footer_nav'))      $ftr_menu=fetch_all($DB,"SELECT * FROM ui_footer_nav  WHERE is_active=1 ORDER BY sort_order,id");
if(tbl_exists($DB,'ui_sidebar_menu'))    $sid_menu=fetch_all($DB,"SELECT * FROM ui_sidebar_menu WHERE is_active=1 ORDER BY (group_label IS NULL), group_label, sort_order, id");

/* -------------------- View Router (server) ----------------- */
$force = isset($_GET['view']) ? ($_GET['view']==='mobile'?'mobile':($_GET['view']==='desktop'?'desktop':'')) : '';
if($force){ setcookie('force_view',$force,time()+7*86400,'/'); $_COOKIE['force_view']=$force; }
$chosen = !empty($_COOKIE['force_view']) ? $_COOKIE['force_view'] : '';
if(!$chosen){
  $ua = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
  $isMobileUA = preg_match('~(iphone|ipod|ipad|android|blackberry|bb10|windows phone|mobi|opera mobi|mobile)~i',$ua);
  $chosen = $isMobileUA ? 'mobile' : 'desktop';
}

/* ---------------------- Theme session (persist via link toggle) ----------------- */
if(isset($_GET['set_theme'])){
    $t = ($_GET['set_theme']==='dark') ? 'dark' : 'light';
    $_SESSION['theme_mode']=$t;
    // no redirect - client JS handles immediate class toggle
}
$theme_mode = $_SESSION['theme_mode'] ?? ( ($FORCE_THEME && $DEFAULT_THEME==='dark') ? 'dark' : $DEFAULT_THEME );
$bodyClass = ($theme_mode === 'dark') ? 'theme-dark' : '';

/* ---------------------- Renderers -------------------------- */
function render_mobile($ctx){
  extract($ctx);
  $BANNER_H = 260;
  // ensure ASSET_PREFIX is available for assets
  $ASSET = $ASSET_PREFIX ?? '';
  ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title><?php echo h($metaTitle); ?></title>
<meta name="description" content="<?php echo h(mb_strimwidth($metaDesc,0,155,'…','UTF-8')); ?>">
<link rel="canonical" href="<?php echo h($canonical); ?>">
<meta name="robots" content="index,follow">
<meta name="theme-color" content="#0d0f14" media="(prefers-color-scheme: dark)">
<meta name="theme-color" content="#f6f7fb" media="(prefers-color-scheme: light)">

<!-- Soziety theme CSS (from uploaded kit) -->
<link rel="stylesheet" href="<?php echo h($ASSET.'assets/vendor/bootstrap/css/bootstrap.min.css'); ?>">
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
<?php if($ogImage){ ?>
<meta property="og:type" content="website">
<meta property="og:title" content="<?php echo h($metaTitle); ?>">
<meta property="og:description" content="<?php echo h($metaDesc); ?>">
<meta property="og:image" content="<?php echo h($ogImage); ?>">
<meta property="og:url" content="<?php echo h($canonical); ?>">
<meta name="twitter:card" content="summary_large_image">
<?php } ?>

<!-- Inline tokens fallback for quick rendering (keeps your original token_or usage) -->
<style>
:root{
  --bg:<?php echo h(token_or('bg','#f6f7fb','#0d0f14')); ?>;
  --text:<?php echo h(token_or('text','#121926','#e7ebf3')); ?>;
  --muted:<?php echo h(token_or('muted','#5f6a7d','#9aa4b2')); ?>;
  --primary:<?php echo h(token_or('primary','#1753fc','#3f82ff')); ?>;
  --line:<?php echo h(token_or('line','rgba(0,0,0,.08)','rgba(255,255,255,.10)')); ?>;
  --card:<?php echo h(token_or('card','#ffffff','#121723')); ?>;
}
</style>

</head>
<body class="<?php echo h($bodyClass); ?>">
<?php
// Pluggable mobile header; prefer header_mobile.php then header.php then fallback to inline minimal header matching theme classes
if (is_file(__DIR__.'/header_mobile.php')) {
  include __DIR__.'/header_mobile.php';
} elseif (is_file(__DIR__.'/header.php')) {
  include __DIR__.'/header.php';
} else {
  // minimal header matching Soziety markup
  $logo = $hdr_cfg['logo_url_light'] ?? ($ASSET.'assets/images/logo.png');
  if($theme_mode==='dark') $logo = $hdr_cfg['logo_url_dark'] ?? ($ASSET.'assets/images/logo-dark.png');
  echo '<header class="header"><div class="container"><div class="main-bar"><div class="left-content"><a href="'.h($BASE?:'/').'" class="logo-link"><img src="'.h($logo).'" alt="logo" class="logo" style="height:36px"></a></div><div class="mid-content"></div><div class="right-content d-flex align-items-center">';
  // theme toggle - uses JS to add/remove .theme-dark and calls ?set_theme= to persist
  echo '<button id="themeToggle" class="theme-btn me-2" type="button" title="Toggle theme"><span class="light">🌞</span><span class="dark">🌙</span></button>';
  echo '<a href="'.h($ASSET.'reels.html').'" class="bell-icon me-2">⤴</a><a href="'.h($ASSET.'notification.html').'" class="bell-icon me-2">🔔</a>';
  echo '<div class="dropdown"><a href="#" class="btn btn-sm dropdown-toggle" data-bs-toggle="dropdown">Account</a><ul class="dropdown-menu dropdown-menu-end"><li><a class="dropdown-item" href="'.h($ASSET.'edit-profile.html').'">Edit profile</a></li><li><a class="dropdown-item" href="'.h($ASSET.'change-password.html').'">Change password</a></li><li><hr class="dropdown-divider"></li><li><a class="dropdown-item" href="'.h($ASSET.'login.html').'">Logout</a></li></ul></div>';
  echo '</div></div></div></header>';
}
?>

<main class="page" id="main" role="main">
  <!-- Banner -->
  <section class="section" aria-label="Promotions">
    <div class="banner" role="region" aria-roledescription="carousel" aria-label="Featured Banners">
      <div class="slides" id="mSlides" aria-live="polite">
        <?php if($banners){ foreach($banners as $ix=>$b){ ?>
          <a class="slide" href="<?php echo h($b['link_url'] ?: '#'); ?>" aria-label="<?php echo h(($b['title']?:'Banner').' – open'); ?>">
            <?php
              $img = $b['image_url'] ?: ($ASSET.'assets/images/bg-shape-dark.png');
              echo hm_picture($img, ($b['title']?:'Banner'), 520, (int)$BANNER_H, ['priority'=>$ix===0,'sizes'=>'(max-width:520px) 100vw, 520px']);
            ?>
          </a>
        <?php }} else { ?>
          <div class="slide"><div style="display:flex;height:var(--banner-h);align-items:center;justify-content:center;color:#fff;font-weight:900">Banner</div></div>
        <?php } ?>
      </div>
      <div class="dots" id="mDots" aria-hidden="true"><?php $c=max(1,count($banners)); for($i=0;$i<$c;$i++){ echo '<div class="dot '.($i===0?'active':'').'"></div>'; } ?></div>
    </div>
  </section>

  <!-- Highlights -->
  <section class="section" aria-label="Project Highlights">
    <div class="hscroll">
      <?php if($highlights){ foreach($highlights as $h){ ?>
        <a class="chip" href="<?php echo h($h['link_url'] ?: '#'); ?>" aria-label="<?php echo h(($h['label']?:$h['title']?:'Project').' – open'); ?>">
          <?php if(!empty($h['badge_text'])){ ?><div class="badge"><?php echo h($h['badge_text']); ?></div><?php } ?>
          <div class="thumb"><?php if(!empty($h['image_url'])) echo hm_picture($h['image_url'], ($h['label']?:'Project'), 150, 84, ['sizes'=>'150px']); ?></div>
          <div class="label"><?php echo h($h['label'] ?: $h['title'] ?: ''); ?></div>
        </a>
      <?php }} elseif($homeProjects){ foreach($homeProjects as $hp){ ?>
        <a class="chip" href="<?php echo h($hp['url']); ?>"><div class="thumb"><?php if(!empty($hp['img'])) echo hm_picture($hp['img'],$hp['title'],150,84,['sizes'=>'150px']); ?></div><div class="label"><?php echo h($hp['title']); ?></div></a>
      <?php } } else { ?>
        <div class="chip"><div class="badge">New</div><div class="thumb"></div><div class="label">Project</div></div>
      <?php } ?>
    </div>
  </section>

  <!-- Quick actions -->
  <section class="section" aria-label="Quick Actions">
    <div class="qactions">
      <?php if($quickActions){ foreach($quickActions as $qa){ ?>
        <a class="qa" href="<?php echo h($qa['link_url'] ?: '#'); ?>"><div class="ico"><?php echo $qa['icon_svg'] ?: '<svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/></svg>'; ?></div><div class="t"><?php echo h($qa['label'] ?: $qa['title']); ?></div></a>
      <?php }} else { ?>
        <div class="qa"><div class="ico"><svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/></svg></div><div class="t">Calls</div></div>
      <?php } ?>
    </div>
  </section>

  <!-- Projects -->
  <section class="section" aria-labelledby="projectsHeading">
    <div class="title-row"><h2 id="projectsHeading" class="h">Projects</h2><a class="link" href="<?php echo h($BASE.'projects_mobile.php'); ?>">View all</a></div>
    <?php if($homeProjects){ echo '<div class="projrow" aria-label="Featured Projects">'; foreach($homeProjects as $p){ ?>
      <article class="project-card" itemscope itemtype="https://schema.org/Place">
        <a class="p-img" href="<?php echo h($p['url']); ?>" aria-label="<?php echo h($p['title'].' – open details'); ?>">
          <?php if(!empty($p['img'])) echo hm_picture($p['img'],$p['title'],520,200,['sizes'=>'(max-width:520px) 92vw, 520px']); ?>
        </a>
        <div class="p-body">
          <div class="p-name" itemprop="name"><?php echo h($p['title']); ?></div>
          <?php if(!empty($p['sub'])){ ?><div class="p-sub" itemprop="address"><?php echo h($p['sub']); ?></div><?php } ?>
          <?php if(!empty($p['price'])){ ?><div class="p-price"><?php echo h($p['price']); ?></div><?php } ?>
          <?php if(!empty($p['badges'])){ ?><div class="badges"><?php foreach($p['badges'] as $bt){ echo '<span class="badge">'.h($bt).'</span>'; } ?></div><?php } ?>
        </div>
      </article>
    <?php } echo '</div>'; } else { ?>
      <article class="project-card"><div class="p-img"></div><div class="p-body"><div class="p-name">Sample Project</div><div class="p-sub">Location</div><div class="p-price">Rs. 0 onwards</div></div></article>
    <?php } ?>
  </section>

  <!-- Opportunities + Stats -->
  <section class="section" aria-label="Opportunities and Stats">
    <div class="opprow">
      <?php $op = $opps ? $opps[0] : null; ?>
      <div class="opp"><div class="t"><?php echo h($op['title'] ?? 'Discover untapped potential!'); ?></div><div class="b"><?php echo h($op['body'] ?? 'Start exploring projects today.'); ?></div><a class="cta" href="<?php echo h($op['link_url'] ?? '#'); ?>">Explore Opportunities</a></div>
      <div class="stats">
        <div class="stat"><div class="ring"><span><?php echo (int)$stats['matches']; ?></span></div><div class="meta"><div class="k">Explore Matches</div><div class="v"><?php echo (int)$stats['matches']; ?></div></div></div>
        <div class="stat"><div class="ring"><span><?php echo h($stats['earnings']['currency']); ?></span></div><div class="meta"><div class="k">Earned till date</div><div class="v"><?php echo h($stats['earnings']['currency']).number_format((float)$stats['earnings']['amount']); ?></div></div></div>
      </div>
    </div>
  </section>

  <!-- Network -->
  <section class="section" aria-label="Syndicate Network">
    <div class="network">
      <div class="nthumb"><?php if(!empty($network['image_url'])) echo hm_picture($network['image_url'],'Network image',64,64,['sizes'=>'64px']); ?></div>
      <div class="meta"><div class="t"><?php echo h($network['title'] ?? 'Syndicate Network'); ?></div><div class="b"><?php echo h($network['body'] ?? 'Network is net worth. Collaborate and build.'); ?></div></div>
      <a class="cta" href="<?php echo h($network['link_url'] ?? '#'); ?>">Explore</a>
    </div>
  </section>

  <!-- 6-tile grid -->
  <section class="section" aria-label="Quick Tools">
    <div class="grid6">
      <?php if($grid){ foreach($grid as $g){ $ico=$g['icon_svg']?:'<svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>'; ?>
        <a class="g" href="<?php echo h($g['link_url'] ?: '#'); ?>"><div class="ico"><?php echo $ico; ?></div><div class="t"><?php echo h($g['label'] ?: $g['title']); ?></div></a>
      <?php }} else { ?><div class="g"><div class="ico"><svg viewBox="0 0 24 24" width="28" height="28"></svg></div><div class="t">Item</div></div><?php } ?>
    </div>
  </section>

  <!-- Events -->
  <section class="section events" aria-labelledby="eventsHeading">
    <div class="title-row"><h2 id="eventsHeading" class="h">Glimpses of Syndicate Events</h2><span></span></div>
    <?php if($events){ foreach($events as $e){ ?>
      <article class="event-card" itemscope itemtype="https://schema.org/Event">
        <div class="event-thumb"><?php if(!empty($e['image_url'])) echo hm_picture($e['image_url'], ($e['title']?:'Event'), 520,150,['sizes'=>'(max-width:520px) 100vw, 520px']); ?></div>
        <div class="event-body">
          <div class="event-title" itemprop="name"><?php echo h($e['title'] ?: ''); ?></div>
          <div class="event-sub"><span itemprop="location"><?php echo h($e['location'] ?: ''); ?></span><?php if(!empty($e['event_date'])){ ?><span> • <time itemprop="startDate" datetime="<?php echo h(date('c', strtotime($e['event_date']))); ?>"><?php echo h(date('d M Y', strtotime($e['event_date']))); ?></time></span><?php } ?></div>
        </div>
      </article>
    <?php }} else { ?><article class="event-card"><div class="event-thumb"></div><div class="event-body"><div class="event-title">Event Title</div><div class="event-sub">Location • 01 Jan</div></div></article><?php } ?>
  </section>
</main>

<noscript><div style="max-width:520px;margin:8px auto;padding:12px;background:#fff;color:#111;border:1px solid #ddd">JavaScript is disabled. Some interactive features (carousel, theme toggle) are unavailable.</div></noscript>

<?php
// Pluggable footer: footer_mobile.php, footer.php or fallback to theme footer
if (is_file(__DIR__.'/footer_mobile.php')) {
  include __DIR__.'/footer_mobile.php';
} elseif (is_file(__DIR__.'/footer.php')) {
  include __DIR__.'/footer.php';
} else {
  echo '<footer class="site-footer"><nav><ul class="d-flex justify-content-center list-unstyled mb-2">';
  if($ftr_menu){ foreach($ftr_menu as $n){ echo '<li class="me-3"><a href="'.h($n['href']?:'#').'">'.h($n['label']?:'').'</a></li>'; } }
  echo '</ul></nav><div class="text-center small">© '.date('Y').' Your Company</div></footer>';
}
?>

<!-- Theme + slider JS (use kit's JS where possible) -->
<script src="<?php echo h($ASSET.'assets/vendor/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
<script src="<?php echo h($ASSET.'app.js'); ?>"></script>

<script>
/* Theme toggle - syncs with server-side session via ?set_theme=  */
(function(){
  var btn=document.getElementById('themeToggle');
  function setBodyMode(mode){
    if(mode==='dark'){ document.documentElement.classList.add('theme-dark'); }
    else { document.documentElement.classList.remove('theme-dark'); }
  }
  btn && btn.addEventListener('click', function(){
    var isDark = document.documentElement.classList.contains('theme-dark');
    setBodyMode(isDark? 'light' : 'dark');
    // persist (non-blocking)
    try{ fetch('?set_theme=' + (isDark? 'light' : 'dark'), {method:'GET',credentials:'same-origin'}); }catch(e){}
  });
})();

/* Mobile banner slider */
(function(){
  var slides=document.getElementById('mSlides'); var dots=document.querySelectorAll('#mDots .dot');
  if(!slides) return; var total=slides.children.length||1; var idx=0, t=null, playing=true;
  function go(i){ idx=(i+total)%total; slides.style.transform='translateX('+(-idx*100)+'%)'; dots.forEach((d,k)=>d.classList.toggle('active',k===idx)); }
  function play(){ if(t) clearInterval(t); t=setInterval(function(){ if(playing) go(idx+1); }, 4500); }
  slides.addEventListener('pointerdown',()=>{playing=false;}); slides.addEventListener('pointerup',()=>{playing=true;});
  go(0); play();
})();
</script>
</body></html>
<?php
}

function render_desktop($ctx){
  extract($ctx);
  $ASSET = $ASSET_PREFIX ?? '';
  /* Pull heights & autoplay from settings if present */
  $HERO_H     = (int)(tbl_exists($DB,'ui_app_settings') ? (get_setting($DB,'hero_h','620') ?: 620) : 620);
  $PROJ_IMG_H = (int)(tbl_exists($DB,'ui_app_settings') ? (get_setting($DB,'proj_img_h','260') ?: 260) : 260);
  $EVENT_IMG_H= (int)(tbl_exists($DB,'ui_app_settings') ? (get_setting($DB,'event_img_h','260') ?: 260) : 260);
  $AUTOPLAY   = (int)(tbl_exists($DB,'ui_app_settings') ? (get_setting($DB,'autoplay_ms','4500') ?: 4500) : 4500);
  ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title><?php echo h($metaTitle); ?></title>
<meta name="description" content="<?php echo h(mb_strimwidth($metaDesc,0,160,'…','UTF-8')); ?>"><link rel="canonical" href="<?php echo h($canonical); ?>"><meta name="robots" content="index,follow">
<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'); ?>">
<style>
:root{
  --bg:<?php echo h(token_or('bg','#f6f7fb','#0d0f14')); ?>;
  --text:<?php echo h(token_or('text','#121926','#e7ebf3')); ?>;
  --muted:<?php echo h(token_or('muted','#5f6a7d','#9aa4b2')); ?>;
  --primary:<?php echo h(token_or('primary','#1753fc','#3f82ff')); ?>;
  --line:<?php echo h(token_or('line','rgba(0,0,0,.08)','rgba(255,255,255,.10)')); ?>;
  --card:<?php echo h(token_or('card','#ffffff','#121723')); ?>;
  --chip:<?php echo h(token_or('chip','#eef3ff','#0f1a31')); ?>;
}
</style>
</head>
<body class="<?php echo h($bodyClass); ?>">

<?php
/* Top header – pluggable */
if (is_file(__DIR__.'/header_desktop.php')) {
  include __DIR__.'/header_desktop.php';
} elseif (is_file(__DIR__.'/header.php')) {
  include __DIR__.'/header.php';
} else {
  $logo = $DEFAULT_THEME==='dark' ? ($hdr_cfg['logo_url_dark']??'') : ($hdr_cfg['logo_url_light']??'');
  echo '<div class="topbar"><div class="topinner">';
  echo '<div style="display:flex;align-items:center;gap:14px"><div class="logo">';
  if($logo){ echo '<img src="'.h($logo).'" alt="Logo" style="height:26px">'; } else { echo '<span>Syndicate</span>'; }
  if(!empty($hdr_cfg['version_text'])) echo '<span style="color:var(--muted);font-size:12px">'.h($hdr_cfg['version_text']).'</span>';
  echo '</div><nav class="nav">';
  if($hdr_menu){ foreach($hdr_menu as $m){
    $icon = ($DEFAULT_THEME==='dark') ? ($m['icon_url_dark']??'') : ($m['icon_url_light']??'');
    $iw=(int)($m['icon_w']??18); $ih=(int)($m['icon_h']??18);
    echo '<a href="'.h($m['href']?:'#').'">'.($icon?'<img src="'.h($icon).'" alt="" width="'.max(12,$iw).'" height="'.max(12,$ih).'">':'').'<span>'.h($m['label']?:'').'</span></a>';
  }} else { echo '<a href="projects_desktop.php">Projects</a>'; }
  echo '</nav></div>';
  echo '<button id="openSidebar" class="hamb" aria-label="Open menu"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 6h18M3 12h18M3 18h18"/></svg></button>';
  echo '</div></div>';
}

/* Pill menubar from footer tabs */
if (!is_file(__DIR__.'/header_desktop.php')) {
  echo '<div class="tabbar"><div class="tabbar-inner">';
  if($ftr_menu){
    foreach($ftr_menu as $m){
      $icon = ($DEFAULT_THEME==='dark') ? ($m['icon_url_dark']??'') : ($m['icon_url_light']??'');
      $iw=(int)($m['icon_w']??18); $ih=(int)($m['icon_h']??18);
      echo '<a class="tab-pill" href="'.h($m['href']?:'#').'">'.($icon?'<img src="'.h($icon).'" alt="" width="'.max(12,$iw).'" height="'.max(12,$ih).'">':'').'<span>'.h($m['label']?:'').'</span></a>';
    }
  } else { echo '<span style="color:var(--muted);font-size:13px">Add footer tabs in ui_footer_nav to show here.</span>'; }
  echo '</div></div>';
}
?>

<!-- Right off-canvas sidebar -->
<div id="sidebarBackdrop" class="backdrop" aria-hidden="true"></div>
<?php
echo '<aside id="sidebar" class="sidebar" role="complementary">';
echo '<div class="side-head">Menu <button id="closeSidebar" class="hamb" aria-label="Close" style="width:28px;height:28px"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg></button></div>';
echo '<div class="side-body">';
if (is_file(__DIR__.'/sidebar_desktop.php')) { include __DIR__.'/sidebar_desktop.php'; }
else {
  if($sid_menu){
    $grp=null; foreach($sid_menu as $s){
      if($s['group_label']!==$grp){ $grp=$s['group_label']; echo '<div style="padding:12px;color:var(--muted);font-weight:700">'.h($grp?:'').'</div>'; }
      $icon = ($DEFAULT_THEME==='dark') ? ($s['icon_url_dark']??'') : ($s['icon_url_light']??'');
      $iw=(int)($s['icon_w']??20); $ih=(int)($s['icon_h']??20);
      if(($s['type']??'link')==='label'){ echo '<div style="padding:8px 14px;color:var(--muted)">'.h($s['label']).'</div>'; }
      else { echo '<a href="'.h($s['href']?:'#').'" style="display:flex;gap:10px;align-items:center;padding:10px 14px;border-bottom:1px solid var(--line)">'.($icon?'<img src="'.h($icon).'" alt="" width="'.max(12,$iw).'" height="'.max(12,$ih).'">':'').'<span style="font-weight:600">'.h($s['label']).'</span>'.(!empty($s['subtitle'])?'<small style="color:var(--muted);margin-left:auto">'.h($s['subtitle']).'</small>':'').'</a>'; }
    }
  } else { echo '<div style="padding:12px;color:var(--muted)">Add sidebar items in ui_sidebar_menu.</div>'; }
}
echo '</div></aside>';
?>

<main id="main" class="wrap" role="main">
  <!-- HERO (full width, taller) -->
  <section class="section-full hero">
    <div class="slider" id="heroSlider" data-autoplay="<?php echo (int)$AUTOPLAY; ?>">
      <div class="slides">
        <?php if($banners){ foreach($banners as $ix=>$b){ ?>
          <a class="slide" href="<?php echo h($b['link_url'] ?: '#'); ?>" aria-label="<?php echo h(($b['title']?:'Banner').' – open'); ?>">
            <?php $img = $b['image_url'] ?: ($ASSET.'assets/images/bg-shape-dark.png'); echo hm_picture($img, ($b['title']?:'Banner'), 1920, (int)$HERO_H, ['priority'=>$ix===0,'sizes'=>'100vw']); ?>
          </a>
        <?php }} else { ?><div class="slide"><div style="display:grid;place-items:center;height:var(--hero-h);font-weight:900;color:#333">Banner</div></div><?php } ?>
      </div>
      <button class="arrow prev" aria-label="Previous slide" type="button">&#10094;</button>
      <button class="arrow next" aria-label="Next slide" type="button">&#10095;</button>
      <div class="dots" aria-hidden="true"></div>
    </div>
  </section>

  <!-- HIGHLIGHTS -->
  <section class="section-full">
    <div class="slider" id="highlightsSlider" data-autoplay="<?php echo (int)$AUTOPLAY; ?>">
      <div class="slides">
        <?php if($highlights){ foreach($highlights as $h){ ?>
          <div class="slide">
            <a class="hi-card" href="<?php echo h($h['link_url'] ?: '#'); ?>">
              <div class="hi-thumb"><?php if(!empty($h['image_url'])) echo hm_picture($h['image_url'], ($h['label']?:'Highlight'), 120, 86, ['sizes'=>'120px']); ?></div>
              <div>
                <?php if(!empty($h['badge_text'])){ ?><span class="hi-badge"><?php echo h($h['badge_text']); ?></span><?php } ?>
                <span class="hi-title"><?php echo h($h['label'] ?: $h['title'] ?: ''); ?></span>
                <?php if(!empty($h['body'])){ ?><div class="hi-sub"><?php echo h(strip_tags(mb_strimwidth($h['body'],0,140,'…','UTF-8'))); ?></div><?php } ?>
              </div>
            </a>
          </div>
        <?php }} else { ?><div class="slide"><div class="hi-card"><div class="hi-thumb"></div><div><span class="hi-badge">New</span><span class="hi-title">Project</span><div class="hi-sub">Description</div></div></div></div><?php } ?>
      </div>
      <button class="arrow prev" type="button">&#10094;</button><button class="arrow next" type="button">&#10095;</button><div class="dots" aria-hidden="true"></div>
    </div>
  </section>

  <!-- PROJECTS -->
  <section class="section-full">
    <div class="section-inner">
      <div style="display:flex;align-items:center;justify-content:space-between;margin:4px 0 10px">
        <h2 style="margin:0;font-size:20px;font-weight:900">Projects</h2>
        <a href="projects_desktop.php" style="color:var(--primary);font-weight:700">View all</a>
      </div>
      <div class="grid cols-3">
        <?php if($homeProjects){ foreach($homeProjects as $p){ ?>
          <article class="card" itemscope itemtype="https://schema.org/Place">
            <a class="thumb" href="<?php echo h($p['url']); ?>" aria-label="<?php echo h($p['title'].' – open details'); ?>">
              <?php if(!empty($p['img'])) echo hm_picture($p['img'],$p['title'],1200,(int)$PROJ_IMG_H,['sizes'=>'(min-width:1200px) 33vw, (min-width:768px) 50vw, 100vw']); ?>
            </a>
            <div class="body">
              <div class="name" itemprop="name"><?php echo h($p['title']); ?></div>
              <?php if(!empty($p['sub'])){ ?><div class="sub" itemprop="address"><?php echo h($p['sub']); ?></div><?php } ?>
              <?php if(!empty($p['price'])){ ?><div class="price"><?php echo h($p['price']); ?></div><?php } ?>
              <?php if(!empty($p['badges'])){ ?><div class="badges"><?php foreach($p['badges'] as $bt){ echo '<span class="badge">'.h($bt).'</span>'; } ?></div><?php } ?>
            </div>
          </article>
        <?php }} else { ?><article class="card"><div class="thumb"></div><div class="body"><div class="name">Sample Project</div><div class="sub">Location</div><div class="price">Rs. 0 onwards</div></div></article><?php } ?>
      </div>
    </div>
  </section>

  <!-- OPPORTUNITY + STATS -->
  <section class="section-full">
    <div class="block">
      <?php $op = $opps ? $opps[0] : null; ?>
      <div style="display:grid;grid-template-columns:2fr 1fr;gap:20px">
        <div>
          <div class="name" style="font-weight:900"><?php echo h($op['title'] ?? 'Discover untapped potential!'); ?></div>
          <div class="sub" style="color:var(--muted);margin-top:6px"><?php echo h($op['body'] ?? 'Start exploring projects today.'); ?></div>
          <a href="<?php echo h($op['link_url'] ?? '#'); ?>" class="badge" style="display:inline-block;margin-top:12px;background:var(--primary);color:#fff;border-color:transparent">Explore Opportunities</a>
        </div>
        <div class="stats">
          <div class="stat"><div class="ring"><span><?php echo (int)$stats['matches']; ?></span></div><div><div style="color:var(--muted);font-size:13px">Explore Matches</div><div style="font-weight:900"><?php echo (int)$stats['matches']; ?></div></div></div>
          <div class="stat"><div class="ring"><span><?php echo h($stats['earnings']['currency']); ?></span></div><div><div style="color:var(--muted);font-size:13px">Earned till date</div><div style="font-weight:900"><?php echo h($stats['earnings']['currency']).number_format((float)$stats['earnings']['amount']); ?></div></div></div>
        </div>
      </div>
    </div>
  </section>

  <!-- NETWORK -->
  <section class="section-full">
    <div class="network">
      <div class="nthumb"><?php if(!empty($network['image_url'])) echo hm_picture($network['image_url'],'Network image',172,172,['sizes'=>'172px']); ?></div>
      <div style="flex:1"><div class="name" style="font-weight:900"><?php echo h($network['title'] ?? 'Syndicate Network'); ?></div><div class="sub" style="color:var(--muted);margin-top:6px"><?php echo h($network['body'] ?? 'Network is net worth. Collaborate and build.'); ?></div></div>
      <a class="badge" style="background:var(--primary);color:#fff;border-color:transparent" href="<?php echo h($network['link_url'] ?? '#'); ?>">Explore</a>
    </div>
  </section>

  <!-- EVENTS -->
  <section class="section-full event">
    <div class="slider" id="eventsSlider" data-autoplay="<?php echo (int)$AUTOPLAY; ?>">
      <div class="slides">
        <?php if($events){ foreach($events as $e){ ?>
          <div class="slide" itemscope itemtype="https://schema.org/Event">
            <div class="event-wrap">
              <div class="event-img"><?php if(!empty($e['image_url'])) echo hm_picture($e['image_url'], ($e['title']?:'Event'), 1200,(int)$EVENT_IMG_H,['sizes'=>'(min-width:1200px) 42vw, 100vw']); ?></div>
              <div class="event-body">
                <div class="event-title" itemprop="name"><?php echo h($e['title'] ?: ''); ?></div>
                <div class="event-sub"><span itemprop="location"><?php echo h($e['location'] ?: ''); ?></span><?php if(!empty($e['event_date'])){ ?><span> • <time itemprop="startDate" datetime="<?php echo h(date('c', strtotime($e['event_date']))); ?>"><?php echo h(date('d M Y', strtotime($e['event_date']))); ?></time></span><?php } ?></div>
              </div>
            </div>
          </div>
        <?php }} else { ?><div class="slide"><div class="event-wrap"><div class="event-img"></div><div class="event-body"><div class="event-title">Event Title</div><div class="event-sub">Location • 01 Jan</div></div></div></div><?php } ?>
      </div>
      <button class="arrow prev" type="button">&#10094;</button><button class="arrow next" type="button">&#10095;</button><div class="dots" aria-hidden="true"></div>
    </div>
  </section>
</main>

<?php
if (is_file(__DIR__.'/footer_desktop.php')) include __DIR__.'/footer_desktop.php';
else echo '<div class="footer">© '.date('Y').' Syndicate</div>';
?>

<script src="<?php echo h($ASSET.'assets/vendor/bootstrap/js/bootstrap.bundle.min.js'); ?>"></script>
<script src="<?php echo h($ASSET.'app.js'); ?>"></script>

<script>
/* Generic slider / sidebar scripts (kept similar to mobile but desktop-friendly) */
(function(){
  document.querySelectorAll('.slider').forEach(function(root){
    var track=root.querySelector('.slides'); if(!track) return;
    var slides=[].slice.call(track.children);
    var dotsWrap=root.querySelector('.dots');
    var prev=root.querySelector('.prev'); var next=root.querySelector('.next');
    var count=slides.length||1, idx=0, autoplay=parseInt(root.getAttribute('data-autoplay')||'0',10)||0, t;
    function mkDots(){ if(!dotsWrap) return; dotsWrap.innerHTML=''; for(var i=0;i<count;i++){ var d=document.createElement('div'); d.className='dot'+(i===0?' active':''); d.addEventListener('click',(function(k){return function(){go(k); reset();};})(i)); dotsWrap.appendChild(d);} }
    function go(i){ idx=(i+count)%count; track.style.transform='translateX('+(-idx*100)+'%)'; if(dotsWrap){ [].forEach.call(dotsWrap.children,function(d,k){ d.classList.toggle('active',k===idx); }); } }
    function nextF(){ go(idx+1); } function prevF(){ go(idx-1); }
    function play(){ if(!autoplay) return; stop(); t=setInterval(nextF,autoplay); }
    function stop(){ if(t){ clearInterval(t); t=null; } }
    function reset(){ if(!autoplay) return; stop(); play(); }
    if(prev) prev.addEventListener('click',function(){ prevF(); reset(); });
    if(next) next.addEventListener('click',function(){ nextF(); reset(); });
    root.addEventListener('mouseenter',stop); root.addEventListener('mouseleave',play);
    mkDots(); go(0); play();
  });
})();

/* Right sidebar toggle */
(function(){
  var sb=document.getElementById('sidebar'), bd=document.getElementById('sidebarBackdrop'), o=document.getElementById('openSidebar'), c=document.getElementById('closeSidebar');
  function open(){ if(sb){ sb.classList.add('open'); if(bd){ bd.classList.add('show'); bd.setAttribute('aria-hidden','false'); } } }
  function close(){ if(sb){ sb.classList.remove('open'); if(bd){ bd.classList.remove('show'); bd.setAttribute('aria-hidden','true'); } } }
  if(o) o.addEventListener('click',open); if(c) c.addEventListener('click',close); if(bd) bd.addEventListener('click',close); document.addEventListener('keydown',e=>{if(e.key==='Escape') close();});
})();
</script>

</body></html>
<?php
}

/* -------------------- Client viewport check ----------------
 * If server chose desktop but real viewport is small, redirect to mobile.
 * This runs only when no cookie override exists.
 */
$needsClientCheck = empty($_COOKIE['force_view']);

/* --------------- Dispatch the selected renderer ------------ */
$ctx = compact('DB','DEFAULT_THEME','FORCE_THEME','TOK','banners','highlights','quickActions','opps','stats','network','grid','events','homeProjects','metaTitle','metaDesc','ogImage','canonical','hdr_cfg','hdr_menu','ftr_menu','sid_menu','ASSET_PREFIX','BASE','theme_mode','bodyClass','ASSET');

if ($chosen === 'mobile'){
  render_mobile($ctx);
} else {
  if($needsClientCheck){
    echo '<script>(function(){try{var w=Math.max(document.documentElement.clientWidth,window.innerWidth||0); if(w<992){var u=new URL(window.location.href); u.searchParams.set("view","mobile"); window.location.replace(u.toString());}}catch(e){}})();</script>';
  }
  render_desktop($ctx);
}
