<?php
// File: index.php

function sanitize_output($buffer) {
    $search  = ['/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', '/<!--(.|\\s)*?-->/'];
    $replace = ['>', '<', '\\1', ''];
    return preg_replace($search, $replace, $buffer);
}
ob_start("sanitize_output");

ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once 'includes/db_connect.php';
require_once 'includes/functions.php';
require_once 'includes/cache.php';

// --- VISITOR COUNTER ---
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['has_visited'])) {
    try { $pdo->exec("UPDATE config_cabang SET visit_count = visit_count + 1 WHERE id = 1"); $_SESSION['has_visited'] = true; } catch (Exception $e) {}
}

// --- FETCH DATA ---
$config = getConfig($pdo);
if (!$config) {
    $config = [
        'nama_cabang' => 'Dealer Mobil', 'brand' => 'Mobil', 'logo_url' => '',
        'alamat' => '', 'footer_text' => '', 'hero_image_url' => '',
        'google_map_embed' => '', 'gemini_api_key' => '',
        'google_ads_wa_tag' => '', 'google_analytics_id' => '',
        'kota' => '', 'kecamatan' => '', 'provinsi' => '', 'kode_region' => '',
        'latitude' => '', 'longitude' => '', 'kode_pos' => '',
        'twitter_handle' => '', 'price_range' => '$$', 'currencies' => 'IDR',
        'payment_accepted' => 'Cash, Kredit, Transfer Bank',
        'jam_buka_senin_jumat' => '08:00', 'jam_tutup_senin_jumat' => '17:00',
        'jam_buka_sabtu' => '08:00', 'jam_tutup_sabtu' => '15:00',
        'buka_minggu' => 0, 'jam_buka_minggu' => '09:00', 'jam_tutup_minggu' => '13:00',
    ];
}

$brandName     = cfg($config, 'brand', 'Mobil');
$kotaName      = cfg($config, 'kota', '');
$provinsi      = cfg($config, 'provinsi', '');
$kodeRegion    = cfg($config, 'kode_region', '');
$lat           = cfg($config, 'latitude', '');
$lng           = cfg($config, 'longitude', '');
$tahunSekarang = date('Y');

$sales = getSalesProfile($pdo) ?: [
    'nama_lengkap' => 'Sales Executive', 'no_wa' => '', 'foto_profil_url' => '',
    'youtube_url' => '', 'instagram_url' => '', 'tiktok_url' => '', 'facebook_url' => '',
    'jabatan' => 'Sales Executive',
];
$config['sales'] = $sales;

// --- INPUT SANITASI (HARUS SEBELUM getPageData) ---
$page = preg_replace('/[^a-z0-9\-]/', '', strtolower($_GET['page'] ?? ''));
$id   = intval($_GET['id'] ?? 0);

$creditFull   = getCreditData($pdo);
// Muat data hanya sesuai kebutuhan halaman (hemat query DB)
$pageDataAll  = getPageData($pdo, $page, $id);
$products     = $pageDataAll['products'];
$promos       = $pageDataAll['promos'];
$testimonials = $pageDataAll['testimonials'];
$articles     = $pageDataAll['articles'];
$aggRating    = getAggregateRating($pdo);

// --- BASE URL ---
$protocol    = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
$siteBaseUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . str_replace('/index.php', '', $_SERVER['PHP_SELF']);
$siteBaseUrl = rtrim($siteBaseUrl, '/');

// --- SEO DEFAULTS ---
$siteName    = htmlspecialchars($config['nama_cabang']);
$footerText  = strip_tags(cfg($config, 'footer_text'));
$defaultDesc = mb_substr($footerText, 0, 155) . (mb_strlen($footerText) > 155 ? '...' : '');
$metaTitle   = $siteName . ' | Dealer Resmi ' . $brandName . ' ' . $kotaName;
$metaDesc    = $defaultDesc;
$metaImage   = makeAbsoluteUrl(cfg($config, 'hero_image_url'), $siteBaseUrl);
$canonicalUrl = $siteBaseUrl . '/';
$pageType    = 'website';
$breadcrumbs = null;

