<?php
// ═══ Public site front controller ═══
require __DIR__ . '/app/bootstrap.php';

$uri  = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$base = rtrim((string) config('base_url'), '/');
if ($base !== '' && strpos($uri, $base) === 0) $uri = substr($uri, strlen($base));
$path = trim(rawurldecode($uri), '/');
$path = preg_replace('/\.html$/', '', $path);

// ─── Individual blog post: /blog-<slug> (flat so shared nav links resolve) ───
if (preg_match('#^blog-([a-z0-9\-]+)$#', $path, $m)) {
  $post = find_post($m[1], true);
  if ($post) {
    $pseudo = [
      'title' => $post['title'], 'meta_title' => $post['meta_title'],
      'meta_description' => $post['meta_description'], 'meta_keywords' => null,
      'canonical' => null, 'og_image' => $post['banner'], 'robots' => 'index,follow',
    ];
    echo render_document($pseudo, render_post($post));
    exit;
  }
}

// ─── Regular page ───  ('' and 'index' both map to the Home page)
$slug = ($path === '' || $path === 'index') ? 'home' : $path;
$page = find_page($slug, true);

if (!$page) {
  http_response_code(404);
  $p = [
    'title' => 'Page Not Found', 'meta_title' => '404 | ' . setting('site_name'),
    'meta_description' => null, 'meta_keywords' => null, 'canonical' => null, 'og_image' => null,
    'robots' => 'noindex,follow', 'hero_show' => 1, 'hero_image' => 'images/hero-2.jpg',
    'hero_eyebrow' => 'Error 404', 'hero_heading' => 'Page Not Found',
    'hero_subtext' => "The page you're looking for doesn't exist or has moved.",
  ];
  echo render_document($p, render_hero($p)
    . '<section class="sp"><div class="container"><a class="btn btn-purple" href="' . base_url() . '">Back to Home</a></div></section>');
  exit;
}

$body  = render_hero($page);
$body .= ($slug === 'blogs') ? render_blog_list() : render_sections($page['id']);
echo render_document($page, $body);
