PHP WebShell

Текущая директория: /var/www/bitcardoApp/user/wallets

Просмотр файла: wallets.php

<?php
include '../common/header.php';
// user/wallets/wallets.php

// ---------- Amount formatting helpers (safe to redefine) ----------
if (!function_exists('coin_decimals_ui')) {
    function coin_decimals_ui(string $coin): int {
        $coin = strtoupper($coin);
        return match ($coin) {
            'BTC' => 8,
            'ETH' => 10,
            'SOL' => 9,
            'TRX' => 6,
            'USDT', 'USDC' => 6,
            'USD', 'NGN' => 2,
            default => 8,
        };
    }
}
if (!function_exists('fmt_coin_amount')) {
    function fmt_coin_amount($amount, string $coin): string {
        $scale = coin_decimals_ui($coin);
        return number_format((float)$amount, $scale, '.', '');
    }
}

// ---------- Rate helpers (prevents TRX showing $1:1) ----------
if (!function_exists('wallet_norm_rate_coin')) {
    function wallet_norm_rate_coin(string $coin): string {
        $coin = strtoupper(trim($coin));
        $map = [
            'USDT-TRC20' => 'USDT',
            'TRX'        => 'TRON', // many tables store TRON instead of TRX
        ];
        return $map[$coin] ?? $coin;
    }
}
if (!function_exists('wallet_get_usd_rate')) {
    function wallet_get_usd_rate(array $usdPrice, string $coin): float {
        $coin = strtoupper($coin);

        if (isset($usdPrice[$coin]) && (float)$usdPrice[$coin] > 0) return (float)$usdPrice[$coin];

        $norm = wallet_norm_rate_coin($coin);
        if (isset($usdPrice[$norm]) && (float)$usdPrice[$norm] > 0) return (float)$usdPrice[$norm];

        if (in_array($coin, ['USDT', 'USDC', 'USDT-TRC20'], true)) return 1.0;

        return 0.0;
    }
}

// ---------- Ensure $user_id ----------
if (!isset($user_id) || !$user_id) {
    $user_id = $_SESSION['user_id'] ?? null;
}
$user_id = (int)$user_id;

// ---------- Load wallets if not already loaded by other includes ----------
if (!isset($wallets) || !is_array($wallets)) {
    $wallets = [];
    if (isset($conn) && $user_id > 0) {
        $stmt = $conn->prepare("SELECT wallet_id, coin, label, wallet_add, balance, type, icon FROM user_wallets WHERE user_id=?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $wallets[] = $row;
        }
        $stmt->close();
    }
}

// ---------- Fetch USD rates ----------
$usdPrice = [];
if (isset($conn)) {
    $r = $conn->query("SELECT UPPER(coin) AS coin, rate FROM online_coin_rates");
    if ($r) {
        while ($row = $r->fetch_assoc()) {
            $usdPrice[strtoupper($row['coin'])] = (float)($row['rate'] ?? 0);
        }
        $r->free();
    }
}

// ---------- Compute totals + per-wallet USD ----------
$totalNgn = 0.0;
$totalUsd = 0.0;

if (!empty($wallets)) {
    foreach ($wallets as &$w) {
        $coin = strtoupper($w['coin'] ?? '');
        $bal  = (float)($w['balance'] ?? 0);

        if ($coin === 'NGN') {
            $totalNgn += $bal;
            $w['usd_equiv'] = null;
        } else {
            $rate = wallet_get_usd_rate($usdPrice, $coin);
            if ($rate > 0) {
                $w['usd_equiv'] = $bal * $rate;
                $totalUsd += $w['usd_equiv'];
            } else {
                $w['usd_equiv'] = null;
            }
        }
    }
    unset($w);
}
?>

