<?php
require_once __DIR__.'/inc/config.php';
require_once __DIR__.'/inc/db.php';
require_once __DIR__.'/inc/helpers.php';
require_once __DIR__.'/inc/csrf.php';



// Menjejak lawatan (tracking)
$ab = (($_COOKIE['ab'] ?? '')==='b') ? 'b' : 'a';
setcookie('ab',$ab,time()+60*60*24*90,'/');
$ip=client_ip(); $ua=$_SERVER['HTTP_USER_AGENT'] ?? '';
db()->prepare("INSERT INTO visits(ip,ua,ab_variant) VALUES(?,?,?)")->execute([$ip,$ua,$ab]);

// Mengambil semua tetapan dari pangkalan data
$site_title = setting('SITE_TITLE', APP_NAME); // <-- TAMBAH YANG INI
$favicon_url = setting('FAVICON_URL', ''); // <-- TAMBAH YANG INI
$faq_title = setting('FAQ_TITLE', 'Soalan Lazim (FAQ)');
$faqs = db()->query("SELECT * FROM faq WHERE active=1 ORDER BY id ASC")->fetchAll();
$features_title = setting('FEATURES_TITLE', 'Kenapa Ia Pilihan Peniaga Bijak?');
$features_list = db()->query("SELECT * FROM features WHERE active=1 ORDER BY id ASC")->fetchAll();
$calculator_enabled = setting('CALCULATOR_ENABLED', '0'); // <-- TAMBAH YANG INI
$logo_url = setting('LOGO_URL', 'https://via.placeholder.com/200x50.png/1e293b/FFFFFF?text=Logo+Anda');
$hero_image_url = setting('HERO_IMAGE_URL', 'https://via.placeholder.com/600x600.png/e2e8f0/475569?text=SILA+TETAPKAN+IMEJ+UTAMA');
$guarantee_image_url = setting('GUARANTEE_IMAGE_URL', 'https://via.placeholder.com/100x100.png/34d399/ffffff?text=Sila+Tetapkan+Logo+Jaminan');
$trust_logo_1_url = setting('TRUST_LOGO_1_URL');
$trust_logo_2_url = setting('TRUST_LOGO_2_URL');
$trust_logo_3_url = setting('TRUST_LOGO_3_URL');
$headlineA = setting('headline_a', 'Headline A: Sila edit di halaman Tetapan');
$headlineB = setting('headline_b', 'Headline B: Sila edit di halaman Tetapan');
$hero_subheadline = setting('HERO_SUBHEADLINE', 'Formula Vanilla Blue direka khas untuk peniaga: warna biru susu yang viral, larut dengan cepat, dan rasa premium yang menambat selera pelanggan datang kembali.');
$problem_title = setting('PROBLEM_TITLE', 'Adakah Ini Masalah Anda Sebagai Peniaga Air?');
$testimonials_title = setting('TESTIMONIALS_TITLE', 'Lihat Apa Kata Pelanggan Kami');
$packages_title = setting('PACKAGES_TITLE', 'Pilih Pakej Permulaan Anda Hari Ini');
$guarantee_title = setting('GUARANTEE_TITLE', 'Jaminan Kepuasan 100%');
$guarantee_text = setting('GUARANTEE_TEXT', 'Jika anda tidak berpuas hati, hubungi kami dalam masa 7 hari untuk pemulangan wang.');
$packages = db()->query("SELECT * FROM packages WHERE active=1 ORDER BY id")->fetchAll();

// === KEDUDUKAN YANG BETUL ===
// Sediakan data harga untuk JavaScript SELEPAS $packages dimuatkan
$js_prices = [];
foreach ($packages as $p) {
    $js_prices[$p['id']] = (float)$p['price'];
}
$pricing_data = [
    'packages' => $js_prices,
    'order_bump' => (float)setting('ORDER_BUMP_PRICE', 5.00),
    'transaction_fee' => 1.00
];

