<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

$id = (int)($_GET['order'] ?? $_GET['order_id'] ?? 0);
$st=db()->prepare("SELECT * FROM orders WHERE id=?");
$st->execute([$id]);
$o=$st->fetch();

if(!$o){ http_response_code(404); exit('Order tidak ditemui'); }

// Ambil semua tetapan yang diperlukan
$upsell_enabled = setting('UPSELL_ENABLED', '1');
$upsell_image_url = setting('UPSELL_IMAGE_URL');
$upsell_headline = setting('UPSELL_HEADLINE', 'Tawaran Istimewa (Kali Ini Sahaja!)');
$upsell_description = setting('UPSELL_DESCRIPTION', 'Tambah 1 pek eksklusif pada harga runtuh, hanya');
$upsell_price = (float)setting('UPSELL_PRICE','10.00');

$downsell_price = (float)setting('DOWNSELL_PRICE','5.00');
$downsell_headline = setting('DOWNSELL_HEADLINE', 'Tunggu! Tawaran Terakhir Untuk Anda...');
$downsell_description = setting('DOWNSELL_DESCRIPTION', 'Dapatkan produk tambahan ini pada harga istimewa yang tidak akan diulang.');

$button_enabled = setting('MAIN_WEBSITE_BUTTON_ENABLED', '1');
$main_website_url = setting('MAIN_WEBSITE_URL');
$admin_phone = setting('ADMIN_PHONE');
?>


<!doctype html><html lang="ms"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="<?=e(PUBLIC_URL)?>assets/css/style.css"><title>Terima Kasih</title>

<?php
// --- KOD BARU UNTUK PURCHASE TRACKING ---
$fb_pixel_id = setting('FACEBOOK_PIXEL_ID');
$tiktok_pixel_id = setting('TIKTOK_PIXEL_ID');

// Hanya jalankan jika ada pesanan dan pixel ID wujud
if ($o && (!empty($fb_pixel_id) || !empty($tiktok_pixel_id))) {
    // Semak jika event ini sudah dihantar sebelum ini untuk elak duplikasi
    if (!isset($_SESSION['purchase_event_sent_for_' . $o['id']])) {
        $order_value = (float)$o['amount'];
        $currency = 'MYR';
?>

<?php if (!empty($fb_pixel_id)): ?>
<script>
    if (typeof fbq === 'function') {
        fbq('track', 'Purchase', {
            value: <?= json_encode($order_value) ?>,
            currency: <?= json_encode($currency) ?>
        });
    }
</script>
<?php endif; ?>

<?php if (!empty($tiktok_pixel_id)): ?>
<script>
    if (typeof ttq === 'function') {
        ttq.track('CompletePayment', {
            value: <?= json_encode($order_value) ?>,
            currency: <?= json_encode($currency) ?>
        });
    }
</script>
<?php endif; ?>

<?php
        // Tandakan bahawa event sudah dihantar untuk order ID ini
        $_SESSION['purchase_event_sent_for_' . $o['id']] = true;
    }
}
// --- TAMAT KOD BARU ---
?>

