<?php
/**
 * ExpertAims (EAC), AimsHub CMS · front-end render layer
 * ────────────────────────────────────────────────────────────────────────
 * This file turns DB rows into the exact "Meridian" markup the approved
 * static site ships. It replaces NTPPA's design layer entirely, EAC shares
 * the engine (routing, sections model, hardened forms, HQ status API) but
 * none of NTPPA's visual design.
 *
 *   render_document($page, $body), <head> + header/nav + <main>$body</main> + footer
 *   render_hero($page), hero is a section on EAC, so this is a no-op
 *   render_sections($page_id), visible sections, in sort order, each as EAC markup
 *
 * The header, mega-menus and footer are site chrome (fixed structure); the
 * per-page editable unit is the SECTION. Contact bits (phones, email,
 * WhatsApp, addresses, social) come from Settings so the client can edit
 * them once and have every page follow.
 */

// ── Small helpers ───────────────────────────────────────────────────────

/** A nav/footer link: internal slug → base_url('slug'), external URL untouched. */
function ea_link($slug){
  if ($slug === '' || $slug === 'index' || $slug === 'home') return base_url();
  if (preg_match('#^(https?:)?//#i', $slug) || $slug[0] === '#') return $slug;
  return base_url($slug);
}

/** Is $slug the page we're currently on? (drives aria-current / .on) */
function ea_is_current($slug, $current){
  $slug = ($slug === '' || $slug === 'index') ? 'home' : $slug;
  return $slug === $current;
}

// ── Hero: on EAC the hero is a section (type "hero"), so nothing here ─────
function render_hero($p){ return ''; }

// ── Sections ─────────────────────────────────────────────────────────────
/**
 * Render every VISIBLE section of a page, in sort order. Each row's `type`
 * selects a renderer; unknown/raw types fall back to emitting the stored
 * body verbatim (so a bespoke band can live as a single editable "html"
 * section). The admin already exposes visible (enable/disable), sort
 * (reorder) and add/delete for every one of these.
 */
function render_sections($page_id){
  $rows = db()->prepare('SELECT * FROM sections WHERE page_id=? AND visible=1 ORDER BY sort ASC, id ASC');
  $rows->execute([(int)$page_id]);
  $out = '';
  foreach ($rows->fetchAll() as $s){
    $out .= render_section($s);
  }
  return $out;
}

/** Dispatch one section row to its renderer by `type`. */
function render_section($s){
  $type = (string)($s['type'] ?? 'richtext');
  switch ($type){
    case 'html':      // bespoke band, stored markup emitted as-is (already EAC-styled)
    case 'raw':
      return ea_prepare((string)($s['body'] ?? ''));
    case 'richtext':
      return ea_sec_richtext($s);
    default:
      // Unknown type: don't lose content, emit the body so nothing 404s visually.
      return ea_prepare((string)($s['body'] ?? ''));
  }
}

/** Full render-time prep for a stored HTML band: fix paths, expand markers,
 *  and upgrade the contact form to post into the CMS enquiry inbox. */
function ea_prepare($html){
  $html = ea_rewrite_links($html);
  $html = ea_markers($html);
  $html = ea_upgrade_contact_form($html);
  return $html;
}

