<?php
/**
 * MOVEX – Admin Wallet Stats
 * Path: /backend/admin/get-wallet-stats.php
 *
 * Returns hot wallet USDT balance and BNB gas balance
 * (Static fallback if no blockchain integration yet)
 */

error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

require_once '../config/db.php';

// ── Option A: Fetch from DB if you store wallet balance ──
// If you have a table like `admin_wallet` with usdt/bnb columns, use this:
$wallet_row = null;
if ($conn) {
    $res = mysqli_query($conn, "SELECT * FROM admin_wallet ORDER BY id DESC LIMIT 1");
    if ($res) $wallet_row = mysqli_fetch_assoc($res);
}

if ($wallet_row) {
    echo json_encode([
        'status' => 'success',
        'hot_wallet' => [
            'usdt' => floatval($wallet_row['usdt_balance'] ?? 0),
            'bnb'  => floatval($wallet_row['bnb_balance']  ?? 0),
        ]
    ]);
    exit;
}

// ── Option B: Calculate from withdrawal transactions ──
// Total deposited - Total withdrawn = available balance estimate
$deposited  = 0;
$withdrawn  = 0;

$dep_res = mysqli_query($conn, "SELECT SUM(amount) as total FROM deposits WHERE status='success'");
if ($dep_res) {
    $row = mysqli_fetch_assoc($dep_res);
    $deposited = floatval($row['total'] ?? 0);
}

$wdl_res = mysqli_query($conn, "SELECT SUM(net_amount) as total FROM withdrawals WHERE status IN ('success','completed')");
if ($wdl_res) {
    $row = mysqli_fetch_assoc($wdl_res);
    $withdrawn = floatval($row['total'] ?? 0);
}

$balance = max(0, $deposited - $withdrawn);

echo json_encode([
    'status' => 'success',
    'hot_wallet' => [
        'usdt' => $balance,
        'bnb'  => 0.0000, // Update this if you have BNB balance stored
    ]
]);