$testi = db()->query("SELECT * FROM testimonials WHERE active=1 ORDER BY id LIMIT 3")->fetchAll();
$bump_enabled = setting('ORDER_BUMP_ENABLED', '1');
$bump_headline = setting('ORDER_BUMP_HEADLINE', 'Ya, saya nak tambah 1 Pek!');
$bump_price = (float)setting('ORDER_BUMP_PRICE','5.00');
$bump_description = setting('ORDER_BUMP_DESCRIPTION', 'Resepi istimewa.');
$exit_intent_enabled = setting('EXIT_INTENT_ENABLED', '1');
$exitCode = setting('EXIT_INTENT_COUPON_CODE','JANGANPERGI10');
$exitPct = (int)setting('EXIT_INTENT_PERCENT','10');
$whatsapp_redirect_url = setting('WHATSAPP_REDIRECT_URL', '');
$whatsapp_icon_url = setting('WHATSAPP_ICON_URL', ''); // <-- TAMBAH YANG INI
$packages_subtitle = setting('PACKAGES_SUBTITLE', ''); // <-- TAMBAH YANG INI
$problems = db()->query("SELECT * FROM problems WHERE active=1 ORDER BY id")->fetchAll(); // <-- TAMBAH YANG INI
$hero_badge_text = setting('HERO_BADGE_TEXT', 'Rahsia Rasa Mak Tok – Sedap, Sihat, Tanpa MSG!');
$hero_disclaimer_text = setting('HERO_DISCLAIMER_TEXT', 'Anggaran penggunaan: 1 botol (100g) boleh digunakan sehingga 10–20 hidangan keluarga.');
$order_bump_image_url = setting('ORDER_BUMP_IMAGE_URL', ''); // <-- TAMBAH YANG INI
$footer_about_title = setting('FOOTER_ABOUT_TITLE');
$fb_pixel_id = setting('FACEBOOK_PIXEL_ID'); // <-- TAMBAH BARIS INI
$tiktok_pixel_id = setting('TIKTOK_PIXEL_ID'); // <-- TAMBAH BARIS INI
$cod_enabled = setting('PAYMENT_COD_ENABLED', '1'); // Semak status COD dari tetapan

?>
<!doctype html><html lang="ms">
<?php
// ... SEMUA KOD PHP SEDIA ADA DI ATAS ...
$footer_about_title = setting('FOOTER_ABOUT_TITLE'); 

// KOD BARU BERMULA DI SINI: Logik untuk memaparkan video YouTube
$youtube_embed_url = '';
$youtube_url = setting('YOUTUBE_URL');
if (filter_var($youtube_url, FILTER_VALIDATE_URL) && (strpos($youtube_url, 'youtube.com') !== false || strpos($youtube_url, 'youtu.be') !== false)) {
    preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $youtube_url, $match);
    $video_id = $match[1] ?? '';
    if ($video_id) {
        $youtube_embed_url = 'https://www.youtube.com/embed/' . $video_id;
    }
}
// KOD BARU TAMAT DI SINI

?>

<!doctype html><html lang="ms">
    
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <?php
    // Ambil semua tetapan SEO dari pangkalan data
    $site_title = setting('SITE_TITLE', APP_NAME);
    $meta_description = setting('SEO_META_DESCRIPTION', 'Serbuk Minuman Viral No.1 untuk Peniaga Air Balang dan Kafe. Modal Rendah, Untung Berganda!');
    $meta_keywords = setting('SEO_META_KEYWORDS', 'vanilla blue, serbuk minuman, pembekal air balang, mukmin rich');
    $favicon_url = setting('FAVICON_URL', '');
    $og_image = setting('SEO_OG_IMAGE', setting('HERO_IMAGE_URL')); // Guna hero image jika tiada imej khas
    $current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    ?>

    <title><?= e($site_title) ?></title>
    <meta name="description" content="<?= e($meta_description) ?>">
    <meta name="keywords" content="<?= e($meta_keywords) ?>">
    <?php if (!empty($favicon_url)): ?>
        <link rel="icon" href="<?= e($favicon_url) ?>">
    <?php endif; ?>

    <meta property="og:title" content="<?= e($site_title) ?>">
    <meta property="og:description" content="<?= e($meta_description) ?>">
    <meta property="og:image" content="<?= e($og_image) ?>">
    <meta property="og:url" content="<?= e($current_url) ?>">
    <meta property="og:type" content="website">

    <link rel="stylesheet" href="<?=e(PUBLIC_URL)?>assets/css/style.css?v=<?=filemtime(__DIR__.'/public/assets/css/style.css')?>">
    <?php if ($exit_intent_enabled === '1'): ?><script defer src="<?=e(PUBLIC_URL)?>assets/js/exit_intent.js"></script><?php endif; ?>
    <script defer src="<?=e(PUBLIC_URL)?>assets/js/ai_chatbot.js?v=<?=filemtime(__DIR__.'/public/assets/js/ai_chatbot.js')?>"></script>
    
    <?php if (!empty($fb_pixel_id)): ?>