<style>
    .order-summary { border: 1px solid #e5e7eb; border-radius: 12px; margin-top: 16px; }
    .order-summary h4 { margin: 0; padding: 12px 16px; background-color: #f8fafc; border-bottom: 1px solid #e5e7eb; }
    .summary-item, .summary-total, .summary-status { display: flex; justify-content: space-between; padding: 12px 16px; border-bottom: 1px solid #e5e7eb; }
    .summary-item:last-child, .summary-total:last-child, .summary-status:last-child { border-bottom: none; }
    .summary-total { font-weight: bold; font-size: 18px; }
    .summary-item.discount span { color: #16a34a; }
    .upsell-offer-image { max-width: 100%; height: auto; border-radius: 8px; margin-bottom: 16px; }
    .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.7); display: none; justify-content: center; align-items: center; z-index: 1000; }
    .modal-content { background-color: white; padding: 30px; border-radius: 15px; max-width: 500px; width: 90%; position: relative; text-align: center; }
    .modal-close { position: absolute; top: 15px; right: 15px; font-size: 24px; font-weight: bold; text-decoration: none; color: #888; }
</style>
</head><body>
<div class="container">
  <div class="card">
    <h2>Terima kasih, <?=e($o['name'])?>!</h2>
    <p>Pesanan anda telah kami terima dan sedang diproses. Arahan selanjutnya akan dipaparkan sebentar lagi.</p>
    <div class="order-summary">
        <h4>Ringkasan Pesanan #<?= e((string)$o['id']) ?></h4>
        <?php
            $package_parts = explode(' + ', $o['package_name']);
            $base_package_name = $package_parts[0];
            $original_price = (float)$o['amount'] + (float)$o['coupon_discount'] - ((float)$o['order_bump'] * (float)$o['order_bump_price']) - (float)($o['cod_fee'] ?? 0) - (float)($o['transaction_fee'] ?? 0);
            if (strpos($o['package_name'], 'UPSELL') !== false) $original_price -= $upsell_price;
            if (strpos($o['package_name'], 'DOWNSELL') !== false) $original_price -= $downsell_price;
        ?>
        <div class="summary-item"><span>Pakej: <?= e($base_package_name) ?></span><span><?= money($original_price) ?></span></div>
        <?php if ($o['order_bump']): ?><div class="summary-item"><span>+ Tambahan (Order Bump)</span><span><?= money($o['order_bump_price']) ?></span></div><?php endif; ?>
        <?php if (strpos($o['package_name'], 'UPSELL') !== false): ?><div class="summary-item"><span>+ Tawaran Upsell</span><span><?= money($upsell_price) ?></span></div><?php endif; ?>
        <?php if (strpos($o['package_name'], 'DOWNSELL') !== false): ?><div class="summary-item"><span>+ Tawaran Downsell</span><span><?= money($downsell_price) ?></span></div><?php endif; ?>
        <?php if ($o['coupon_discount'] > 0): ?><div class="summary-item discount"><span>Diskaun Kupon (<?= e($o['coupon_code']) ?>)</span><span>-<?= money($o['coupon_discount']) ?></span></div><?php endif; ?>
        <?php if (($o['cod_fee'] ?? 0) > 0): ?><div class="summary-item"><span>+ Caj Pengendalian COD</span><span><?= money($o['cod_fee']) ?></span></div><?php endif; ?>
        <?php if (($o['transaction_fee'] ?? 0) > 0): ?><div class="summary-item"><span>+ Caj Transaksi Online</span><span><?= money($o['transaction_fee']) ?></span></div><?php endif; ?>
        <div class="summary-total"><span style="font-size: 1.1em;">Jumlah Keseluruhan</span><span id="summary-total-price" style="font-size: 1.1em; font-weight: bold;"><?= money($o['amount']) ?></span></div>
        <div class="summary-status"><span>Status Pesanan</span><span><?= e($o['status']) ?></span></div>
    </div>
  </div>
  
<?php
// KOD BARU BERMULA DI SINI
// Semak jika kaedah bayaran adalah COD
if ($o['payment_method'] === 'COD'):
    // Dapatkan nombor telefon admin dari tetapan
    $admin_phone = setting('ADMIN_PHONE');
?>
<div class="card" style="margin-top: 24px; background-color: #fef9c3; border-color: #fde047;">
    <h3 style="color: #854d0e;">PENTING: Maklumat Pesanan COD Anda</h3>
    <p>Sila sediakan wang tunai secukupnya (<strong><?= money($o['amount']) ?></strong>) untuk membuat bayaran kepada pihak kurier semasa penghantaran. Penyediaan wang tunai yang tepat akan melancarkan proses penerimaan barang anda.</p>
    <p>Jika terdapat sebarang pertanyaan atau masalah, sila hubungi kami melalui WhatsApp:</p>

    <?php if ($admin_phone):
        // Sediakan mesej pra-isi untuk pautan WhatsApp
        $whatsapp_message = urlencode("Salam, saya ada soalan mengenai pesanan COD saya #" . $o['id']);
    ?>
        <a href="https://wa.me/<?= e($admin_phone) ?>?text=<?= $whatsapp_message ?>" class="cta" target="_blank" style="display: inline-block; text-decoration: none; background-color: #25d366;">💬 Hubungi Admin di WhatsApp</a>
    <?php endif; ?>
</div>
<?php 
endif; 
// KOD BARU TAMAT DI SINI
?>


<?php

// KOD BARU BERMULA DI SINI
// Semak jika ini adalah pesanan ToyyibPay yang belum dibayar
// KOD YANG TELAH DIBAIKI

// Semak jika ini adalah pesanan ToyyibPay, statusnya Pending, DAN mempunyai bill_code
if ($o['payment_method'] === 'ToyyibPay' && $o['status'] === 'Pending' && !empty($o['bill_code'])):
?>
<div class="card" style="margin-top: 24px; text-align: center; border: 2px solid var(--color-secondary);">
    <h3 style="font-size: 24px;">Satu Langkah Terakhir!</h3>
    <p>Pesanan anda telah direkodkan. Sila klik butang di bawah untuk melengkapkan pembayaran anda dengan selamat melalui ToyyibPay.</p>

    <?php
    // Bina pautan pembayaran ToyyibPay menggunakan bill_code yang telah disimpan
    $payment_url = 'https://toyyibpay.com/' . e($o['bill_code']);
    ?>

    <a href="<?= $payment_url ?>" class="cta cta-primary" style="font-size: 20px; padding: 18px 28px; text-decoration: none; display: inline-block; margin-top: 10px;">
        Bayar RM<?= e(number_format((float)$o['amount'], 2)) ?> Sekarang
    </a>
</div>
<?php 
endif;

// KOD BARU TAMAT DI SINI
?>
  
    <?php if (isset($_GET['upload_success'])): ?>
    <div class="card" style="background-color: #dcfce7; border-color: #86efac;">
        <h3 style="color: #166534;">Terima Kasih!</h3>
        <p style="color: #15803d;">Bukti pembayaran anda telah berjaya dihantar. Kami akan memproses pesanan anda secepat mungkin.</p>
    </div>
    <?php endif; ?>
    
    
</div>

 <?php
// LETAK KOD BARU ANDA DI SINI
// Dapatkan tetapan butang dari pangkalan data
$button_enabled = setting('MAIN_WEBSITE_BUTTON_ENABLED', '1');
$main_website_url = setting('MAIN_WEBSITE_URL');

// Paparkan butang hanya jika ia diaktifkan DAN URL tidak kosong
if ($button_enabled == '1' && !empty($main_website_url)):
?>
<div style="text-align: center; margin-top: 30px; padding-bottom: 30px;">
    <a href="<?= e($main_website_url) ?>" style="text-decoration: underline; color: #475569;">
        &larr; Kembali ke Laman Web Utama
    </a>
</div>
<?php
endif;
// KOD BARU TAMAT DI SINI
?>




<?php if($upsell_enabled == '1' && strpos($o['package_name'], 'UPSELL') === false && strpos($o['package_name'], 'DOWNSELL') === false && $o['status'] === 'Pending'): ?>
<div id="upsell-modal" class="modal-overlay">
    <div class="modal-content">
        <a href="#" id="close-upsell-modal" class="modal-close">&times;</a>
        <h3><?= e($upsell_headline) ?></h3>
        <?php if($upsell_image_url): ?><img src="<?= e($upsell_image_url) ?>" alt="Tawaran Upsell" class="upsell-offer-image"><?php endif; ?>
        <p><?= nl2br(e($upsell_description)) ?> <strong><?=money($upsell_price)?></strong>.</p>
        <form action="upsell.php" method="post" style="display:block; margin-bottom: 10px;"><?=csrf_field()?><input type="hidden" name="order_id" value="<?=$o['id']?>"><button class="cta cta-primary">Ya, tambah sekarang</button></form>
        <button id="show-downsell-offer" class="cta" style="background-color: #6b7280; width:100%;">Tak nak, tunjuk tawaran lain</button>
        <a href="#" id="decline-upsell-offer" style="display: block; margin-top: 15px; font-size: 14px; color: #666;">Tidak, terima kasih.</a>
    </div>
</div> 

<div id="downsell-modal" class="modal-overlay">
    <div class="modal-content">
        <a href="#" id="close-downsell-modal" class="modal-close">&times;</a>
        <h3><?= e($downsell_headline ?? '') ?></h3>
        <?php if($upsell_image_url): ?><img src="<?= e($upsell_image_url) ?>" alt="Tawaran Downsell" class="upsell-offer-image"><?php endif; ?>
        <p><?= nl2br(e($downsell_description ?? '')) ?> <strong><?= money($downsell_price) ?></strong>.</p>
        <form action="downsell.php" method="post" style="display:block; margin-bottom: 10px;">
            <?= csrf_field() ?>
            <input type="hidden" name="order_id" value="<?= $o['id'] ?>">
            <button type="submit" class="cta cta-primary">Ya, Saya Nak Tawaran Ini</button>
        </form>
        <a href="#" id="decline-downsell-offer" style="display: block; margin-top: 15px; font-size: 14px; color: #666;">
            Tidak, terima kasih.
        </a>
    </div>
</div>
        
        
      <div id="downsell-modal" class="modal-overlay">
    <div class="modal-content">
        <a href="#" id="close-downsell-modal" class="modal-close">&times;</a>
        <h3><?= e($downsell_headline) ?></h3>
        <?php if($upsell_image_url): ?><img src="<?= e($upsell_image_url) ?>" alt="Tawaran Downsell" class="upsell-offer-image"><?php endif; ?>
        <p><?= nl2br(e($downsell_description)) ?> <strong><?= money($downsell_price) ?></strong>.</p>

        <form action="downsell.php" method="post" style="display:block; margin-bottom: 10px;">
            <?= csrf_field() ?>
            <input type="hidden" name="order_id" value="<?= $o['id'] ?>">
            <button type="submit" class="cta cta-primary">Ya, Saya Nak Tawaran Ini</button>
        </form>

        <a href="#" id="decline-downsell-offer" style="display: block; margin-top: 15px; font-size: 14px; color: #666;">
            Tidak, terima kasih.
        </a>
    </div>
</div>
    
    
</div>
<?php endif; ?>

<div id="payment-modal" class="modal-overlay">
    <div class="modal-content">
        <h3>Lengkapkan Pembayaran Anda</h3>
        <p>Sila buat pembayaran berjumlah <strong><?= money($o['amount']) ?></strong> ke akaun di bawah.</p>
        <div style="background-color: #f8fafc; padding: 15px; border-radius: 8px; text-align: center; margin-top: 10px;">
            <p><strong>Nama Bank:</strong> <?= e(setting('BANK_NAME')) ?><br>
               <strong>Nama Akaun:</strong> <?= e(setting('BANK_ACCOUNT_NAME')) ?><br>
               <strong>Nombor Akaun:</strong> <?= e(setting('BANK_ACCOUNT_NO')) ?></p>
            <?php $qr_url = setting('QR_CODE_IMAGE_URL'); ?>
            <?php if ($qr_url): ?><img src="<?= e($qr_url) ?>" alt="Kod QR" style="max-width: 200px;"><?php endif; ?>
        </div>
        <hr style="margin: 20px 0;">
        <h4>Muat Naik Bukti Pembayaran</h4>
        <form action="upload_proof.php" method="post" enctype="multipart/form-data">
            <?= csrf_field() ?>
            <input type="hidden" name="order_id" value="<?= $o['id'] ?>">
            <input type="file" name="proof_file" required style="width:100%; padding: 8px; border: 1px solid #ccc; border-radius: 6px; margin-bottom: 10px;">
            <button type="submit" class="cta">Saya Sudah Bayar & Muat Naik Resit</button>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const orderData = <?= json_encode($o) ?>;
    const upsellModal = document.getElementById('upsell-modal');
    const paymentModal = document.getElementById('payment-modal');

    // Satu fungsi utama untuk hantar notifikasi dan tunjuk arahan bayaran
function finalizeOrderFlow() {
    // Hantar notifikasi HANYA JIKA BAYARAN ADALAH COD
    if (orderData && orderData.notification_sent == 0 && orderData.payment_method === 'COD') {
        fetch('send_notification.php?order_id=' + orderData.id)
            .then(() => {
                orderData.notification_sent = 1; 
            });
    }

    // Tunjuk arahan bayaran manual jika perlu
    if (orderData && orderData.payment_method === 'Manual' && orderData.status === 'Pending') {
        if (paymentModal) paymentModal.style.display = 'flex';
    }
}
    // Hanya jalankan semua logik jika modal upsell wujud di halaman
    if (upsellModal) {
        const downsellModal = document.getElementById('downsell-modal');

        const closeUpsellBtn = upsellModal.querySelector('#close-upsell-modal');
        const declineUpsellLink = upsellModal.querySelector('#decline-upsell-offer');
        const showDownsellBtn = upsellModal.querySelector('#show-downsell-offer');

        setTimeout(() => { upsellModal.style.display = 'flex'; }, 2000);

        if (showDownsellBtn) {
            showDownsellBtn.addEventListener('click', function(e) {
                e.preventDefault();
                upsellModal.style.display = 'none';
                if (downsellModal) {
                    downsellModal.style.display = 'flex';
                }
            });
        }

        function closeUpsellAndFinish(e) {
            e.preventDefault();
            upsellModal.style.display = 'none';
            finalizeOrderFlow();
        }
        if (closeUpsellBtn) closeUpsellBtn.addEventListener('click', closeUpsellAndFinish);
        if (declineUpsellLink) declineUpsellLink.addEventListener('click', closeUpsellAndFinish);

        if (downsellModal) {
            const closeDownsellBtn = downsellModal.querySelector('#close-downsell-modal');
            const declineDownsellLink = downsellModal.querySelector('#decline-downsell-offer');

            function closeDownsellAndFinish(e) {
                e.preventDefault();
                downsellModal.style.display = 'none';
                finalizeOrderFlow();
            }
            if (closeDownsellBtn) closeDownsellBtn.addEventListener('click', closeDownsellAndFinish);
            if (declineDownsellLink) declineDownsellLink.addEventListener('click', closeDownsellAndFinish);
        }

    } else {
        // Jika TIADA modal upsell di halaman, terus jalankan fungsi akhir
        finalizeOrderFlow();
    }
});
</script>
</body></html>