<?php
// =========================================================================
// BACKEND PROXY (MENGAMANKAN API KEY KAJE STORE)
// =========================================================================
if (isset($_GET['api_action'])) {
    $apiKey = '8eb9026f46a9ebed7c3de2292bd6353fea402c2ae8328f04b728f879a963';
    $baseUrl = 'https://end.kaje-store.com';
    
    header('Content-Type: application/json');
    $action = $_GET['api_action'];
    $input = json_decode(file_get_contents('php://input'), true) ?: [];

    $endpoint = '';
    if ($action == 'get_otp') $endpoint = '/api/xl-auth/get-otp';
    elseif ($action == 'login_otp') $endpoint = '/api/xl-auth/login-otp';
    elseif ($action == 'login_sesi') $endpoint = '/api/xl-auth/login-sesi';
    elseif ($action == 'get_quota') $endpoint = '/api/xl-info/quotas';
    elseif ($action == 'get_balance') $endpoint = '/api/xl-info/balance';
    elseif ($action == 'list_package_otp') $endpoint = '/api/service/list-package-otp';
    elseif ($action == 'order_package_otp') $endpoint = '/api/service/order-package-otp';
    elseif ($action == 'check_status') $endpoint = '/api/info/trx-id';

    if ($endpoint) {
        $ch = curl_init($baseUrl . $endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($input));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'x-api-key: ' . $apiKey,
            'accept: application/json',
            'Content-Type: application/json'
        ]);
        $response = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);
        
        if ($err) {
            echo json_encode(['success' => false, 'message' => 'CURL Error: ' . $err]);
        } else {
            echo $response;
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Action Tidak Valid']);
    }
    exit;
}
?>

