<?php
session_start();
include 'config.php';

// ==========================================
// 0. SET TIMEZONE JAKARTA (WIB)
// ==========================================
date_default_timezone_set('Asia/Jakarta');

// ==========================================
// 1. CEK LOGIN SESSION
// ==========================================
if(!isset($_SESSION['user_id'])) { 
    header("Location: login.php"); exit();
}

$user_id = $_SESSION['user_id'];

// ==========================================
// 2. AMBIL DATA USER & SETTINGS
// ==========================================
// Ambil data user terbaru
$sql = "SELECT * FROM users WHERE id = $user_id";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $user = $result->fetch_assoc();
} else {
    session_unset(); session_destroy();
    header("Location: login.php?msg=session_expired"); exit();
}

// -------------------------------------------------------------------
// LOGIC: HITUNG KEDALAMAN DOWNLINE (MAX DEPTH FROM CURRENT USER)
// -------------------------------------------------------------------
$network_depth = 0; 
// Query Recursive CTE untuk menghitung kedalaman, membutuhkan MySQL 8.0+
$sql_depth = "
    WITH RECURSIVE DownlineTree AS (
        SELECT id, 1 AS depth
        FROM users
        WHERE upline_id = $user_id
        UNION ALL
        SELECT u.id, dt.depth + 1
        FROM users u
        INNER JOIN DownlineTree dt ON u.upline_id = dt.id
        WHERE dt.depth < 35 
    )
    SELECT MAX(depth) as max_depth FROM DownlineTree;
";

try {
    // Jalankan query hanya jika koneksi mendukung CTE
    if ($conn->server_version >= 80000) {
        $qDepth = $conn->query($sql_depth);
        if ($qDepth && $qDepth->num_rows > 0) {
            $rowD = $qDepth->fetch_assoc();
            $network_depth = $rowD['max_depth'] ? intval($rowD['max_depth']) : 0;
        }
    }
} catch (Exception $e) { $network_depth = 0; }

// Cek Status Upgrade Terakhir (Manual 500k)
$qUp = $conn->query("SELECT status FROM transactions WHERE user_id = $user_id AND type = 'upgrade_starter' ORDER BY id DESC LIMIT 1");
$upgrade_status = ($qUp->num_rows > 0) ? $qUp->fetch_assoc()['status'] : null;

// --- [UPDATED] AUTO UPGRADE KE PREMIUM (SELF OR DOWNLINE CHECK) ---
// Aturan: Jadi Premium jika BELI SENDIRI atau DOWNLINE LANGSUNG BELI
if (isset($user['role']) && $user['role'] !== 'premium') {
    $become_premium = false;

    // 1. Cek Pembelian Diri Sendiri
    $check_self = $conn->query("SELECT id FROM transactions WHERE user_id = $user_id AND type IN ('buy_stokis','buy_crowd','buy_crypto') AND status = 'success' LIMIT 1");
    if ($check_self && $check_self->num_rows > 0) {
        $become_premium = true;
    }

    // 2. Cek Pembelian Downline Langsung (Jika diri sendiri belum beli)
    if (!$become_premium) {
        $check_dl = $conn->query("SELECT t.id FROM transactions t 
                                  JOIN users u ON t.user_id = u.id 
                                  WHERE u.upline_id = $user_id 
                                  AND t.type IN ('buy_stokis','buy_crowd','buy_crypto') 
                                  AND t.status = 'success' 
                                  LIMIT 1");
        if ($check_dl && $check_dl->num_rows > 0) {
            $become_premium = true;
        }
    }

    // 3. Eksekusi Update Role
    if ($become_premium) {
        $conn->query("UPDATE users SET role = 'premium' WHERE id = $user_id");
        $user['role'] = 'premium'; // Update variable agar UI langsung berubah
    }
}

// Ambil Settings System
$settings = [];
$qSet = $conn->query("SELECT * FROM settings");
while ($r = $qSet->fetch_assoc()) $settings[$r['setting_key']] = $r['setting_value'];

// Default Values
$fee_send_pct = isset($settings['fee_send_percent']) ? floatval($settings['fee_send_percent']) : 2.5;
$fee_swap_pct = isset($settings['fee_swap_percent']) ? floatval($settings['fee_swap_percent']) : 2.5;
$fee_wd_pct   = isset($settings['fee_withdraw_percent']) ? floatval($settings['fee_withdraw_percent']) : 2.5;
$withdraw_active = isset($settings['withdraw_status']) ? $settings['withdraw_status'] : 'on'; // STATUS WD (ON/OFF)

// APY Settings
$apy_staking = isset($settings['apy_staking']) ? $settings['apy_staking'] : 7.5;
$apy_mining  = isset($settings['apy_mining']) ? $settings['apy_mining'] : 7.0;
$apy_earning = isset($settings['apy_earning']) ? $settings['apy_earning'] : 7.0;

$company_wallet = isset($settings['company_wallet_address']) ? $settings['company_wallet_address'] : 'TBA';
$company_qr = isset($settings['company_wallet_qr']) ? $settings['company_wallet_qr'] : '';

// Helper Rupiah
if(!function_exists('formatRupiah')){
    function formatRupiah($angka){ return "Rp " . number_format($angka,0,',','.'); }
}

// ==========================================
// 3. LOGIC TRANSAKSI (HANDLER)
// ==========================================

// A. HANDLE MARK MESSAGES AS READ (AJAX)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'mark_read') {
    $qUnread = $conn->query("SELECT id FROM admin_messages WHERE id NOT IN (SELECT message_id FROM message_reads WHERE user_id = $user_id)");
    while($rowMsg = $qUnread->fetch_assoc()) {
        $msgId = $rowMsg['id'];
        $conn->query("INSERT IGNORE INTO message_reads (user_id, message_id) VALUES ($user_id, $msgId)");
    }
    echo "ok"; exit();
}

// B. HANDLE TOP UP
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'topup') {
    $amount = $_POST['amount'];
    $method = $_POST['method'];
    $proof = ""; 
    
    if(!isset($_FILES['proof']['name']) || empty($_FILES['proof']['name'])) {
        $_SESSION['flash'] = "Gagal: Bukti Transfer Wajib Diupload!";
        header("Location: dashboard.php"); exit();
    }
    
    // Pastikan folder uploads ada
    if (!file_exists("uploads/")) { mkdir("uploads/", 0777, true); }

    if($_FILES['proof']['error'] == 0) { 
        $proof = "topup_" . time() . "_" . $user_id . "." . pathinfo($_FILES['proof']['name'], PATHINFO_EXTENSION);
        move_uploaded_file($_FILES['proof']['tmp_name'], "uploads/" . $proof);
    } else {
        $_SESSION['flash'] = "Gagal: Error saat upload file.";
        header("Location: dashboard.php"); exit();
    }
    
    $desc = "Deposit via $method";
    $stmt = $conn->prepare("INSERT INTO transactions (user_id, type, amount, status, description, proof_image, created_at) VALUES (?, 'topup', ?, 'pending', ?, ?, NOW())");
    $stmt->bind_param("idss", $user_id, $amount, $desc, $proof);
    $stmt->execute();
    
    $_SESSION['flash'] = "Permintaan Top Up dikirim! Menunggu konfirmasi.";
    header("Location: dashboard.php"); exit();
}

// C. HANDLE SEND MONEY
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'send') {
    $target_user = $conn->real_escape_string($_POST['username']);
    $amount = floatval($_POST['amount']);
    $fee = $amount * ($fee_send_pct / 100);
    $total_deduct = $amount + $fee;

    $check = $conn->query("SELECT id FROM users WHERE username = '$target_user'");
    if ($check->num_rows > 0) {
        $target_id = $check->fetch_assoc()['id'];
        if ($user['balance_idr'] >= $total_deduct) {
            $conn->begin_transaction();
            try {
                $conn->query("UPDATE users SET balance_idr = balance_idr - $total_deduct WHERE id = $user_id");
                $conn->query("UPDATE users SET balance_idr = balance_idr + $amount WHERE id = $target_id");
                
                $desc_sender = "Transfer ke $target_user (Fee $fee_send_pct% : ".formatRupiah($fee).")";
                $conn->query("INSERT INTO transactions (user_id, type, amount, status, description, created_at) VALUES ($user_id, 'transfer_out', $total_deduct, 'success', '$desc_sender', NOW())"); // Simpan total deduct
                $conn->query("INSERT INTO transactions (user_id, type, amount, status, description, created_at) VALUES ($target_id, 'transfer_in', $amount, 'success', 'Terima dari ".$user['username']."', NOW())");
                $conn->commit();
                $_SESSION['flash'] = "Transfer Berhasil!";
            } catch (Exception $e) { $conn->rollback(); $_SESSION['flash'] = "Gagal: Kesalahan Sistem. ".$e->getMessage(); }
        } else { $_SESSION['flash'] = "Gagal: Saldo tidak mencukupi."; }
    } else { $_SESSION['flash'] = "Gagal: Username tujuan tidak ditemukan."; }
    header("Location: dashboard.php"); exit();
}

// D. HANDLE SWAP (FIXED: Update balance_usd)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'swap') {
    $amount = floatval($_POST['amount']);
    $fee = $amount * ($fee_swap_pct / 100);
    $total_deduct = $amount + $fee;
    $rate = 16000;  
    $crypto_result = $amount / $rate; // USDT conversion

    if ($user['balance_idr'] >= $total_deduct) {
        $conn->begin_transaction();
        try {
            $conn->query("UPDATE users SET balance_idr = balance_idr - $total_deduct WHERE id = $user_id");
            
            // FIX: Tambahkan saldo USD/Crypto ke wallet
            $conn->query("UPDATE users SET balance_usd = balance_usd + $crypto_result WHERE id = $user_id");
            
            $desc = "Swap IDR ke USDT (".number_format($crypto_result, 2).") (Fee $fee_swap_pct% : ".formatRupiah($fee).")";
            $conn->query("INSERT INTO transactions (user_id, type, amount, status, description, created_at) VALUES ($user_id, 'swap', $total_deduct, 'success', '$desc', NOW())");
            $conn->commit();
            $_SESSION['flash'] = "Swap Berhasil! +".number_format($crypto_result, 2)." USDT";
        } catch (Exception $e) { $conn->rollback(); $_SESSION['flash'] = "Gagal: Kesalahan Sistem."; }
    } else { $_SESSION['flash'] = "Gagal: Saldo tidak cukup."; }
    header("Location: dashboard.php"); exit();
}

