<?php
// Memuatkan fail-fail yang diperlukan
require_once __DIR__.'/inc/config.php';
require_once __DIR__.'/inc/db.php';
require_once __DIR__.'/inc/helpers.php';
require_once __DIR__.'/inc/csrf.php';

// Dapatkan ID Pesanan dari URL
$id = (int)($_GET['order'] ?? 0);
if (!$id) { exit('ID Pesanan tidak sah.'); }

// Ambil butiran pesanan dari pangkalan data
$st = db()->prepare("SELECT * FROM orders WHERE id = ?");
$st->execute([$id]);
$o = $st->fetch();

if (!$o) { exit('Pesanan tidak ditemui.'); }

// Jika pesanan sudah dibayar, hantar ke halaman terima kasih biasa
if ($o['status'] !== 'Pending' && $o['status'] !== 'Payment Review') {
    header('Location: thank_you.php?order=' . $id);
    exit;
}

// BARU: Ambil templat teks dari tetapan
$cod_instructions = setting('COD_INSTRUCTIONS', 'Anda telah memilih untuk Bayar Waktu Terima (COD). Sila sediakan wang tunai secukupnya ({jumlah}) untuk diserahkan kepada kurier semasa penghantaran.');
$manual_instructions = setting('MANUAL_PAYMENT_INSTRUCTIONS', 'Sila buat pembayaran berjumlah {jumlah} ke akaun di bawah.');
$toyyibpay_instructions = setting('TOYYIBPAY_INSTRUCTIONS', 'Pesanan anda telah direkodkan. Sila klik butang di bawah untuk melengkapkan pembayaran anda.');

// BARU: Gantikan pemboleh ubah dalam teks
$placeholders = ['{jumlah}', '{id_pesanan}'];
$values = [money($o['amount']), $o['id']];
$cod_instructions = str_replace($placeholders, $values, $cod_instructions);
$manual_instructions = str_replace($placeholders, $values, $manual_instructions);
$toyyibpay_instructions = str_replace($placeholders, $values, $toyyibpay_instructions);

?>
<!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>Lengkapkan Pembayaran</title>
    <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 { display: flex; justify-content: space-between; padding: 12px 16px; border-bottom: 1px solid #e5e7eb; }
        .summary-total { font-weight: bold; }
    </style>
</head>
<body>
<div class="container" style="padding-top: 40px; padding-bottom: 40px;">
    <div class="card">
        <h2>Lengkapkan Pesanan Anda #<?= e((string)$o['id']) ?></h2>
        <div class="order-summary">
            <h4>Ringkasan Pesanan</h4>
            <div class="summary-item"><span>Pakej: <?= e($o['package_name']) ?></span><span><?= money((float)$o['amount'] - (float)($o['cod_fee'] ?? 0) - (float)($o['transaction_fee'] ?? 0)) ?></span></div>
            <?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>Jumlah Keseluruhan</span><span><?= money($o['amount']) ?></span></div>
        </div>
    </div>

    <?php if ($o['payment_method'] === 'ToyyibPay' && !empty($o['bill_code'])): ?>
    <div class="card" style="margin-top: 24px; text-align: center;">
        <h3>Pembayaran Online</h3>
        <p><?= nl2br(e($toyyibpay_instructions)) ?></p>
        <a href="https://toyyibpay.com/<?= e($o['bill_code']) ?>" class="cta cta-primary" style="font-size: 20px;">
            Bayar <?= money($o['amount']) ?> Sekarang
        </a>
    </div>
    <?php endif; ?>

    <?php if ($o['payment_method'] === 'Manual'): ?>
    <div class="card" style="margin-top: 24px;">
        <h3>Pindahan Manual / Perbankan Segera</h3>
        <p><?= nl2br(e($manual_instructions)) ?></p>
        <div style="background-color: #f8fafc; padding: 15px; border-radius: 8px; text-align: center; margin: 10px 0;">
            <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>
    <?php endif; ?>

    <?php if ($o['payment_method'] === 'COD'): ?>
    <div class="card" style="margin-top: 24px; background-color: #fef9c3;">
        <h3>Pesanan Anda Sedang Diproses</h3>
        <p><?= nl2br(e($cod_instructions)) ?></p>
    </div>
    <?php endif; ?>
</div>
</body>
</html>