/** Expand engine markers inside a stored band (server-generated fields). */
function ea_markers($html){
  if (stripos($html, '<!--CAPTCHA-->') !== false || stripos($html, '<!-- CAPTCHA -->') !== false){
    $html = str_ireplace(['<!--CAPTCHA-->', '<!-- CAPTCHA -->'], captcha_fields_html(), $html);
  }
  if (stripos($html, '<!--PARTNERS-->') !== false){
    $html = str_ireplace('<!--PARTNERS-->', function_exists('partners_slider_html') ? partners_slider_html() : '', $html);
  }
  if (stripos($html, '<!--HOSTINGSEARCH-->') !== false){
    $html = str_ireplace('<!--HOSTINGSEARCH-->', function_exists('hosting_search_html') ? hosting_search_html() : '', $html);
  }
  if (stripos($html, '<!--HOSTINGPLANS-->') !== false){
    $html = str_ireplace('<!--HOSTINGPLANS-->', function_exists('hosting_plans_grid_html') ? hosting_plans_grid_html() : '', $html);
  }
  if (stripos($html, '<!--HOSTINGPORTAL-->') !== false){
    $html = str_ireplace('<!--HOSTINGPORTAL-->', function_exists('hosting_portal_html') ? hosting_portal_html() : '', $html);
  }
  if (stripos($html, '<!--HOSTINGTEASER-->') !== false){
    $html = str_ireplace('<!--HOSTINGTEASER-->', function_exists('hosting_teaser_html') ? hosting_teaser_html() : '', $html);
  }
  return $html;
}

/**
 * Turn the approved static contact form (class "ct-form", data-mailto) into a
 * CMS-captured enquiry form: tag it for cms-forms.js and inject the server-
 * rendered spam-protection block (sum captcha + honeypot + CSRF token) before
 * the submit button. data-mailto is LEFT in place, so if JS is off or the
 * fetch fails the original mail-client flow still works, no dead form.
 */
function ea_upgrade_contact_form($html){
  if (stripos($html, 'ct-form') === false) return $html;
  // tag the <form> (keep every existing attribute, add data-cms="enquiry")
  $html = preg_replace('/<form\b(?![^>]*data-cms=)([^>]*\bct-form\b[^>]*)>/i',
                       '<form$1 data-cms="enquiry">', $html, 1);
  // inject the captcha/token/honeypot right before the submit button
  if (stripos($html, 'form-captcha') === false){
    $html = preg_replace('/(<button\b[^>]*type="submit"[^>]*>)/i',
                         captcha_fields_html() . '$1', $html, 1);
  }
  return $html;
}

/**
 * Make the approved static markup work under the CMS router. Stored section
 * bodies keep their original *relative* paths ("assets/…", "about.html"),
 * so the migration is byte-for-byte the design we shipped, this filter
 * rewrites them at render time:
 *   src|href|srcset="assets/…"   → base_url('assets/…')   (subfolder-safe)
 *   href="page.html"             → base_url('page')       (slug routing)
 *   href="page.html#anchor"      → base_url('page')#anchor
 *   href="index.html"            → base_url()
 * External URLs, mailto:, tel:, wa.me and #fragments are left untouched.
 */
function ea_rewrite_links($html){
  if ($html === '') return $html;
  // 1) asset paths on src / href / srcset / poster / data-src / content
  $html = preg_replace_callback(
    '#\b(src|href|poster|data-src|content)\s*=\s*"(assets/[^"]*)"#i',
    function($m){ return $m[1] . '="' . base_url($m[2]) . '"'; },
    $html
  );
  $html = preg_replace_callback(
    '#\bsrcset\s*=\s*"([^"]*)"#i',
    function($m){
      $parts = array_map(function($p){
        $p = trim($p);
        return preg_replace_callback('#^(assets/\S+)#', function($mm){ return base_url($mm[1]); }, $p);
      }, explode(',', $m[1]));
      return 'srcset="' . implode(', ', $parts) . '"';
    },
    $html
  );
  // 2) internal .html links → slug routes
  $html = preg_replace_callback(
    '~\bhref\s*=\s*"([a-z0-9\-]+)\.html(#[^"]*)?"~i',
    function($m){
      $slug = strtolower($m[1]);
      $frag = $m[2] ?? '';
      $url  = ($slug === 'index') ? base_url() : base_url($slug);
      return 'href="' . $url . $frag . '"';
    },
    $html
  );
  return $html;
}