// --- PER-PAGE SEO ---
switch ($page) {
    case 'produk':
        $metaTitle    = 'Harga ' . $brandName . ' ' . $kotaName . ' ' . $tahunSekarang . ' | ' . $siteName;
        $metaDesc     = 'Daftar harga lengkap semua model ' . $brandName . ' terbaru ' . $tahunSekarang . ' di ' . cfg($config, 'nama_cabang') . '. DP ringan, cicilan murah, proses cepat.';
        $canonicalUrl = $siteBaseUrl . '/index.php?page=produk';
        break;
    case 'promo':
        $metaTitle    = 'Promo ' . $brandName . ' ' . $kotaName . ' ' . $tahunSekarang . ' | ' . $siteName;
        $metaDesc     = 'Promo spesial ' . $brandName . ' terbatas! Diskon, DP ringan, bonus menarik di ' . $kotaName . '. Hubungi ' . cfg($sales, 'nama_lengkap') . ' sekarang.';
        $canonicalUrl = $siteBaseUrl . '/index.php?page=promo';
        break;
    case 'simulasi':
        $metaTitle    = 'Simulasi Kredit ' . $brandName . ' ' . $kotaName . ' | ' . $siteName;
        $metaDesc     = 'Hitung cicilan kredit ' . $brandName . ' impian Anda secara online. Cek estimasi TDP & angsuran per bulan dengan mudah dan akurat.';
        $canonicalUrl = $siteBaseUrl . '/index.php?page=simulasi';
        break;
    case 'tradein':
        $metaTitle    = 'Trade-In Mobil | Tukar Tambah ' . $brandName . ' ' . $kotaName . ' | ' . $siteName;
        $metaDesc     = 'Tukar mobil lama dengan ' . $brandName . ' baru di ' . cfg($config, 'nama_cabang') . '. Estimasi harga instan, proses mudah & transparan.';
        $canonicalUrl = $siteBaseUrl . '/index.php?page=tradein';
        break;
    case 'artikel':
        $metaTitle    = 'Berita & Tips ' . $brandName . ' | ' . $siteName;
        $metaDesc     = 'Baca artikel dan tips seputar ' . $brandName . ' terbaru: review, perbandingan, dan info otomotif terkini dari ' . cfg($config, 'nama_cabang') . '.';
        $canonicalUrl = $siteBaseUrl . '/index.php?page=artikel';
        break;
    case 'testimoni':
        $metaTitle    = 'Testimoni & Gallery Serah Terima | ' . $siteName;
        $metaDesc     = 'Lihat foto serah terima dan ulasan pelanggan puas di ' . cfg($config, 'nama_cabang') . '. Ratusan customer sudah mempercayakan pembelian ' . $brandName . ' kepada kami.';
        $canonicalUrl = $siteBaseUrl . '/index.php?page=testimoni';
        break;
    case 'kontak':
        $metaTitle    = 'Hubungi ' . cfg($sales, 'nama_lengkap') . ' | ' . $siteName;
        $metaDesc     = 'Hubungi ' . cfg($sales, 'nama_lengkap') . ' untuk info harga, promo, dan test drive ' . $brandName . ' di ' . $kotaName . '. Respon cepat via WhatsApp.';
        $canonicalUrl = $siteBaseUrl . '/index.php?page=kontak';
        break;
    case 'produk-detail':
        if ($id) {
            foreach ($products as $p) {
                if ($p['id'] == $id) {
                    $metaTitle    = 'Harga ' . $p['name'] . ' ' . $tahunSekarang . ' ' . $kotaName . ' | ' . $siteName;
                    $metaDesc     = mb_substr('Promo ' . $p['name'] . ' DP ringan cicilan terjangkau di ' . cfg($config, 'nama_cabang') . '. ' . strip_tags($p['desc'] ?? ''), 0, 155) . '...';
                    $metaImage    = makeAbsoluteUrl($p['image'] ?? '', $siteBaseUrl);
                    $canonicalUrl = $siteBaseUrl . '/index.php?page=produk-detail&id=' . $id;
                    $currentProduct = $p;
                    $breadcrumbs  = [
                        ['name' => $siteName,              'url' => $siteBaseUrl . '/'],
                        ['name' => 'Produk ' . $brandName, 'url' => $siteBaseUrl . '/index.php?page=produk'],
                        ['name' => $p['name'],             'url' => $canonicalUrl],
                    ];
                    break;
                }
            }
        }
        break;
    case 'artikel-detail':
        if ($id) {
            foreach ($articles as $a) {
                if ($a['id'] == $id) {
                    $metaTitle    = $a['title'] . ' | ' . $siteName;
                    $metaDesc     = mb_substr(strip_tags($a['content'] ?? ''), 0, 155) . '...';
                    $metaImage    = makeAbsoluteUrl($a['image'] ?? '', $siteBaseUrl);
                    $canonicalUrl = $siteBaseUrl . '/index.php?page=artikel-detail&id=' . $id;
                    $pageType     = 'article';
                    $currentArticle = $a;
                    $breadcrumbs  = [
                        ['name' => $siteName,   'url' => $siteBaseUrl . '/'],
                        ['name' => 'Artikel',   'url' => $siteBaseUrl . '/index.php?page=artikel'],
                        ['name' => $a['title'], 'url' => $canonicalUrl],
                    ];
                    break;
                }
            }
        }
        break;
    case 'promo-detail':
        if ($id) {
            foreach ($promos as $pr) {
                if ($pr['id'] == $id) {
                    $metaTitle    = ($pr['title'] ?? '') . ' | Promo ' . $brandName . ' | ' . $siteName;
                    $metaDesc     = mb_substr(strip_tags($pr['desc'] ?? ''), 0, 155) . '...';
                    $metaImage    = makeAbsoluteUrl($pr['image'] ?? '', $siteBaseUrl);
                    $canonicalUrl = $siteBaseUrl . '/index.php?page=promo-detail&id=' . $id;
                    $currentPromo = $pr;
                    $breadcrumbs  = [
                        ['name' => $siteName,    'url' => $siteBaseUrl . '/'],
                        ['name' => 'Promo',      'url' => $siteBaseUrl . '/index.php?page=promo'],
                        ['name' => $pr['title'], 'url' => $canonicalUrl],
                    ];
                    break;
                }
            }
        }
        break;
}