<style>
    .session-card { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 12px; padding: 12px; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 2px 4px rgba(0,0,0,0.02); }
    .session-info b { font-size: 14px; color: #1e293b; letter-spacing: 0.5px; }
    .session-actions { display: flex; gap: 8px; }
    .btn-session-login { background: var(--primary); color: white; border: none; padding: 6px 12px; border-radius: 6px; font-size: 11px; font-weight: bold; cursor: pointer; }
    .btn-session-del { background: #fee2e2; color: #ef4444; border: none; padding: 6px 10px; border-radius: 6px; font-size: 11px; cursor: pointer; }
    
    .filter-container { display: flex; gap: 10px; overflow-x: auto; padding-bottom: 10px; margin-bottom: 10px; scrollbar-width: none; -ms-overflow-style: none; }
    .filter-container::-webkit-scrollbar { display: none; }
    .filter-pill { background: #e2e8f0; color: #475569; padding: 8px 16px; border-radius: 20px; font-size: 11px; font-weight: bold; white-space: nowrap; cursor: pointer; border: 1px solid transparent; transition: 0.2s; }
    .filter-pill.active-type { background: var(--primary); color: white; box-shadow: 0 4px 10px rgba(30,58,138,0.3); }
    .filter-pill.active-category { background: #0ea5e9; color: white; box-shadow: 0 4px 10px rgba(14,165,233,0.3); }
</style>

<div class="header" style="padding-bottom:30px; margin-bottom:20px;">
    <div style="display:flex; justify-content:space-between; align-items:center;">
        <div style="font-weight:bold; font-size:20px; color:white;">Akrab Spesial</div>
        <i class="fas fa-times" onclick="tutupAkrabMenu()" style="color:white; font-size:20px; cursor:pointer;"></i>
    </div>
</div>

<div style="padding:0 20px;">
    <div class="prof-card" id="akrabAuthCard" style="margin:0; margin-bottom:20px;">
        <h4 style="margin-top:0; margin-bottom:15px; color:#1e3a8a;"><i class="fas fa-sign-in-alt"></i> Login Nomor Pelanggan</h4>
        <div class="input-group">
            <input type="tel" id="akrabNumber" class="form-input" placeholder="087xxxx (Nomor XL)" oninput="this.value = this.value.replace(/[^0-9]/g, '')">
            <i class="fas fa-mobile-alt"></i>
        </div>
        <button class="btn-konfirmasi" id="btnReqOtp" onclick="akrabMintaOtp()">Minta OTP</button>
        
        <div id="akrabOtpArea" style="display:none; margin-top:15px; border-top:1px dashed #eee; padding-top:15px;">
            <p style="font-size:11px; color:#666; margin-bottom:10px;">Cek SMS pada nomor tersebut lalu masukkan 6 digit kode OTP.</p>
            <div class="input-group">
                <input type="text" id="akrabOtpCode" class="form-input" placeholder="Masukkan Kode OTP" maxlength="6">
                <i class="fas fa-key"></i>
            </div>
            <button class="btn-konfirmasi" style="background:var(--success);" id="btnLoginOtp" onclick="akrabLoginOtp()">Login & Simpan Sesi</button>
        </div>

        <div id="akrabSavedArea" style="margin-top:25px; border-top:2px solid #f1f5f9; padding-top:15px;">
            <h5 style="margin-top:0; margin-bottom:12px; color:#64748b; font-size:12px; text-transform:uppercase; font-weight:bold;"><i class="fas fa-history"></i> Sesi Login Tersimpan</h5>
            <div id="akrabSessionList">
                <p style="font-size:11px; color:#94a3b8; text-align:center;">Memuat data sesi...</p>
            </div>
        </div>
    </div>

    <div id="akrabDashboard" style="display:none;">
        <div style="background:linear-gradient(135deg, #1e3a8a, #0f172a); color:white; padding:15px; border-radius:15px; margin-bottom:20px; box-shadow:0 5px 15px rgba(0,0,0,0.1);">
            <div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px dashed rgba(255,255,255,0.2); padding-bottom:10px; margin-bottom:10px;">
                <div>
                    <div style="font-size:10px; opacity:0.8;">Nomor Target</div>
                    <div style="font-weight:bold; font-size:16px; letter-spacing:1px;" id="akrabDashNumber">-</div>
                </div>
                <div style="text-align:right;">
                    <div style="font-size:10px; opacity:0.8;">Pulsa Tersedia</div>
                    <div style="font-weight:bold; font-size:16px; color:#f1c40f;" id="akrabDashPulsa"><i class="fas fa-spinner fa-spin"></i></div>
                </div>
            </div>
            <div style="font-size:11px; display:flex; justify-content:space-between; align-items:center;">
                <span>Masa Aktif: <b id="akrabDashExpired">-</b></span>
                <button onclick="kembaliKeDaftarSesi()" style="background:rgba(255,255,255,0.2); border:none; color:white; padding:5px 10px; border-radius:5px; font-size:10px; cursor:pointer;"><i class="fas fa-exchange-alt"></i> Ganti Nomor</button>
            </div>
        </div>

        <h4 style="margin-bottom:15px; color:#333;"><i class="fas fa-box-open"></i> Daftar Paket</h4>
        
        <div id="filterArea" style="display:none; margin-bottom:20px;">
            <div class="filter-container" id="typeFilters"></div>
            <div class="filter-container" id="categoryFilters"></div>
        </div>

        <div id="akrabPackageList">
            <div style="text-align:center; padding:20px; color:#999;"><i class="fas fa-circle-notch fa-spin"></i> Memuat daftar paket...</div>
        </div>
    </div>
</div>

<div id="modalAkrabConfirm" class="modal" style="display:none; position:fixed; z-index:99999; left:0; top:0; width:100%; height:100%; background-color:rgba(0,0,0,0.6); align-items:center; justify-content:center;">
    <div style="background:white; width:90%; max-width:380px; border-radius:15px; padding:20px; box-shadow:0 15px 30px rgba(0,0,0,0.3); position:relative;">
        <h3 style="margin-top:0; color:#1e3a8a; text-align:center; border-bottom:1px dashed #cbd5e1; padding-bottom:12px; margin-bottom:15px; font-size:18px;">Info Detail</h3>
        <div style="display:flex; justify-content:space-between; margin-bottom:10px;"><span style="color:#64748b; font-size:12px;">Nomor XL</span><strong id="modalAkrabNoXL" style="font-size:13px; color:#1e293b;">-</strong></div>
        <div style="display:flex; justify-content:space-between; margin-bottom:10px;"><span style="color:#64748b; font-size:12px;">Product</span><strong id="modalAkrabProduct" style="font-size:13px; color:#1e293b; text-align:right; max-width:60%;">-</strong></div>
        <div style="display:flex; justify-content:space-between; margin-bottom:10px; align-items:center;"><span style="color:#64748b; font-size:12px;">Metode Pembayaran</span><select id="modalPaymentMethod" onchange="updateModalPrice()"></select></div>
        <div style="display:flex; justify-content:space-between; margin-bottom:15px; align-items:center; background:#e6fffa; padding:8px 10px; border-radius:8px;"><span style="color:#00b894; font-size:12px; font-weight:bold;">Total Biaya</span><strong id="modalAkrabHarga" style="font-size:16px; color:var(--success);">-</strong></div>
        <div id="modalAkrabDesc" style="background:#f8fafc; padding:12px; border-radius:8px; font-size:11px; color:#475569; line-height:1.6; margin-bottom:15px; border:1px solid #e2e8f0; max-height:100px; overflow-y:auto;"></div>
        <div id="modalAkrabWarning" style="text-align:center; font-size:12px; font-weight:bold; color:#e74c3c; margin-bottom:20px; padding:8px; background:#fef2f2; border-radius:6px;"></div>
        <div style="display:flex; gap:10px;">
            <button onclick="tutupModalAkrab()" style="flex:1; padding:12px; border:none; border-radius:8px; background:#e2e8f0; color:#475569; font-weight:bold; cursor:pointer;">Batal</button>
            <button onclick="prosesTembakPaket()" style="flex:1; padding:12px; border:none; border-radius:8px; background:var(--primary); color:white; font-weight:bold; cursor:pointer;">Beli Sekarang</button>
        </div>
    </div>
</div>

<div id="floatingDebug" style="display:none; position:fixed; bottom:70px; right:15px; width:300px; max-height:350px; background:rgba(20,20,20,0.95); color:#0f0; z-index:999999; border-radius:8px; font-family:monospace; font-size:10px; flex-direction:column; box-shadow:0 10px 25px rgba(0,0,0,0.5); border:1px solid #333; backdrop-filter:blur(5px);">
    <div style="background:#333; padding:8px; border-radius:8px 8px 0 0; display:flex; justify-content:space-between; color:white; align-items:center;"><b><i class="fas fa-terminal"></i> Debug Console</b><button onclick="document.getElementById('floatingDebug').style.display='none'" style="background:#ff4757; color:white; border:none; border-radius:4px; cursor:pointer; padding:3px 8px; font-weight:bold;">X</button></div>
    <div id="debugContent" style="padding:10px; overflow-y:auto; flex:1; white-space:pre-wrap; word-break:break-all;"></div>
</div>
<button onclick="toggleDebug()" style="position:fixed; bottom:20px; right:20px; z-index:999998; background:#1e272e; color:#0fb9b1; border:2px solid #0fb9b1; padding:12px; border-radius:50%; box-shadow:0 4px 10px rgba(0,0,0,0.3); cursor:pointer;"><i class="fas fa-bug"></i></button>

<script>
    let currentXlNumber = '';
    const akrabUserId = localStorage.getItem('user_id') || 'guest_user';
    let allAkrabProducts = [];
    let selectedType = '';
    let selectedCategory = '';
    let pendingAkrabOrder = null;
    let isStatusMonitoring = false;

    function toggleDebug() { const el = document.getElementById('floatingDebug'); el.style.display = (el.style.display === 'none') ? 'flex' : 'none'; }
    function logDebug(action, data, status = "INFO") {
        const dbg = document.getElementById('debugContent');
        let color = status === "ERROR" ? "#ff4757" : (status === "SUCCESS" ? "#2ed573" : "#7bed9f");
        dbg.innerHTML += `<div style="margin-bottom:8px; border-bottom:1px dashed #444; padding-bottom:5px;"><span style="color:${color}; font-weight:bold;">[${status}] ${action}</span><br><span style="color:#dcdde1">${typeof data === 'object' ? JSON.stringify(data) : data}</span></div>`;
        dbg.scrollTop = dbg.scrollHeight;
    }

    function getAkrabUid() { return (window.auth && window.auth.currentUser) ? window.auth.currentUser.uid : null; }
    function getAkrabDb() { return (typeof window.db !== 'undefined') ? window.db : null; }

    function loadSavedSessions() {
        const activeDb = getAkrabDb(); const activeUid = getAkrabUid();
        if (!activeDb || !activeUid || typeof window.onSnapshot === 'undefined') { setTimeout(loadSavedSessions, 2000); return; }
        const sessionsCol = window.collection(activeDb, 'users', activeUid, 'akrab_sessions');
        window.onSnapshot(sessionsCol, (snapshot) => {
            const listArea = document.getElementById('akrabSessionList');
            if (snapshot.empty) { listArea.innerHTML = '<p style="font-size:11px; color:#94a3b8; text-align:center;">Tiada sesi tersimpan.</p>'; return; }
            let html = '';
            snapshot.forEach(doc => {
                html += `<div class="session-card"><div class="session-info"><b>${doc.id}</b></div><div class="session-actions"><button class="btn-session-login" onclick="akrabLoginSesi('${doc.id}')">LOGIN</button><button class="btn-session-del" onclick="hapusSesi('${doc.id}')"><i class="fas fa-trash"></i></button></div></div>`;
            });
            listArea.innerHTML = html;
        });
    }

    async function akrabMintaOtp() {
        const num = document.getElementById('akrabNumber').value;
        if (!num || num.length < 9) return alert('Nomor tidak valid!');
        window.showNotice('loading', 'Menghubungkan', 'Meminta OTP...');
        try {
            const req = await fetch('akrab_spesial.php?api_action=get_otp', { method: 'POST', body: JSON.stringify({ number: num }) });
            const res = await req.json();
            logDebug("API Minta OTP", res, res.success ? "SUCCESS" : "ERROR");
            if (res.success) { document.getElementById('akrabOtpArea').style.display = 'block'; currentXlNumber = num; window.showNotice('success', 'Berhasil', 'OTP Terkirim'); }
            else { window.showNotice('error', 'Gagal', res.message); }
        } catch (e) { window.showNotice('error', 'Error', 'Server tidak merespons.'); }
    }

    async function akrabLoginOtp() {
        const otp = document.getElementById('akrabOtpCode').value;
        if (!otp) return alert('Sila masukkan kod OTP!');
        window.showNotice('loading', 'Mengesahkan', 'Log masuk...');
        try {
            const req = await fetch('akrab_spesial.php?api_action=login_otp', { method: 'POST', body: JSON.stringify({ number: currentXlNumber, code_otp: otp }) });
            const res = await req.json();
            if (res.success) {
                const activeDb = getAkrabDb(); const activeUid = getAkrabUid();
                if (activeDb && activeUid) { const docRef = window.doc(activeDb, 'users', activeUid, 'akrab_sessions', currentXlNumber); window.setDoc(docRef, { active: true, saved_at: new Date().toISOString() }); }
                window.showNotice('success', 'Berhasil', 'Log masuk berjaya.');
                bukaDashboardAkrab();
            } else { window.showNotice('error', 'Gagal', 'OTP Salah'); }
        } catch (e) { window.showNotice('error', 'Error', 'Gagal memproses login.'); }
    }

    async function akrabLoginSesi(num) {
        window.showNotice('loading', 'Menyambung', 'Memuat sesi...');
        try {
            const req = await fetch('akrab_spesial.php?api_action=login_sesi', { method: 'POST', body: JSON.stringify({ number: num }) });
            const res = await req.json();
            if (res.success) { currentXlNumber = num; window.showNotice('success', 'Berhasil', 'Sesi aktif.'); bukaDashboardAkrab(); }
            else { window.showNotice('error', 'Gagal', 'Sesi kadaluarsa.'); }
        } catch (e) { window.showNotice('error', 'Error', 'Gagal menghubungkan sesi.'); }
    }

    function hapusSesi(num) {
        if(confirm('Hapus sesi nomor ' + num + '?')) {
            try { const docRef = window.doc(getAkrabDb(), 'users', getAkrabUid(), 'akrab_sessions', num); window.deleteDoc(docRef); } catch(e) {}
        }
    }

    function bukaDashboardAkrab() {
        document.getElementById('akrabAuthCard').style.display = 'none';
        document.getElementById('akrabDashboard').style.display = 'block';
        document.getElementById('akrabDashNumber').innerText = currentXlNumber;
        loadAkrabInfo(); 
        loadAkrabPackages(); // Panggil fungsi muat paket
        if(!isStatusMonitoring) startKajeStatusMonitor();
    }

    async function loadAkrabInfo() {
        try {
            const req = await fetch('akrab_spesial.php?api_action=get_balance', { method: 'POST', body: JSON.stringify({ number: currentXlNumber }) });
            const res = await req.json();
            if (res.success && res.data) {
                document.getElementById('akrabDashPulsa').innerText = res.data.remaining_text || 'Rp 0';
                document.getElementById('akrabDashExpired').innerText = res.data.expired_at || '-';
            }
        } catch (e) {}
    }

    // ==========================================
    // PERBAIKAN: SAFE LOADER DAFTAR PAKET
    // ==========================================
    async function loadAkrabPackages() {
        const listArea = document.getElementById('akrabPackageList');
        listArea.innerHTML = '<div style="text-align:center; padding:20px; color:#999;"><i class="fas fa-circle-notch fa-spin"></i> Sedang menarik produk dari pusat...</div>';
        
        try {
            const req = await fetch('akrab_spesial.php?api_action=list_package_otp', { method: 'POST', body: JSON.stringify({}) });
            const res = await req.json();
            logDebug("API Load Packages", res, res.success ? "SUCCESS" : "ERROR");

            if (res.success && res.data && (res.data.products || Array.isArray(res.data))) {
                // Support baik produk di dalam data.products atau data langsung berupa array
                allAkrabProducts = res.data.products || (Array.isArray(res.data) ? res.data : []);
                
                if(allAkrabProducts.length > 0) {
                    document.getElementById('filterArea').style.display = 'block';
                    renderTypeFilters();
                } else {
                    listArea.innerHTML = '<div style="text-align:center; padding:20px; color:#e74c3c;"><i class="fas fa-exclamation-circle"></i> Stok produk sedang kosong dari pusat.</div>';
                }
            } else {
                listArea.innerHTML = `<div style="text-align:center; padding:20px; color:#e74c3c;"><i class="fas fa-times-circle"></i> Gagal memuat: ${res.message || 'Respons tidak valid'}</div>`;
            }
        } catch (e) {
            logDebug("Load Packages Crash", e.message, "ERROR");
            listArea.innerHTML = '<div style="text-align:center; padding:20px; color:#e74c3c;"><i class="fas fa-wifi"></i> Gagal menghubungi server. Periksa koneksi atau API Key.</div>';
        }
    }

    function renderTypeFilters() {
        const types = [...new Set(allAkrabProducts.map(p => p.type).filter(Boolean))];
        if (types.length === 0) { renderFinalProducts(); return; }

        if (!types.includes(selectedType)) selectedType = types[0];
        let html = '';
        types.forEach(t => { html += `<button class="filter-pill ${t === selectedType ? 'active-type' : ''}" onclick="selectedType='${t}';renderTypeFilters()">${t}</button>`; });
        document.getElementById('typeFilters').innerHTML = html;
        renderCategoryFilters();
    }

    function renderCategoryFilters() {
        const filtered = allAkrabProducts.filter(p => p.type === selectedType);
        const cats = [...new Set(filtered.map(p => p.category).filter(Boolean))];
        if (cats.length === 0) { renderFinalProducts(); return; }

        if (!cats.includes(selectedCategory)) selectedCategory = cats[0];
        let html = '';
        cats.forEach(c => { html += `<button class="filter-pill ${c === selectedCategory ? 'active-category' : ''}" onclick="selectedCategory='${c}';renderCategoryFilters()">${c}</button>`; });
        document.getElementById('categoryFilters').innerHTML = html;
        renderFinalProducts();
    }

    function renderFinalProducts() {
        const listArea = document.getElementById('akrabPackageList');
        const final = allAkrabProducts.filter(p => {
            let matchType = selectedType ? p.type === selectedType : true;
            let matchCat = selectedCategory ? p.category === selectedCategory : true;
            return matchType && matchCat;
        });

        if (final.length === 0) {
            listArea.innerHTML = '<div style="text-align:center; padding:20px; color:#999;">Tidak ada produk di kategori ini.</div>';
            return;
        }

        let html = '';
        final.forEach(p => {
            let hPulsa = p.fee || 0;
            let hNon = (p.price && p.price.non_pulsa ? p.price.non_pulsa : 0) + hPulsa;
            html += `
            <div style="background:white; border-radius:12px; padding:15px; margin-bottom:12px; border:1px solid #eee; box-shadow:0 2px 5px rgba(0,0,0,0.02);">
                <div style="display:flex; justify-content:space-between; align-items:flex-start;">
                    <div style="flex:1"><b>${p.name}</b><br><small style="color:#95a5a6">Stok: ${p.stock}</small></div>
                    <div style="text-align:right">
                        <div style="font-size:10px; color:#e74c3c; font-weight:bold;">Pulsa: Rp ${hPulsa.toLocaleString()}</div>
                        <div style="font-size:10px; color:#27ae60; font-weight:bold; margin-top:2px;">Saldo: Rp ${hNon.toLocaleString()}</div>
                    </div>
                </div>
                <button class="btn-konfirmasi" style="padding:10px; margin-top:10px; font-size:12px;" onclick="bukaModalKonfirmasi('${encodeURIComponent(JSON.stringify(p))}')">
                    <i class="fas fa-shopping-cart"></i> Pilih Pembayaran
                </button>
            </div>`;
        });
        listArea.innerHTML = html;
    }

    function bukaModalKonfirmasi(data) {
        pendingAkrabOrder = JSON.parse(decodeURIComponent(data));
        document.getElementById('modalAkrabNoXL').innerText = currentXlNumber;
        document.getElementById('modalAkrabProduct').innerText = pendingAkrabOrder.name;
        const sel = document.getElementById('modalPaymentMethod'); sel.innerHTML = '';
        (pendingAkrabOrder.payment_methods || ['SALDO']).forEach(m => { let o = document.createElement('option'); o.value=m; o.text=m; sel.add(o); });
        updateModalPrice();
        document.getElementById('modalAkrabConfirm').style.display = 'flex';
    }

    function updateModalPrice() {
        const m = document.getElementById('modalPaymentMethod').value;
        let p = (m === 'PULSA') ? (pendingAkrabOrder.fee || 0) : ((pendingAkrabOrder.price?.non_pulsa || 0) + (pendingAkrabOrder.fee || 0));
        document.getElementById('modalAkrabHarga').innerText = 'Rp ' + p.toLocaleString();
        document.getElementById('modalAkrabWarning').innerText = `Memotong Saldo Sistem Rp ${p.toLocaleString()}`;
        pendingAkrabOrder.final_price = p;
    }

    function tutupModalAkrab() { document.getElementById('modalAkrabConfirm').style.display = 'none'; }

    async function prosesTembakPaket() {
        const p = pendingAkrabOrder; const method = document.getElementById('modalPaymentMethod').value; tutupModalAkrab();
        const db = getAkrabDb(); const uid = getAkrabUid();
        const price = p.final_price; const refId = "AKRAB-" + Math.floor(Date.now() / 1000);

        window.showNotice('loading', 'Memproses', 'Mengecek Saldo...');
        try {
            const userRef = window.doc(db, 'users', uid);
            const userSnap = await window.getDoc(userRef);
            let saldoSekarang = userSnap.data().saldo || 0;

            if (saldoSekarang < price) {
                await catatRiwayatFirebase(db, uid, refId, p.name, price, 'GAGAL', 'Saldo Kurang');
                return window.showNotice('error', 'Saldo Kurang', 'Saldo tidak cukup');
            }

            let saldoSisa = saldoSekarang - price;
            await window.updateDoc(userRef, { saldo: saldoSisa });
            if(window.triggerDoniGuard) window.triggerDoniGuard({ action:'transaksi', produk: 'Tembak XL: '+p.name, nominal: price, trx_id: refId, saldo_akhir_client: saldoSisa });

            await catatRiwayatFirebase(db, uid, refId, p.name, price, 'PENDING', 'Diproses Server');

            const req = await fetch('akrab_spesial.php?api_action=order_package_otp', { method: 'POST', body: JSON.stringify({ destination: currentXlNumber, ref_id: refId, code: p.code, payment: method }) });
            const res = await req.json();

            if (res.success) {
                let trxIdKaje = res.data?.trx_id || refId;
                await window.updateDoc(window.doc(db, 'users', uid, 'riwayat_transaksi', refId), { sn: "#" + trxIdKaje });
                window.showNotice('success', 'Terkirim', 'Transaksi sedang diproses pusat.');
            } else { throw new Error(res.message); }
        } catch (e) {
            logDebug("Order Error", e.message, "ERROR");
            refundAkrab(db, uid, refId, price, p.name, e.message);
        }
    }

    function startKajeStatusMonitor() {
        isStatusMonitoring = true;
        setInterval(async () => {
            const db = getAkrabDb(); const uid = getAkrabUid();
            if(!db || !uid) return;
            const q = window.query(window.collection(db, 'users', uid, 'riwayat_transaksi'), window.where("status", "==", "PENDING"));
            const snap = await window.getDocs(q);
            snap.forEach(async (docTrans) => {
                const data = docTrans.data();
                if (data.sn && data.sn.startsWith("#")) {
                    const trxIdClean = data.sn.replace("#", "");
                    const req = await fetch('akrab_spesial.php?api_action=check_status', { method: 'POST', body: JSON.stringify({ trx_id: trxIdClean }) });
                    const res = await req.json();
                    if (res.success && res.data) {
                        const newStatus = res.data.status.toLowerCase();
                        if (newStatus === 'success' || newStatus === 'sukses') {
                            await window.updateDoc(docTrans.ref, { status: 'BERHASIL', sn: res.data.serial_number || "", keterangan: res.data.message || "" });
                        } else if (newStatus === 'failed' || newStatus === 'gagal') {
                            refundAkrab(db, uid, docTrans.id, data.harga, data.judul, res.data.message || "");
                        }
                    }
                }
            });
        }, 7000);
    }

    async function refundAkrab(db, uid, refId, price, name, msg) {
        try {
            const userRef = window.doc(db, 'users', uid);
            const snap = await window.getDoc(userRef);
            let sAfter = (snap.data().saldo || 0) + price;
            await window.updateDoc(userRef, { saldo: sAfter });
            if(window.triggerDoniGuard) window.triggerDoniGuard({ action:'topup', produk: 'Refund: '+name, nominal: price, trx_id: refId+'-REF', saldo_akhir_client: sAfter });
            await window.updateDoc(window.doc(db, 'users', uid, 'riwayat_transaksi', refId), { status: 'GAGAL', keterangan: msg });
            window.showNotice('error', 'Gagal', 'Produk gagal diinject. Saldo telah direfund.');
        } catch(e) {}
    }

    async function catatRiwayatFirebase(db, uid, refId, prod, price, stat, ket) {
        const ref = window.doc(db, 'users', uid, 'riwayat_transaksi', refId);
        await window.setDoc(ref, { judul: prod, target: currentXlNumber, kategori: 'Akrab Spesial', harga: price, status: stat, keterangan: ket, waktu: new Date().toLocaleString('id-ID'), timestamp: new Date(), jenis: 'Pengeluaran', ref_id: refId, sn: '-' });
    }

    function kembaliKeDaftarSesi() { document.getElementById('akrabDashboard').style.display = 'none'; document.getElementById('akrabAuthCard').style.display = 'block'; }
    function tutupAkrabMenu() { if (typeof navSwitch === 'function') navSwitch('home'); }
    setTimeout(loadSavedSessions, 1500);
</script>