/** A plain prose band wrapped in the site's reveal/section rhythm. */
function ea_sec_richtext($s){
  $body = (string)($s['body'] ?? '');
  $head = trim((string)($s['heading'] ?? ''));
  $sub  = trim((string)($s['subheading'] ?? ''));
  $id   = trim((string)($s['extra'] ?? '')); // optional anchor id stored in extra
  $anchor = $id !== '' ? ' id="'.e($id).'"' : '';
  ob_start(); ?>
<section class="sec rv"<?= $anchor ?>>
  <div class="wrap">
<?php if ($sub  !== ''): ?>    <p class="stn"><?= e($sub) ?></p>
<?php endif; if ($head !== ''): ?>    <h2 class="d2"><?= e($head) ?></h2>
<?php endif; ?>    <div class="prose"><?= $body ?></div>
  </div>
</section>
<?php return ob_get_clean();
}

// ── Document shell ───────────────────────────────────────────────────────
/**
 * The EAC "Meridian" chrome: exact <head>, header + mega-menus + mobile
 * drawer, then <main>$body</main>, then the footer. $body is the rendered
 * sections for this page.
 */
function render_document($p, $body){
  $slug   = (string)($p['slug'] ?? '');
  $cur    = ($slug === '' || $slug === 'index') ? 'home' : $slug;
  $siteNm = setting('site_name', 'ExpertAims Consultancy');
  $title  = trim((string)($p['meta_title'] ?? '')) ?: (trim((string)($p['title'] ?? '')) . ' | ' . $siteNm);
  if ($cur === 'home') $title = trim((string)($p['meta_title'] ?? '')) ?: ($p['title'] ?? $siteNm);
  $desc   = trim((string)($p['meta_description'] ?? ''));
  $canon  = trim((string)($p['canonical'] ?? ''));
  $ogimg  = trim((string)($p['og_image'] ?? '')) ?: 'assets/brand/og-image.png';
  $ogimg  = media_url($ogimg);

  // Editable contact bits (Settings → follow every page)
  $email   = setting('email', 'info@expertaims.com');
  $waE164  = preg_replace('/\D+/', '', setting('whatsapp', '96590908625'));
  $phoneKW = setting('phone', '+965 9090 8625');
  $phoneIN = setting('phone_in', '+91 471 291 0255');
  $hostUrl = setting('hosting_url', 'https://expertaims.xyz');
  $hostOn  = !function_exists('hosting_page_enabled') || hosting_page_enabled();

  // Services mega-menu (fixed site structure; hrefs route through base_url)
  $svc = [
    ['Run','IT Infrastructure &amp; AMC','Networks, servers and maintenance contracts that keep you running.','services#s1'],
    ['Move','Cloud, Email &amp; Hosting','Google Workspace, Microsoft 365 &amp; Zoho, and the hosting under it.','services#s2'],
    ['Protect','Cybersecurity &amp; Backup','Sensible protection and backups that are actually tested.','services#s3'],
    ['Build','Websites, E-commerce &amp; Apps','Fast sites, stores and custom software, you own the code.','services#s4'],
    ['Grow','SEO, Branding &amp; Marketing','Being found, looking credible, measured by leads.','services#s5'],
    ['Enable','Training &amp; Workshops','Your team, upskilled on the systems they use daily.','services#s6'],
    ['Transform','Digital Transformation &amp; AI','Workflows digitised, systems integrated, AI in your sector.','services#s7'],
  ];
  $company = [
    ['Since 2012','About us','Since 2012, vision, mission, and how we work.','about'],
    ['In their words','Clients &amp; industries','Who we serve, in their words.','clients'],
    ['The atlas','Innovation','The capability atlas and what we\'re exploring.','innovation'],
    ['Dispatches','News &amp; insights','Notes from the practice.','news'],
    ['Join us','Careers','We hire for the bench, not the vacancy.','careers'],
    ['Our companies','Companies','ExpertAims &amp; IrrigAims, one discipline, several companies.','companies'],
    ['Our IP','Products','What we build for ourselves, Orblance, the ExpertAims CMS and more.','products'],
  ];

  ob_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= e($title) ?></title>
<?php if ($desc !== ''): ?><meta name="description" content="<?= e($desc) ?>">
<?php endif; ?><?php if ($canon !== ''): ?><link rel="canonical" href="<?= e($canon) ?>">
<?php endif; ?><meta name="author" content="<?= e($siteNm) ?>">
<meta name="theme-color" content="#F6F4F2">
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#141011">
<meta property="og:type" content="website">
<meta property="og:site_name" content="<?= e($siteNm) ?>">
<?php if ($canon !== ''): ?><meta property="og:url" content="<?= e($canon) ?>">
<?php endif; ?><meta property="og:title" content="<?= e($title) ?>">
<?php if ($desc !== ''): ?><meta property="og:description" content="<?= e($desc) ?>">
<?php endif; ?><meta property="og:image" content="<?= e($ogimg) ?>">
<meta name="twitter:card" content="summary_large_image">
<link rel="icon" type="image/svg+xml" href="<?= base_url('assets/brand/logo-e.svg') ?>">
<link rel="icon" type="image/png" sizes="32x32" href="<?= base_url('assets/brand/favicon-32.png') ?>">
<link rel="apple-touch-icon" sizes="180x180" href="<?= base_url('assets/brand/apple-touch-icon.png') ?>">
<script>(function(){try{var t=localStorage.getItem('ea-theme');if(t==='dark'||t==='light')document.documentElement.setAttribute('data-theme',t);}catch(e){}})();</script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,600;12..96,650;12..96,700;12..96,800&family=Instrument+Serif:ital@1&family=Schibsted+Grotesk:wght@400;500;600;700&family=Spline+Sans+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="<?= asset_url('assets/site.css') ?>">
<noscript><style>.rv{opacity:1;transform:none}.hb-s{position:relative;opacity:1;visibility:visible}</style></noscript>
<?php $hc = trim((string)setting('head_code')); if ($hc !== ''): ?><?= $hc . "\n" ?><?php endif; ?></head>
<body>
<a class="skip" href="#main">Skip to content</a>
<header class="hd">
  <div class="hd-in">
    <a class="hd-logo" href="<?= base_url() ?>" aria-label="ExpertAims home"><span class="lg-s"><img class="logo-l" src="<?= base_url('assets/brand/logo-e.svg') ?>" alt="ExpertAims" width="1114" height="1115"><img class="logo-d" src="<?= base_url('assets/brand/logo-e-dark.svg') ?>" alt="ExpertAims" width="1114" height="1115"></span><span class="lg-f"><img class="logo-l" src="<?= base_url('assets/brand/logo-full.svg') ?>" alt="ExpertAims, Consulting · Technology · Outsourcing" width="718" height="137"><img class="logo-d" src="<?= base_url('assets/brand/logo-full-dark.svg') ?>" alt="ExpertAims, Consulting · Technology · Outsourcing" width="718" height="137"></span></a>
    <nav class="hd-nav" aria-label="Primary">
      <div class="hd-item"><a class="hd-lnk<?= $cur==='home'?' on':'' ?>" href="<?= base_url() ?>"<?= $cur==='home'?' aria-current="page"':'' ?>>Home</a></div>
      <div class="hd-item">
        <button class="hd-lnk" type="button" aria-expanded="false" aria-haspopup="true">Services <span class="car"></span></button>
        <div class="mega">
<?php foreach ($svc as $m): ?>          <a class="mg" href="<?= e(ea_link($m[3])) ?>"><span class="mono"><?= $m[0] ?></span><b><?= $m[1] ?></b><span><?= $m[2] ?></span></a>
<?php endforeach; ?>        </div>
      </div>
      <div class="hd-item"><a class="hd-lnk<?= $cur==='projects'?' on':'' ?>" href="<?= base_url('projects') ?>">Projects</a></div><div class="hd-item"><?php if ($hostOn): ?><a class="hd-lnk<?= $cur==='hosting'?' on':'' ?>" href="<?= base_url('hosting') ?>">Hosting</a><?php else: ?><a class="hd-lnk" href="<?= e($hostUrl) ?>" target="_blank" rel="noopener">Hosting <span aria-hidden="true" style="font-size:.82em">&#8599;</span></a><?php endif; ?></div>
      <div class="hd-item">
        <button class="hd-lnk" type="button" aria-expanded="false" aria-haspopup="true">Company <span class="car"></span></button>
        <div class="mega slim">
<?php foreach ($company as $m): ?>          <a class="mg" href="<?= e(ea_link($m[3])) ?>"><span class="mono"><?= $m[0] ?></span><b><?= $m[1] ?></b><span><?= $m[2] ?></span></a>
<?php endforeach; ?>        </div>
      </div>
      <div class="hd-item"><a class="hd-lnk<?= $cur==='contact'?' on':'' ?>" href="<?= base_url('contact') ?>">Contact</a></div>
    </nav>
    <div class="hd-acts">
      <button class="thm" type="button" aria-label="Toggle light and dark theme">
        <svg class="i-moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>
        <svg class="i-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>
      </button>
      <a class="btn btn-acc" href="<?= base_url('contact') ?>">Get a consultation</a>
      <button class="mbt" id="mbt" type="button" aria-label="Open menu" aria-expanded="false" aria-controls="msh"><span></span><span></span><span></span></button>
    </div>
  </div>
</header>
<div class="msh" id="msh" aria-label="Mobile navigation">
  <a href="<?= base_url() ?>">Home</a>
  <details><summary>Services</summary>
<?php foreach ($svc as $m): ?>    <a href="<?= e(ea_link($m[3])) ?>"><?= $m[1] ?></a>
<?php endforeach; ?>  </details>
  <a href="<?= base_url('projects') ?>">Projects</a>
  <?php if ($hostOn): ?><a href="<?= base_url('hosting') ?>">Hosting</a><?php else: ?><a href="<?= e($hostUrl) ?>" target="_blank" rel="noopener">Hosting &#8599;</a><?php endif; ?>
  <details><summary>Company</summary>
<?php foreach ($company as $m): ?>    <a href="<?= e(ea_link($m[3])) ?>"><?= $m[1] ?></a>
<?php endforeach; ?>  </details>
  <a href="<?= base_url('contact') ?>">Contact</a>
  <a class="mcta" href="<?= base_url('contact') ?>">Get a consultation &rarr;</a>
</div>
<main id="main">
<?= $body ?>
</main>
<footer class="ft">
  <div class="ft-line">
    <div class="ft-tag">
      <div>
        <p class="stn rv">End of line <i>·</i> Next stop, your project</p>
        <h2 class="d1 rv" style="margin-top:18px">We show up. <em>We follow through</em><span class="aim" aria-hidden="true"></span></h2>
        <p class="lede rv" style="margin-top:22px;max-width:52ch">Tell us what's slow, broken or missing. We reply within one working day, with questions, not a sales pitch. NDA before the first call, happily.</p>
        <div class="rv" style="margin-top:30px;display:flex;gap:14px;flex-wrap:wrap">
          <a class="btn btn-acc" href="<?= base_url('contact') ?>">Start a conversation</a>
          <a class="btn btn-ln" href="https://wa.me/<?= e($waE164) ?>" target="_blank" rel="noopener">WhatsApp us</a>
        </div>
      </div>
    </div>
    <div class="ft-grid">
      <div><img class="logo-l" src="<?= base_url('assets/brand/logo-full.svg') ?>" alt="ExpertAims, Consulting · Technology · Outsourcing" width="718" height="137" style="height:36px;width:auto"><img class="logo-d" src="<?= base_url('assets/brand/logo-full-dark.svg') ?>" alt="ExpertAims, Consulting · Technology · Outsourcing" width="718" height="137" style="height:36px;width:auto"><p class="fp">Technology consulting, cloud, cybersecurity and digital solutions for growing businesses, since 2012. ISO 9001, 27001 &amp; 22301 certified.</p></div>
      <div class="ft-col"><h3>Services</h3>
        <a href="<?= base_url('services') ?>#s7">Digital Transformation &amp; AI</a>
        <a href="<?= base_url('services') ?>#s1">Infrastructure &amp; AMC</a>
        <a href="<?= base_url('services') ?>#s2">Cloud, Email &amp; Hosting</a>
        <a href="<?= base_url('services') ?>#s3">Cybersecurity &amp; Backup</a>
        <a href="<?= base_url('services') ?>#s4">Web, E-commerce &amp; Apps</a>
        <a href="<?= base_url('services') ?>#s5">SEO &amp; Marketing</a>
        <?php if ($hostOn): ?><a href="<?= base_url('hosting') ?>">Web hosting</a><?php else: ?><a href="<?= e($hostUrl) ?>" target="_blank" rel="noopener">Web hosting &#8599;</a><?php endif; ?>
      </div>
      <div class="ft-col"><h3>Company</h3>
        <a href="<?= base_url('about') ?>">About us</a>
        <a href="<?= base_url('projects') ?>">Projects</a>
        <a href="<?= base_url('clients') ?>">Clients</a>
        <a href="<?= base_url('innovation') ?>">Innovation</a>
        <a href="<?= base_url('news') ?>">News &amp; insights</a>
        <a href="<?= base_url('careers') ?>">Careers</a>
        <a href="<?= base_url('companies') ?>">Companies</a>
        <a href="<?= base_url('products') ?>">Products</a>
      </div>
      <div class="ft-col"><h3>Get in touch</h3>
        <a href="https://wa.me/<?= e($waE164) ?>" target="_blank" rel="noopener">WhatsApp <?= e($phoneKW) ?></a>
        <a href="tel:<?= e(preg_replace('/\s+/', '', $phoneKW)) ?>">Kuwait <?= e($phoneKW) ?></a>
        <a href="tel:<?= e(preg_replace('/\s+/', '', $phoneIN)) ?>">India <?= e($phoneIN) ?></a>
        <a href="mailto:<?= e($email) ?>"><?= e($email) ?></a>
        <div class="fclk" aria-label="Office local times">
          <span>Kuwait <i data-tz="Asia/Kuwait">, :, </i></span>
          <span>India <i data-tz="Asia/Kolkata">, :, </i></span>
          <span>Malaysia <i data-tz="Asia/Kuala_Lumpur">, :, </i></span>
          <em>wherever the hour lands, WhatsApp reaches a person</em>
        </div>
      </div>
    </div>
    <div class="ft-bar"><span class="ft-em" aria-hidden="true"><img class="logo-l" src="<?= base_url('assets/brand/logo-e.svg') ?>" alt=""><img class="logo-d" src="<?= base_url('assets/brand/logo-e-dark.svg') ?>" alt=""></span>
      <span>&copy; 2012&#8211;<span class="yr"><?= date('Y') ?></span> <?= e($siteNm) ?>. All rights reserved.</span>
      <span class="mono">Committed to perfection<span class="aim" aria-hidden="true"></span></span>
      <button class="ft-top" type="button" data-top><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 19V5m0 0-6 6m6-6 6 6"/></svg>Back to top</button>
    </div>
  </div>
</footer>
<script src="<?= asset_url('assets/cms-forms.js') ?>" defer></script>
<script src="<?= asset_url('assets/site.js') ?>" defer></script>
<?php
  // Page-specific behaviour scripts (the atlas on Innovation, the sector
  // interactions on Clients/Products) that sat after </main> on the static site.
  $pageJs = ['clients' => ['assets/clients-page.js'], 'products' => ['assets/clients-page.js'],
             'innovation' => ['assets/atlas-page.js']];
  foreach ($pageJs[$cur] ?? [] as $js): ?>
<script src="<?= asset_url($js) ?>" defer></script>
<?php endforeach; ?>
<?php $bc = trim((string)setting('body_code')); if ($bc !== ''): ?><?= $bc . "\n" ?><?php endif; ?></body>
</html>
<?php return ob_get_clean();
}