<!-- Main Container -->
<div class="container mt-3">
    <div class="row">

        <?php include '../common/nav.php'; ?>

        <!-- Main Content -->
        <main class="col-md-9 col-lg-10 px-md-5 mb-5">
            <?php include '../common/page-header.php'; ?>

            <div class="container my-5">
                <div class="row g-4">
                    <!-- Left Column -->
                    <div class="offset-md-1 col-md-5 mt-2">
                        <div class="card-soft">
                            <div class="offset-5 col-4 mb-3">
                                <div class="rounded-icon align-item-center">
                                    <i class="bi bi-person"></i>
                                </div>
                            </div>

                            <h4 class="fw-bold mt-3 mb-0"><?= htmlspecialchars(($userFName ?? '') . ' ' . ($userLName ?? '')); ?></h4>
                            <p class="text-muted small mb-2">Your personal account</p>

                            <div class="open-business bg-light mt-3">
                                <i class="bi bi-briefcase me-1"></i>
                                <span id="totalNgnText">
                                    <?= '₦' . number_format((float)($totalNgn ?? 0), 2) . ' <small>NGN</small>'; ?>
                                </span>
                            </div>
                            <p style="font-size:small; color: #8f8e94;" class="small mb-4">
                                Total Naira Balance
                            </p>

                            <div class="open-business bg-light mt-3">
                                <i class="bi bi-briefcase me-1"></i>
                                <span id="totalUsdText">
                                    <?= '$' . number_format((float)($totalUsd ?? 0), 2) . ' <small>USD</small>'; ?>
                                </span>
                            </div>
                            <p style="font-size:small; color: #8f8e94;" class="small mb-4">
                                Total USD Balance
                            </p>
                        </div>
                    </div>

                    <!-- Right Column -->
                    <div class="col-md-6">
                        <!-- Balance List -->
                        <?php if (!empty($wallets)): ?>
                            <?php foreach ($wallets as $wallet): ?>
                                <?php
                                  $coin  = strtoupper($wallet['coin'] ?? '');
                                  $label = $wallet['label'] ?: $coin;
                                  $bal   = (float)($wallet['balance'] ?? 0);

                                  // Raw display
                                  $rawTxt = ($coin === 'NGN')
                                        ? '₦' . number_format($bal, 2, '.', ',')
                                        : fmt_coin_amount($bal, $coin);

                                  // Primary right-side amount
                                  if ($coin === 'NGN') {
                                      $primary = '₦' . number_format($bal, 2, '.', ',');
                                  } else {
                                      $primary = !empty($wallet['usd_equiv'])
                                          ? '$' . number_format((float)$wallet['usd_equiv'], 2, '.', ',')
                                          : '';
                                  }
                                ?>
                                <a href="single-wallet.php?ussgwt=<?= urlencode($wallet['wallet_id']); ?>&coin=<?= urlencode($coin); ?>"
                                   class="list-group-item ps-3 balance-item d-flex justify-content-between align-items-center">
                                    <div class="d-flex align-items-center gap-3">
                                        <img src="../../assets/icons/<?= htmlspecialchars($wallet['icon']); ?>" class="bg-white flag" alt="<?= htmlspecialchars($coin); ?>">
                                        <div>
                                            <div class="fw-semibold"><?= htmlspecialchars($label); ?></div>
                                            <small class="text-muted">
                                                <span data-coin-raw="<?= htmlspecialchars($coin) ?>"><?= htmlspecialchars($rawTxt); ?></span>
                                                <span class="ms-1"><?= htmlspecialchars($coin); ?></span>
                                            </small>
                                        </div>
                                    </div>

                                    <div class="d-flex align-items-center gap-2">
                                        <div class="text-end" style="min-width: 110px;">
                                            <?php if ($primary !== ''): ?>
                                                <div class="fw-semibold" style="line-height:1.1;">
                                                    <span data-coin-primary="<?= htmlspecialchars($coin) ?>"><?= htmlspecialchars($primary); ?></span>
                                                </div>
                                            <?php else: ?>
                                                <div class="fw-semibold" style="line-height:1.1;">
                                                    <span data-coin-primary="<?= htmlspecialchars($coin) ?>"></span>
                                                </div>
                                            <?php endif; ?>

                                            <div class="small text-muted" style="line-height:1.1;">
                                                <span data-coin-raw="<?= htmlspecialchars($coin) ?>"><?= htmlspecialchars($rawTxt); ?></span>
                                            </div>
                                        </div>
                                        <i class="bi bi-chevron-right pe-3"></i>
                                    </div>
                                </a>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <!-- CREATE NAIRA WALLET CARD -->
                            <div class="card">
                                <div class="card-body text-center mt-3">
                                    <p>You have no wallet yet, <a href="" class="btn btn-primary btn-sm">Create Naira Wallet</a></p>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php
                        // Flags for presence (use 'USDT' not 'TUSDT')
                        $hasNGN  = false;
                        $hasUSDT = false;
                        if (!empty($wallets)) {
                            foreach ($wallets as $w) {
                                if (!isset($w['coin'])) continue;
                                $c = strtoupper($w['coin']);
                                if ($c === 'NGN')  $hasNGN  = true;
                                if ($c === 'USDT') $hasUSDT = true;
                            }
                        }
                        ?>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<?php include '../common/footer.php'; ?>

<!-- Live wallet balance updates (no refresh) -->
<script>
(function () {
  async function poll() {
    try {
      const res = await fetch("/user/dashboard/wallet_balances.php?ts=" + Date.now(), {
        credentials: "include",
        cache: "no-store"
      });

      if (!res.ok) return;

      const data = await res.json();
      if (!data.ok) return;

      // totals (strings already formatted by endpoint)
      const tn = document.getElementById("totalNgnText");
      const tu = document.getElementById("totalUsdText");
      if (tn) tn.innerHTML = data.totals?.ngn || '';
      if (tu) tu.innerHTML = data.totals?.usd || '';

      // wallets
      const wallets = data.wallets || {};
      Object.keys(wallets).forEach((coin) => {
        const w = wallets[coin] || {};
        const primary = w.primary ?? '';
        const raw = w.raw ?? '';

        // Update ALL elements matching this coin (in case coin appears twice)
        document.querySelectorAll('[data-coin-primary="' + coin + '"]').forEach((el) => {
          el.textContent = primary;
        });
        document.querySelectorAll('[data-coin-raw="' + coin + '"]').forEach((el) => {
          el.textContent = raw;
        });
      });

    } catch (e) {
      console.error("Wallet poll error", e);
    }
  }

  poll();
  setInterval(poll, 5000);
})();
</script>

Выполнить команду


Для локальной разработки. Не используйте в интернете!