<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', '<?= e($fb_pixel_id) ?>');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=<?= e($fb_pixel_id) ?>&ev=PageView&noscript=1"
/></noscript>
<?php endif; ?>

<?php if (!empty($tiktok_pixel_id)): ?>
<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('<?= e($tiktok_pixel_id) ?>');
  ttq.page();
}(window, document, 'ttq');
</script>
<?php endif; ?>

<script defer src="<?=e(PUBLIC_URL)?>assets/js/whatsapp_button.js"></script>

</head>
    

<body data-whatsapp-url="<?= e($whatsapp_redirect_url) ?>" data-whatsapp-icon-url="<?= e($whatsapp_icon_url) ?>">

<header class="header">

<body data-whatsapp-url="<?= e($whatsapp_redirect_url) ?>" data-whatsapp-icon-url="<?= e($whatsapp_icon_url) ?>">

<header class="header">
    <div class="container">
        <nav class="navbar">
            <div class="logo"><a href="#"><img src="<?= e($logo_url) ?>" alt="Logo Syarikat"></a></div>
            <a href="#packages" class="cta-header">Tempah Sekarang</a>
        </nav>
    </div>
</header>

<main>
    <section class="hero-section section-light">
        <div class="container">
            <div class="hero-content">
                <div class="hero-text">
                    <span class="hero-badge"><?= e($hero_badge_text) ?></span>
                    <h1><?=e($ab==='a'?$headlineA:$headlineB)?></h1>
                    <p class="subtitle"><?= e($hero_subheadline) ?></p>
                    <div class="hero-buttons">
                        <a href="#checkout" class="cta cta-primary">Tempah Sekarang</a>
                        <a href="#packages" class="cta cta-secondary">Lihat Pakej</a>
                    </div>
                    <p class="disclaimer"><?= e($hero_disclaimer_text) ?></p>
                </div>
                <div class="hero-image"><img src="<?= e($hero_image_url) ?>" alt="Imej Produk Utama"></div>
            </div>
        </div>
    </section>

    <section class="problem-section section-dark"><div class="container">
        <h2 class="section-title"><?= e($problem_title) ?></h2>
        <div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(300px,1fr))">
            <?php foreach($problems as $p): ?>
            <div class="card">
                <b><?= e($p['icon']) ?> <?= e($p['headline']) ?></b>
                <p><?= e($p['text']) ?></p>
            </div>
            <?php endforeach; ?>
        </div>
    </div></section>
    

<?php if (!empty($features_list)): ?>
<section class="features-section section-white">
    <div class="container">
        <h2 class="section-title"><?= e($features_title) ?></h2>
        <div class="features-grid">
            <?php foreach($features_list as $feature): ?>
            <div class="feature-item">
                <?php if(!empty($feature['image_url'])): ?><img src="<?= e($feature['image_url']) ?>" alt="<?= e($feature['headline']) ?>" class="feature-icon"><?php endif; ?>
                <h3 class="feature-headline"><?= e($feature['headline']) ?></h3>
                <p class="feature-text"><?= e($feature['text']) ?></p>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>
    