// E. HANDLE WITHDRAW (Backend Check - Double Security)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'withdraw') {
    
    // CEK STATUS DARI SETTINGS (Double Check di PHP)
    if ($withdraw_active == 'off') {
        $_SESSION['flash'] = "Gagal: Withdraw sedang mengalami gangguan, silahkan mencoba kembali beberapa saat kedepan";
        header("Location: dashboard.php"); exit();
    }

    $amount = floatval($_POST['amount']);
    $bank_name = $conn->real_escape_string($_POST['bank_name']);
    $acc_number = $conn->real_escape_string($_POST['acc_number']);
    $acc_name = $conn->real_escape_string($_POST['acc_name']);
    $fee = $amount * ($fee_wd_pct / 100);
    $total_deduct = $amount + $fee;

    if ($user['balance_idr'] >= $total_deduct) {
        $conn->query("UPDATE users SET balance_idr = balance_idr - $total_deduct WHERE id = $user_id");
        $desc = "Withdraw ke $bank_name ($acc_number a.n $acc_name). Fee: ".formatRupiah($fee);
        $conn->query("INSERT INTO transactions (user_id, type, amount, status, description, created_at) VALUES ($user_id, 'withdraw', $amount, 'pending', '$desc', NOW())");
        $_SESSION['flash'] = "Permintaan Withdraw Dikirim! Menunggu Admin.";
    } else {
        $_SESSION['flash'] = "Gagal: Saldo tidak cukup (Perlu ".formatRupiah($total_deduct).")";
    }
    header("Location: dashboard.php"); exit();
}

// F. HANDLE BUY PROJECT
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'buy_project') {
    $p_category = $_POST['category']; 
    $p_name = $_POST['package_name'];
    $amount = floatval($_POST['amount']);
    $duration = $_POST['duration']; 
    $pay_method = $_POST['payment_method']; 
    
    if ($amount <= 0) { 
        $_SESSION['flash'] = "Gagal: Nominal tidak valid. Pilih paket atau input nominal."; 
        header("Location: dashboard.php"); exit(); 
    }

    $type_db = "";
    if ($p_category == 'Stokis') $type_db = 'buy_stokis';
    elseif ($p_category == 'Crowd') $type_db = 'buy_crowd';
    elseif ($p_category == 'Crypto') $type_db = 'buy_crypto';
    else $type_db = 'buy_other';

    $proof = "";
    $status = "pending";
    $desc = "Beli $p_category: $p_name ($duration). Via $pay_method";

    if ($pay_method == 'saldo') {
        if ($user['balance_idr'] >= $amount) {
            $conn->query("UPDATE users SET balance_idr = balance_idr - $amount WHERE id = $user_id");
            $status = "pending"; 
            $desc .= " (Potong Saldo)";
        } else {
            $_SESSION['flash'] = "Gagal: Saldo Utama tidak mencukupi.";
            header("Location: dashboard.php"); exit();
        }
    } else {
        // Transfer / QR
        if (!file_exists("uploads/")) { mkdir("uploads/", 0777, true); }
        if(isset($_FILES['proof']['name']) && $_FILES['proof']['error'] == 0) { 
            $proof = "buy_" . strtolower($p_category) . "_" . time() . "_" . $user_id . "." . pathinfo($_FILES['proof']['name'], PATHINFO_EXTENSION);
            move_uploaded_file($_FILES['proof']['tmp_name'], "uploads/" . $proof);
        } else {
            $_SESSION['flash'] = "Gagal: Bukti transfer wajib diupload.";
            header("Location: dashboard.php"); exit();
        }
    }
    
    $stmt = $conn->prepare("INSERT INTO transactions (user_id, type, amount, status, description, proof_image, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
    $stmt->bind_param("isdsss", $user_id, $type_db, $amount, $status, $desc, $proof);
    
    if($stmt->execute()) { $_SESSION['flash'] = "Pembelian $p_category Berhasil diajukan! Menunggu Approval Admin."; } 
    else { $_SESSION['flash'] = "Gagal Sistem: " . $conn->error; }
    
    header("Location: dashboard.php"); exit();
}

// G. HANDLE UPGRADE LEVEL (500k)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'upgrade_level') {
    $amount = 500000; 
    $pay_method = $_POST['payment_method'];
    
    $proof = "";
    $status = "pending";
    $desc = "Upgrade Level (500k). Via $pay_method";

    if ($pay_method == 'saldo') {
        if ($user['balance_idr'] >= $amount) {
            $conn->query("UPDATE users SET balance_idr = balance_idr - $amount WHERE id = $user_id");
            $status = "pending";
            $desc .= " (Potong Saldo)";
        } else {
            $_SESSION['flash'] = "Gagal: Saldo Utama tidak mencukupi.";
            header("Location: dashboard.php"); exit();
        }
    } else {
        if (!file_exists("uploads/")) { mkdir("uploads/", 0777, true); }
        if(isset($_FILES['proof']['name']) && $_FILES['proof']['error'] == 0) { 
            $proof = "upgrade_" . time() . "_" . $user_id . "." . pathinfo($_FILES['proof']['name'], PATHINFO_EXTENSION);
            move_uploaded_file($_FILES['proof']['tmp_name'], "uploads/" . $proof);
        } else {
            $_SESSION['flash'] = "Gagal: Bukti transfer wajib diupload.";
            header("Location: dashboard.php"); exit();
        }
    }
    
    $stmt = $conn->prepare("INSERT INTO transactions (user_id, type, amount, status, description, proof_image, created_at) VALUES (?, 'upgrade_starter', ?, ?, ?, ?, NOW())");
    $stmt->bind_param("idsss", $user_id, $amount, $status, $desc, $proof);
    
    if($stmt->execute()) { $_SESSION['flash'] = "Upgrade Level Diajukan! Menunggu Approval Admin."; } 
    else { $_SESSION['flash'] = "Gagal Sistem: " . $conn->error; }
    
    header("Location: dashboard.php"); exit();
}

// H. HANDLE UPDATE PROFILE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'update_profile') {
    $fullname = $conn->real_escape_string($_POST['full_name']);
    $email = $conn->real_escape_string($_POST['email']);
    $phone = $conn->real_escape_string($_POST['phone']);
    $bank_name = $conn->real_escape_string($_POST['bank_name']);
    if(isset($_POST['custom_bank']) && !empty($_POST['custom_bank'])) { $bank_name = $conn->real_escape_string($_POST['custom_bank']); }
    $acc_number = $conn->real_escape_string($_POST['acc_number']);
    $acc_name = $conn->real_escape_string($_POST['acc_name']);
    
    // Ambil nilai wallet yang mungkin null
    $wallet_trc20 = isset($_POST['wallet_trc20']) ? $conn->real_escape_string($_POST['wallet_trc20']) : $user['wallet_trc20'];
    $wallet_bnb20 = isset($_POST['wallet_bnb20']) ? $conn->real_escape_string($_POST['wallet_bnb20']) : $user['wallet_bnb20'];

    $pass_sql = "";
    if(!empty($_POST['password'])) {
        $new_pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $pass_sql = ", password = '$new_pass'";
    }

    $sql_update = "UPDATE users SET 
        full_name = '$fullname', email = '$email', phone = '$phone',
        bank_name = '$bank_name', acc_number = '$acc_number', acc_name = '$acc_name',
        wallet_trc20 = '$wallet_trc20', wallet_bnb20 = '$wallet_bnb20'
        $pass_sql WHERE id = $user_id";

    if ($conn->query($sql_update)) { $_SESSION['flash'] = "Profile Berhasil Disimpan!"; } 
    else { $_SESSION['flash'] = "Gagal Update: " . $conn->error; }
    header("Location: dashboard.php"); exit();
}


// ==========================================
// 4. UI & NOTIF
// ==========================================
$sql_bell = "SELECT COUNT(*) as total FROM transactions WHERE user_id = $user_id AND status = 'pending'";
$notif_bell = $conn->query($sql_bell)->fetch_assoc()['total'];

// UNREAD ADMIN MESSAGE
$sql_msg = "SELECT COUNT(*) as total FROM admin_messages m 
            WHERE NOT EXISTS (SELECT 1 FROM message_reads r WHERE r.message_id = m.id AND r.user_id = $user_id)";
$unread_msg = $conn->query($sql_msg)->fetch_assoc()['total']; 

// --- LOGIKA UCAPAN SALAM SESUAI JAM JAKARTA ---
$jam = date('H'); // Format 00-23
if ($jam >= 4 && $jam < 11) { 
    $salam = "Selamat Pagi"; 
    $icon_waktu = "fa-cloud-sun"; 
} elseif ($jam >= 11 && $jam < 15) { 
    $salam = "Selamat Siang"; 
    $icon_waktu = "fa-sun"; 
} elseif ($jam >= 15 && $jam < 19) { 
    $salam = "Selamat Sore"; 
    $icon_waktu = "fa-cloud-sun"; 
} else { 
    $salam = "Selamat Malam"; 
    $icon_waktu = "fa-moon"; 
}

// SweetAlert Session Flash
$swal_script = "";
if(isset($_SESSION['flash'])){
    $msg = $_SESSION['flash'];
    // Jika ada kata 'Gagal' atau 'gangguan', tampilkan error. Sisanya success.
    $type = (stripos($msg, 'gagal') !== false || stripos($msg, 'gangguan') !== false || stripos($msg, 'error') !== false) ? 'error' : 'success';
    $title = ($type == 'error') ? 'Gagal' : 'Berhasil!';
    $swal_script = "Swal.fire({ icon: '$type', title: '$title', text: '$msg', confirmButtonColor: '#10b981' });";
    unset($_SESSION['flash']);
}
$base_url = "http://" . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']) . "/register.php?ref=";
?>

<!DOCTYPE html>
<html lang="id" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Trust Style</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: { 
                extend: { 
                    colors: { primary: '#10b981', darkbg: '#0f172a' },
                    animation: { 'float': 'float 3s ease-in-out infinite', 'fadeIn': 'fadeIn 0.5s ease-out' },
                    keyframes: {
                        float: { '0%, 100%': { transform: 'translateY(0)' }, '50%': { transform: 'translateY(-5px)' } },
                        fadeIn: { '0%': { opacity: '0', transform: 'translateY(10px)' }, '100%': { opacity: '1', transform: 'translateY(0)' } }
                    }
                } 
            }
        }
    </script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <style>
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .marquee-container { overflow: hidden; white-space: nowrap; position: relative; }
        .marquee-content { display: inline-block; animation: marquee 25s linear infinite; }
        @keyframes marquee { 0% { transform: translateX(0); } 100% { transform: translateX(-50%); } }
    </style>