if (empty($metaImage)) $metaImage = makeAbsoluteUrl(cfg($config, 'logo_url'), $siteBaseUrl);
$metaImageSecure = strpos($metaImage, 'https://') === 0 ? $metaImage : str_replace('http://', 'https://', $metaImage);

// ================================================================
// JSON-LD SCHEMAS
// ================================================================
$autoDealer = [
    '@context' => 'https://schema.org',
    '@type'    => ['AutoDealer', 'LocalBusiness'],
    '@id'      => $siteBaseUrl . '/#organization',
    'name'     => cfg($config, 'nama_cabang'),
    'url'      => $siteBaseUrl . '/',
    'logo'     => ['@type' => 'ImageObject', 'url' => makeAbsoluteUrl(cfg($config, 'logo_url'), $siteBaseUrl)],
    'image'    => makeAbsoluteUrl(cfg($config, 'hero_image_url'), $siteBaseUrl),
    'telephone'=> cfg($sales, 'no_wa'),
    'description' => $footerText,
    'brand'    => ['@type' => 'Brand', 'name' => $brandName],
    'priceRange'  => cfg($config, 'price_range', '$$'),
    'currenciesAccepted' => cfg($config, 'currencies', 'IDR'),
    'paymentAccepted'    => cfg($config, 'payment_accepted', 'Cash, Kredit, Transfer Bank'),
    'address'  => [
        '@type'           => 'PostalAddress',
        'streetAddress'   => cfg($config, 'alamat'),
        'addressLocality' => $kotaName,
        'addressRegion'   => $provinsi,
        'postalCode'      => cfg($config, 'kode_pos'),
        'addressCountry'  => 'ID',
    ],
];
if (!empty($lat) && !empty($lng)) {
    $autoDealer['geo'] = ['@type' => 'GeoCoordinates', 'latitude' => $lat, 'longitude' => $lng];
}
if ($aggRating) {
    $autoDealer['aggregateRating'] = [
        '@type' => 'AggregateRating',
        'ratingValue' => $aggRating['ratingValue'],
        'reviewCount' => $aggRating['reviewCount'],
        'bestRating'  => 5,
        'worstRating' => 1,
    ];
}
$openingHours = [
    ['@type' => 'OpeningHoursSpecification', 'dayOfWeek' => ['Monday','Tuesday','Wednesday','Thursday','Friday'], 'opens' => cfg($config, 'jam_buka_senin_jumat', '08:00'), 'closes' => cfg($config, 'jam_tutup_senin_jumat', '17:00')],
    ['@type' => 'OpeningHoursSpecification', 'dayOfWeek' => ['Saturday'], 'opens' => cfg($config, 'jam_buka_sabtu', '08:00'), 'closes' => cfg($config, 'jam_tutup_sabtu', '15:00')],
];
if (!empty($config['buka_minggu'])) {
    $openingHours[] = ['@type' => 'OpeningHoursSpecification', 'dayOfWeek' => ['Sunday'], 'opens' => cfg($config, 'jam_buka_minggu', '09:00'), 'closes' => cfg($config, 'jam_tutup_minggu', '13:00')];
}
$autoDealer['openingHoursSpecification'] = $openingHours;
$sameAs = array_values(array_filter([cfg($sales,'youtube_url'), cfg($sales,'instagram_url'), cfg($sales,'tiktok_url'), cfg($sales,'facebook_url')]));
if ($sameAs) $autoDealer['sameAs'] = $sameAs;

$websiteSchema = [
    '@context' => 'https://schema.org', '@type' => 'WebSite',
    '@id'      => $siteBaseUrl . '/#website',
    'url'      => $siteBaseUrl . '/', 'name' => cfg($config, 'nama_cabang'),
    'description' => $footerText, 'inLanguage' => 'id-ID',
    'publisher'   => ['@id' => $siteBaseUrl . '/#organization'],
    'potentialAction' => [
        '@type'  => 'SearchAction',
        'target' => ['@type' => 'EntryPoint', 'urlTemplate' => $siteBaseUrl . '/index.php?page=produk&q={search_term_string}'],
        'query-input' => 'required name=search_term_string',
    ],
];