<section class="section-light"><div class="container">
        <h2 class="section-title"><?= e($testimonials_title) ?></h2>
        <div class="testimonials-grid">
            <?php foreach($testi as $t): ?>
            <div class="card testimonial-card">
                <?php if(!empty($t['image_url'])): ?>
                    <img src="<?= e($t['image_url']) ?>" alt="<?= e($t['name']) ?>" class="testimonial-image">
                <?php endif; ?>
                <p class="testimonial-text">"<?= nl2br(e($t['text'])) ?>"</p>
                <div class="testimonial-author">
                    <b class="testimonial-name"><?= e($t['name']) ?></b>
                    <?php if(!empty($t['job_title'])): ?>
                        <span class="testimonial-job"><?= e($t['job_title']) ?></span>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div></section>
    
    <?php if ($calculator_enabled === '1'): ?>
<section class="calculator-section section-white">
    <div class="container">
        <h2 class="section-title">Kira Sendiri Potensi Keuntungan Anda</h2>
        <div class="calculator-wrapper">
            <div class="calculator-inputs card">
                <div class="form-grid">
                    <label>Kos Secawan (RM)<input type="number" id="calc-cost" value="0.80" step="0.01"></label>
                    <label>Harga Jual (RM)<input type="number" id="calc-price" value="4.00" step="0.01"></label>
                    <label>Cawan Sehari<input type="number" id="calc-cups" value="50"></label>
                    <label>Hari Berniaga/Bulan<input type="number" id="calc-days" value="26"></label>
                </div>
                <button id="calculate-profit" class="cta" style="width:100%; margin-top: 20px;">Kira Sekarang</button>
            </div>
            <div class="calculator-results">
                <div class="result-box">
                    <span>Untung / Cawan</span>
                    <strong id="profit-cup">RM 3.20</strong>
                </div>
                <div class="result-box">
                    <span>Untung / Hari</span>
                    <strong id="profit-day">RM 160.00</strong>
                </div>
                <div class="result-box-highlight">
                    <span>Anggaran Untung Sebulan</span>
                    <strong id="profit-month">RM 4,160.00</strong>
                </div>
            </div>
        </div>
    </div>
</section>
<?php endif; ?>
    
    <?php
// Kod ini akan mengambil pautan dari tetapan dan memaparkan video jika pautan itu wujud
$youtube_url_from_settings = setting('YOUTUBE_URL');
if (!empty($youtube_url_from_settings)) {
    preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $youtube_url_from_settings, $match);
    $video_id = $match[1] ?? '';
    if ($video_id) {
        $embed_url = 'https://www.youtube.com/embed/' . $video_id;
        echo '
        <section class="video-section section-dark">
            <div class="container">
                <h2 class="section-title">Lihat Sendiri Betapa Mudahnya!</h2>
                <div class="video-container" style="position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; border-radius: 14px; box-shadow: 0 10px 20px rgba(0,0,0,0.1);">
                    <iframe src="' . e($embed_url) . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></iframe>
                </div>
            </div>
        </section>';
    }
}
?>

<section id="packages" class="packages-section section-light"><div class="container">
    <h2 class="section-title"><?= e($packages_title) ?></h2>
    <?php if (!empty($packages_subtitle)): ?>
        <p class="section-subtitle"><?= e($packages_subtitle) ?></p>
    <?php endif; ?>
    <div class="packages-grid">
    <?php foreach($packages as $p): $features=array_filter(array_map('trim',explode('|',$p['features']))); ?>
    <div class="card package-card <?= $p['best_seller'] ? 'package-highlight' : '' ?>">
        <?php if($p['best_seller']):?><div class="badge">Paling Laris</div><?php endif; ?>
        <h3 class="package-name-title"><?=e($p['name'])?></h3>

        <div class="price-wrapper">
            <div class="price"><?=money($p['price'])?></div>
            <?php if(!empty($p['subtitle'])): ?><div class="package-subtitle"><?= e($p['subtitle']) ?></div><?php endif; ?>
        </div>

        <ul class="features-list"><?php foreach($features as $f): ?><li><?=$f?></li><?php endforeach; ?></ul>
        <a class="cta" href="#checkout" data-id="<?=e((string)$p['id'])?>">
            <?= $p['best_seller'] ? 'Saya Mahu Pakej Ini!' : 'Pilih Pakej Ini' ?>
        </a>
    </div><?php endforeach; ?>
    </div>
