<?php
// =========================================================================
// DEBUG.PHP - ALAT SUNTIK RIWAYAT TOPUP (Bypass Telegram & Fix Doniguard)
// =========================================================================

// BAGIAN BACKEND (Mengkoreksi log DoniGuard agar tanggalnya mundur/maju natural)
if (isset($_GET['action']) && $_GET['action'] == 'fix_doniguard') {
    header('Content-Type: application/json');
    $uid = $_POST['uid'] ?? '';
    $newDate = $_POST['new_date'] ?? ''; // Format: YYYY-MM-DD HH:MM:SS
    $file = 'user/' . $uid . '.txt';
    
    if (file_exists($file)) {
        $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if (!empty($lines)) {
            // Ambil baris terakhir yang baru saja di-push
            $lastIndex = count($lines) - 1;
            $lastLine = $lines[$lastIndex];
            
            // Ganti timestamp saat ini menjadi timestamp kustom yang dipilih Admin
            $modifiedLine = preg_replace('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/', $newDate, $lastLine);
            $lines[$lastIndex] = $modifiedLine;
            
            // Urutkan ulang berdasarkan tanggal agar tidak ketahuan disuntik belakangan
            usort($lines, function($a, $b) {
                preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/', $a, $ma);
                preg_match('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/', $b, $mb);
                $timeA = isset($ma[0]) ? strtotime($ma[0]) : 0;
                $timeB = isset($mb[0]) ? strtotime($mb[0]) : 0;
                return $timeA - $timeB;
            });

            // Timpa file dengan isi yang baru
            $newContent = implode("\n", $lines) . "\n";
            file_put_contents($file, $newContent);
            
            echo json_encode(["status" => "success", "msg" => "DoniGuard disesuaikan dan diurutkan."]);
            exit;
        }
    }
    echo json_encode(["status" => "error", "msg" => "File DoniGuard tidak ditemukan untuk user ini."]);
    exit;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Suntik Riwayat Topup</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { font-family: 'Segoe UI', sans-serif; background: #f1f5f9; padding: 20px; color: #333; }
        .container { max-width: 500px; margin: 0 auto; background: white; padding: 25px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border-top: 4px solid #10b981; }
        h2 { margin-top: 0; color: #0f172a; font-size: 20px; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; font-weight: 600; font-size: 13px; margin-bottom: 5px; color: #475569; }
        .form-control { width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px; box-sizing: border-box; font-size: 14px; background: #f8fafc; }
        .form-control:focus { outline: none; border-color: #10b981; }
        .btn { width: 100%; background: #10b981; color: white; border: none; padding: 12px; border-radius: 6px; font-weight: bold; cursor: pointer; margin-top: 10px; font-size: 14px; transition: 0.3s; }
        .btn:hover { background: #059669; }
        .btn:disabled { background: #9ca3af; cursor: not-allowed; }
        .alert { padding: 15px; border-radius: 6px; display: none; margin-bottom: 15px; font-size: 13px; font-weight: 600; }
        .alert-success { background: #d1fae5; color: #065f46; border: 1px solid #34d399; }
        .alert-warning { background: #fef3c7; color: #92400e; border: 1px solid #fbbf24; }
    </style>
</head>
<body>

<div class="container">
    <h2><i class="fas fa-syringe"></i> Suntik Riwayat Topup</h2>
    <p style="font-size: 12px; color: #64748b; margin-bottom: 20px;">Mode senyap aktif. 100% identik dengan riwayat asli. Tidak memicu Bot Telegram.</p>
    
    <div id="msg" class="alert"></div>

    <div class="form-group">
        <label>Pilih User target</label>
        <select id="userSelect" class="form-control">
            <option value="">Memeriksa Otorisasi Login...</option>
        </select>
    </div>

    <div class="form-group">
        <label>Metode Topup (Contoh: DANA, BCA, QRIS_AUTO)</label>
        <input type="text" id="metodeTopup" class="form-control" placeholder="Contoh: QRIS_AUTO">
    </div>

    <div class="form-group">
        <label>Nominal Topup (Rp)</label>
        <input type="number" id="nominalTopup" class="form-control" placeholder="Contoh: 50000">
    </div>

    <div class="form-group">
        <label>Tanggal & Jam Injeksi</label>
        <input type="datetime-local" id="tanggalTopup" class="form-control">
    </div>

    <div class="form-group">
        <label>Status Saldo User</label>
        <select id="tambahSaldo" class="form-control">
            <option value="tidak">Hanya buat riwayat (Saldo tidak ditambah)</option>
            <option value="ya">Tambahkan nominal ini ke saldo user sekarang</option>
        </select>
    </div>

    <button class="btn" id="btnSuntik" onclick="suntikRiwayat()" disabled><i class="fas fa-lock"></i> MENUNGGU AUTH...</button>
</div>

<script type="module">
    import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js";
    import { getFirestore, collection, addDoc, getDocs, doc, updateDoc } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore.js";
    import { getAuth, onAuthStateChanged } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js";

    // Konfigurasi Firebase
    const firebaseConfig = {
        apiKey: "AIzaSyDYj0BA6cZDUxNBA7lmxBoXzah7H4y8yu4",
        authDomain: "pandawa-store.firebaseapp.com",
        projectId: "pandawa-store",
        storageBucket: "pandawa-store.firebasestorage.app",
        messagingSenderId: "974440930132",
        appId: "1:974440930132:web:57fcb857cfd5ac51b386c1"
    };

    const app = initializeApp(firebaseConfig);
    const db = getFirestore(app);
    const auth = getAuth(app);
    let usersData = {};

    // 1. Cek Sesi Login Admin (Sesuai dengan Rules Firestore Baru)
    onAuthStateChanged(auth, (user) => {
        const btnSuntik = document.getElementById("btnSuntik");
        const msgBox = document.getElementById("msg");

        if (user) {
            btnSuntik.innerHTML = '<i class="fas fa-check-circle"></i> SUNTIK KE DATABASE';
            btnSuntik.disabled = false;
            loadUsers();
        } else {
            msgBox.style.display = "block";
            msgBox.className = "alert alert-warning";
            msgBox.innerHTML = "<i class='fas fa-exclamation-triangle'></i> Anda belum login! Akses ke database diblokir. Silakan login ke Panel Admin di tab sebelah, lalu refresh halaman ini.";
            document.getElementById("userSelect").innerHTML = '<option value="">Akses Ditolak</option>';
        }
    });

    // 2. Load Data User untuk dropdown
    async function loadUsers() {
        try {
            const querySnapshot = await getDocs(collection(db, "users"));
            const select = document.getElementById("userSelect");
            select.innerHTML = '<option value="">-- Pilih User --</option>';
            
            querySnapshot.forEach((docSnap) => {
                const data = docSnap.data();
                usersData[docSnap.id] = data;
                const opt = document.createElement("option");
                opt.value = docSnap.id;
                opt.text = `${data.nama || data.username || 'User'} (${data.email}) - Saldo: Rp ${data.saldo || 0}`;
                select.add(opt);
            });
        } catch (error) {
            console.error("Gagal memuat user:", error);
            alert("Gagal memuat data user. Pastikan akun yang login memiliki hak Admin.");
        }
    }

    // 3. Fungsi Utama Injeksi
    window.suntikRiwayat = async function() {
        const uid = document.getElementById("userSelect").value;
        const metode = document.getElementById("metodeTopup").value;
        const nominal = parseInt(document.getElementById("nominalTopup").value);
        const tglInput = document.getElementById("tanggalTopup").value;
        const isTambahSaldo = document.getElementById("tambahSaldo").value === "ya";

        if (!uid || !metode || !nominal || !tglInput) {
            alert("Harap lengkapi semua kolom (User, Metode, Nominal, Tanggal)!"); return;
        }

        const btn = document.getElementById("btnSuntik");
        const msgBox = document.getElementById("msg");
        btn.innerHTML = "Memproses Injeksi...";
        btn.disabled = true;
        msgBox.style.display = "none";

        try {
            const userData = usersData[uid];
            const customDate = new Date(tglInput);
            
            // Format waktu spesifik untuk disisipkan ke file txt DoniGuard (YYYY-MM-DD HH:MM:SS)
            const yy = customDate.getFullYear();
            const mm = String(customDate.getMonth() + 1).padStart(2, '0');
            const dd = String(customDate.getDate()).padStart(2, '0');
            const hh = String(customDate.getHours()).padStart(2, '0');
            const mns = String(customDate.getMinutes()).padStart(2, '0');
            const ss = String(customDate.getSeconds()).padStart(2, '0');
            const dateDoniGuard = `${yy}-${mm}-${dd} ${hh}:${mns}:${ss}`;

            let saldoAkhirClient = parseInt(userData.saldo) || 0;

            // A. Update Saldo User (Opsional)
            if (isTambahSaldo) {
                saldoAkhirClient += nominal;
                await updateDoc(doc(db, "users", uid), { saldo: saldoAkhirClient });
            }

            // B. Injeksi ke Firestore (Struktur dijamin 100% sama dengan asli)
            const idTrx = "TU" + Math.floor(customDate.getTime() / 1000); 
            
            await addDoc(collection(db, "users", uid, "riwayat_transaksi"), {
                uid: uid,
                username: userData.username || userData.nama || "-",
                tujuan: "Topup Saldo",
                produk: "Topup via " + metode,
                kode_produk: "TOPUP",
                harga: nominal,
                status: "BERHASIL",
                sn: "Topup Berhasil",
                trx_id: idTrx,
                unique_code: idTrx,
                metode: metode,
                metode_lengkap: {
                    code: metode,
                    name: metode,
                    type: "MANUAL",
                    fee: 0
                },
                timestamp: customDate 
            });

            // C. Trigger log DoniGuard standar (memakai waktu server saat ini)
            const dgPayload = {
                uid: uid,
                email: userData.email,
                trx_id: idTrx,
                action: 'topup',
                produk: 'TOPUP MANUAL ' + metode,
                nominal: nominal,
                saldo_akhir_client: saldoAkhirClient
            };

            await fetch('doniguard.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(dgPayload)
            });

            // D. Koreksi Tanggal di File txt DoniGuard melalui backend PHP
            const formData = new URLSearchParams();
            formData.append("uid", uid);
            formData.append("new_date", dateDoniGuard);

            await fetch('debug.php?action=fix_doniguard', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: formData
            });

            // Berhasil
            msgBox.className = "alert alert-success";
            msgBox.style.display = "block";
            msgBox.innerHTML = "<i class='fas fa-check'></i> Injeksi berhasil 100%! Silakan cek riwayat user di aplikasi atau Panel Admin.";
            
        } catch (e) {
            console.error(e);
            alert("Error Sistem: " + e.message);
        } finally {
            btn.innerHTML = '<i class="fas fa-check-circle"></i> SUNTIK KE DATABASE';
            btn.disabled = false;
        }
    }
</script>
</body>
</html>