$schemaMain = $autoDealer;
if ($page === 'produk-detail' && isset($currentProduct)) {
    $schemaMain = [
        '@context' => 'https://schema.org', '@type' => 'Product',
        'name'     => $currentProduct['name'], 'url' => $canonicalUrl,
        'image'    => $metaImage, 'description' => strip_tags($currentProduct['desc'] ?? ''),
        'brand'    => ['@type' => 'Brand', 'name' => $brandName],
        'offers'   => [
            '@type' => 'Offer', 'priceCurrency' => cfg($config, 'currencies', 'IDR'),
            'price' => $currentProduct['price'], 'availability' => 'https://schema.org/InStock',
            'url'   => $canonicalUrl,
            'seller' => ['@type' => 'AutoDealer', 'name' => cfg($config, 'nama_cabang'), 'telephone' => cfg($sales, 'no_wa')],
        ],
    ];
} elseif ($page === 'artikel-detail' && isset($currentArticle)) {
    $rawDate = $currentArticle['raw_date'] ?? date('Y-m-d');
    $isoDate = date('c', strtotime($rawDate));
    $schemaMain = [
        '@context' => 'https://schema.org', '@type' => 'NewsArticle',
        'mainEntityOfPage' => ['@type' => 'WebPage', '@id' => $canonicalUrl],
        'headline'      => $currentArticle['title'], 'image' => [$metaImage],
        'datePublished' => $isoDate, 'dateModified' => $isoDate, 'inLanguage' => 'id-ID',
        'author'    => ['@type' => 'Person', 'name' => cfg($sales, 'nama_lengkap'), 'url' => $siteBaseUrl . '/index.php?page=kontak'],
        'publisher' => ['@type' => 'Organization', 'name' => cfg($config, 'nama_cabang'), 'logo' => ['@type' => 'ImageObject', 'url' => makeAbsoluteUrl(cfg($config, 'logo_url'), $siteBaseUrl)]],
    ];
}

$schemaBreadcrumb = null;
if ($breadcrumbs) {
    $bcItems = [];
    foreach ($breadcrumbs as $pos => $bc) {
        $bcItems[] = ['@type' => 'ListItem', 'position' => $pos + 1, 'name' => $bc['name'], 'item' => $bc['url']];
    }
    $schemaBreadcrumb = ['@context' => 'https://schema.org', '@type' => 'BreadcrumbList', 'itemListElement' => $bcItems];
}

// --- DATA PAYLOAD KE JS — Hapus data sensitif sebelum kirim ke client ---
$configPublic = $config;
unset(
    $configPublic['gemini_api_key'],        // API key tidak perlu di client
    $configPublic['google_ads_wa_tag'],      // Hanya perlu di PHP
    $configPublic['google_analytics_id'],    // Sama
    $configPublic['google_places_api_key'],  // AUDIT FIX: API key tidak boleh di client
    $configPublic['google_place_id']         // AUDIT FIX: Place ID internal, tidak perlu di client
);

$dataPayload = [
    'config' => $configPublic,
    'db'     => ['products' => $products, 'promos' => $promos, 'testimonials' => $testimonials, 'articles' => $articles],
    'credit' => $creditFull,
];

// Cache-busting untuk asset CSS/JS
$cssBust = file_exists('assets/css/style.css')   ? filemtime('assets/css/style.css')   : time();
$jsBust  = file_exists('assets/js/script.js')    ? filemtime('assets/js/script.js')    : time();

$pageTitlesJS = [
    'home'      => $siteName . ' | Dealer Resmi ' . $brandName . ' ' . $kotaName,
    'produk'    => 'Harga ' . $brandName . ' ' . $kotaName . ' ' . $tahunSekarang . ' | ' . $siteName,
    'promo'     => 'Promo ' . $brandName . ' ' . $kotaName . ' ' . $tahunSekarang . ' | ' . $siteName,
    'simulasi'  => 'Simulasi Kredit ' . $brandName . ' ' . $kotaName . ' | ' . $siteName,
    'tradein'   => 'Trade-In Mobil | Tukar Tambah ' . $brandName . ' ' . $kotaName . ' | ' . $siteName,
    'artikel'   => 'Berita & Tips ' . $brandName . ' | ' . $siteName,
    'testimoni' => 'Testimoni & Gallery Serah Terima | ' . $siteName,
    'kontak'    => 'Hubungi ' . htmlspecialchars(cfg($sales, 'nama_lengkap')) . ' | ' . $siteName,
];
$pageDescsJS = [
    'home'      => $metaDesc,
    'produk'    => 'Daftar harga lengkap semua model ' . $brandName . ' terbaru ' . $tahunSekarang . ' di ' . cfg($config, 'nama_cabang') . '. DP ringan, cicilan murah, proses cepat.',
    'promo'     => 'Promo spesial ' . $brandName . ' terbatas! Diskon, DP ringan, bonus menarik di ' . $kotaName . '.',
    'simulasi'  => 'Hitung cicilan kredit ' . $brandName . ' impian Anda secara online. Cek estimasi TDP & angsuran per bulan.',
    'tradein'   => 'Tukar mobil lama dengan ' . $brandName . ' baru. Estimasi harga instan, proses mudah & transparan.',
    'artikel'   => 'Baca artikel dan tips seputar ' . $brandName . ' terbaru: review, perbandingan, dan info otomotif terkini.',
    'testimoni' => 'Lihat foto serah terima dan ulasan pelanggan puas ' . cfg($config, 'nama_cabang') . '.',
    'kontak'    => 'Hubungi ' . cfg($sales, 'nama_lengkap') . ' untuk info harga, promo, dan test drive ' . $brandName . ' di ' . $kotaName . '.',
];

$twitterHandle = cfg($config, 'twitter_handle');
$authorName    = cfg($sales, 'nama_lengkap', cfg($config, 'nama_cabang'));
$geoPlacename  = trim(implode(', ', array_filter([$kotaName, $provinsi])));