</div></section>
    
    



    <section id="checkout" class="section-dark"><div class="container">
        <div class="card" style="max-width: 720px; margin: 0 auto;">
            <h2 style="text-align:center;">Lengkapkan Maklumat Pesanan</h2>
            <form action="process_order.php" method="post" enctype="multipart/form-data">
                <?=csrf_field()?>
                <label>Nama Penuh <input name="name" required></label>
                <label>Emel <input name="email" type="email"></label>
                <label>Nombor Telefon (WhatsApp) <input name="phone" placeholder="+601..." required></label>
                <label>Alamat Penuh <textarea name="address" required></textarea></label>
                <label>Pilihan Pakej
    <select name="package_id" required>
        <?php foreach($packages as $p): ?>
            <option value="<?=e($p['id'])?>" <?= $p['best_seller'] ? 'selected' : '' ?>>
                <?=e($p['name'])?> - <?=money($p['price'])?>
            </option>
        <?php endforeach; ?>
    </select>
</label>
                
                <label>Tujuan Pembelian
    <select name="purchase_purpose" required>
        <option value="" selected disabled>-- Sila Pilih --</option>
        <option value="Niaga Air Balang">Untuk niaga air balang</option>
        <option value="Kegunaan Kafe">Untuk kegunaan kafe</option>
        <option value="Katering">Untuk katering</option>
        <option value="Kegunaan Sendiri">Untuk kegunaan sendiri</option>
    </select>
</label>
                
<?php if($bump_enabled === '1'): ?>

<div class="order-bump-wrapper <?= !empty($order_bump_image_url) ? 'with-image' : '' ?>">
    
    <div class="order-bump-content">
        <input type="checkbox" id="order_bump" name="order_bump" value="1">
        <div class="order-bump-text-main">
            <label for="order_bump">
                <strong>"<?= e($bump_headline) ?>"</strong> (Tambah Hanya <?=money($bump_price)?>)
            </label>
            <div class="order-bump-description-final">
                <?= nl2br($bump_description) ?>
            </div>
        </div>
    </div>

    <?php if(!empty($order_bump_image_url)): ?>
    <div class="order-bump-image">
        <img src="<?= e($order_bump_image_url) ?>" alt="Tawaran Tambahan">
    </div>
    <?php endif; ?>



</div>
<?php endif; ?>
                <label>Kod Kupon <input name="coupon" placeholder="Jika ada"></label>
                
                <div id="orderSummary" class="order-summary" style="margin-bottom: 20px;">
    <h4>Ringkasan Pesanan</h4>
    <div class="summary-item">
        <span>Pakej Asal</span>
        <span id="summary-package-price">RM0.00</span>
    </div>
    <div class="summary-item" id="summary-bump-row" style="display: none;">
        <span>+ Tambahan (Order Bump)</span>
        <span id="summary-bump-price">RM0.00</span>
    </div>
    <div class="summary-item" id="summary-cod-row" style="display: none;">
        <span>+ Caj Pengendalian COD&nbsp; </span>
        <span id="summary-cod-fee">RM0.00</span>
    </div>
    <div class="summary-item" id="summary-trx-row" style="display: none;">
        <span>+ Caj Transaksi Online&nbsp; </span>
        <span id="summary-trx-fee"> RM0.00</span>
    </div>
    <div class="summary-total">
    <span style="color:red;"><span style="font-size: 1.1em;">Jumlah Keseluruhan</span>
    <span id="summary-total-price" style="font-size: 1.1em; font-weight: bold;">RM0.00</span></span>
</div>
</div>
                
