<!DOCTYPE html>
<html lang="id">

<script>
const urlOlshop = 'https://bukaolshop.my.id';
</script>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <title>Pembayaran</title>
    <style>
        /* ================================
           TEMA WARNA (EDIT DISINI)
           ================================ */
        :root {
            --primary: #2563eb;
            --bg-body: #f1f5f9;
            --bg-card: #ffffff;
            --text-dark: #1e293b;
            --text-gray: #64748b;
            --border-color: #e2e8f0;
            --highlight: #f0f9ff;
        }

        /* RESET & LAYOUT */
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
        body { background: var(--bg-body); color: var(--text-dark); display: flex; justify-content: center; min-height: 100vh; padding: 15px; }
        .app-card { background: var(--bg-card); width: 100%; max-width: 400px; border-radius: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); overflow: hidden; display: flex; flex-direction: column; min-height: 80vh; max-height: 95vh; position: relative; }

        /* HEADER */
        .header { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); background: #fff; z-index: 10; }
        .order-id { font-size: 11px; font-weight: 700; color: var(--text-gray); letter-spacing: 1px; text-transform: uppercase; margin-bottom: 5px; }
        .main-amount { font-size: 26px; font-weight: 800; color: var(--text-dark); }
        .amount-note { font-size: 10px; color: var(--text-gray); margin-top: 2px; }

        /* CONTENT */
        .content { flex: 1; overflow-y: auto; padding: 20px; position: relative; }

        /* LIST BANK */
        .section-label { font-size: 13px; font-weight: 600; color: var(--text-gray); margin-bottom: 12px; }
        .bank-item { 
            display: flex; align-items: center; gap: 15px; padding: 15px; margin-bottom: 10px;
            background: #fff; border: 1px solid var(--border-color); border-radius: 14px;
            cursor: pointer; transition: all 0.2s;
        }
        .bank-item:active { transform: scale(0.98); background: var(--highlight); border-color: var(--primary); }
        .bank-logo { 
            width: 45px; height: 45px; background: var(--highlight); color: var(--primary);
            border-radius: 12px; display: flex; align-items: center; justify-content: center;
            font-weight: 800; font-size: 16px; flex-shrink: 0; 
        }
        .bank-info { flex: 1; }
        .bank-name { font-weight: 700; font-size: 14px; color: var(--text-dark); }
        .fee-badge { font-size: 10px; background: #fffbeb; color: #d97706; padding: 2px 6px; border-radius: 4px; display: inline-block; margin-top: 2px; }
        .arrow { color: #cbd5e1; font-size: 18px; }

        /* DETAIL VIEW */
        .detail-view { display: none; animation: slideIn 0.3s ease-out; }
        .btn-back {
            background: none; border: none; color: var(--primary); font-weight: 600; font-size: 13px;
            display: flex; align-items: center; gap: 5px; cursor: pointer; margin-bottom: 15px; padding: 0;
        }
        .payment-box {
            background: #fff; border: 1px solid var(--border-color); border-radius: 16px;
            padding: 20px; margin-bottom: 20px; text-align: center;
        }
        .qris-img { width: 100%; max-width: 200px; margin: 10px auto; mix-blend-mode: multiply; display: block; }
        
        .field { text-align: left; margin-bottom: 15px; }
        .field:last-child { margin-bottom: 0; }
        .field-label { font-size: 11px; font-weight: 600; color: var(--text-gray); margin-bottom: 5px; text-transform: uppercase; }
        .field-wrap { 
            display: flex; justify-content: space-between; align-items: center; 
            background: var(--bg-body); padding: 12px; border-radius: 10px; border: 1px solid var(--border-color);
        }
        .field-val { font-family: monospace; font-size: 16px; font-weight: 700; color: var(--text-dark); }
        .btn-copy { border: none; background: none; color: var(--primary); font-weight: 700; font-size: 12px; cursor: pointer; }

        .total-box {
            background: #fff7ed; border: 1px dashed #fdba74; border-radius: 14px; padding: 15px; text-align: center; margin-bottom: 20px;
        }
        .total-val { font-size: 24px; font-weight: 800; color: #c2410c; margin: 5px 0; font-family: monospace; letter-spacing: -1px; }
        .total-note { font-size: 11px; color: #ea580c; line-height: 1.4; }
        .btn-help {
            width: 100%; padding: 14px; background: transparent; border: 1px solid var(--border-color);
            border-radius: 12px; color: var(--text-gray); font-size: 13px; font-weight: 600; cursor: pointer;
        }

        /* LOADING & OVERLAY */
        .loading-overlay { position: absolute; inset: 0; background: rgba(255,255,255,0.8); display: flex; align-items: center; justify-content: center; z-index: 50; backdrop-filter: blur(2px); }
        .spinner { width: 30px; height: 30px; border: 3px solid var(--border-color); border-top-color: var(--primary); border-radius: 50%; animation: spin 1s linear infinite; }

        .hidden { display: none !important; }
        .toast { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%) translateY(100px); background: #1e293b; color: #fff; padding: 10px 20px; border-radius: 30px; font-size: 12px; font-weight: 600; opacity: 0; transition: 0.3s; z-index: 100; pointer-events: none; }
        .toast.show { transform: translateX(-50%) translateY(0); opacity: 1; }

        @keyframes slideIn { from { opacity: 0; transform: translateX(20px); } to { opacity: 1; transform: translateX(0); } }
        @keyframes spin { to { transform: rotate(360deg); } }
    </style>
</head>
<body>

    <div class="app-card">
        <div id="loading" class="loading-overlay hidden"><div class="spinner"></div></div>

        <!-- HEADER -->
        <div class="header">
            <div class="order-id">ORDER #{{order_id}}</div>
            <div class="main-amount">Rp {{total_transfer}}</div>
            <div class="amount-note">Total Tagihan (Tanpa Biaya Admin)</div>
        </div>

        <div class="content">
            <!-- VIEW 1: LIST -->
            <div id="view-list">
                <div class="section-label">Pilih Metode Pembayaran</div>
                <div id="bank-container"></div>
            </div>

            <!-- VIEW 2: DETAIL -->
            <div id="view-detail" class="detail-view">
                <button class="btn-back" onclick="goBack()">← Ganti Metode</button>
                <div id="detail-container"></div>
                <div style="text-align: center; margin: 20px 0; font-size: 12px; color: var(--border-color)">● ● ●</div>
                <!--
                <button class="btn-help" onclick="window.location.href= urlOlshop + '?konfirmasi_manual_dari_override=true'">Kendala Pembayaran? Konfirmasi Manual</button>
                -->
            </div>
        </div>
    </div>

    <div id="toast" class="toast">Berhasil disalin!</div>

    <script>
        const banks = {{bank_data_json}}; 
        const token = '{{token_js}}';
        
        // GUNAKAN API URL YANG DISUNTIKKAN DARI PHP AGAR STABIL DI WEBVIEW
        const apiUrl = '{{api_url}}'; 

        function init() {
            const container = document.getElementById('bank-container');
            container.innerHTML = '';
            banks.forEach((b, idx) => {
                let feeText = '';
                if(b.fee > 0) feeText = `<div class="fee-badge">+Admin Rp ${parseInt(b.fee).toLocaleString('id-ID')}</div>`;
                const html = `
                <div class="bank-item" onclick="selectBank(${idx})">
                    <div class="bank-logo">${b.is_qris ? 'QR' : b.logo_char}</div>
                    <div class="bank-info"><div class="bank-name">${b.name}</div>${feeText}</div>
                    <div class="arrow">›</div>
                </div>`;
                container.insertAdjacentHTML('beforeend', html);
            });
        }

        async function selectBank(idx) {
            const b = banks[idx];
            const loading = document.getElementById('loading');
            
            // 1. UPDATE SERVER DB
            loading.classList.remove('hidden');
            try {
                // GUNAKAN API URL ABSOLUT
                const res = await fetch(apiUrl + '?action=select_method', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ token: token, bank_id: b.id, bank_name: b.name })
                });
                
                // Cek jika response bukan JSON (biasanya error 404/500 dalam bentuk HTML)
                const contentType = res.headers.get("content-type");
                if (!contentType || !contentType.includes("application/json")) {
                   // Coba ambil text errornya
                   const text = await res.text();
                   console.log("Server Error HTML:", text);
                   throw new Error("Server Response Not JSON (" + res.status + ")");
                }
                
                const data = await res.json();
                
                if(!data.status) {
                    alert('Gagal memilih metode: ' + (data.message || 'Unknown'));
                    loading.classList.add('hidden');
                    return;
                }
                
                renderDetail(b, data.new_total, data.new_total_fmt, data.fee);
                
            } catch(e) {
                console.error(e);
                // Tampilkan pesan error spesifik agar tahu masalahnya apa (misal: Failed to fetch, Network Error, dll)
                alert('Error: ' + e.message + '\nURL: ' + apiUrl);
            }
            loading.classList.add('hidden');
        }

        function renderDetail(b, totalRaw, totalFmt, feeRaw) {
            const detailDiv = document.getElementById('detail-container');
            let visual = '';
            
            if (b.is_qris) {
                const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&margin=10&data=${encodeURIComponent(b.qris_data)}`;
                visual = `
                <div class="payment-box">
                    <div class="section-label" style="text-align:center">Scan QRIS (${b.owner})</div>
                    <img src="${qrUrl}" class="qris-img">
                    <div style="font-size:11px; color:var(--text-gray)">Scan menggunakan E-Wallet/Mobile Banking</div>
                </div>`;
            } else {
                visual = `
                <div class="payment-box" style="text-align:left">
                    <div class="field"><div class="field-label">Bank Tujuan</div><div class="field-wrap"><span class="field-val" style="font-size:14px">${b.name}</span></div></div>
                    <div class="field"><div class="field-label">Nomor Rekening</div><div class="field-wrap"><span class="field-val">${b.account}</span><button class="btn-copy" onclick="copy('${b.account}')">SALIN</button></div></div>
                    <div class="field"><div class="field-label">Atas Nama</div><div class="field-wrap"><span class="field-val" style="font-size:14px;color:var(--text-gray)">${b.owner}</span></div></div>
                </div>`;
            }

            const totalBox = `
            <div class="total-box">
                <div class="field-label" style="color:#c2410c">TOTAL YANG HARUS DITRANSFER</div>
                <div class="total-val" onclick="copy('${totalRaw}')">Rp ${totalFmt} <span style="font-size:12px;cursor:pointer">❐</span></div>
                <div class="total-note">
                    Mohon transfer TEPAT hingga 3 digit terakhir.<br>
                    ${feeRaw > 0 ? `(Sudah termasuk biaya admin Rp ${parseInt(feeRaw).toLocaleString('id-ID')})` : ''}
                </div>
            </div>`;

            detailDiv.innerHTML = visual + totalBox;
            document.getElementById('view-list').classList.add('hidden');
            document.getElementById('view-detail').classList.remove('hidden');
            document.getElementById('view-detail').style.display = 'block';
        }

        function goBack() {
            document.getElementById('view-detail').style.display = 'none';
            document.getElementById('view-list').classList.remove('hidden');
        }

        function copy(text) {
            navigator.clipboard.writeText(text).then(() => {
                const t = document.getElementById('toast');
                t.classList.add('show');
                setTimeout(() => t.classList.remove('show'), 2000);
            });
        }

        init();
    </script>
</body>
</html>