// Google Tracking flags
$hasAds = !empty($config['google_ads_wa_tag']);
$hasGA  = !empty($config['google_analytics_id']);
?>
<!DOCTYPE html>
<html lang="id" class="scroll-smooth">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($metaTitle) ?></title>
    <meta name="description" content="<?= htmlspecialchars($metaDesc) ?>">
    <meta name="author" content="<?= htmlspecialchars($authorName) ?>">
    <link rel="canonical" href="<?= htmlspecialchars($canonicalUrl) ?>">

    <!-- Hreflang -->
    <link rel="alternate" hreflang="id" href="<?= htmlspecialchars($canonicalUrl) ?>">
    <link rel="alternate" hreflang="x-default" href="<?= htmlspecialchars($canonicalUrl) ?>">

    <!-- Favicon -->
    <link rel="icon" href="<?= htmlspecialchars(makeAbsoluteUrl(cfg($config,'logo_url'), $siteBaseUrl)) ?>" type="image/png">
    <link rel="shortcut icon" href="<?= htmlspecialchars(makeAbsoluteUrl(cfg($config,'logo_url'), $siteBaseUrl)) ?>">
    <link rel="apple-touch-icon" href="<?= htmlspecialchars(makeAbsoluteUrl(cfg($config,'logo_url'), $siteBaseUrl)) ?>">
    <link rel="manifest" href="manifest.json">
    <meta name="theme-color" content="#EB0A1E">
    <meta name="msapplication-TileColor" content="#EB0A1E">

    <!-- Robots -->
    <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1">

    <!-- Open Graph -->
    <meta property="og:type" content="<?= htmlspecialchars($pageType) ?>">
    <meta property="og:title" content="<?= htmlspecialchars($metaTitle) ?>">
    <meta property="og:description" content="<?= htmlspecialchars($metaDesc) ?>">
    <meta property="og:image" content="<?= htmlspecialchars($metaImage) ?>">
    <meta property="og:image:secure_url" content="<?= htmlspecialchars($metaImageSecure) ?>">
    <meta property="og:image:width" content="1200">
    <meta property="og:image:height" content="630">
    <meta property="og:image:alt" content="<?= htmlspecialchars($metaTitle) ?>">
    <meta property="og:url" content="<?= htmlspecialchars($canonicalUrl) ?>">
    <meta property="og:site_name" content="<?= htmlspecialchars(cfg($config,'nama_cabang')) ?>">
    <meta property="og:locale" content="id_ID">

    <!-- Twitter Card -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="<?= htmlspecialchars($metaTitle) ?>">
    <meta name="twitter:description" content="<?= htmlspecialchars($metaDesc) ?>">
    <meta name="twitter:image" content="<?= htmlspecialchars($metaImageSecure) ?>">
    <meta name="twitter:image:alt" content="<?= htmlspecialchars($metaTitle) ?>">
    <?php if (!empty($twitterHandle)): ?>
    <meta name="twitter:site" content="@<?= htmlspecialchars($twitterHandle) ?>">
    <meta name="twitter:creator" content="@<?= htmlspecialchars($twitterHandle) ?>">
    <?php endif; ?>

    <!-- Geo Tags (hanya render jika data tersedia) -->
    <?php if (!empty($kodeRegion)): ?><meta name="geo.region" content="<?= htmlspecialchars($kodeRegion) ?>"><?php endif; ?>
    <?php if (!empty($geoPlacename)): ?><meta name="geo.placename" content="<?= htmlspecialchars($geoPlacename) ?>"><?php endif; ?>
    <?php if (!empty($lat) && !empty($lng)): ?><meta name="ICBM" content="<?= htmlspecialchars($lat) ?>, <?= htmlspecialchars($lng) ?>"><?php endif; ?>

    <!-- Preconnect & Preload -->
    <link rel="preconnect" href="https://cdn.tailwindcss.com">
    <link rel="preconnect" href="https://cdnjs.cloudflare.com" crossorigin>
    <link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <?php if (!empty($config['hero_image_url'])): ?>
    <link rel="preload" as="image" href="<?= htmlspecialchars($config['hero_image_url']) ?>" fetchpriority="high">
    <?php endif; ?>
    <link rel="preload" as="style" href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800&display=swap">

    <!-- JSON-LD: WebSite + SearchAction -->
    <script type="application/ld+json"><?= json_encode($websiteSchema, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_HEX_TAG|JSON_HEX_AMP) ?></script>
    <!-- JSON-LD: Schema utama halaman -->
    <script type="application/ld+json"><?= json_encode($schemaMain, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_HEX_TAG|JSON_HEX_AMP) ?></script>
    <?php if ($schemaBreadcrumb): ?>
    <script type="application/ld+json"><?= json_encode($schemaBreadcrumb, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_HEX_TAG|JSON_HEX_AMP) ?></script>
    <?php endif; ?>

    <!-- GOOGLE TAGS (Ads + Analytics) — hanya inject jika diisi di admin -->
    <?php if ($hasAds || $hasGA):
        $baseScriptId = $hasGA ? trim($config['google_analytics_id']) : explode('/', trim($config['google_ads_wa_tag']))[0];
    ?>
    <script async src="https://www.googletagmanager.com/gtag/js?id=<?= htmlspecialchars($baseScriptId) ?>"></script>
    <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    <?php if ($hasGA): ?>
    gtag('config','<?= htmlspecialchars(trim($config['google_analytics_id'])) ?>',{send_page_view:false});
    <?php endif; ?>
    <?php if ($hasAds): $base_aw = explode('/', trim($config['google_ads_wa_tag']))[0]; ?>
    gtag('config','<?= htmlspecialchars($base_aw) ?>');
    <?php endif; ?>
    </script>
    <?php endif; ?>

    <!-- External CSS/JS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- DOMPurify: sanitasi HTML dari DB sebelum render ke DOM (cegah Stored XSS) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.1.6/purify.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/style.css?v=<?= $cssBust ?>">
    <script>
        tailwind.config = { theme: { extend: { colors: { toyota: { red: '#EB0A1E', dark: '#1a1a1a', gray: '#f4f4f4' } } } } }
    </script>