<label>Cara Bayaran
    <select name="payment_method" required> <option value="" selected disabled>-- Pilih Cara Bayaran --</option> <option value="ToyyibPay">Pembayaran Online</option>
        <option value="Manual">Pindahan Manual</option>
        <?php if ($cod_enabled == '1'): ?>
        <option value="COD">Bayar Waktu Terima (COD)</option>
        <?php endif; ?>
    </select>
</label>


                
                <button id="submitButton" class="cta cta-secondary" type="submit" style="width:100%;">Hantar Pesanan Saya Sekarang!</button>
            </form>
        </div>
    </div></section>
    
<section class="final-trust-section section-dark">
    <div class="container">
        <div class="trust-wrapper-merged">
            
            <img src="<?= e($guarantee_image_url) ?>" alt="Jaminan Kepuasan" class="guarantee-logo">
            <div class="guarantee-text">
                <strong><?= e($guarantee_title) ?></strong>
                <span><?= e($guarantee_text) ?></span>
            </div>

            <div class="trust-divider"></div>

            <?php if($trust_logo_1_url):?><img src="<?= e($trust_logo_1_url) ?>" alt="Logo Keyakinan 1" class="trust-logo"><?php endif; ?>
            <?php if($trust_logo_2_url):?><img src="<?= e($trust_logo_2_url) ?>" alt="Logo Keyakinan 2" class="trust-logo"><?php endif; ?>
            <?php if($trust_logo_3_url):?><img src="<?= e($trust_logo_3_url) ?>" alt="Logo Keyakinan 3" class="trust-logo"><?php endif; ?>

        </div>
    </div>
</section>

<?php if (!empty($faqs)): ?>
<section class="faq-section section-dark">
    <div class="container">
        <h2 class="section-title"><?= e($faq_title) ?></h2>
        <div class="faq-accordion">
            <?php foreach($faqs as $faq): ?>
            <div class="faq-item">
                <button class="faq-question">
                    <span><?= e($faq['q']) ?></span>
                    <span class="faq-icon">+</span>
                </button>
                <div class="faq-answer">
                    <p><?= nl2br(e($faq['a'])) ?></p>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>
<?php endif; ?>
    
    <?php if ($exit_intent_enabled === '1'): ?>
    <div class="modal" id="exit-modal" data-code="<?=e($exitCode)?>">
        <div class="modal-inner">
          <h3>Tunggu Sebentar!</h3>
          <p>Diskaun khas <strong><?=e($exitPct)?>%</strong> untuk anda. Gunakan kod di bawah:</p>
          <h2 style="text-align:center; background-color: #eef2ff; padding:12px; border-radius:8px;"><?=e($exitCode)?></h2>
          <div style="display:flex;gap:8px;justify-content:flex-end; margin-top:16px;">
            <button id="exit-apply" class="cta">Guna Kod</button>
            <button id="exit-close">Tidak Perlu, Terima Kasih</button>
          </div>
        </div>
    </div>
    <?php endif; ?>
</main>

<?php if (!empty($footer_about_title)): ?>
<footer class="main-footer section-dark">
    <div class="container">
        <h3 class="footer-location-title">Lokasi Kami</h3>
        <div class="footer-grid">
            <div class="footer-map">
                <iframe 
                    src="<?= e(setting('FOOTER_MAP_URL')) ?>" 
                    width="100%" height="350" style="border:0;" 
                    allowfullscreen="" loading="lazy" 
                    referrerpolicy="no-referrer-when-downgrade">
                </iframe>
            </div>
            <div class="footer-about">
                <h3><?= e(setting('FOOTER_ABOUT_TITLE')) ?></h3>
                <p><?= nl2br(e(setting('FOOTER_ABOUT_TEXT'))) ?></p>
            </div>
        </div>
    </div>
</footer>
<?php endif; ?>

