<?php
// ===================================================================
// GLOWSPACE — STANDALONE PRODUCT LANDING PAGE
// Ad-optimized single-product page. No site header/nav/footer.
// Self-contained: does not modify or depend on index.php / admin.php
// internals, only shares the session (cart/order) and database.
// ===================================================================
session_start();
ob_start();

// Load configuration and database
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';

// Initialize auth
auth()->getInstance();

function lpSanitize($str) {
    return sanitize($str);
}
function lpImgUrl($path) {
    return imgUrl($path);
}
function lpBaseUrl() {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') || ($_SERVER['SERVER_PORT']??'')==443 ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $dir = rtrim(str_replace('\\','/', dirname($_SERVER['SCRIPT_NAME'] ?? '/landing.php')), '/');
    return $scheme.'://'.$host.$dir;
}

// Shared CSRF/cart token bootstrap — MUST match index.php's session key exactly
// so the buy-now form on this page can call index.php's existing, unmodified
// add_to_cart / place_order endpoints.
if(empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

// ---- Lightweight click/interaction tracking endpoint (no CSRF needed — counters only) ----
if(isset($_GET['ajax']) && $_GET['ajax']==='track') {
    header('Content-Type: application/json');
    $slug = lpSanitize($_GET['slug'] ?? ($_POST['slug'] ?? ''));
    $type = lpSanitize($_GET['type'] ?? ($_POST['type'] ?? ''));
    $allowed = ['click'=>'clicks','atc'=>'add_to_cart','order'=>'orders'];
    if($slug==='' || !isset($allowed[$type])) { echo json_encode(['success'=>false]); exit; }
    incrementLandingPageStats($slug, $allowed[$type]);
    echo json_encode(['success'=>true]);
    exit;
}

$settings = getSettings();
$landingList = getLandingPages();
$reviews = getReviews();

$slug = lpSanitize($_GET['slug'] ?? '');
$landing = getLandingPageBySlug($slug);

$product = null;
if($landing) { 
    $product = getProductById($landing['product_id']); 
}

$notFound = !$landing || !$product || empty($landing['enabled']) || !(($product['status']??1)==1);

if(!$notFound) {
    // Count the view directly (server-rendered, no extra request needed)
    incrementLandingPageStats($slug, 'views');
}

$currency = $settings['currency'] ?? '৳';
$primary = $settings['primary_color'] ?? '#D4AF37';
$secondary = $settings['secondary_color'] ?? '#F5A623';
$accent = $settings['accent_color'] ?? '#FF4D6D';

if(!$notFound) {
    $images = array_map('lpImgUrl', $product['images'] ?? []);
    if(empty($images)) $images = ['https://placehold.co/700x700?text='.urlencode($product['title'])];
    $price = floatval($product['offer_price'] ?? 0) > 0 ? floatval($product['offer_price']) : floatval($product['price'] ?? 0);
    $orig = floatval($product['price'] ?? 0);
    $disc = ($orig > 0 && $price < $orig) ? round((($orig-$price)/$orig)*100) : 0;

    $features = $product['features'] ?? '';
    if(is_string($features)) {
        $features = array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n|,/', $features))));
    }
    if(!is_array($features)) $features = [];

    $specs = $product['specifications'] ?? [];
    if(!is_array($specs)) $specs = [];

    $sizesRaw = $product['sizes'] ?? '';
    $sizes = [];
    if(is_string($sizesRaw) && trim($sizesRaw) !== '') {
        $decoded = json_decode($sizesRaw, true);
        $sizes = is_array($decoded) ? $decoded : array_values(array_filter(array_map('trim', explode(',', $sizesRaw))));
    }

    $prodReviews = array_values(array_filter($reviews, fn($r) => ($r['product_id'] ?? '') === $product['id'] && ($r['status'] ?? 0) == 1));
    $avgRating = 0;
    if(count($prodReviews)) { $avgRating = round(array_sum(array_column($prodReviews, 'rating')) / count($prodReviews), 1); }

    $related = array_values(array_filter($products, fn($p) => $p['id'] !== $product['id'] && ($p['category'] ?? '') === ($product['category'] ?? '') && ($p['status'] ?? 1) == 1));
    $related = array_slice($related, 0, 4);

    $seoTitle = $landing['seo_title'] ?: $product['title'];
    $seoDesc = $landing['seo_description'] ?: ($product['subtitle'] ?? $product['description'] ?? '');
    $ogImage = !empty($landing['og_image']) ? lpImgUrl($landing['og_image']) : $images[0];
    $canonical = $landing['canonical_url'] ?: lpBaseUrl().'/landing.php?slug='.rawurlencode($slug);
    $pageUrl = lpBaseUrl().'/landing.php?slug='.rawurlencode($slug);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<?php if($notFound): ?>
<title>Product Not Available</title>
<meta name="robots" content="noindex">
<?php else: ?>
<title><?=lpSanitize($seoTitle)?></title>
<meta name="description" content="<?=lpSanitize($seoDesc)?>">
<?php if(!empty($landing['seo_keywords'])): ?><meta name="keywords" content="<?=lpSanitize($landing['seo_keywords'])?>"><?php endif; ?>
<link rel="canonical" href="<?=lpSanitize($canonical)?>">
<meta property="og:type" content="product">
<meta property="og:title" content="<?=lpSanitize($seoTitle)?>">
<meta property="og:description" content="<?=lpSanitize($seoDesc)?>">
<meta property="og:image" content="<?=lpSanitize($ogImage)?>">
<meta property="og:url" content="<?=lpSanitize($pageUrl)?>">
<meta name="twitter:card" content="summary_large_image">
<?php if(!empty($settings['favicon_path'])): ?><link rel="icon" href="<?=lpSanitize($settings['favicon_path'])?>"><?php endif; ?>
<?php // Admin-authored raw meta tags — trusted input, same trust level as other site settings fields
if(!empty($landing['meta_tags'])) echo $landing['meta_tags']."\n"; ?>
<?php if(!empty($landing['fb_pixel'])): ?>
<script>
!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '<?=lpSanitize($landing['fb_pixel'])?>');
fbq('track', 'PageView');
fbq('track', 'ViewContent');
</script>
<?php endif; ?>
<?php if(!empty($landing['tiktok_pixel'])): ?>
<script>
!function (w, d, t) {w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e},ttq.load=function(e,n){var i="https://analytics.tiktok.com/i18n/pixel/events.js";ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=i,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src=i+"?sdkid="+e+"&lib="+t;var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)};ttq.load('<?=lpSanitize($landing['tiktok_pixel'])?>');ttq.page();}(window, document, 'ttq');
</script>
<?php endif; ?>
<?php if(!empty($landing['ga_id'])): ?>
<script async src="https://www.googletagmanager.com/gtag/js?id=<?=lpSanitize($landing['ga_id'])?>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '<?=lpSanitize($landing['ga_id'])?>');
</script>
<?php endif; ?>
<?php endif; ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
:root{--p:<?=lpSanitize($primary)?>;--s:<?=lpSanitize($secondary)?>;--a:<?=lpSanitize($accent)?>;--navy:#0F172A;--bg:#F8FAFC;--t:#0F172A;--t2:#475569;--t3:#94A3B8;--bd:#E2E8F0;--g:linear-gradient(135deg,var(--p),var(--s))}
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Inter',sans-serif;background:var(--bg);color:var(--t);line-height:1.6;padding-bottom:78px}
.container{max-width:980px;margin:0 auto;padding:0 16px}
a{text-decoration:none;color:inherit}
img{max-width:100%;display:block}

/* Top strip */
.top-strip{background:var(--navy);color:#fff;text-align:center;padding:9px 12px;font-size:.82rem;font-weight:600}
.top-strip i{color:var(--p);margin-right:6px}

/* Hero */
.hero{padding:22px 0 10px}
.hero-grid{display:grid;grid-template-columns:1fr 1fr;gap:34px;align-items:flex-start}
@media(max-width:820px){.hero-grid{grid-template-columns:1fr}}
.gallery-main{border-radius:16px;overflow:hidden;background:#fff;border:1px solid var(--bd);box-shadow:0 6px 24px rgba(0,0,0,.06)}
.gallery-main img{width:100%;aspect-ratio:1/1;object-fit:cover}
.thumbs{display:flex;gap:8px;margin-top:10px;flex-wrap:wrap}
.thumbs img{width:64px;height:64px;object-fit:cover;border-radius:8px;border:2px solid var(--bd);cursor:pointer}
.thumbs img.active{border-color:var(--p)}
.banner-strip{border-radius:16px;overflow:hidden;margin-bottom:16px}
.banner-strip img{width:100%}

.badge-row{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px}
.badge{font-size:.72rem;font-weight:700;padding:4px 10px;border-radius:20px;background:rgba(212,175,55,.12);color:#9a7b0f}
.badge.sale{background:rgba(255,77,109,.12);color:var(--a)}
h1.title{font-size:1.7rem;font-weight:900;margin-bottom:6px;line-height:1.25}
.brand-line{color:var(--t3);font-size:.88rem;margin-bottom:10px}
.rating-line{display:flex;align-items:center;gap:8px;margin-bottom:16px;font-size:.85rem;color:var(--t2)}
.rating-line .stars{color:#F5A623}
.price-box{display:flex;align-items:baseline;gap:12px;margin-bottom:18px;flex-wrap:wrap}
.price-now{font-size:2.1rem;font-weight:900;color:var(--t)}
.price-old{font-size:1.15rem;color:var(--t3);text-decoration:line-through}
.price-save{background:var(--a);color:#fff;font-size:.78rem;font-weight:800;padding:4px 10px;border-radius:6px}

.countdown{display:flex;align-items:center;gap:10px;background:var(--navy);color:#fff;border-radius:12px;padding:12px 16px;margin-bottom:18px}
.countdown i{color:var(--p)}
.countdown-timer{display:flex;gap:8px;font-weight:800;font-size:1rem}
.countdown-timer span{background:rgba(255,255,255,.12);border-radius:6px;padding:4px 8px;min-width:38px;text-align:center}

.desc-block{margin-bottom:18px;color:var(--t2);font-size:.95rem}
.benefits{list-style:none;margin-bottom:20px}
.benefits li{display:flex;gap:10px;align-items:flex-start;margin-bottom:8px;font-size:.92rem}
.benefits li i{color:#16A34A;margin-top:3px}

.qty-row{display:flex;align-items:center;gap:14px;margin-bottom:16px;flex-wrap:wrap}
.qty-box{display:flex;align-items:center;border:2px solid var(--bd);border-radius:10px;overflow:hidden}
.qty-box button{width:38px;height:38px;background:#fff;border:none;font-size:1rem;cursor:pointer}
.qty-box input{width:48px;text-align:center;border:none;font-weight:700;font-size:.95rem}
.size-select{padding:9px 14px;border:2px solid var(--bd);border-radius:10px;font-size:.9rem}

.cta-btn{display:flex;align-items:center;justify-content:center;gap:10px;background:linear-gradient(135deg, #0ea5e9 0%, #38bdf8 50%, #7dd3fc 100%);color:#fff;font-weight:800;font-size:1.02rem;padding:16px 20px;border-radius:16px;border:none;width:100%;cursor:pointer;box-shadow:0 8px 24px rgba(14,165,233,.4),0 0 20px rgba(14,165,233,.2);transition:all 0.3s ease;position:relative;overflow:hidden}
.cta-btn::before{content:'';position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);transition:left 0.5s}
.cta-btn:hover::before{left:100%}
.cta-btn:hover{transform:translateY(-2px);box-shadow:0 12px 32px rgba(14,165,233,.5),0 0 30px rgba(14,165,233,.3)}
.cta-btn:active{transform:translateY(0)}
.cta-btn:disabled{opacity:.6;cursor:not-allowed;transform:none;box-shadow:0 8px 24px rgba(14,165,233,.4)}

.trust-badges{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin:20px 0}
@media(max-width:560px){.trust-badges{grid-template-columns:repeat(2,1fr)}}
.trust-badge{text-align:center;background:#fff;border:1px solid var(--bd);border-radius:12px;padding:14px 8px;font-size:.72rem;font-weight:700;color:var(--t2)}
.trust-badge i{display:block;font-size:1.3rem;color:var(--p);margin-bottom:6px}

.secure-box{display:flex;align-items:center;gap:10px;background:rgba(22,163,74,.08);border:1px solid rgba(22,163,74,.25);border-radius:10px;padding:12px 14px;font-size:.82rem;color:#15803D;font-weight:600;margin-top:14px}

/* Sections */
.section{background:#fff;border-radius:16px;padding:26px;margin-top:22px;border:1px solid var(--bd)}
.section h2{font-size:1.25rem;font-weight:900;margin-bottom:16px;display:flex;align-items:center;gap:10px}
.section h2 i{color:var(--p)}

.feat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:16px}
.feat-card{text-align:center;padding:16px 10px}
.feat-card i{font-size:1.6rem;color:var(--p);margin-bottom:10px;display:block}
.feat-card h4{font-size:.92rem;font-weight:700;margin-bottom:4px}
.feat-card p{font-size:.78rem;color:var(--t3)}

.spec-table{width:100%;border-collapse:collapse}
.spec-table tr:nth-child(odd){background:var(--bg)}
.spec-table td{padding:10px 14px;font-size:.88rem}
.spec-table td:first-child{font-weight:700;color:var(--t2);width:40%}

.ba-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}
.ba-grid figure{margin:0}
.ba-grid img{border-radius:12px;width:100%;aspect-ratio:1/1;object-fit:cover}
.ba-grid figcaption{text-align:center;font-weight:700;font-size:.82rem;margin-top:8px;color:var(--t2)}

.testi-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px}
.testi-card{background:var(--bg);border-radius:12px;padding:16px}
.testi-card .stars{color:#F5A623;font-size:.8rem;margin-bottom:8px}
.testi-card p{font-size:.86rem;color:var(--t2);margin-bottom:10px}
.testi-user{display:flex;align-items:center;gap:10px}
.testi-user img{width:36px;height:36px;border-radius:50%;object-fit:cover}
.testi-user span{font-weight:700;font-size:.85rem}

.faq-item{border-bottom:1px solid var(--bd)}
.faq-item:last-child{border-bottom:none}
.faq-q{display:flex;justify-content:space-between;align-items:center;padding:14px 0;cursor:pointer;font-weight:700;font-size:.92rem}
.faq-a{display:none;padding:0 0 14px;color:var(--t2);font-size:.87rem}
.faq-item.open .faq-a{display:block}
.faq-item.open .faq-q i{transform:rotate(180deg)}
.faq-q i{transition:transform .2s;color:var(--p)}

.related-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:14px}
.related-card{border:1px solid var(--bd);border-radius:12px;overflow:hidden;background:#fff}
.related-card img{width:100%;aspect-ratio:1/1;object-fit:cover}
.related-card .rc-body{padding:10px}
.related-card h5{font-size:.82rem;font-weight:700;margin-bottom:4px;height:2.4em;overflow:hidden}
.related-card .rc-price{font-weight:800;font-size:.88rem;color:var(--t)}

/* Order form */
.order-form .form-row{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px}
@media(max-width:560px){.order-form .form-row{grid-template-columns:1fr}}
.order-form input, .order-form textarea, .order-form select{width:100%;padding:11px 13px;border:2px solid var(--bd);border-radius:10px;font-size:.9rem;font-family:inherit}
.order-form label{font-size:.8rem;font-weight:700;color:var(--t2);margin-bottom:5px;display:block}

/* Sticky bar */
.sticky-bar{position:fixed;left:0;right:0;bottom:0;background:#fff;border-top:1px solid var(--bd);padding:10px 16px;display:flex;align-items:center;gap:12px;z-index:800;box-shadow:0 -6px 24px rgba(0,0,0,.08)}
.sticky-bar .sb-price{font-weight:900;font-size:1.05rem;white-space:nowrap}
.sticky-bar .cta-btn{padding:12px 18px;font-size:.92rem}

.float-wrap{position:fixed;right:18px;bottom:96px;z-index:850;display:flex;flex-direction:column;gap:12px}
.float-btn{width:52px;height:52px;border-radius:50%;display:flex;align-items:center;justify-content:center;color:#fff;font-size:1.4rem;box-shadow:0 6px 20px rgba(0,0,0,.25)}
.float-btn.wa{background:#25D366}
.float-btn.msg{background:#0084FF}

.toast{position:fixed;top:16px;right:16px;background:var(--navy);color:#fff;padding:12px 18px;border-radius:10px;font-size:.85rem;font-weight:600;z-index:1000;box-shadow:0 8px 24px rgba(0,0,0,.2);opacity:0;transform:translateY(-10px);transition:.3s}
.toast.show{opacity:1;transform:translateY(0)}

.footer-mini{text-align:center;padding:26px 16px;color:var(--t3);font-size:.78rem}
.notfound{max-width:480px;margin:80px auto;text-align:center;padding:20px}
.notfound i{font-size:3rem;color:var(--t3);margin-bottom:16px}
</style>
</head>
<body>

<?php if($notFound): ?>
<div class="notfound">
    <i class="fa-solid fa-triangle-exclamation"></i>
    <h2>This landing page isn't available</h2>
    <p style="color:var(--t3);margin-top:8px">It may have been disabled or the link is incorrect.</p>
</div>
<?php else: ?>

<div id="toast" class="toast"></div>

<div class="top-strip"><i class="fa-solid fa-truck-fast"></i> Cash on Delivery Available &nbsp;•&nbsp; Fast Nationwide Shipping</div>

<div class="container hero">
    <div class="hero-grid">
        <div>
            <?php if(!empty($landing['banner_image'])): ?>
            <div class="banner-strip"><img src="<?=lpSanitize(lpImgUrl($landing['banner_image']))?>" alt="Banner"></div>
            <?php endif; ?>
            <div class="gallery-main"><img id="mainImg" src="<?=lpSanitize($images[0])?>" alt="<?=lpSanitize($product['title'])?>"></div>
            <?php if(count($images) > 1): ?>
            <div class="thumbs">
                <?php foreach($images as $i => $img): ?>
                <img src="<?=lpSanitize($img)?>" class="<?=$i===0?'active':''?>" onclick="setMainImg(this)">
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <?php if(!empty($landing['promo_video_url'])): ?>
            <div class="section" style="margin-top:16px">
                <h2><i class="fa-solid fa-circle-play"></i> Watch It In Action</h2>
                <?php
                $vid = $landing['promo_video_url'];
                $ytId = '';
                if(preg_match('#(?:youtube\.com/watch\?v=|youtu\.be/|youtube\.com/embed/)([A-Za-z0-9_-]{6,})#', $vid, $m)) $ytId = $m[1];
                ?>
                <?php if($ytId): ?>
                <div style="position:relative;padding-top:56.25%;border-radius:12px;overflow:hidden">
                    <iframe src="https://www.youtube.com/embed/<?=lpSanitize($ytId)?>" style="position:absolute;top:0;left:0;width:100%;height:100%;border:0" allowfullscreen></iframe>
                </div>
                <?php else: ?>
                <video controls style="width:100%;border-radius:12px"><source src="<?=lpSanitize($vid)?>"></video>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>

        <div>
            <div class="badge-row">
                <?php if($disc > 0): ?><span class="badge sale"><i class="fa-solid fa-fire"></i> <?=$disc?>% OFF</span><?php endif; ?>
                <?php if(!empty($product['flash_sale'])): ?><span class="badge sale">Flash Sale</span><?php endif; ?>
                <?php if(!empty($product['best_seller'])): ?><span class="badge">Best Seller</span><?php endif; ?>
                <?php if(!empty($product['new_arrival'])): ?><span class="badge">New Arrival</span><?php endif; ?>
            </div>
            <h1 class="title"><?=lpSanitize($landing['headline'] ?: $product['title'])?></h1>
            <?php if(!empty($product['brand'])): ?><div class="brand-line"><i class="fa-solid fa-tag"></i> <?=lpSanitize($product['brand'])?></div><?php endif; ?>

            <?php if(count($prodReviews) > 0): ?>
            <div class="rating-line">
                <span class="stars"><?php for($s=1;$s<=5;$s++) echo $s<=round($avgRating)?'<i class="fa-solid fa-star"></i>':'<i class="fa-regular fa-star"></i>'; ?></span>
                <span><?=$avgRating?> (<?=count($prodReviews)?> reviews)</span>
            </div>
            <?php endif; ?>

            <div class="price-box">
                <span class="price-now"><?=$currency?><?=number_format($price)?></span>
                <?php if($disc > 0): ?>
                <span class="price-old"><?=$currency?><?=number_format($orig)?></span>
                <span class="price-save">Save <?=$disc?>%</span>
                <?php endif; ?>
            </div>

            <?php if(!empty($landing['countdown_enabled']) && !empty($landing['countdown_end'])): ?>
            <div class="countdown">
                <i class="fa-solid fa-clock"></i>
                <div>
                    <div style="font-size:.75rem;opacity:.85;margin-bottom:2px">Offer ends in</div>
                    <div class="countdown-timer" id="countdownTimer" data-end="<?=lpSanitize($landing['countdown_end'])?>">
                        <span id="cd-d">00</span><span id="cd-h">00</span><span id="cd-m">00</span><span id="cd-s">00</span>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <?php if(!empty($landing['description'])): ?>
            <div class="desc-block"><?=nl2br(lpSanitize($landing['description']))?></div>
            <?php endif; ?>

            <?php if(!empty($landing['benefits'])): ?>
            <ul class="benefits">
                <?php foreach($landing['benefits'] as $b): ?>
                <li><i class="fa-solid fa-circle-check"></i> <?=lpSanitize($b)?></li>
                <?php endforeach; ?>
            </ul>
            <?php endif; ?>

            <form id="orderForm">
                <?php if(!empty($sizes)): ?>
                <div class="qty-row">
                    <select class="size-select" id="sizeSelect">
                        <?php foreach($sizes as $sz): ?><option value="<?=lpSanitize($sz)?>"><?=lpSanitize($sz)?><?=!empty($product['size_unit']) ? ' '.lpSanitize($product['size_unit']) : ''?></option><?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="qty-row">
                    <div class="qty-box">
                        <button type="button" onclick="qtyStep(-1)"><i class="fa-solid fa-minus"></i></button>
                        <input type="number" id="qtyInput" value="1" min="1" max="20">
                        <button type="button" onclick="qtyStep(1)"><i class="fa-solid fa-plus"></i></button>
                    </div>
                    <span style="color:var(--t3);font-size:.85rem"><?=intval($product['stock'] ?? 0)?> in stock</span>
                </div>
                <button type="button" class="cta-btn" id="mainCtaBtn" onclick="scrollToOrder()"><i class="fa-solid fa-bolt"></i> <?=lpSanitize($landing['cta_text'] ?: 'Order Now')?></button>
            </form>

            <div class="secure-box"><i class="fa-solid fa-lock"></i> 100% Secure Checkout — Your information is protected</div>

            <div class="trust-badges">
                <div class="trust-badge"><i class="fa-solid fa-truck"></i>Fast Delivery</div>
                <div class="trust-badge"><i class="fa-solid fa-money-bill-wave"></i>Cash on Delivery</div>
                <div class="trust-badge"><i class="fa-solid fa-rotate-left"></i>Easy Returns</div>
                <div class="trust-badge"><i class="fa-solid fa-shield-halved"></i>Warranty<?=!empty($product['warranty']) ? ': '.lpSanitize($product['warranty']) : ''?></div>
            </div>
        </div>
    </div>
</div>

<div class="container">

    <?php if(!empty($landing['feature_icons'])): ?>
    <div class="section">
        <h2><i class="fa-solid fa-award"></i> Why You'll Love It</h2>
        <div class="feat-grid">
            <?php foreach($landing['feature_icons'] as $f): ?>
            <div class="feat-card">
                <i class="<?=preg_match('/^fa[srlbdt]?(\s+fa-[a-z0-9-]+)+$/i', $f['icon'] ?? '') ? lpSanitize($f['icon']) : 'fa-solid fa-check'?>"></i>
                <h4><?=lpSanitize($f['title'])?></h4>
                <?php if(!empty($f['desc'])): ?><p><?=lpSanitize($f['desc'])?></p><?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if(!empty($product['description']) || !empty($features)): ?>
    <div class="section">
        <h2><i class="fa-solid fa-file-lines"></i> Product Details</h2>
        <?php if(!empty($product['description'])): ?><p style="color:var(--t2);font-size:.92rem;margin-bottom:14px"><?=nl2br(lpSanitize($product['description']))?></p><?php endif; ?>
        <?php if(!empty($features)): ?>
        <ul class="benefits">
            <?php foreach($features as $feat): ?><li><i class="fa-solid fa-circle-check"></i> <?=lpSanitize($feat)?></li><?php endforeach; ?>
        </ul>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <?php if(!empty($specs)): ?>
    <div class="section">
        <h2><i class="fa-solid fa-list-check"></i> Specifications</h2>
        <table class="spec-table">
            <?php foreach($specs as $sk => $sv): ?>
            <tr><td><?=lpSanitize($sk)?></td><td><?=lpSanitize($sv)?></td></tr>
            <?php endforeach; ?>
        </table>
    </div>
    <?php endif; ?>

    <?php if(!empty($landing['before_image']) && !empty($landing['after_image'])): ?>
    <div class="section">
        <h2><i class="fa-solid fa-arrows-left-right"></i> Before &amp; After</h2>
        <div class="ba-grid">
            <figure><img src="<?=lpSanitize(lpImgUrl($landing['before_image']))?>" alt="Before"><figcaption>Before</figcaption></figure>
            <figure><img src="<?=lpSanitize(lpImgUrl($landing['after_image']))?>" alt="After"><figcaption>After</figcaption></figure>
        </div>
    </div>
    <?php endif; ?>

    <?php if(!empty($landing['testimonials'])): ?>
    <div class="section">
        <h2><i class="fa-solid fa-quote-left"></i> What Customers Say</h2>
        <div class="testi-grid">
            <?php foreach($landing['testimonials'] as $t): ?>
            <div class="testi-card">
                <div class="stars"><?php for($s=1;$s<=5;$s++) echo $s<=intval($t['rating']??5)?'<i class="fa-solid fa-star"></i>':'<i class="fa-regular fa-star"></i>'; ?></div>
                <p>"<?=lpSanitize($t['text'])?>"</p>
                <div class="testi-user">
                    <?php if(!empty($t['image'])): ?><img src="<?=lpSanitize(lpImgUrl($t['image']))?>" alt=""><?php else: ?><div style="width:36px;height:36px;border-radius:50%;background:var(--g);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:.8rem"><?=strtoupper(substr($t['name']??'?',0,1))?></div><?php endif; ?>
                    <span><?=lpSanitize($t['name'])?></span>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if(count($prodReviews) > 0): ?>
    <div class="section">
        <h2><i class="fa-solid fa-star"></i> Customer Reviews</h2>
        <?php foreach(array_slice($prodReviews, 0, 6) as $r): ?>
        <div style="border-bottom:1px solid var(--bd);padding:12px 0">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px">
                <strong style="font-size:.88rem"><?=lpSanitize($r['name'] ?? 'Customer')?></strong>
                <span style="color:#F5A623;font-size:.8rem"><?php for($s=1;$s<=5;$s++) echo $s<=intval($r['rating']??5)?'★':'☆'; ?></span>
            </div>
            <p style="font-size:.86rem;color:var(--t2)"><?=lpSanitize($r['text'] ?? '')?></p>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div class="section">
        <h2><i class="fa-solid fa-truck-fast"></i> Delivery Information</h2>
        <p style="color:var(--t2);font-size:.9rem"><?=nl2br(lpSanitize($landing['delivery_info']))?></p>
    </div>

    <div class="section">
        <h2><i class="fa-solid fa-rotate-left"></i> Return Policy</h2>
        <p style="color:var(--t2);font-size:.9rem"><?=nl2br(lpSanitize($landing['return_policy']))?></p>
    </div>

    <div class="section order-form" id="orderSection">
        <h2><i class="fa-solid fa-bag-shopping"></i> Complete Your Order</h2>
        <div class="secure-box" style="margin-bottom:16px"><i class="fa-solid fa-lock"></i> 100% Secure Checkout — Cash on Delivery Available</div>
        <div class="form-row">
            <div><label>Full Name *</label><input type="text" id="ofName" required></div>
            <div><label>Phone Number *</label><input type="tel" id="ofPhone" required></div>
        </div>
        <div class="form-row">
            <div><label>District *</label><input type="text" id="ofDistrict" required></div>
            <div><label>Upazila / Area *</label><input type="text" id="ofUpazila" required></div>
        </div>
        <div style="margin-bottom:12px"><label>Full Address *</label><textarea id="ofAddress" rows="2" required></textarea></div>
        <button type="button" class="cta-btn" id="placeOrderBtn" onclick="submitLandingOrder()"><i class="fa-solid fa-bolt"></i> <?=lpSanitize($landing['cta_text'] ?: 'Order Now')?> — <span id="ofTotal"><?=$currency?><?=number_format($price)?></span></button>
    </div>

    <?php if(!empty($landing['faq'])): ?>
    <div class="section">
        <h2><i class="fa-solid fa-circle-question"></i> Frequently Asked Questions</h2>
        <?php foreach($landing['faq'] as $i => $f): ?>
        <div class="faq-item">
            <div class="faq-q" onclick="this.parentElement.classList.toggle('open')"><?=lpSanitize($f['q'])?> <i class="fa-solid fa-chevron-down"></i></div>
            <div class="faq-a"><?=lpSanitize($f['a'])?></div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <?php if(!empty($related)): ?>
    <div class="section">
        <h2><i class="fa-solid fa-layer-group"></i> You May Also Like</h2>
        <div class="related-grid">
            <?php foreach($related as $rp):
                $rpImg = lpImgUrl($rp['images'][0] ?? '');
                $rpPrice = floatval($rp['offer_price'] ?? 0) > 0 ? floatval($rp['offer_price']) : floatval($rp['price'] ?? 0);
            ?>
            <a class="related-card" href="index.php?page=product&slug=<?=lpSanitize($rp['slug'] ?? '')?>">
                <img src="<?=lpSanitize($rpImg ?: 'https://placehold.co/150x150?text=No+Image')?>" alt="">
                <div class="rc-body"><h5><?=lpSanitize($rp['title'])?></h5><div class="rc-price"><?=$currency?><?=number_format($rpPrice)?></div></div>
            </a>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <div class="footer-mini">© <?=date('Y')?> <?=lpSanitize($settings['site_name'] ?? 'GlowSpace')?>. All rights reserved.</div>
</div>

<!-- Sticky order bar -->
<div class="sticky-bar">
    <div class="sb-price"><?=$currency?><?=number_format($price)?></div>
    <button type="button" class="cta-btn" onclick="scrollToOrder()"><i class="fa-solid fa-bolt"></i> <?=lpSanitize($landing['cta_text'] ?: 'Order Now')?></button>
</div>

<!-- Floating chat buttons -->
<div class="float-wrap">
    <?php if(!empty($settings['whatsapp'])): ?>
    <a href="<?=lpSanitize($settings['whatsapp'])?>" target="_blank" class="float-btn wa" onclick="trackClick('click')" aria-label="WhatsApp"><i class="fa-brands fa-whatsapp"></i></a>
    <?php endif; ?>
    <?php if(!empty($settings['messenger'])): ?>
    <a href="<?=lpSanitize($settings['messenger'])?>" target="_blank" class="float-btn msg" onclick="trackClick('click')" aria-label="Messenger"><i class="fa-brands fa-facebook-messenger"></i></a>
    <?php endif; ?>
</div>

<script>
const LP_SLUG = <?=json_encode($slug)?>;
const CSRF = <?=json_encode($_SESSION['csrf_token'])?>;
const PRODUCT_ID = <?=json_encode($product['id'])?>;
const UNIT_PRICE = <?=json_encode($price)?>;
const CURRENCY = <?=json_encode($currency)?>;

function toastMsg(msg, isErr) {
    const t = document.getElementById('toast');
    t.textContent = msg;
    t.style.background = isErr ? '#DC2626' : '#0F172A';
    t.classList.add('show');
    setTimeout(()=>t.classList.remove('show'), 3000);
}

function setMainImg(el) {
    document.getElementById('mainImg').src = el.src;
    document.querySelectorAll('.thumbs img').forEach(i=>i.classList.remove('active'));
    el.classList.add('active');
}

function qtyStep(dir) {
    const inp = document.getElementById('qtyInput');
    let v = Math.max(1, Math.min(20, parseInt(inp.value||1) + dir));
    inp.value = v;
    updateTotal();
}
document.getElementById('qtyInput')?.addEventListener('input', updateTotal);
function updateTotal() {
    const qty = Math.max(1, parseInt(document.getElementById('qtyInput').value || 1));
    document.getElementById('ofTotal').textContent = CURRENCY + (UNIT_PRICE*qty).toLocaleString();
}

function scrollToOrder() {
    trackClick('click');
    document.getElementById('orderSection').scrollIntoView({behavior:'smooth', block:'start'});
}

function trackClick(type) {
    fetch('landing.php?ajax=track', {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:'slug='+encodeURIComponent(LP_SLUG)+'&type='+type}).catch(()=>{});
}

let orderInFlight = false;
async function submitLandingOrder() {
    if(orderInFlight) return;
    const name = document.getElementById('ofName').value.trim();
    const phone = document.getElementById('ofPhone').value.trim();
    const district = document.getElementById('ofDistrict').value.trim();
    const upazila = document.getElementById('ofUpazila').value.trim();
    const address = document.getElementById('ofAddress').value.trim();
    if(!name || !phone || !district || !upazila || !address) { toastMsg('Please fill all required fields', true); return; }

    const qty = Math.max(1, parseInt(document.getElementById('qtyInput').value || 1));
    const size = document.getElementById('sizeSelect') ? document.getElementById('sizeSelect').value : '';

    const btn = document.getElementById('placeOrderBtn');
    orderInFlight = true;
    btn.disabled = true;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Placing order...';

    try {
        // Step 1: add to cart via the existing, unmodified index.php cart logic
        const cartFd = new FormData();
        cartFd.append('action','add_to_cart'); cartFd.append('product_id', PRODUCT_ID);
        cartFd.append('qty', qty); cartFd.append('size', size); cartFd.append('csrf_token', CSRF);
        const cartRes = await fetch('index.php', {method:'POST', body:cartFd});
        const cartData = await cartRes.json();
        if(!cartData.success) { toastMsg(cartData.msg || 'Could not add to cart', true); throw new Error('cart'); }
        trackClick('atc');

        // Step 2: place the order via the existing, unmodified index.php checkout logic
        const orderFd = new FormData();
        orderFd.append('action','place_order');
        orderFd.append('fullname', name); orderFd.append('phone', phone);
        orderFd.append('district', district); orderFd.append('upazila', upazila); orderFd.append('address', address);
        orderFd.append('csrf_token', CSRF);
        const orderRes = await fetch('index.php', {method:'POST', body:orderFd});
        const orderData = await orderRes.json();
        if(orderData.success) {
            trackClick('order');
            document.getElementById('orderSection').innerHTML = '<h2><i class="fa-solid fa-circle-check" style="color:#16A34A"></i> Order Placed!</h2><p style="color:var(--t2);margin-top:10px">Your order <strong>'+orderData.order_id+'</strong> has been received. Our team will contact you shortly to confirm delivery.</p>';
            window.scrollTo({top: document.getElementById('orderSection').offsetTop - 20, behavior:'smooth'});
        } else {
            toastMsg(orderData.msg || 'Could not place order', true);
        }
    } catch(e) {
        if(e.message !== 'cart') toastMsg('Something went wrong. Please try again.', true);
    } finally {
        orderInFlight = false;
        btn.disabled = false;
        btn.innerHTML = '<i class="fa-solid fa-bolt"></i> <?=lpSanitize($landing['cta_text'] ?: 'Order Now')?> — <span id="ofTotal">'+CURRENCY+(UNIT_PRICE*qty).toLocaleString()+'</span>';
    }
}

<?php if(!empty($landing['countdown_enabled']) && !empty($landing['countdown_end'])): ?>
(function() {
    const el = document.getElementById('countdownTimer');
    if(!el) return;
    const end = new Date(el.dataset.end).getTime();
    function tick() {
        const dist = end - Date.now();
        if(dist <= 0) { document.querySelector('.countdown').style.display='none'; return; }
        const d = Math.floor(dist/86400000), h = Math.floor((dist%86400000)/3600000), m = Math.floor((dist%3600000)/60000), s = Math.floor((dist%60000)/1000);
        document.getElementById('cd-d').textContent = String(d).padStart(2,'0');
        document.getElementById('cd-h').textContent = String(h).padStart(2,'0');
        document.getElementById('cd-m').textContent = String(m).padStart(2,'0');
        document.getElementById('cd-s').textContent = String(s).padStart(2,'0');
    }
    tick(); setInterval(tick, 1000);
})();
<?php endif; ?>
</script>

<?php endif; ?>
</body>
</html>
