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

ini_set('display_errors', 0); // Production mode
error_reporting(E_ALL);

require 'includes/db_connect.php';
require 'includes/functions.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'=>'Toyota Sales', 'brand'=>'Toyota', 'logo_url'=>'', 'alamat'=>'', 'footer_text'=>'', 'hero_image_url'=>''];
}
$brandName = !empty($config['brand']) ? $config['brand'] : 'Mobil';
$sales = getSalesProfile($pdo) ?: ['nama_lengkap'=>'Sales', 'no_wa'=>'', 'foto_profil_url'=>'', 'youtube_url'=>'', 'instagram_url'=>'', 'tiktok_url'=>'', 'facebook_url'=>''];
$config['sales'] = $sales;

$creditFull = getCreditData($pdo);
$products = getAllProducts($pdo) ?: [];
$promos = getAllPromos($pdo) ?: [];
$testimonials = getAllTestimonials($pdo) ?: [];
$articles = getAllArticles($pdo) ?: [];

// --- SEO LOGIC ---
$metaTitle = $config['nama_cabang'] . " - Penawaran Terbaik " . $brandName;
$metaDesc = $config['footer_text'];
$metaImage = $config['hero_image_url'];
$metaUrl = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$pageType = 'website';

$page = $_GET['page'] ?? '';
$id = $_GET['id'] ?? 0;

if ($page == 'produk-detail' && $id) {
    foreach ($products as $p) {
        if ($p['id'] == $id) {
            $metaTitle = "Harga & Spesifikasi " . $p['name'] . " 2025 - " . $config['nama_cabang'];
            $metaDesc = "Promo kredit " . $p['name'] . " DP Ringan. Hubungi " . $sales['nama_lengkap'];
            $metaImage = (strpos($p['image'], 'http') === 0) ? $p['image'] : $p['image']; 
            $pageType = 'product';
            $currentProduct = $p;
            break;
        }
    }
} elseif ($page == 'artikel-detail' && $id) {
    foreach ($articles as $a) {
        if ($a['id'] == $id) {
            $metaTitle = $a['title'];
            $metaDesc = substr(strip_tags($a['content']), 0, 160) . "...";
            $metaImage = (strpos($a['image'], 'http') === 0) ? $a['image'] : $a['image'];
            $pageType = 'article';
            $currentArticle = $a;
            break;
        }
    }
} elseif ($page == 'promo-detail' && $id) {
    foreach ($promos as $pr) {
        if ($pr['id'] == $id) {
            $metaTitle = $pr['title'] . " - Promo Terbatas";
            $metaDesc = strip_tags($pr['desc']);
            $metaImage = (strpos($pr['image'], 'http') === 0) ? $pr['image'] : $pr['image'];
            break;
        }
    }
}