<div class="footer-bar">
    <div class="container footer-bar-content">
        <span><strong><?= e(setting('FOOTER_COMPANY_NAME', 'Mukmin Rich Solution')) ?></strong></span>
        <span class="footer-contact">
            <?php if(setting('FOOTER_EMAIL')): ?>E-mel: <?= e(setting('FOOTER_EMAIL')) ?><?php endif; ?>
            <?php if(setting('FOOTER_PHONE')): ?> | Telefon: <?= e(setting('FOOTER_PHONE')) ?><?php endif; ?>
        </span>
        <span>&copy; <?= date('Y') ?> <?= e(setting('FOOTER_COPYRIGHT')) ?></span>
    </div>
</div>

<script>
const PRICING_DATA = <?= json_encode($pricing_data) ?>;

document.addEventListener('DOMContentLoaded', function() {
    // --- Bahagian Elemen ---
    const packageButtons = document.querySelectorAll('#packages .cta[data-id]');
    const packageSelect = document.querySelector('select[name="package_id"]');
    const bumpCheckbox = document.querySelector('input[name="order_bump"]');
    const paymentMethodSelect = document.querySelector('select[name="payment_method"]');
    const summaryPackagePrice = document.getElementById('summary-package-price');
    const summaryBumpRow = document.getElementById('summary-bump-row');
    const summaryBumpPrice = document.getElementById('summary-bump-price');
    const summaryCodRow = document.getElementById('summary-cod-row');
    const summaryCodFee = document.getElementById('summary-cod-fee');
    const summaryTrxRow = document.getElementById('summary-trx-row');
    const summaryTrxFee = document.getElementById('summary-trx-fee');
    const summaryTotalPrice = document.getElementById('summary-total-price');
    const calcButton = document.getElementById('calculate-profit');
    const checkoutForm = document.querySelector('#checkout form');
    const questions = document.querySelectorAll('.faq-question');

    // --- Bahagian Fungsi ---
    function updateOrderSummary() {
        if (!packageSelect) return; // Keluar jika tiada pilihan pakej

        let packagePrice = 0, bumpPrice = 0, codFee = 0, transactionFee = 0;
        const selectedPackageId = packageSelect.value;

        if (selectedPackageId && PRICING_DATA.packages[selectedPackageId]) {
            packagePrice = PRICING_DATA.packages[selectedPackageId];
        }

        if (bumpCheckbox && bumpCheckbox.checked) {
            bumpPrice = PRICING_DATA.order_bump;
            summaryBumpRow.style.display = 'flex';
        } else if (summaryBumpRow) {
            summaryBumpRow.style.display = 'none';
        }

        const subtotal = packagePrice + bumpPrice;
        const selectedPayment = paymentMethodSelect.value;

        summaryCodRow.style.display = 'none';
        summaryTrxRow.style.display = 'none';

        if (selectedPayment === 'COD') {
            codFee = Math.max(7.00, subtotal * 0.04);
            summaryCodRow.style.display = 'flex';
        } else if (selectedPayment === 'ToyyibPay') {
            transactionFee = PRICING_DATA.transaction_fee;
            summaryTrxRow.style.display = 'flex';
        }

        const total = subtotal + codFee + transactionFee;
        const formatter = new Intl.NumberFormat('ms-MY', { style: 'currency', currency: 'MYR' });

        summaryPackagePrice.textContent = formatter.format(packagePrice);
        summaryBumpPrice.textContent = formatter.format(bumpPrice);
        summaryCodFee.textContent = " " + formatter.format(codFee);
        summaryTrxFee.textContent = " " + formatter.format(transactionFee);
        summaryTotalPrice.textContent = formatter.format(total);
    }

    function calculateAndDisplay() {
        const costInput = document.getElementById('calc-cost');
        const priceInput = document.getElementById('calc-price');
        const cupsInput = document.getElementById('calc-cups');
        const daysInput = document.getElementById('calc-days');

        if (!costInput) return; // Keluar jika kalkulator tidak wujud

        const cost = parseFloat(costInput.value) || 0;
        const price = parseFloat(priceInput.value) || 0;
        const cups = parseInt(cupsInput.value) || 0;
        const days = parseInt(daysInput.value) || 0;

        const profitPerCup = price - cost;
        const profitPerDay = profitPerCup * cups;
        const profitPerMonth = profitPerDay * days;

        const formatter = new Intl.NumberFormat('ms-MY', { style: 'currency', currency: 'MYR' });

        document.getElementById('profit-cup').textContent = formatter.format(profitPerCup);
        document.getElementById('profit-day').textContent = formatter.format(profitPerDay);
        document.getElementById('profit-month').textContent = formatter.format(profitPerMonth);
    }

    // --- Bahagian Event Listeners ---
if (packageButtons.length > 0 && packageSelect) {
    packageButtons.forEach(button => {
        button.addEventListener('click', function() {
            packageSelect.value = this.getAttribute('data-id');
            updateOrderSummary();

            // BARU: Hantar event AddToCart ke FB & TikTok
            if (typeof fbq === 'function') { fbq('track', 'AddToCart'); }
            if (typeof ttq === 'function') { ttq.track('AddToCart'); }
        });
    });
}

    if (packageSelect) packageSelect.addEventListener('change', updateOrderSummary);
    if (bumpCheckbox) bumpCheckbox.addEventListener('change', updateOrderSummary);
    if (paymentMethodSelect) paymentMethodSelect.addEventListener('change', updateOrderSummary);
    if (calcButton) calcButton.addEventListener('click', calculateAndDisplay);

if (checkoutForm) {
    checkoutForm.addEventListener('submit', function(event) {
        if (!paymentMethodSelect || !paymentMethodSelect.value) { 
            event.preventDefault(); 
            alert('Sila pilih cara bayaran anda terlebih dahulu.');
        } else {
            // BARU: Hantar event InitiateCheckout ke FB & TikTok
            if (typeof fbq === 'function') { fbq('track', 'InitiateCheckout'); }
            if (typeof ttq === 'function') { ttq.track('InitiateCheckout'); }
        }
    });
}

    questions.forEach(question => {
        question.addEventListener('click', () => {
            const icon = question.querySelector('.faq-icon');
            question.classList.toggle('active');
            const answer = question.nextElementSibling;

            if (answer.style.maxHeight) {
                answer.style.maxHeight = null;
                icon.textContent = '+';
            } else {
                answer.style.maxHeight = answer.scrollHeight + 'px';
                icon.textContent = '−';
            }
        });
    });

    // --- Panggilan Fungsi Permulaan ---
    updateOrderSummary();
    if (calcButton) {
        calculateAndDisplay();
    }
});
</script>