</head>
<body class="bg-gray-100 dark:bg-darkbg text-gray-800 dark:text-gray-200 transition-colors duration-300 font-sans" x-data="dashboardApp()">

    <div class="max-w-md mx-auto min-h-screen relative shadow-2xl bg-white dark:bg-slate-900 pb-28">
        
        <div class="p-6 pt-8 flex justify-between items-start bg-slate-800 text-white rounded-b-[2.5rem] shadow-lg pb-12 relative z-10">
            <div class="flex items-center gap-3 w-3/4">
                <div class="w-12 h-12 rounded-full bg-primary flex items-center justify-center font-bold shadow-md border-2 border-slate-600 relative overflow-hidden flex-shrink-0">
                    <?php if (!empty($user['avatar']) && file_exists("uploads/".$user['avatar'])): ?>
                        <img src="uploads/<?php echo $user['avatar']; ?>" class="w-full h-full object-cover">
                    <?php else: ?>
                        <span class="text-white text-lg"><?php echo strtoupper(substr($user['username'], 0, 1)); ?></span>
                    <?php endif; ?>
                </div>
                <div class="flex flex-col justify-center">
                    <p class="text-[10px] text-emerald-400 uppercase tracking-wider font-bold mb-0.5"><i class="fas <?php echo $icon_waktu; ?> mr-1"></i> <?php echo $salam; ?></p>
                    <p class="font-bold text-sm leading-tight break-words"><?php echo !empty($user['full_name']) ? $user['full_name'] : $user['username']; ?></p>
                    
                    <?php 
                        $role_badge = 'STARTER';
                        $badge_color = 'bg-gray-600 text-gray-200 border-gray-500';
                        if(isset($user['role']) && strtolower($user['role']) == 'premium') {
                            $role_badge = 'PREMIUM';
                            $badge_color = 'bg-yellow-500/20 text-yellow-300 border-yellow-500 animate-pulse';
                        }
                    ?>
                    <span class="mt-1 inline-block <?php echo $badge_color; ?> border text-[9px] font-bold px-2 py-0.5 rounded-full w-fit">
                        <i class="fas fa-crown mr-1"></i> <?php echo $role_badge; ?>
                    </span>
                    <span class="mt-1 text-[9px] text-gray-400 font-mono">Team Depth: <?php echo $network_depth; ?></span>
                </div>
            </div>
            <div class="flex items-center gap-4 mt-1 w-1/4 justify-end">
                <button onclick="openInbox()" class="relative text-gray-400 hover:text-white transition group">
                    <i class="fas fa-envelope text-2xl group-hover:scale-110 transition"></i>
                    <span x-show="unreadCount > 0" x-text="unreadCount" class="absolute -top-1 -right-1 bg-red-500 text-white text-[9px] font-bold px-1.5 py-0.5 rounded-full animate-bounce"></span>
                </button>
                <button onclick="showNotif()" class="relative text-gray-400 hover:text-white transition group">
                    <i class="fas fa-bell text-2xl group-hover:scale-110 transition"></i>
                    <?php if($notif_bell > 0): ?><span class="absolute -top-1 -right-1 bg-red-500 text-white text-[9px] font-bold px-1.5 py-0.5 rounded-full animate-pulse"><?php echo $notif_bell; ?></span><?php endif; ?>
                </button>
            </div>
        </div>

        <div class="px-5 mt-[-40px] relative z-20">
            <div class="bg-gradient-to-r from-[#11998e] to-[#38ef7d] rounded-3xl p-6 shadow-2xl text-white relative overflow-hidden ring-4 ring-white dark:ring-slate-900 transition-all duration-300 animate-[fadeIn_0.6s_ease-out]">
                <div class="absolute -right-10 -top-10 w-40 h-40 bg-white/20 rounded-full blur-3xl animate-pulse"></div>
                <div class="absolute -left-10 -bottom-10 w-32 h-32 bg-black/10 rounded-full blur-2xl"></div>
                <button @click="toggleCurrency()" class="absolute top-5 right-5 w-8 h-8 rounded-full bg-white/20 hover:bg-white/30 backdrop-blur-sm flex items-center justify-center transition active:scale-95 shadow-lg border border-white/10 z-30"><i class="fas fa-exchange-alt rotate-90 text-[10px]"></i></button>

                <div class="absolute top-16 right-5 z-30">
                    <?php if ($upgrade_status == 'success'): ?>
                             <button class="bg-green-500 text-white font-bold py-1 px-3 rounded-full shadow-lg border border-green-400 text-[10px] flex items-center gap-1 cursor-default">
                                 <i class="fas fa-check-circle"></i> UPGRADED
                             </button>
                    <?php else: ?>
                        <?php if ($network_depth >= 30): ?>
                            <button onclick="openModal('upgradeModal')" class="bg-red-500 hover:bg-red-600 text-white font-bold py-1 px-3 rounded-full shadow-lg border border-red-400 text-[10px] flex items-center gap-1 animate-pulse active:scale-95 transition">
                                <i class="fas fa-arrow-circle-up"></i> UPGRADE
                            </button>
                        <?php else: ?>
                            <button class="bg-gray-500 text-gray-300 font-bold py-1 px-3 rounded-full shadow border border-gray-400 text-[10px] flex items-center gap-1 cursor-not-allowed opacity-70" disabled>
                                <i class="fas fa-lock"></i> Depth: <?php echo $network_depth; ?>/30
                            </button>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>

                <div class="relative z-10 flex flex-col items-start text-left">
                    <p class="text-xs text-emerald-100 font-bold uppercase tracking-widest mb-2 flex items-center gap-2 bg-black/20 px-3 py-1 rounded-full"><i class="fas fa-shield-alt"></i> Main Wallet</p>
                    <div id="balanceContainer" class="mb-2 transition-all duration-500 w-full">
                        <div x-show="isIDR">
                            <h2 class="text-3xl font-bold tracking-tight drop-shadow-md"><?php echo formatRupiah($user['balance_idr']); ?></h2>
                            <p class="text-xs text-emerald-50 mt-1 opacity-90">≈ $ <span x-text="usdValIDR">0.00</span> USD</p> 
                        </div>
                        <div x-show="!isIDR" style="display: none;">
                            <h2 class="text-3xl font-bold tracking-tight drop-shadow-md">$ <span x-text="usdValUSD"><?php echo number_format($user['balance_usd'], 2) ?></span></h2>
                            <p class="text-xs text-emerald-50 mt-1 opacity-90">≈ Rp <span x-text="idrValUSD">0</span></p>
                        </div>
                    </div>
                    <div class="text-[9px] text-emerald-100/80 mb-3"><i class="fas fa-chart-line mr-1"></i> Rate: 1 USD = Rp <span x-text="rate">16,000</span></div>
                    
                    <button onclick="checkWithdraw()" class="bg-white/20 hover:bg-white/30 border border-white/40 text-white font-bold py-1.5 px-4 rounded-lg shadow-sm active:scale-95 transition flex items-center gap-2 text-xs backdrop-blur-sm">
                        <i class="fas fa-paper-plane transform -rotate-45 relative top-0.5"></i> Withdraw
                    </button>
                </div>
            </div>
        </div>

        <div class="px-6 mt-4 grid grid-cols-2 gap-4">
            <?php 
                $t_sponsor = $conn->query("SELECT SUM(amount) as t FROM transactions WHERE user_id=$user_id AND type='bonus_sponsor'")->fetch_assoc()['t'] ?? 0;
                $t_royalty = $conn->query("SELECT SUM(amount) as t FROM transactions WHERE user_id=$user_id AND type='bonus_royalty'")->fetch_assoc()['t'] ?? 0;
            ?>
            <div class="bg-white dark:bg-slate-800 p-3 rounded-2xl shadow-sm border border-emerald-100 dark:border-slate-700">
                <p class="text-[10px] text-gray-500 font-bold uppercase">Bonus Sponsor</p>
                <p class="font-bold text-emerald-500 text-sm"><?php echo formatRupiah($t_sponsor); ?></p>
            </div>
            <div class="bg-white dark:bg-slate-800 p-3 rounded-2xl shadow-sm border border-blue-100 dark:border-slate-700">
                <p class="text-[10px] text-gray-500 font-bold uppercase">Bonus Royalty</p>
                <p class="font-bold text-blue-500 text-sm"><?php echo formatRupiah($t_royalty); ?></p>
            </div>
        </div>

        <div class="grid grid-cols-4 gap-4 px-6 mt-6 text-center">
            <button onclick="openModal('sendModal')" class="flex flex-col items-center gap-2 group cursor-pointer">
                <div class="w-14 h-14 rounded-2xl bg-emerald-50 dark:bg-slate-800 flex items-center justify-center text-emerald-600 dark:text-emerald-400 group-hover:bg-emerald-500 group-hover:text-white transition shadow-sm border border-emerald-100 dark:border-slate-700"><i class="fas fa-paper-plane text-xl"></i></div>
                <span class="text-[11px] font-bold text-gray-600 dark:text-gray-400">Send</span>
            </button>
            <a href="qris.php" class="flex flex-col items-center gap-2 group cursor-pointer">
                <div class="w-14 h-14 rounded-2xl bg-blue-50 dark:bg-slate-800 flex items-center justify-center text-blue-600 dark:text-blue-400 group-hover:bg-blue-500 group-hover:text-white transition shadow-sm border border-blue-100 dark:border-slate-700"><i class="fas fa-qrcode text-xl"></i></div>
                <span class="text-[11px] font-bold text-gray-600 dark:text-gray-400">Receive</span>
            </a>
            <button onclick="openModal('swapModal')" class="flex flex-col items-center gap-2 group cursor-pointer">
                <div class="w-14 h-14 rounded-2xl bg-purple-50 dark:bg-slate-800 flex items-center justify-center text-purple-600 dark:text-purple-400 group-hover:bg-purple-500 group-hover:text-white transition shadow-sm border border-purple-100 dark:border-slate-700"><i class="fas fa-sync-alt text-xl"></i></div>
                <span class="text-[11px] font-bold text-gray-600 dark:text-gray-400">Swap</span>
            </button>
            <button onclick="openModal('topupModal')" class="flex flex-col items-center gap-2 group cursor-pointer">
                <div class="w-14 h-14 rounded-2xl bg-orange-50 dark:bg-slate-800 flex items-center justify-center text-orange-600 dark:text-orange-400 group-hover:bg-orange-500 group-hover:text-white transition shadow-sm border border-orange-100 dark:border-slate-700"><i class="fas fa-plus-circle text-xl"></i></div>
                <span class="text-[11px] font-bold text-gray-600 dark:text-gray-400">Top Up</span>
            </button>
        </div>

        <div class="px-6 mt-8">
            <div class="flex justify-between items-center mb-3">
                <h3 class="font-bold text-sm text-gray-700 dark:text-gray-300">Project Investment</h3>
                <span class="text-[10px] bg-emerald-100 text-emerald-600 px-2 py-0.5 rounded-full font-bold">Hot</span>
            </div>
            <div class="grid grid-cols-3 gap-3">
                <button onclick="openModal('modalStokis')" class="bg-white dark:bg-slate-800 p-3 py-4 rounded-2xl shadow-sm text-center border border-gray-100 dark:border-slate-700 hover:border-blue-400 cursor-pointer transition transform hover:-translate-y-1 group">
                    <div class="w-10 h-10 mx-auto bg-blue-50 dark:bg-blue-900/30 rounded-full flex items-center justify-center text-blue-500 mb-2 group-hover:scale-110 transition"><i class="fas fa-cubes text-lg"></i></div>
                    <p class="text-[10px] font-bold uppercase tracking-wide text-gray-600 dark:text-gray-300">Stokis</p>
                </button>
                <button onclick="openModal('modalCrowd')" class="bg-white dark:bg-slate-800 p-3 py-4 rounded-2xl shadow-sm text-center border border-gray-100 dark:border-slate-700 hover:border-purple-400 cursor-pointer transition transform hover:-translate-y-1 group">
                    <div class="w-10 h-10 mx-auto bg-purple-50 dark:bg-purple-900/30 rounded-full flex items-center justify-center text-purple-500 mb-2 group-hover:scale-110 transition"><i class="fas fa-users text-lg"></i></div>
                    <p class="text-[10px] font-bold uppercase tracking-wide text-gray-600 dark:text-gray-300">Crowd</p>
                </button>
                <button onclick="openModal('modalCrypto')" class="bg-white dark:bg-slate-800 p-3 py-4 rounded-2xl shadow-sm text-center border border-gray-100 dark:border-slate-700 hover:border-orange-400 cursor-pointer transition transform hover:-translate-y-1 group">
                    <div class="w-10 h-10 mx-auto bg-orange-50 dark:bg-orange-900/30 rounded-full flex items-center justify-center text-orange-500 mb-2 group-hover:scale-110 transition"><i class="fab fa-bitcoin text-lg"></i></div>
                    <p class="text-[10px] font-bold uppercase tracking-wide text-gray-600 dark:text-gray-300">Crypto</p>
                </button>
            </div>
        </div>

        <div class="px-6 mt-8">
            <h3 class="font-bold text-sm mb-3 text-gray-500 dark:text-gray-400">Info & Promo</h3>
            <div class="bg-slate-900 rounded-2xl p-0 shadow-lg relative overflow-hidden border border-slate-700">
                <div class="marquee-container h-40">
                    <div class="marquee-content flex h-full">
                        <?php 
                        $qBan = $conn->query("SELECT * FROM banners ORDER BY id DESC");
                        $banners = [];
                        while($rb = $qBan->fetch_assoc()) $banners[] = $rb;
                        for($i=0; $i<2; $i++):
                            if(count($banners) > 0):
                                foreach($banners as $rb): ?>
                                    <div class="w-[300px] h-full flex-shrink-0 relative">
                                        <img src="uploads/banners/<?php echo $rb['image']; ?>" class="w-full h-full object-cover opacity-80 hover:opacity-100 transition">
                                        <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent"></div>
                                    </div>
                                <?php endforeach; 
                            else: ?>
                                <div class="w-[300px] h-full bg-slate-800 flex items-center justify-center text-gray-500">No Banner</div>
                            <?php endif;
                        endfor; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="px-6 mt-8 mb-4">
            <h3 class="font-bold text-sm mb-3 text-gray-500 dark:text-gray-400">Undang Teman</h3>
            <div class="bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 rounded-2xl p-4 flex justify-between items-center shadow-sm relative overflow-hidden group">
                <div class="absolute -right-4 -bottom-4 text-emerald-50 dark:text-slate-700 opacity-50 transition transform group-hover:scale-110"><i class="fas fa-share-alt text-6xl"></i></div>
                <div class="relative z-10 w-full pr-4">
                    <p class="text-[10px] text-gray-400 mb-1 font-bold uppercase">Referral Code</p>
                    <div class="flex items-center gap-2 mb-1"><span class="font-mono font-bold text-2xl text-primary tracking-wider" id="refCode"><?php echo $user['referral_code']; ?></span></div>
                    <p class="text-[9px] text-gray-400 truncate w-full opacity-70 font-mono"><?php echo $base_url . $user['referral_code']; ?></p>
                </div>
                <button onclick="copyReferral()" class="relative z-10 w-12 h-12 rounded-xl bg-gray-50 dark:bg-slate-700 flex items-center justify-center text-gray-500 hover:bg-primary hover:text-white transition shadow-sm active:scale-95 border border-gray-100 dark:border-slate-600"><i class="fas fa-copy text-lg"></i></button>
            </div>
        </div>

        <?php $active_menu = 'home'; // Set aktif di Home ?>
        <div class="fixed bottom-0 w-full max-w-md bg-white dark:bg-slate-900 border-t border-gray-200 dark:border-slate-800 pb-4 pt-3 z-[99] rounded-t-2xl shadow-[0_-5px_20px_rgba(0,0,0,0.05)]">
            <div class="flex justify-around items-center px-2">
                
                <a href="dashboard.php" class="flex flex-col items-center group text-primary">
                    <div class="mb-1 transition-transform group-hover:-translate-y-1"><i class="fas fa-home text-xl"></i></div>
                    <span class="text-[10px] font-bold">Home</span>
                </a>
                
                <a href="network.php" class="flex flex-col items-center group text-gray-400 dark:text-slate-500 hover:text-primary">
                    <div class="mb-1 transition-transform group-hover:-translate-y-1"><i class="fas fa-sitemap text-xl"></i></div>
                    <span class="text-[10px]">Network</span>
                </a>
                
                <div class="relative -top-8">
                    <a href="qris.php" class="w-16 h-16 bg-gradient-to-br from-emerald-400 to-emerald-600 rounded-full flex items-center justify-center shadow-lg shadow-emerald-500/30 border-[6px] border-white dark:border-slate-900 text-white cursor-pointer hover:scale-105 transition transform">
                        <i class="fas fa-qrcode text-2xl"></i>
                    </a>
                </div>
                
                <a href="history.php" class="flex flex-col items-center group cursor-pointer text-gray-400 dark:text-slate-500 hover:text-primary">
                    <div class="mb-1 transition-transform group-hover:-translate-y-1"><i class="fas fa-history text-xl"></i></div>
                    <span class="text-[10px]">History</span>
                </a>
                
                <a href="profile.php" class="flex flex-col items-center group cursor-pointer text-gray-400 dark:text-slate-500 hover:text-primary">
                    <div class="mb-1 transition-transform group-hover:-translate-y-1"><i class="fas fa-user text-xl"></i></div>
                    <span class="text-[10px]">Profile</span>
                </a>
                
            </div>
        </div>


        <div id="modalStokis" class="fixed inset-0 bg-black/80 hidden z-[70] flex items-end justify-center backdrop-blur-sm" x-data="{ subtab: 'standar', payment: 'saldo', price: '25000000', dur: '3bln' }">
            <div class="bg-white dark:bg-slate-800 w-full max-w-md h-[85vh] rounded-t-3xl p-6 relative animate-[float_0.3s_ease-out] overflow-y-auto">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="font-bold text-lg text-blue-500"><i class="fas fa-cubes mr-2"></i>Paket Stokis</h3>
                    <button onclick="closeModal('modalStokis')" class="text-gray-400 hover:text-red-500"><i class="fas fa-times text-xl"></i></button>
                </div>

                <div class="flex p-1 bg-gray-100 dark:bg-slate-700 rounded-xl mb-4">
                    <button type="button" @click="subtab = 'standar'" :class="subtab==='standar' ? 'bg-white dark:bg-slate-600 shadow text-blue-500' : 'text-gray-400'" class="flex-1 py-2 rounded-lg text-xs font-bold transition">STANDAR</button>
                    <button type="button" @click="subtab = 'premium'" :class="subtab==='premium' ? 'bg-white dark:bg-slate-600 shadow text-purple-500' : 'text-gray-400'" class="flex-1 py-2 rounded-lg text-xs font-bold transition">PREMIUM</button>
                </div>

                <form method="POST" enctype="multipart/form-data" class="space-y-4">
                    <input type="hidden" name="action" value="buy_project">
                    <input type="hidden" name="category" value="Stokis">
                    <input type="hidden" name="package_name" :value="'Stokis ' + subtab.toUpperCase() + ' ' + (price/1000000) + ' Juta'">
                    
                    <div x-show="subtab === 'standar'">
                        <label class="text-xs font-bold text-gray-500 mb-2 block">Pilih Paket Standar</label>
                        <select x-model="price" name="amount" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 p-3 rounded-xl text-sm mb-3">
                            <option value="25000000">25 Juta</option>
                            <option value="50000000">50 Juta</option>
                            <option value="100000000">100 Juta</option>
                        </select>
                        <label class="text-xs font-bold text-gray-500 mb-2 block">Durasi Kontrak</label>
                        <select name="duration" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 p-3 rounded-xl text-sm mb-3">
                            <option value="3bln">3 Bulan</option>
                            <option value="6bln">6 Bulan</option>
                            <option value="12bln">12 Bulan</option> 
                        </select>
                        <div class="bg-blue-50 dark:bg-slate-700/50 p-3 rounded-lg text-xs text-blue-600 dark:text-blue-300 border border-blue-100 dark:border-slate-600 mb-4">
                            <i class="fas fa-info-circle mr-1"></i> Cashback 10% / bulan (Akhir Bulan)
                        </div>
                    </div>

                    <div x-show="subtab === 'premium'" style="display:none;">
                        <label class="text-xs font-bold text-gray-500 mb-2 block">Pilih Paket Premium</label>
                        <select x-model="price" name="amount" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 p-3 rounded-xl text-sm mb-3">
                            <option value="25000000">25 Juta</option>
                            <option value="50000000">50 Juta</option>
                            <option value="100000000">100 Juta</option>
                        </select>
                        <label class="text-xs font-bold text-gray-500 mb-2 block">Durasi Kontrak</label>
                        <select name="duration" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 p-3 rounded-xl text-sm mb-3">
                            <option value="3bln">3 Bulan</option>
                            <option value="6bln">6 Bulan</option>
                            <option value="12bln">12 Bulan</option> 
                        </select>
                        <div class="bg-purple-50 dark:bg-slate-700/50 p-3 rounded-lg text-xs text-purple-600 dark:text-purple-300 border border-purple-100 dark:border-slate-600 mb-4">
                            <i class="fas fa-crown mr-1"></i> Cashback 10% / bulan + Bonus Priority
                        </div>
                    </div>

                    <div class="border-t border-gray-200 dark:border-slate-700 pt-4">
                        <label class="text-xs font-bold text-gray-500 mb-2 block">Metode Pembayaran</label>
                        <div class="grid grid-cols-2 gap-3 mb-3">
                            <button type="button" @click="payment='saldo'" :class="payment=='saldo' ? 'bg-primary/10 border-primary text-primary' : 'bg-gray-50 border-gray-200 text-gray-500'" class="p-3 rounded-xl border text-xs font-bold">Potong Saldo</button>
                            <button type="button" @click="payment='transfer'" :class="payment=='transfer' ? 'bg-primary/10 border-primary text-primary' : 'bg-gray-50 border-gray-200 text-gray-500'" class="p-3 rounded-xl border text-xs font-bold">Transfer/QR</button>
                        </div>
                        <input type="hidden" name="payment_method" :value="payment">

                        <div x-show="payment=='transfer'" class="bg-gray-100 dark:bg-slate-700 p-4 rounded-xl mb-3">
                            <p class="text-xs text-gray-500 dark:text-gray-300 font-bold mb-1">Upload Bukti Transfer</p>
                            <p class="text-[10px] text-gray-400 mb-2">Ke Rekening/Wallet Company di menu Top Up</p>
                            <input type="file" name="proof" class="w-full text-xs bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-600 rounded-lg p-2">
                        </div>
                    </div>

                    <div class="mt-4 mb-4 border-t border-gray-100 dark:border-slate-700 pt-2">
                        <h4 class="text-xs font-bold text-gray-500 mb-2">My Investment (History)</h4>
                        <div class="space-y-2 max-h-32 overflow-y-auto pr-1">
                            <?php
                            $qStk = $conn->query("SELECT * FROM transactions WHERE user_id='$user_id' AND type='buy_stokis' ORDER BY id DESC");
                            if ($qStk->num_rows > 0) {
                                while($r = $qStk->fetch_assoc()) {
                                    $statusColor = ($r['status'] == 'success') ? 'text-green-500' : 'text-yellow-500';
                                    echo '<div class="bg-gray-50 dark:bg-slate-700/50 p-2 rounded border border-gray-100 dark:border-slate-600 text-[10px]">';
                                    echo '<div class="flex justify-between font-bold"><span>'.$r['description'].'</span> <span class="'.$statusColor.' uppercase">'.$r['status'].'</span></div>';
                                    echo '<div class="flex justify-between text-gray-500 mt-1"><span>'.formatRupiah($r['amount']).'</span> <span>'.date('d/m/y', strtotime($r['created_at'])).'</span></div>';
                                    echo '</div>';
                                }
                            } else {
                                echo '<p class="text-[10px] text-gray-400 text-center">Belum ada investasi.</p>';
                            }
                            ?>
                        </div>
                    </div>

                    <button type="submit" class="w-full bg-primary text-white py-3 rounded-xl font-bold shadow-lg hover:bg-emerald-600">Beli Paket Sekarang</button>
                </form>
            </div>
        </div>

        <div id="modalCrowd" class="fixed inset-0 bg-black/80 hidden z-[70] flex items-end justify-center backdrop-blur-sm" x-data="{ ctype: 'std', cprice: 10000000, custom_val: 0, payment: 'saldo' }">
            <div class="bg-white dark:bg-slate-800 w-full max-w-md h-[85vh] rounded-t-3xl p-6 relative animate-[float_0.3s_ease-out] overflow-y-auto">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="font-bold text-lg text-purple-500"><i class="fas fa-users mr-2"></i>Crowdfunding</h3>
                    <button onclick="closeModal('modalCrowd')" class="text-gray-400 hover:text-red-500"><i class="fas fa-times text-xl"></i></button>
                </div>

                <form method="POST" enctype="multipart/form-data" class="space-y-4">
                    <input type="hidden" name="action" value="buy_project">
                    <input type="hidden" name="category" value="Crowd">
                    <input type="hidden" name="package_name" :value="'Crowd ' + ctype.toUpperCase()">
                    <input type="hidden" name="amount" :value="ctype === 'custom' ? custom_val : cprice">
                    <input type="hidden" name="duration" value="Flexible">

                    <div class="grid grid-cols-2 gap-3 mb-4">
                        <div type="button" @click="ctype='std'; cprice=10000000" :class="ctype=='std' ? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20' : 'border-gray-200'" class="border p-3 rounded-xl cursor-pointer">
                            <p class="font-bold text-xs text-gray-700 dark:text-gray-300">Standar</p>
                            <p class="text-[10px] text-purple-500">10 Juta (1 Kolam)</p>
                        </div>
                        <div type="button" @click="ctype='med'; cprice=30000000" :class="ctype=='med' ? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20' : 'border-gray-200'" class="border p-3 rounded-xl cursor-pointer">
                            <p class="font-bold text-xs text-gray-700 dark:text-gray-300">Medium</p>
                            <p class="text-[10px] text-purple-500">30 Juta (3 Kolam)</p>
                        </div>
                        <div type="button" @click="ctype='lrg'; cprice=60000000" :class="ctype=='lrg' ? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20' : 'border-gray-200'" class="border p-3 rounded-xl cursor-pointer">
                            <p class="font-bold text-xs text-gray-700 dark:text-gray-300">Large</p>
                            <p class="text-[10px] text-purple-500">60 Juta (6 Kolam)</p>
                        </div>
                        <div type="button" @click="ctype='custom'; cprice=0" :class="ctype=='custom' ? 'border-purple-500 bg-purple-50 dark:bg-purple-900/20' : 'border-gray-200'" class="border p-3 rounded-xl cursor-pointer">
                            <p class="font-bold text-xs text-gray-700 dark:text-gray-300">Custom</p>
                            <p class="text-[10px] text-purple-500">Input Manual</p>
                        </div>
                    </div>

                    <div x-show="ctype === 'custom'" class="mb-3">
                        <label class="text-xs font-bold text-gray-500 mb-1 block">Nominal Custom (Kelipatan 10jt)</label>
                        <input type="number" x-model.number="custom_val" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 p-3 rounded-xl text-sm font-bold" placeholder="Contoh: 20000000">
                    </div>

                    <label class="text-xs font-bold text-gray-500 mb-2 block">Durasi</label>
                    <select name="duration" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 p-3 rounded-xl text-sm mb-3">
                        <option value="3bln">3 Bulan</option>
                        <option value="6bln">6 Bulan</option>
                        <option value="12bln">12 Bulan</option>
                    </select>

                    <div class="border-t border-gray-200 dark:border-slate-700 pt-4">
                        <label class="text-xs font-bold text-gray-500 mb-2 block">Metode Pembayaran</label>
                        <div class="grid grid-cols-2 gap-3 mb-3">
                            <button type="button" @click="payment='saldo'" :class="payment=='saldo' ? 'bg-primary/10 border-primary text-primary' : 'bg-gray-50 border-gray-200 text-gray-500'" class="p-3 rounded-xl border text-xs font-bold">Potong Saldo</button>
                            <button type="button" @click="payment='transfer'" :class="payment=='transfer' ? 'bg-primary/10 border-primary text-primary' : 'bg-gray-50 border-gray-200 text-gray-500'" class="p-3 rounded-xl border text-xs font-bold">Transfer/QR</button>
                        </div>
                        <input type="hidden" name="payment_method" :value="payment">
                        <div x-show="payment=='transfer'" class="bg-gray-100 dark:bg-slate-700 p-4 rounded-xl mb-3">
                            <p class="text-xs text-gray-500 dark:text-gray-300 font-bold mb-1">Upload Bukti</p>
                            <input type="file" name="proof" class="w-full text-xs bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-600 rounded-lg p-2">
                        </div>
                    </div>

                    <div class="mt-4 mb-4 border-t border-gray-100 dark:border-slate-700 pt-2">
                        <h4 class="text-xs font-bold text-gray-500 mb-2">My Investment (History)</h4>
                        <div class="space-y-2 max-h-32 overflow-y-auto pr-1">
                            <?php
                            $qCrd = $conn->query("SELECT * FROM transactions WHERE user_id='$user_id' AND type='buy_crowd' ORDER BY id DESC");
                            if ($qCrd->num_rows > 0) {
                                while($r = $qCrd->fetch_assoc()) {
                                    $statusColor = ($r['status'] == 'success') ? 'text-green-500' : 'text-yellow-500';
                                    echo '<div class="bg-gray-50 dark:bg-slate-700/50 p-2 rounded border border-gray-100 dark:border-slate-600 text-[10px]">';
                                    echo '<div class="flex justify-between font-bold"><span>'.$r['description'].'</span> <span class="'.$statusColor.' uppercase">'.$r['status'].'</span></div>';
                                    echo '<div class="flex justify-between text-gray-500 mt-1"><span>'.formatRupiah($r['amount']).'</span> <span>'.date('d/m/y', strtotime($r['created_at'])).'</span></div>';
                                    echo '</div>';
                                }
                            } else {
                                echo '<p class="text-[10px] text-gray-400 text-center">Belum ada investasi.</p>';
                            }
                            ?>
                        </div>
                    </div>

                    <button type="submit" class="w-full bg-purple-500 text-white py-3 rounded-xl font-bold shadow-lg hover:bg-purple-600">Join Crowd</button>
                </form>
            </div>
        </div>

        <div id="modalCrypto" class="fixed inset-0 bg-black/80 hidden z-[70] flex items-end justify-center backdrop-blur-sm" x-data="{ ctab: 'staking', payment: 'saldo', camount: 0, cstype: 'std', cmtype: 'std' }">
            <div class="bg-white dark:bg-slate-800 w-full max-w-md h-[85vh] rounded-t-3xl p-6 relative animate-[float_0.3s_ease-out] overflow-y-auto">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="font-bold text-lg text-orange-500"><i class="fab fa-bitcoin mr-2"></i>Crypto Investment</h3>
                    <button onclick="closeModal('modalCrypto')" class="text-gray-400 hover:text-red-500"><i class="fas fa-times text-xl"></i></button>
                </div>

                <div class="flex p-1 bg-gray-100 dark:bg-slate-700 rounded-xl mb-4">
                    <button type="button" @click="ctab = 'staking'" :class="ctab==='staking' ? 'bg-white dark:bg-slate-600 shadow text-orange-500' : 'text-gray-400'" class="flex-1 py-2 rounded-lg text-xs font-bold transition">STAKING</button>
                    <button type="button" @click="ctab = 'mining'" :class="ctab==='mining' ? 'bg-white dark:bg-slate-600 shadow text-orange-500' : 'text-gray-400'" class="flex-1 py-2 rounded-lg text-xs font-bold transition">MINING</button>
                    <button type="button" @click="ctab = 'earning'" :class="ctab==='earning' ? 'bg-white dark:bg-slate-600 shadow text-orange-500' : 'text-gray-400'" class="flex-1 py-2 rounded-lg text-xs font-bold transition">EARNING</button>
                </div>

                <form method="POST" enctype="multipart/form-data" class="space-y-4">
                    <input type="hidden" name="action" value="buy_project">
                    <input type="hidden" name="category" value="Crypto">
                    <input type="hidden" name="package_name" :value="'Crypto ' + ctab.toUpperCase()">
                    <input type="hidden" name="duration" value="Flexible">
                    
                    <input type="hidden" name="amount" :value="camount">

                    <div x-show="ctab === 'staking'" class="text-center py-2">
                        <i class="fas fa-coins text-4xl text-orange-500 mb-2"></i>
                        <h4 class="font-bold text-gray-700 dark:text-gray-200">USDT Staking</h4>
                        <p class="text-xs text-gray-500 mb-4 font-bold text-green-500">APY <?php echo $apy_staking; ?>% / Month</p>
                        
                        <div class="grid grid-cols-2 gap-3 mb-3 text-left">
                            <div @click="camount=1000000; cstype='std'" :class="cstype=='std' ? 'border-orange-500 bg-orange-50 dark:bg-orange-900/20' : 'border-gray-200 dark:border-slate-600'" class="border p-2 rounded-lg cursor-pointer transition">
                                <p class="font-bold text-xs">Standar</p>
                                <p class="text-[10px] text-gray-500">Rp 1.000.000</p>
                            </div>
                            <div @click="camount=5000000; cstype='med'" :class="cstype=='med' ? 'border-orange-500 bg-orange-50 dark:bg-orange-900/20' : 'border-gray-200 dark:border-slate-600'" class="border p-2 rounded-lg cursor-pointer transition">
                                <p class="font-bold text-xs">Medium</p>
                                <p class="text-[10px] text-gray-500">Rp 5.000.000</p>
                            </div>
                            <div @click="camount=10000000; cstype='lrg'" :class="cstype=='lrg' ? 'border-orange-500 bg-orange-50 dark:bg-orange-900/20' : 'border-gray-200 dark:border-slate-600'" class="border p-2 rounded-lg cursor-pointer transition">
                                <p class="font-bold text-xs">Large</p>
                                <p class="text-[10px] text-gray-500">Rp 10.000.000</p>
                            </div>
                            <div @click="cstype='custom'; camount=0" :class="cstype=='custom' ? 'border-orange-500 bg-orange-50 dark:bg-orange-900/20' : 'border-gray-200 dark:border-slate-600'" class="border p-2 rounded-lg cursor-pointer transition">
                                <p class="font-bold text-xs">Custom</p>
                                <p class="text-[10px] text-gray-500">Input Manual</p>
                            </div>
                        </div>

                        <div x-show="cstype === 'custom'" class="mb-2">
                             <input type="number" x-model.number="camount" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 p-3 rounded-xl text-sm font-bold" placeholder="Nominal IDR">
                        </div>
                    </div>

                    <div x-show="ctab === 'mining'" style="display:none;" class="text-center py-2">
                        <i class="fas fa-server text-4xl text-blue-500 mb-2"></i>
                        <h4 class="font-bold text-gray-700 dark:text-gray-200">Cloud Mining</h4>
                        <p class="text-xs text-gray-500 mb-4 font-bold text-green-500">APY <?php echo $apy_mining; ?>% / Month</p>
                        
                        <div class="grid grid-cols-2 gap-3 mb-3 text-left">
                            <div @click="camount=5000000; cmtype='10th'" :class="cmtype=='10th' ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20' : 'border-gray-200 dark:border-slate-600'" class="border p-2 rounded-lg cursor-pointer transition">
                                <p class="font-bold text-xs">10 TH/s</p>
                                <p class="text-[10px] text-gray-500">Rp 5.000.000</p>
                            </div>
                            <div @click="camount=25000000; cmtype='50th'" :class="cmtype=='50th' ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20' : 'border-gray-200 dark:border-slate-600'" class="border p-2 rounded-lg cursor-pointer transition">
                                <p class="font-bold text-xs">50 TH/s</p>
                                <p class="text-[10px] text-gray-500">Rp 25.000.000</p>
                            </div>
                            <div @click="camount=50000000; cmtype='100th'" :class="cmtype=='100th' ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20' : 'border-gray-200 dark:border-slate-600'" class="border p-2 rounded-lg cursor-pointer transition col-span-2">
                                <p class="font-bold text-xs">100 TH/s</p>
                                <p class="text-[10px] text-gray-500">Rp 50.000.000</p>
                            </div>
                        </div>
                    </div>

                    <div x-show="ctab === 'earning'" style="display:none;" class="text-center py-2">
                        <i class="fas fa-chart-line text-4xl text-green-500 mb-2"></i>
                        <h4 class="font-bold text-gray-700 dark:text-gray-200">Simple Earn</h4>
                        <p class="text-xs text-gray-500 mb-4 font-bold text-green-500">APY <?php echo $apy_earning; ?>% / Month</p>
                        <label class="text-xs font-bold text-gray-500 mb-1 block text-left">Invest Amount</label>
                        <input type="number" x-model.number="camount" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-600 p-3 rounded-xl text-sm font-bold mb-3" placeholder="Min 500.000">
                    </div>

                    <div class="border-t border-gray-200 dark:border-slate-700 pt-4">
                        <label class="text-xs font-bold text-gray-500 mb-2 block">Metode Pembayaran</label>
                        <div class="grid grid-cols-2 gap-3 mb-3">
                            <button type="button" @click="payment='saldo'" :class="payment=='saldo' ? 'bg-primary/10 border-primary text-primary' : 'bg-gray-50 border-gray-200 text-gray-500'" class="p-3 rounded-xl border text-xs font-bold">Potong Saldo</button>
                            <button type="button" @click="payment='transfer'" :class="payment=='transfer' ? 'bg-primary/10 border-primary text-primary' : 'bg-gray-50 border-gray-200 text-gray-500'" class="p-3 rounded-xl border text-xs font-bold">Transfer/QR</button>
                        </div>
                        <input type="hidden" name="payment_method" :value="payment">
                        <div x-show="payment=='transfer'" class="bg-gray-100 dark:bg-slate-700 p-4 rounded-xl mb-3">
                            <p class="text-xs text-gray-500 dark:text-gray-300 font-bold mb-1">Upload Bukti</p>
                            <input type="file" name="proof" class="w-full text-xs bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-600 rounded-lg p-2">
                        </div>
                    </div>

                    <div class="mt-4 mb-4 border-t border-gray-100 dark:border-slate-700 pt-2">
                        <h4 class="text-xs font-bold text-gray-500 mb-2">My Investment (History)</h4>
                        <div class="space-y-2 max-h-32 overflow-y-auto pr-1">
                            <?php
                            $qCry = $conn->query("SELECT * FROM transactions WHERE user_id='$user_id' AND type='buy_crypto' ORDER BY id DESC");
                            if ($qCry->num_rows > 0) {
                                while($r = $qCry->fetch_assoc()) {
                                    $statusColor = ($r['status'] == 'success') ? 'text-green-500' : 'text-yellow-500';
                                    echo '<div class="bg-gray-50 dark:bg-slate-700/50 p-2 rounded border border-gray-100 dark:border-slate-600 text-[10px]">';
                                    echo '<div class="flex justify-between font-bold"><span>'.$r['description'].'</span> <span class="'.$statusColor.' uppercase">'.$r['status'].'</span></div>';
                                    echo '<div class="flex justify-between text-gray-500 mt-1"><span>'.formatRupiah($r['amount']).'</span> <span>'.date('d/m/y', strtotime($r['created_at'])).'</span></div>';
                                    echo '</div>';
                                }
                            } else {
                                echo '<p class="text-[10px] text-gray-400 text-center">Belum ada investasi.</p>';
                            }
                            ?>
                        </div>
                    </div>

                    <button type="submit" class="w-full bg-orange-500 text-white py-3 rounded-xl font-bold shadow-lg hover:bg-orange-600">Start Project</button>
                </form>
            </div>
        </div>

        <div id="topupModal" class="fixed inset-0 bg-black/80 hidden z-[60] flex items-center justify-center px-4 backdrop-blur-sm" x-data="{ method: 'Transfer Bank' }">
            <div class="bg-white dark:bg-slate-800 w-full max-w-sm rounded-3xl p-6 relative animate-[fadeIn_0.3s_ease-out] overflow-y-auto max-h-[90vh]">
                <button onclick="closeModal('topupModal')" class="absolute top-4 right-4 text-gray-400 hover:text-red-500 bg-gray-100 dark:bg-slate-700 rounded-full w-8 h-8 flex items-center justify-center"><i class="fas fa-times"></i></button>
                <h3 class="text-xl font-bold mb-4 flex items-center gap-2"><i class="fas fa-wallet text-orange-500"></i> Deposit Saldo</h3>

                <form method="POST" enctype="multipart/form-data" class="space-y-4">
                    <input type="hidden" name="action" value="topup">
                    <input type="hidden" name="method" :value="method">
                    
                    <div>
                        <label class="text-xs text-gray-500 font-bold mb-2 block uppercase">Pilih Metode</label>
                        <div class="grid grid-cols-3 gap-3">
                            <button type="button" @click="method='Transfer Bank'" :class="method=='Transfer Bank' ? 'bg-orange-100 border-orange-500 text-orange-600 dark:bg-orange-900/40 dark:text-orange-300' : 'bg-gray-50 border-gray-200 dark:bg-slate-700 dark:border-slate-600 text-gray-500'" class="p-3 rounded-xl border flex flex-col items-center justify-center gap-2 transition hover:bg-orange-50 dark:hover:bg-slate-600">
                                <i class="fas fa-university text-xl"></i>
                                <span class="text-[10px] font-bold">Bank</span>
                            </button>
                            <button type="button" @click="method='QRIS'" :class="method=='QRIS' ? 'bg-orange-100 border-orange-500 text-orange-600 dark:bg-orange-900/40 dark:text-orange-300' : 'bg-gray-50 border-gray-200 dark:bg-slate-700 dark:border-slate-600 text-gray-500'" class="p-3 rounded-xl border flex flex-col items-center justify-center gap-2 transition hover:bg-orange-50 dark:hover:bg-slate-600">
                                <i class="fas fa-qrcode text-xl"></i>
                                <span class="text-[10px] font-bold">QRIS</span>
                            </button>
                            <button type="button" @click="method='Crypto (USDT)'" :class="method=='Crypto (USDT)' ? 'bg-orange-100 border-orange-500 text-orange-600 dark:bg-orange-900/40 dark:text-orange-300' : 'bg-gray-50 border-gray-200 dark:bg-slate-700 dark:border-slate-600 text-gray-500'" class="p-3 rounded-xl border flex flex-col items-center justify-center gap-2 transition hover:bg-orange-50 dark:hover:bg-slate-600">
                                <i class="fab fa-bitcoin text-xl"></i>
                                <span class="text-[10px] font-bold">Crypto</span>
                            </button>
                        </div>
                    </div>

                    <template x-if="method == 'Transfer Bank'">
                              <div class="bg-blue-50 dark:bg-slate-700 p-4 rounded-xl border border-blue-100 dark:border-slate-600 text-center">
                                <p class="text-xs text-gray-500 dark:text-gray-300 mb-1">Silakan Transfer ke:</p>
                                <p class="font-bold text-blue-600 dark:text-blue-400 text-lg">BCA 1234567890</p>
                                <p class="text-xs text-gray-400">a.n. PT Wallet Company</p>
                            </div>
                    </template>

                    <template x-if="method == 'QRIS' || method == 'Crypto (USDT)'">
                        <div class="bg-gray-100 dark:bg-slate-700 p-4 rounded-xl text-center">
                            <p class="text-xs text-gray-500 dark:text-gray-300 font-bold mb-2" x-text="method == 'QRIS' ? 'Scan QRIS' : 'Scan USDT TRC20'"></p>
                            <?php if(!empty($company_qr) && file_exists("uploads/".$company_qr)): ?>
                                <img src="uploads/<?php echo $company_qr; ?>" class="w-32 h-32 mx-auto rounded-lg border border-gray-300 bg-white p-1">
                            <?php else: ?>
                                <div class="w-32 h-32 mx-auto bg-gray-200 flex items-center justify-center text-xs text-gray-500">No QR Available</div>
                            <?php endif; ?>
                            <div x-show="method == 'Crypto (USDT)'" class="mt-2 text-[10px] break-all bg-white p-1 rounded"><?php echo $company_wallet; ?></div>
                        </div>
                    </template>

                    <div>
                        <label class="text-xs text-gray-500 font-bold mb-2 block uppercase">Nominal (IDR)</label>
                        <input type="number" name="amount" required class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-700 p-4 rounded-xl text-sm font-bold" placeholder="Min 50.000">
                    </div>
                    <div>
                        <label class="text-xs text-gray-500 font-bold mb-2 block uppercase">Bukti Transfer (Wajib)</label>
                        <input type="file" name="proof" required class="w-full text-xs bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-700 rounded-xl p-2">
                    </div>
                    <button type="submit" class="w-full bg-orange-500 py-4 rounded-xl text-white font-bold shadow-lg hover:bg-orange-600 transition mt-2">Buat Tagihan</button>
                </form>
            </div>
        </div>

        <div id="upgradeModal" class="fixed inset-0 bg-black/80 hidden z-[70] flex items-center justify-center px-4 backdrop-blur-sm" x-data="{ payment: 'saldo' }">
            <div class="bg-white dark:bg-slate-800 w-full max-w-sm rounded-3xl p-6 relative animate-[fadeIn_0.3s_ease-out] overflow-y-auto max-h-[90vh]">
                <button onclick="closeModal('upgradeModal')" class="absolute top-4 right-4 text-gray-400 hover:text-red-500 bg-gray-100 dark:bg-slate-700 rounded-full w-8 h-8 flex items-center justify-center"><i class="fas fa-times"></i></button>
                
                <h3 class="text-xl font-bold mb-4 flex items-center gap-2"><i class="fas fa-level-up-alt text-purple-500"></i> Upgrade Level 30</h3>
                <div class="bg-purple-50 dark:bg-slate-700 p-4 rounded-xl mb-4 text-center border border-purple-100 dark:border-slate-600">
                    <p class="text-xs text-gray-500 dark:text-gray-400 uppercase font-bold">Biaya Upgrade</p>
                    <p class="text-2xl font-bold text-purple-600 dark:text-purple-400">Rp 500.000</p>
                </div>

                <form method="POST" enctype="multipart/form-data" class="space-y-4">
                    <input type="hidden" name="action" value="upgrade_level">
                    
                    <div class="border-t border-gray-200 dark:border-slate-700 pt-4">
                        <label class="text-xs font-bold text-gray-500 mb-2 block">Metode Pembayaran</label>
                        <div class="grid grid-cols-2 gap-3 mb-3">
                            <button type="button" @click="payment='saldo'" :class="payment=='saldo' ? 'bg-primary/10 border-primary text-primary' : 'bg-gray-50 border-gray-200 text-gray-500'" class="p-3 rounded-xl border text-xs font-bold">Potong Saldo</button>
                            <button type="button" @click="payment='transfer'" :class="payment=='transfer' ? 'bg-primary/10 border-primary text-primary' : 'bg-gray-50 border-gray-200 text-gray-500'" class="p-3 rounded-xl border text-xs font-bold">Transfer/QR</button>
                        </div>
                        <input type="hidden" name="payment_method" :value="payment">

                        <div x-show="payment=='transfer'" class="bg-gray-100 dark:bg-slate-700 p-4 rounded-xl mb-3">
                            <p class="text-xs text-gray-500 dark:text-gray-300 font-bold mb-1">Upload Bukti Transfer</p>
                            <p class="text-[10px] text-gray-400 mb-2">Ke Rekening/Wallet Company di menu Top Up</p>
                            <input type="file" name="proof" class="w-full text-xs bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-600 rounded-lg p-2">
                        </div>
                    </div>

                    <button type="submit" class="w-full bg-purple-500 py-3 rounded-xl text-white font-bold shadow-lg hover:bg-purple-600 transition mt-2">Bayar & Upgrade</button>
                </form>
            </div>
        </div>

        <div id="withdrawModal" class="fixed inset-0 bg-black/80 hidden z-[60] flex items-center justify-center px-4 backdrop-blur-sm">
            <div class="bg-white dark:bg-slate-800 w-full max-w-sm rounded-3xl p-6 relative animate-[fadeIn_0.3s_ease-out]">
                <button onclick="closeModal('withdrawModal')" class="absolute top-4 right-4 text-gray-400 hover:text-red-500"><i class="fas fa-times"></i></button>
                <h3 class="text-xl font-bold mb-4 flex items-center gap-2"><i class="fas fa-money-bill-wave text-red-500"></i> Withdraw</h3>
                
                <div class="bg-red-50 dark:bg-slate-700/50 p-3 rounded-xl border border-red-100 dark:border-slate-600 mb-4">
                    <p class="text-xs text-red-600 dark:text-red-300"><i class="fas fa-info-circle mr-1"></i> Biaya Admin: <b><?php echo $fee_wd_pct; ?>%</b></p>
                </div>

                <form method="POST" class="space-y-3">
                    <input type="hidden" name="action" value="withdraw">
                    <div>
                        <label class="text-xs font-bold text-gray-500 block mb-1">Nominal Penarikan</label>
                        <input type="number" name="amount" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-700 p-3 rounded-xl" placeholder="Min 50.000" required>
                    </div>
                    <div>
                        <label class="text-xs font-bold text-gray-500 block mb-1">Bank Tujuan</label>
                        <input type="text" name="bank_name" value="<?php echo $user['bank_name'] ?? ''; ?>" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-700 p-3 rounded-xl" placeholder="Contoh: BCA / DANA" required>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="text-xs font-bold text-gray-500 block mb-1">No. Rekening</label>
                            <input type="number" name="acc_number" value="<?php echo $user['acc_number'] ?? ''; ?>" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-700 p-3 rounded-xl" placeholder="123xxx" required>
                        </div>
                        <div>
                            <label class="text-xs font-bold text-gray-500 block mb-1">Atas Nama</label>
                            <input type="text" name="acc_name" value="<?php echo $user['acc_name'] ?? ''; ?>" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-200 dark:border-slate-700 p-3 rounded-xl" placeholder="Nama" required>
                        </div>
                    </div>
                    <button class="w-full bg-red-500 py-3 rounded-xl text-white font-bold shadow-lg hover:bg-red-600 mt-2">Ajukan Withdraw</button>
                </form>
            </div>
        </div>
        
        <div id="modalHistory" class="fixed inset-0 bg-black/80 hidden z-[80] flex items-end justify-center backdrop-blur-sm">
            <div class="bg-white dark:bg-slate-800 w-full max-w-md h-[80vh] rounded-t-3xl p-0 relative animate-[float_0.3s_ease-out] flex flex-col">
                <div class="p-4 flex justify-center cursor-pointer" onclick="closeModal('modalHistory')">
                    <div class="w-12 h-1.5 bg-gray-300 dark:bg-slate-600 rounded-full"></div>
                </div>
                <div class="px-6 pb-4">
                    <h3 class="font-bold text-lg text-gray-800 dark:text-gray-200">Riwayat Transaksi</h3>
                </div>
                <div class="flex-1 overflow-y-auto px-6 pb-6 space-y-4">
                    <?php 
                    $hist = $conn->query("SELECT * FROM transactions WHERE user_id = $user_id ORDER BY created_at DESC LIMIT 20");
                    if($hist->num_rows > 0):
                        while($h = $hist->fetch_assoc()):
                            $is_income = in_array($h['type'], ['topup', 'transfer_in', 'bonus_sponsor', 'bonus_pairing', 'bonus_royalty', 'bonus_stokis', 'bonus_crowd', 'bonus_crypto', 'profit_sharing']);
                            $color = $is_income ? 'text-green-600' : 'text-red-600';
                            $icon = $is_income ? 'fa-arrow-down' : 'fa-arrow-up';
                            $bg_icon = $is_income ? 'bg-green-100 text-green-600' : 'bg-red-100 text-red-600';
                            $sign = $is_income ? '+' : '-';
                            
                            $label_type = str_replace('_', ' ', $h['type']);
                            if ($h['type'] == 'register_starter' || $h['type'] == 'buy_starter') { $label_type = 'Paket Starter (300k)'; }
                            if ($h['type'] == 'upgrade_starter') { $label_type = 'Paket Upgrade (500k)'; }

                            $badge = ($h['status'] == 'success') ? '<span class="text-[9px] bg-green-100 text-green-600 px-2 py-0.5 rounded-full font-bold">SUCCESS</span>' : (($h['status'] == 'pending') ? '<span class="text-[9px] bg-yellow-100 text-yellow-600 px-2 py-0.5 rounded-full font-bold">PENDING</span>' : '<span class="text-[9px] bg-red-100 text-red-600 px-2 py-0.5 rounded-full font-bold">REJECT</span>');

                            $fmt_amt = formatRupiah($h['amount']);
                    ?>
                    <div class="flex justify-between items-center pb-3 border-b border-gray-100 dark:border-slate-700">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-full <?php echo $bg_icon; ?> flex items-center justify-center"><i class="fas <?php echo $icon; ?>"></i></div>
                            <div>
                                <p class="text-sm font-bold capitalize text-gray-700 dark:text-gray-300"><?php echo $label_type; ?></p>
                                <p class="text-[10px] text-gray-400"><?php echo date('d M H:i', strtotime($h['created_at'])); ?> • <?php echo $h['description']; ?></p>
                            </div>
                        </div>
                        <div class="text-right">
                            <p class="text-sm font-bold <?php echo $color; ?>"><?php echo $sign; ?> <?php echo $fmt_amt; ?></p>
                            <?php echo $badge; ?>
                        </div>
                    </div>
                    <?php endwhile; else: ?>
                    <p class="text-center text-gray-400 text-sm py-10">Belum ada transaksi</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div id="profileModal" class="fixed inset-0 bg-black/90 hidden z-[100] flex items-end justify-center backdrop-blur-sm overflow-y-auto">
            <div class="bg-white dark:bg-slate-900 w-full max-w-md min-h-[90vh] rounded-t-3xl p-6 relative animate-[float_0.3s_ease-out]">
                <div class="flex justify-between items-center mb-6">
                    <h3 class="font-bold text-xl">Edit Profile</h3>
                    <button onclick="closeModal('profileModal')" class="text-gray-400 hover:text-red-500 bg-gray-100 dark:bg-slate-800 p-2 rounded-full"><i class="fas fa-times"></i></button>
                </div>
                <form method="POST" action="" class="space-y-6 pb-20">
                    <input type="hidden" name="action" value="update_profile">
                    <div>
                        <h4 class="text-xs font-bold text-gray-400 uppercase mb-3">Data Diri</h4>
                        <div class="space-y-3">
                            <input type="text" name="full_name" value="<?php echo $user['full_name']; ?>" placeholder="Nama Lengkap" class="w-full bg-gray-50 dark:bg-slate-800 border border-gray-200 dark:border-slate-700 p-3 rounded-xl text-sm" required>
                            <input type="email" name="email" value="<?php echo $user['email']; ?>" placeholder="Email" class="w-full bg-gray-50 dark:bg-slate-800 border p-3 rounded-xl text-sm" required>
                            <input type="text" name="phone" value="<?php echo $user['phone']; ?>" placeholder="No. Whatsapp" class="w-full bg-gray-50 dark:bg-slate-800 border p-3 rounded-xl text-sm" required>
                        </div>
                    </div>
                    <div>
                        <h4 class="text-xs font-bold text-gray-400 uppercase mb-3">Ganti Password</h4>
                        <input type="password" name="password" placeholder="Password Baru (Kosongkan jika tidak ubah)" class="w-full bg-gray-50 dark:bg-slate-800 border p-3 rounded-xl text-sm">
                    </div>
                    <div x-data="{ selectedBank: '<?php echo $user['bank_name'] ?? 'BANK'; ?>' }">
                        <h4 class="text-xs font-bold text-gray-400 uppercase mb-3">Akun Bank / E-Wallet</h4>
                        <input type="hidden" name="bank_name" x-model="selectedBank">
                        <div class="grid grid-cols-3 gap-2 mb-3">
                            <div @click="selectedBank='DANA'" :class="selectedBank=='DANA' ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/30' : 'border-gray-200 dark:border-slate-700'" class="border rounded-xl p-2 cursor-pointer flex flex-col items-center justify-center h-16"><span class="text-[10px] font-bold">DANA</span></div>
                            <div @click="selectedBank='OVO'" :class="selectedBank=='OVO' ? 'border-purple-500 bg-purple-50 dark:bg-purple-900/30' : 'border-gray-200 dark:border-slate-700'" class="border rounded-xl p-2 cursor-pointer flex flex-col items-center justify-center h-16"><span class="font-bold text-purple-600 text-sm">OVO</span></div>
                            <div @click="selectedBank='GOPAY'" :class="selectedBank=='GOPAY' ? 'border-green-500 bg-green-50 dark:bg-green-900/30' : 'border-gray-200 dark:border-slate-700'" class="border rounded-xl p-2 cursor-pointer flex flex-col items-center justify-center h-16"><span class="font-bold text-green-600 text-sm">GOPAY</span></div>
                            <div @click="selectedBank='BANK'" :class="selectedBank=='BANK' ? 'border-gray-500 bg-gray-50 dark:bg-slate-700' : 'border-gray-200 dark:border-slate-700'" class="border rounded-xl p-2 cursor-pointer flex flex-col items-center justify-center h-16"><i class="fas fa-university mb-1"></i><span class="text-[10px]">BANK LAIN</span></div>
                        </div>
                        <div class="space-y-3">
                            <div x-show="selectedBank=='BANK'"><input type="text" name="custom_bank" placeholder="Nama Bank (misal: BCA)" class="w-full bg-gray-50 dark:bg-slate-800 border p-3 rounded-xl text-sm" value="<?php echo (!in_array($user['bank_name'] ?? '', ['DANA','OVO','GOPAY'])) ? ($user['bank_name'] ?? '') : ''; ?>"></div>
                            <input type="number" name="acc_number" value="<?php echo $user['acc_number'] ?? ''; ?>" placeholder="Nomor Rekening / HP" class="w-full bg-gray-50 dark:bg-slate-800 border p-3 rounded-xl text-sm">
                            <input type="text" name="acc_name" value="<?php echo $user['acc_name'] ?? ''; ?>" placeholder="Atas Nama" class="w-full bg-gray-50 dark:bg-slate-800 border p-3 rounded-xl text-sm">
                        </div>
                    </div>
                    <div>
                        <h4 class="text-xs font-bold text-gray-400 uppercase mb-3">Crypto Wallet</h4>
                        <div class="space-y-3">
                            <input type="text" name="wallet_trc20" value="<?php echo $user['wallet_trc20'] ?? ''; ?>" placeholder="Address TRC20" class="w-full bg-gray-50 dark:bg-slate-800 border p-3 rounded-xl text-xs font-mono">
                            <input type="text" name="wallet_bnb20" value="<?php echo $user['wallet_bnb20'] ?? ''; ?>" placeholder="Address BNB20" class="w-full bg-gray-50 dark:bg-slate-800 border p-3 rounded-xl text-xs font-mono">
                        </div>
                    </div>
                    <div class="pt-4 border-t dark:border-slate-700">
                        <button type="submit" class="w-full bg-primary text-white py-3 rounded-xl font-bold shadow-lg">SIMPAN PERUBAHAN</button>
                        <a href="login.php?act=logout" class="block w-full text-center text-red-500 font-bold text-sm py-4">LOGOUT</a>
                    </div>
                </form>
            </div>
        </div>

        <div id="sendModal" class="fixed inset-0 bg-black/80 hidden z-[60] flex items-center justify-center px-4 backdrop-blur-sm">
            <div class="bg-white dark:bg-slate-800 w-full max-w-sm rounded-3xl p-6 relative animate-[fadeIn_0.3s_ease-out]">
                <button onclick="closeModal('sendModal')" class="absolute top-4 right-4 text-gray-400 hover:text-red-500"><i class="fas fa-times"></i></button>
                <h3 class="text-xl font-bold mb-6 flex items-center gap-2">Send Money</h3>
                <div class="bg-emerald-50 dark:bg-slate-700/50 p-2 rounded-xl border border-emerald-100 dark:border-slate-600 mb-4">
                    <p class="text-xs text-emerald-600 dark:text-emerald-300"><i class="fas fa-info-circle mr-1"></i> Biaya Admin: <b><?php echo $fee_send_pct; ?>%</b></p>
                </div>
                <form method="POST" class="space-y-4">
                    <input type="hidden" name="action" value="send">
                    <input type="text" name="username" class="w-full bg-gray-50 dark:bg-slate-900 border p-4 rounded-xl" placeholder="Username" required>
                    <input type="number" id="send_amount" name="amount" class="w-full bg-gray-50 dark:bg-slate-900 border p-4 rounded-xl" placeholder="Rp 0" required>
                    <button class="w-full bg-primary py-4 rounded-xl text-white font-bold">Kirim</button>
                </form>
            </div>
        </div>
        
        <div id="receiveModal" class="fixed inset-0 bg-black/80 hidden z-[60] flex items-center justify-center px-4 backdrop-blur-sm">
            <div class="bg-white dark:bg-slate-800 w-full max-w-sm rounded-3xl p-6 relative text-center animate-[fadeIn_0.3s_ease-out]">
                <button onclick="closeModal('receiveModal')" class="absolute top-4 right-4 text-gray-400 hover:text-red-500"><i class="fas fa-times"></i></button>
                <h3 class="text-xl font-bold mb-2">Receive</h3>
                <img src="https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=<?php echo $user['username']; ?>" class="mx-auto my-4 rounded-lg shadow-md border-4 border-gray-100 dark:border-slate-700">
                <span class="font-bold text-lg text-primary"><?php echo $user['username']; ?></span>
            </div>
        </div>

        <div id="swapModal" class="fixed inset-0 bg-black/80 hidden z-[60] flex items-center justify-center px-4 backdrop-blur-sm">
             <div class="bg-white dark:bg-slate-800 w-full max-w-sm rounded-3xl p-6 relative animate-[fadeIn_0.3s_ease-out]">
                <button onclick="closeModal('swapModal')" class="absolute top-4 right-4 text-gray-400 hover:text-red-500"><i class="fas fa-times"></i></button>
                <h3 class="text-xl font-bold mb-6">Swap</h3>
                <div class="bg-purple-50 dark:bg-slate-700/50 p-2 rounded-xl border border-purple-100 dark:border-slate-600 mb-4">
                    <p class="text-xs text-purple-600 dark:text-purple-300"><i class="fas fa-info-circle mr-1"></i> Biaya Admin: <b><?php echo $fee_swap_pct; ?>%</b></p>
                </div>
                <form method="POST" class="space-y-4">
                    <input type="hidden" name="action" value="swap">
                    <input type="number" name="amount" class="w-full bg-gray-50 dark:bg-slate-900 border p-4 rounded-xl" placeholder="IDR Amount" required>
                    <button class="w-full bg-purple-500 py-4 rounded-xl text-white font-bold">Swap Now</button>
                </form>
            </div>
        </div>
        
        <div id="inboxModal" class="fixed inset-0 bg-black/80 hidden z-[70] flex items-end sm:items-center justify-center backdrop-blur-sm">
            <div class="bg-white dark:bg-slate-800 w-full max-w-md h-[80vh] sm:h-[70vh] rounded-t-3xl sm:rounded-3xl p-4 relative animate-[float_0.3s_ease-out] flex flex-col">
                 <button onclick="closeModal('inboxModal')" class="absolute top-4 right-4 text-gray-400 hover:text-red-500"><i class="fas fa-times"></i></button>
                 <h3 class="font-bold text-lg mb-4 ml-2">Pesan Masuk</h3>
                 <div class="flex-1 overflow-y-auto space-y-3 p-2">
                    <?php 
                    $qInbox = $conn->query("SELECT * FROM admin_messages ORDER BY created_at DESC");
                    if($qInbox->num_rows > 0):
                        while($msg = $qInbox->fetch_assoc()):
                    ?>
                    <div class="bg-blue-50 dark:bg-slate-700 p-4 rounded-xl border-l-4 border-blue-500 shadow-sm">
                        <p class="text-xs text-gray-400 font-bold mb-1"><?php echo date('d M H:i', strtotime($msg['created_at'])); ?></p>
                        <h4 class="font-bold text-sm text-gray-800 dark:text-gray-200"><?php echo $msg['title']; ?></h4>
                        <p class="text-xs text-gray-600 dark:text-gray-300 mt-2"><?php echo nl2br($msg['message']); ?></p>
                    </div>
                    <?php endwhile; else: ?>
                    <p class="text-center text-gray-400 mt-10">Tidak ada pesan baru</p>
                    <?php endif; ?>
                 </div>
            </div>
        </div>
        
    </div>

    <script>
        <?php echo $swal_script; ?>
        
        // Pass PHP Variable to JS
        var wdStatus = '<?php echo $withdraw_active; ?>';
        var currentBalanceIDR = <?php echo $user['balance_idr']; ?>;
        var currentBalanceUSD = <?php echo $user['balance_usd'] ?? 0; ?>;
        const rate = 16000;

        function dashboardApp(){ 
            // Calculate initial USD value from IDR
            const usdFromIDR = (currentBalanceIDR / rate).toFixed(2);
            // Calculate IDR value from USD
            const idrFromUSD = (currentBalanceUSD * rate);

            return { 
                isIDR: true, 
                rate: rate.toLocaleString('id-ID'),
                usdValIDR: usdFromIDR,
                usdValUSD: currentBalanceUSD.toFixed(2),
                idrValUSD: idrFromUSD.toLocaleString('id-ID'),
                unreadCount: <?php echo $unread_msg; ?>, 
                toggleCurrency(){ this.isIDR = !this.isIDR; } 
            } 
        }
        
        function openModal(id){ document.getElementById(id).classList.remove('hidden'); }
        function closeModal(id){ document.getElementById(id).classList.add('hidden'); }
        
        // Custom Check Withdraw Status
        function checkWithdraw(){
            if(wdStatus === 'off'){
                Swal.fire({
                    icon: 'error',
                    title: 'Maaf',
                    text: 'Withdraw sedang mengalami gangguan, silahkan mencoba kembali beberapa saat kedepan',
                    confirmButtonColor: '#10b981'
                });
            } else {
                openModal('withdrawModal');
            }
        }

        function openInbox(){
            openModal('inboxModal');
            fetch(window.location.href, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: 'action=mark_read'
            }).then(() => {
                const countSpan = document.querySelector('[x-text="unreadCount"]');
                if (countSpan) {
                     countSpan.style.display = 'none';
                     countSpan.textContent = '0';
                }
            });
        }

        function copyReferral(){ navigator.clipboard.writeText(document.getElementById('refCode').innerText); Swal.fire({icon:'success', title:'Copied', toast:true, position:'top-end', showConfirmButton:false, timer:1000}); }
        function showNotif(){ Swal.fire('Info', 'Cek notifikasi di menu history', 'info'); }
    </script>
</body>
</html>