</head>
<body class="bg-gray-50 text-gray-800 antialiased" data-dealer-name="<?= htmlspecialchars(cfg($config,'nama_cabang')) ?>">

    <!-- LOADER -->
    <div id="loader" class="fixed inset-0 bg-white z-[9999] flex items-center justify-center" role="status">
        <div class="text-center">
            <img src="<?= htmlspecialchars(makeAbsoluteUrl(cfg($config,'logo_url'), $siteBaseUrl)) ?>"
                 alt="Logo <?= htmlspecialchars(cfg($config,'nama_cabang')) ?>"
                 width="100" height="50" class="h-12 w-auto mb-4 mx-auto animate-bounce object-contain">
            <p class="text-sm text-gray-500 animate-pulse">Memuat Data...</p>
        </div>
    </div>

    <!-- NAVIGASI -->
    <nav class="sticky top-0 z-40 bg-white/95 backdrop-blur-md shadow-sm transition-all duration-300" role="navigation" aria-label="Navigasi utama">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <a href="<?= htmlspecialchars($siteBaseUrl) ?>/"
               class="flex items-center gap-3 group cursor-pointer flex-shrink-0"
               onclick="navigate('home'); return false;"
               aria-label="<?= htmlspecialchars(cfg($config,'nama_cabang')) ?> — Halaman Utama">
                <img src="<?= htmlspecialchars(makeAbsoluteUrl(cfg($config,'logo_url'), $siteBaseUrl)) ?>"
                     alt="Logo <?= htmlspecialchars(cfg($config,'nama_cabang')) ?>"
                     width="100" height="40" class="h-6 md:h-8 w-auto object-contain flex-shrink-0">
                <div class="h-6 md:h-8 w-[1px] bg-gray-300" aria-hidden="true"></div>
                <?php $parts = explode(' ', cfg($config,'nama_cabang')); $shortName = strtoupper(end($parts)); ?>
                <span class="text-xs md:text-sm font-bold text-gray-600 tracking-widest uppercase truncate max-w-[100px] md:max-w-none">
                    <?= htmlspecialchars($shortName) ?>
                </span>
            </a>
            <div class="hidden md:flex space-x-3 lg:space-x-5 text-xs lg:text-sm font-semibold uppercase tracking-wide items-center flex-shrink-0" role="menubar">
                <button onclick="navigate('home')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red" role="menuitem">Home</button>
                <button onclick="navigate('promo')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red" role="menuitem">Promo</button>
                <button onclick="navigate('produk')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red" role="menuitem">Produk</button>
                <button onclick="navigate('simulasi')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red" role="menuitem">Simulasi</button>
                <button onclick="navigate('tradein')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red" role="menuitem">Trade-in</button>
                <button onclick="navigate('artikel')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red" role="menuitem">Artikel</button>
                <button onclick="navigate('testimoni')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red" role="menuitem">Testimoni</button>
                <button onclick="navigate('kontak')" class="bg-toyota-red text-white px-3 py-2 rounded-full hover:bg-red-700 transition shadow-lg shadow-red-500/30 transform hover:scale-105 ml-2 whitespace-nowrap" role="menuitem">Hubungi Kami</button>
            </div>
            <button onclick="toggleMobileMenu()" class="md:hidden text-2xl text-toyota-dark focus:outline-none p-2"
                    aria-label="Buka menu navigasi" aria-expanded="false" aria-controls="mobile-menu">
                <i class="fa-solid fa-bars" aria-hidden="true"></i>
            </button>
        </div>
        <div id="mobile-menu" class="hidden md:hidden bg-white border-t absolute w-full left-0 shadow-lg z-50" role="menu">
            <button onclick="mobileNavClick('home')"      class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link" role="menuitem">HOME</button>
            <button onclick="mobileNavClick('promo')"     class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link" role="menuitem">PROMO</button>
            <button onclick="mobileNavClick('produk')"    class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link" role="menuitem">PRODUK</button>
            <button onclick="mobileNavClick('simulasi')"  class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link" role="menuitem">SIMULASI</button>
            <button onclick="mobileNavClick('tradein')"   class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link" role="menuitem">TRADE-IN</button>
            <button onclick="mobileNavClick('artikel')"   class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link" role="menuitem">ARTIKEL</button>
            <button onclick="mobileNavClick('testimoni')" class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link" role="menuitem">TESTIMONI</button>
            <button onclick="mobileNavClick('kontak')"    class="block w-full text-left px-4 py-3 bg-toyota-red text-white font-bold" role="menuitem">KONTAK</button>
        </div>
    </nav>

    <!-- KONTEN UTAMA -->
    <main id="app-content" class="min-h-screen overflow-hidden relative" role="main">
        <noscript>
            <div class="container mx-auto px-4 py-16">
                <h1 class="text-3xl font-bold mb-4"><?= htmlspecialchars(cfg($config,'nama_cabang')) ?></h1>
                <p class="mb-8"><?= htmlspecialchars(mb_substr($footerText, 0, 300)) ?></p>
                <?php if (!empty($products)): ?>
                <h2 class="text-2xl font-bold mb-4">Daftar Produk <?= htmlspecialchars($brandName) ?></h2>
                <ul class="grid grid-cols-2 gap-4 mb-8">
                    <?php foreach ($products as $p): ?>
                    <li><a href="<?= htmlspecialchars($siteBaseUrl.'/index.php?page=produk-detail&id='.$p['id']) ?>" class="text-blue-700 font-semibold hover:underline"><?= htmlspecialchars($p['name']) ?> — <?= htmlspecialchars(formatRupiah($p['price'])) ?></a></li>
                    <?php endforeach; ?>
                </ul>
                <?php endif; ?>
                <?php if (!empty($articles)): ?>
                <h2 class="text-2xl font-bold mb-4">Artikel Terbaru</h2>
                <ul class="mb-8">
                    <?php foreach ($articles as $a): ?>
                    <li><a href="<?= htmlspecialchars($siteBaseUrl.'/index.php?page=artikel-detail&id='.$a['id']) ?>" class="text-blue-700 hover:underline"><?= htmlspecialchars($a['title']) ?></a></li>
                    <?php endforeach; ?>
                </ul>
                <?php endif; ?>
                <address class="not-italic text-gray-600">
                    <strong><?= htmlspecialchars(cfg($sales,'nama_lengkap')) ?></strong><br>
                    <?= htmlspecialchars(cfg($config,'nama_cabang')) ?><br>
                    <?= htmlspecialchars(cfg($config,'alamat')) ?><br>
                    <?= htmlspecialchars($geoPlacename) ?><br>
                    Tel: <?= htmlspecialchars(cfg($sales,'no_wa')) ?>
                </address>
            </div>
        </noscript>
    </main>

    <!-- FOOTER -->
    <footer class="bg-toyota-dark text-white pt-16 pb-8 border-t-4 border-toyota-red" role="contentinfo">
        <div class="container mx-auto px-4">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-10 mb-12">
                <!-- Kolom 1: Brand -->
                <div class="md:col-span-1">
                    <img src="<?= htmlspecialchars(makeAbsoluteUrl(cfg($config,'logo_url'), $siteBaseUrl)) ?>"
                         alt="Logo <?= htmlspecialchars(cfg($config,'nama_cabang')) ?>"
                         width="120" height="50" loading="lazy"
                         class="h-9 mb-5 brightness-0 invert object-contain">
                    <p class="text-gray-400 text-sm leading-relaxed"><?= htmlspecialchars($footerText) ?></p>
                </div>

                <!-- Kolom 2: Navigasi -->
                <nav aria-label="Footer navigasi">
                    <h3 class="text-sm font-bold uppercase tracking-widest text-gray-300 mb-5">Navigasi</h3>
                    <ul class="space-y-3 text-sm">
                        <li><button onclick="navigate('produk')"   class="text-gray-400 hover:text-white transition">Daftar Harga</button></li>
                        <li><button onclick="navigate('simulasi')" class="text-gray-400 hover:text-white transition">Simulasi Kredit</button></li>
                        <li><button onclick="navigate('tradein')"  class="text-gray-400 hover:text-white transition">Trade-in</button></li>
                        <li><button onclick="navigate('promo')"    class="text-gray-400 hover:text-white transition">Promo Spesial</button></li>
                        <li><button onclick="navigate('artikel')"  class="text-gray-400 hover:text-white transition">Artikel &amp; Tips</button></li>
                    </ul>
                </nav>

                <!-- Kolom 3: Kontak Sales -->
                <div>
                    <h3 class="text-sm font-bold uppercase tracking-widest text-gray-300 mb-5">Hubungi Sales</h3>
                    <ul class="space-y-3 text-sm text-gray-400">
                        <li class="flex items-start gap-2">
                            <i class="fa-solid fa-user text-toyota-red mt-0.5 w-4 shrink-0" aria-hidden="true"></i>
                            <span><?= htmlspecialchars(cfg($sales,'nama_lengkap')) ?></span>
                        </li>
                        <li class="flex items-start gap-2">
                            <i class="fa-brands fa-whatsapp text-toyota-red mt-0.5 w-4 shrink-0" aria-hidden="true"></i>
                            <span><?= htmlspecialchars(cfg($sales,'no_wa')) ?></span>
                        </li>
                        <li class="flex items-start gap-2">
                            <i class="fa-solid fa-building text-toyota-red mt-0.5 w-4 shrink-0" aria-hidden="true"></i>
                            <span><?= htmlspecialchars(cfg($config,'nama_cabang')) ?></span>
                        </li>
                    </ul>
                    <div class="flex gap-3 mt-6" aria-label="Media sosial">
                        <?php if (!empty($sales['youtube_url'])): ?><a href="<?= htmlspecialchars($sales['youtube_url']) ?>" target="_blank" rel="noopener noreferrer" aria-label="YouTube <?= htmlspecialchars(cfg($sales,'nama_lengkap')) ?>" class="w-9 h-9 rounded-xl bg-white/5 flex items-center justify-center text-gray-400 hover:text-white hover:bg-red-600 transition border border-white/10"><i class="fa-brands fa-youtube" aria-hidden="true"></i></a><?php endif; ?>
                        <?php if (!empty($sales['instagram_url'])): ?><a href="<?= htmlspecialchars($sales['instagram_url']) ?>" target="_blank" rel="noopener noreferrer" aria-label="Instagram <?= htmlspecialchars(cfg($sales,'nama_lengkap')) ?>" class="w-9 h-9 rounded-xl bg-white/5 flex items-center justify-center text-gray-400 hover:text-white hover:bg-pink-600 transition border border-white/10"><i class="fa-brands fa-instagram" aria-hidden="true"></i></a><?php endif; ?>
                        <?php if (!empty($sales['tiktok_url'])): ?><a href="<?= htmlspecialchars($sales['tiktok_url']) ?>" target="_blank" rel="noopener noreferrer" aria-label="TikTok <?= htmlspecialchars(cfg($sales,'nama_lengkap')) ?>" class="w-9 h-9 rounded-xl bg-white/5 flex items-center justify-center text-gray-400 hover:text-white hover:bg-gray-100 hover:text-black transition border border-white/10"><i class="fa-brands fa-tiktok" aria-hidden="true"></i></a><?php endif; ?>
                        <?php if (!empty($sales['facebook_url'])): ?><a href="<?= htmlspecialchars($sales['facebook_url']) ?>" target="_blank" rel="noopener noreferrer" aria-label="Facebook <?= htmlspecialchars(cfg($sales,'nama_lengkap')) ?>" class="w-9 h-9 rounded-xl bg-white/5 flex items-center justify-center text-gray-400 hover:text-white hover:bg-blue-600 transition border border-white/10"><i class="fa-brands fa-facebook-f" aria-hidden="true"></i></a><?php endif; ?>
                    </div>
                </div>

                <!-- Kolom 4: Alamat -->
                <div>
                    <h3 class="text-sm font-bold uppercase tracking-widest text-gray-300 mb-5">Lokasi</h3>
                    <address class="not-italic text-gray-400 text-sm leading-relaxed">
                        <?= htmlspecialchars(cfg($config,'alamat')) ?>
                        <?php if (!empty($geoPlacename)): ?><br><span class="text-gray-500"><?= htmlspecialchars($geoPlacename) ?></span><?php endif; ?>
                    </address>
                    <?php if (!empty($config['google_map_embed'])): ?>
                    <button onclick="navigate('kontak')"
                        class="mt-4 inline-flex items-center gap-2 text-toyota-red text-xs font-semibold hover:underline">
                        <i class="fa-solid fa-map-pin" aria-hidden="true"></i> Lihat di Peta
                    </button>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Bottom bar -->
            <div class="border-t border-gray-800 pt-8 flex flex-col md:flex-row justify-between items-center gap-3">
                <p class="text-gray-600 text-xs">
                    &copy; <?= $tahunSekarang ?> <?= htmlspecialchars(cfg($config,'nama_cabang')) ?>. All rights reserved.
                </p>
                <p class="text-gray-700 text-xs">Powered by Willie System</p>
            </div>
        </div>
    </footer>

    <!-- DATA JS -->
    <script>
        window.DATA_FROM_PHP  = <?= json_encode($dataPayload, JSON_HEX_TAG|JSON_HEX_AMP|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
        window.SITE_BASE_URL  = <?= json_encode($siteBaseUrl) ?>;
        window.PAGE_TITLES    = <?= json_encode($pageTitlesJS, JSON_UNESCAPED_UNICODE) ?>;
        window.PAGE_DESCS     = <?= json_encode($pageDescsJS, JSON_UNESCAPED_UNICODE) ?>;
        window.CANONICAL_BASE = <?= json_encode($siteBaseUrl) ?>;
        window.TAHUN          = <?= json_encode($tahunSekarang) ?>;
    </script>
    <script src="assets/js/script.js?v=<?= $jsBust ?>" defer></script>
</body>
</html>
<?php ob_end_flush(); ?>