<script>
const PRICING_DATA = <?= json_encode($pricing_data) ?>;
document.addEventListener('DOMContentLoaded', function() {
    // ... (kod sedia ada untuk kalkulator harga) ...
    updateOrderSummary();
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // 1. Dapatkan semua elemen soalan
    const questions = document.querySelectorAll('.faq-question');

    // 2. Lakukan 'loop' pada setiap butang soalan
    questions.forEach(question => {
        // 3. Tambah 'event listener' yang akan berfungsi apabila butang diklik
        question.addEventListener('click', () => {
            // Tukar ikon dari '+' ke '-' dan sebaliknya
            const icon = question.querySelector('.faq-icon');
            question.classList.toggle('active');

            // Dapatkan elemen jawapan yang sepadan
            const answer = question.nextElementSibling;

            // Semak jika panel jawapan sedang terbuka atau tertutup
            if (answer.style.maxHeight) {
                // Jika ia ada nilai (sedang terbuka), tutupnya dengan set kepada null
                answer.style.maxHeight = null;
                icon.textContent = '+';
            } else {
                // Jika ia tertutup (tiada nilai), bukanya dengan set ketinggian maksimum
                // mengikut ketinggian sebenar kandungan di dalamnya (scrollHeight)
                answer.style.maxHeight = answer.scrollHeight + 'px';
                icon.textContent = '−'; // Simbol tolak
            }
        });
    });
});
</script>
</body>
</html>


</body>
</html>