$dataPayload = [
    'config' => $config,
    'db' => [
        'products' => $products,
        'promos' => $promos,
        'testimonials' => $testimonials,
        'articles' => $articles
    ],
    'credit' => $creditFull
];
?>
<!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) ?>">
    <link rel="canonical" href="<?= htmlspecialchars($metaUrl) ?>">
    <link rel="shortcut icon" href="<?= $config['logo_url'] ?>" type="image/x-icon">
    <meta name="robots" content="index, follow, max-image-preview:large">
    <meta property="og:type" content="<?= $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:url" content="<?= htmlspecialchars($metaUrl) ?>">
    <meta property="og:site_name" content="<?= htmlspecialchars($config['nama_cabang']) ?>">
    <meta property="og:locale" content="id_ID">
    <meta name="twitter:card" content="summary_large_image">
    <link rel="preconnect" href="https://cdn.tailwindcss.com">
    <link rel="preconnect" href="https://cdnjs.cloudflare.com">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <?php if(!empty($config['hero_image_url'])): ?>
    <link rel="preload" as="image" href="<?= $config['hero_image_url'] ?>">
    <?php endif; ?>
    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      <?php if ($page == 'produk-detail' && isset($currentProduct)): ?>
          "@type": "Product",
          "name": "<?= htmlspecialchars($currentProduct['name']) ?>",
          "image": "<?= htmlspecialchars($currentProduct['image']) ?>",
          "description": "<?= htmlspecialchars(strip_tags($currentProduct['desc'])) ?>",
          "brand": { "@type": "Brand", "name": "<?= htmlspecialchars($brandName) ?>" },
          "offers": { "@type": "Offer", "priceCurrency": "IDR", "price": "<?= $currentProduct['price'] ?>", "availability": "https://schema.org/InStock", "seller": { "@type": "AutoDealer", "name": "<?= htmlspecialchars($config['nama_cabang']) ?>" } }
      <?php elseif ($page == 'artikel-detail' && isset($currentArticle)): ?>
          "@type": "NewsArticle",
          "headline": "<?= htmlspecialchars($currentArticle['title']) ?>",
          "image": ["<?= htmlspecialchars($currentArticle['image']) ?>"],
          "datePublished": "<?= date('Y-m-d', strtotime($currentArticle['date'])) ?>",
          "author": { "@type": "Person", "name": "<?= htmlspecialchars($sales['nama_lengkap']) ?>" }
      <?php else: ?>
          "@type": "AutoDealer",
          "name": "<?= htmlspecialchars($config['nama_cabang']) ?>",
          "image": "<?= htmlspecialchars($config['logo_url']) ?>",
          "telephone": "<?= htmlspecialchars($sales['no_wa']) ?>",
          "address": { "@type": "PostalAddress", "streetAddress": "<?= htmlspecialchars($config['alamat']) ?>", "addressLocality": "Indonesia", "addressCountry": "ID" }
      <?php endif; ?>
    }
    </script>
    <script src="https://cdn.tailwindcss.com"></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">
    <script>
        tailwind.config = { theme: { extend: { colors: { toyota: { red: '#EB0A1E', dark: '#1a1a1a', gray: '#f4f4f4' } } } } }
    </script>
