<?php
/**
 * Pandawa-Digital - Alat Restorasi & Injeksi Akun Sah
 * Mode: Full Migration (Tambahkan Baru & Update Existing)
 */
date_default_timezone_set('Asia/Jakarta');

$status_msg = "";
$status_type = "";
$sync_needed = false;
$process_logs = []; 
$users_to_sync = []; 

$profile_folder = 'user_profiles/';
if (!file_exists($profile_folder)) mkdir($profile_folder, 0777, true);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input_data = [];

    if (isset($_FILES['json_file']) && $_FILES['json_file']['error'] == 0) {
        $input_data = json_decode(file_get_contents($_FILES['json_file']['tmp_name']), true);
    } elseif (isset($_POST['uid'])) {
        $input_data = [$_POST];
    }

    if (is_array($input_data)) {
        foreach ($input_data as $item) {
            $uid = trim($item['Uid'] ?? $item['uid'] ?? '');
            $email = trim($item['Email'] ?? $item['email'] ?? '');
            $username = trim($item['Username'] ?? $item['username'] ?? '');
            $whatsapp = trim($item['WhatsApp'] ?? $item['whatsapp'] ?? '62000000');
            $saldo = (int)($item['Saldo'] ?? $item['saldo'] ?? 0);

            if (empty($uid)) continue;

            $file_path = $profile_folder . 'profil_' . $uid . '.json';
            $is_new = !file_exists($file_path);

            // SIMPAN / UPDATE PROFIL LOKAL
            $data_profil = [
                'uid' => $uid,
                'email' => $email,
                'username' => $username,
                'whatsapp' => $whatsapp,
                'saldo' => $saldo,
                'role' => 'user',
                'created_at' => $is_new ? date('Y-m-d H:i:s') : null,
                'updated_at' => date('Y-m-d H:i:s')
            ];
            file_put_contents($file_path, json_encode($data_profil, JSON_PRETTY_PRINT));

            // TEMBAK DONIGUARD (PENTING: Agar saldo muncul di Audit Trail Panel Admin)
            $url_doniguard = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . '/doniguard.php';
            $ch = curl_init($url_doniguard);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
                'uid' => $uid, 
                'action' => 'reset_balance', 
                'nominal' => $saldo, 
                'saldo_akhir_client' => $saldo,
                'produk' => 'RESTORASI_SISTEM'
            ]));
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            curl_exec($ch);
            curl_close($ch);

            $users_to_sync[] = $data_profil;
            $process_logs[] = [
                "uid" => $uid, 
                "status" => $is_new ? "NEW_ACCOUNT" : "UPDATED", 
                "msg" => $is_new ? "Berhasil Dibuat" : "Data Diperbarui"
            ];
        }
        $sync_needed = count($users_to_sync) > 0;
        $status_msg = "Restorasi Berhasil! Silakan tunggu proses sinkronisasi Cloud.";
        $status_type = "success";
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Restorasi Akun - Pandawa Digital</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-slate-900 text-slate-200 min-h-screen p-4 flex flex-col items-center">

    <div class="bg-slate-800 p-6 rounded-2xl shadow-2xl w-full max-w-md border border-slate-700 mb-6">
        <div class="text-center mb-6">
            <h2 class="text-xl font-bold text-white">Restorasi Pandawa</h2>
            <p class="text-[10px] text-emerald-400 uppercase tracking-widest font-bold">Migration Mode: Active</p>
        </div>

        <form method="POST" enctype="multipart/form-data" class="space-y-4">
            <div class="border-2 border-dashed border-emerald-600/30 bg-emerald-500/5 rounded-xl p-6 text-center hover:border-emerald-500 transition cursor-pointer" onclick="document.getElementById('fileInput').click()">
                <i class="fas fa-file-export text-3xl mb-2 text-emerald-500"></i>
                <p class="text-xs font-bold">Upload JSON untuk Restorasi</p>
                <input type="file" id="fileInput" name="json_file" accept=".json" class="hidden" onchange="this.form.submit()">
            </div>
            <button type="submit" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-bold py-3 rounded-xl shadow-lg transition">MULAI RESTORASI DATA</button>
        </form>
    </div>

    <div class="w-full max-w-md bg-black rounded-xl border border-slate-700 overflow-hidden shadow-2xl">
        <div class="bg-slate-800 px-4 py-2 border-b border-slate-700 flex justify-between items-center">
            <span class="text-[10px] font-bold text-slate-400"><i class="fas fa-terminal mr-2"></i>RESTORATION LOGS</span>
        </div>
        <div id="logConsole" class="p-4 h-64 overflow-y-auto font-mono text-[10px] space-y-1">
            <?php if (empty($process_logs)): ?>
                <div class="text-slate-600 italic">Menunggu file JSON...</div>
            <?php else: ?>
                <?php foreach ($process_logs as $log): ?>
                    <div class="flex justify-between border-b border-slate-800 pb-1">
                        <span class="text-slate-400"><?php echo $log['uid']; ?></span>
                        <span class="<?php echo $log['status'] == 'NEW_ACCOUNT' ? 'text-emerald-400' : 'text-blue-400'; ?> font-bold">
                            [<?php echo $log['status']; ?>]
                        </span>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($sync_needed): ?>
    <script type="module">
        import { initializeApp } from "https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js";
        import { getFirestore, doc, setDoc } 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 tetap sama sesuai file yang Anda berikan
        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, "AdminPanelApp");
        const auth = getAuth(app);
        const db = getFirestore(app);
        const users = <?php echo json_encode($users_to_sync); ?>;
        const logBox = document.getElementById('logConsole');

        onAuthStateChanged(auth, async (user) => {
            if (user) {
                for (const u of users) {
                    try {
                        // Paksa tulis ke Firestore
                        await setDoc(doc(db, "users", u.uid), u, { merge: true });
                        logBox.innerHTML += `<div class="text-emerald-400">> Firestore Sync: ${u.uid} DONE.</div>`;
                    } catch (e) {
                        logBox.innerHTML += `<div class="text-red-500">> Firestore Error: ${u.uid} FAIL.</div>`;
                    }
                    logBox.scrollTop = logBox.scrollHeight;
                }
                logBox.innerHTML += `<div class="text-white font-bold mt-2">RESTORASI SELESAI SEMPURNA!</div>`;
            } else {
                logBox.innerHTML += `<div class="text-red-500 font-bold">ERROR: Sesi Admin Tidak Ditemukan! Buka Panel Admin dulu di tab sebelah.</div>`;
            }
        });
    </script>
    <?php endif; ?>

</body>
</html>