</head>
<body class="bg-gray-50 text-gray-800 antialiased">
    <div id="loader" class="fixed inset-0 bg-white z-[9999] flex items-center justify-center">
        <div class="text-center">
            <img src="<?= $config['logo_url'] ?>" alt="Logo Loader" 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>
    <nav class="sticky top-0 z-40 bg-white/95 backdrop-blur-md shadow-sm transition-all duration-300">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <a href="#home" class="flex items-center gap-3 group cursor-pointer flex-shrink-0" onclick="navigate('home')">
                <img src="<?= $config['logo_url'] ?>" alt="Logo Navbar" 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"></div> 
                <?php 
                    $parts = explode(' ', $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"><?= $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">
                <button onclick="navigate('home')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red">Home</button>
                <button onclick="navigate('promo')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red">Promo</button>
                <button onclick="navigate('produk')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red">Produk</button>
                <button onclick="navigate('simulasi')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red">Simulasi</button>
                <button onclick="navigate('tradein')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red text-toyota-red">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">Artikel</button>
                <button onclick="navigate('testimoni')" class="nav-link hover:text-toyota-red py-2 border-b-2 border-transparent hover:border-toyota-red">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">Hubungi Kami</button>
            </div>
            <button onclick="toggleMobileMenu()" class="md:hidden text-2xl text-toyota-dark focus:outline-none p-2"><i class="fa-solid fa-bars"></i></button>
        </div>
        <div id="mobile-menu" class="hidden md:hidden bg-white border-t absolute w-full left-0 shadow-lg z-50">
            <button onclick="mobileNavClick('home')" class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link">HOME</button>
            <button onclick="mobileNavClick('promo')" class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link">PROMO</button>
            <button onclick="mobileNavClick('produk')" class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link">PRODUK</button>
            <button onclick="mobileNavClick('simulasi')" class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link">SIMULASI</button>
            <button onclick="mobileNavClick('tradein')" class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link text-toyota-red">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">ARTIKEL</button>
            <button onclick="mobileNavClick('testimoni')" class="block w-full text-left px-4 py-3 hover:bg-gray-50 font-bold mobile-link">TESTIMONI</button>
            <button onclick="mobileNavClick('kontak')" class="block w-full text-left px-4 py-3 bg-toyota-red text-white font-bold">KONTAK</button>
        </div>
    </nav>

    <main id="app-content" class="min-h-screen overflow-hidden relative"></main>

    <footer class="bg-toyota-dark text-white pt-16 pb-8 border-t-4 border-toyota-red">
        <div class="container mx-auto px-4 grid grid-cols-1 md:grid-cols-4 gap-8 mb-8">
            <div>
                <img src="<?= $config['logo_url'] ?>" alt="Logo Footer" width="120" height="50" class="h-8 mb-4 brightness-0 invert object-contain">
                <p class="text-gray-400 text-sm leading-relaxed"><?= $config['footer_text'] ?></p>
            </div>
            <div>
                <h4 class="text-lg font-bold mb-4">Navigasi</h4>
                <ul class="space-y-2 text-gray-400 text-sm">
                    <li><button onclick="navigate('produk')" class="hover:text-white">Daftar Harga</button></li>
                    <li><button onclick="navigate('simulasi')" class="hover:text-white">Simulasi Kredit</button></li>
                    <li><button onclick="navigate('tradein')" class="hover:text-white">Trade-in</button></li>
                    <li><button onclick="navigate('promo')" class="hover:text-white">Promo Spesial</button></li>
                </ul>
            </div>
            <div>
                <h4 class="text-lg font-bold mb-4">Hubungi Saya</h4>
                <ul class="space-y-2 text-gray-400 text-sm">
                    <li><i class="fa-solid fa-user mr-2 text-toyota-red"></i> <?= $sales['nama_lengkap'] ?></li>
                    <li><i class="fa-brands fa-whatsapp mr-2 text-toyota-red"></i> <?= $sales['no_wa'] ?></li>
                    <li><i class="fa-solid fa-location-dot mr-2 text-toyota-red"></i> <?= $config['nama_cabang'] ?></li>
                </ul>
                
                <!-- UPDATE SOSMED FOOTER -->
                <div class="flex gap-4 mt-6">
                    <?php if(!empty($sales['youtube_url'])): ?><a href="<?= $sales['youtube_url'] ?>" target="_blank" class="text-gray-400 hover:text-red-600 transition"><i class="fa-brands fa-youtube text-xl"></i></a><?php endif; ?>
                    <?php if(!empty($sales['instagram_url'])): ?><a href="<?= $sales['instagram_url'] ?>" target="_blank" class="text-gray-400 hover:text-pink-500 transition"><i class="fa-brands fa-instagram text-xl"></i></a><?php endif; ?>
                    <?php if(!empty($sales['tiktok_url'])): ?><a href="<?= $sales['tiktok_url'] ?>" target="_blank" class="text-gray-400 hover:text-white transition"><i class="fa-brands fa-tiktok text-xl"></i></a><?php endif; ?>
                    <?php if(!empty($sales['facebook_url'])): ?><a href="<?= $sales['facebook_url'] ?>" target="_blank" class="text-gray-400 hover:text-blue-500 transition"><i class="fa-brands fa-facebook text-xl"></i></a><?php endif; ?>
                </div>
            </div>
            <div>
                <h4 class="text-lg font-bold mb-4">Alamat</h4>
                <p class="text-gray-400 text-sm"><?= $config['alamat'] ?></p>
            </div>
        </div>
        <div class="border-t border-gray-800 pt-8 text-center">
            <p class="text-gray-500 text-xs">&copy; 2025 <?= $config['nama_cabang'] ?>. Powered by Willie System.</p>
        </div>
    </footer>

    <a href="https://wa.me/<?= $sales['no_wa'] ?>" target="_blank" class="fixed bottom-6 right-6 z-50 bg-green-500 text-white w-14 h-14 rounded-full flex items-center justify-center shadow-lg hover:bg-green-600 animate-bounce"><i class="fa-brands fa-whatsapp text-3xl"></i></a>

    <script>
        window.DATA_FROM_PHP = <?= json_encode($dataPayload) ?>;
        
        window.addEventListener('load', () => {
            setTimeout(() => {
                document.getElementById('loader').style.opacity = '0';
                setTimeout(() => {
                    document.getElementById('loader').style.display = 'none';
                    if(typeof navigate === 'function') navigate('home');
                }, 400);
            }, 500);
        });
    </script>
    <script src="assets/js/script.js"></script>
</body>
</html>
<?php 
ob_end_flush(); 
?>