<?php 
session_start();
include 'includes/head.php';

// Get wallet data
$wallet_sql = "SELECT * FROM wallets WHERE user_id = '$user_id'";
$wallet_result = mysqli_query($conn, $wallet_sql);
$wallet = mysqli_fetch_assoc($wallet_result);

// Get USDT wallet address
$usdt_address = isset($wallet['usdt_address']) ? $wallet['usdt_address'] : '';
if (empty($usdt_address)) {
    // Generate new USDT address if doesn't exist
    $usdt_address = generateUsdtAddress();
    $update_sql = "UPDATE wallets SET usdt_address = '$usdt_address' WHERE user_id = '$user_id'";
    mysqli_query($conn, $update_sql);
}

// Get withdrawal settings from admin
$settings_sql = "SELECT * FROM system_settings WHERE setting_key IN ('withdrawal_fee', 'min_withdrawal', 'max_withdrawal', 'usdt_network')";
$settings_result = mysqli_query($conn, $settings_sql);
$settings = [];
while ($row = mysqli_fetch_assoc($settings_result)) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

$withdrawal_fee = isset($settings['withdrawal_fee']) ? floatval($settings['withdrawal_fee']) : 1.0; // 1%
$min_withdrawal = isset($settings['min_withdrawal']) ? floatval($settings['min_withdrawal']) : 10.0;
$max_withdrawal = isset($settings['max_withdrawal']) ? floatval($settings['max_withdrawal']) : 10000.0;
$usdt_network = isset($settings['usdt_network']) ? $settings['usdt_network'] : 'TRC20';

// Get pending deposits
$pending_deposits = [];
$pending_sql = "SELECT * FROM deposits WHERE user_id = '$user_id' AND status = 'pending' ORDER BY created_at DESC";
$pending_result = mysqli_query($conn, $pending_sql);
while ($row = mysqli_fetch_assoc($pending_result)) {
    $pending_deposits[] = $row;
}

// Get combined transaction history
$transactions_history = [];

// Get deposits
$deposits_sql = "SELECT 
                    id,
                    'deposit' as type,
                    amount,
                    transaction_hash as description,
                    status,
                    created_at,
                    NULL as fee,
                    amount as net_amount,
                    'USDT' as currency
                 FROM deposits 
                 WHERE user_id = '$user_id' 
                 ORDER BY created_at DESC 
                 LIMIT 10";

$deposits_result = mysqli_query($conn, $deposits_sql);
while ($row = mysqli_fetch_assoc($deposits_result)) {
    $row['description'] = 'USDT Deposit (TX: ' . substr($row['description'], 0, 10) . '...)';
    $transactions_history[] = $row;
}

// Get withdrawals
$withdrawals_sql = "SELECT 
                        id,
                        'withdrawal' as type,
                        amount,
                        destination_address as description,
                        status,
                        created_at,
                        fee,
                        amount - fee as net_amount,
                        'USDT' as currency
                    FROM withdrawals 
                    WHERE user_id = '$user_id' 
                    ORDER BY created_at DESC 
                    LIMIT 10";

$withdrawals_result = mysqli_query($conn, $withdrawals_sql);
while ($row = mysqli_fetch_assoc($withdrawals_result)) {
    $row['description'] = 'USDT Withdrawal to: ' . substr($row['description'], 0, 10) . '...';
    $transactions_history[] = $row;
}

// Get other transactions
$other_sql = "SELECT 
                id,
                type,
                amount,
                description,
                status,
                created_at,
                NULL as fee,
                amount as net_amount,
                currency
              FROM transactions 
              WHERE user_id = '$user_id' 
              ORDER BY created_at DESC 
              LIMIT 10";

$other_result = mysqli_query($conn, $other_sql);
while ($row = mysqli_fetch_assoc($other_result)) {
    $transactions_history[] = $row;
}

// Sort all transactions by date
usort($transactions_history, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

// Limit to 10 most recent transactions
$transactions_history = array_slice($transactions_history, 0, 10);

// Function to generate USDT address
function generateUsdtAddress() {
    $prefix = 'T';
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $address = $prefix;
    for ($i = 0; $i < 33; $i++) {
        $address .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $address;
}

// Function to generate QR code URL
function generateQRCodeUrl($address) {
    $url = "https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=" . urlencode($address) . "&choe=UTF-8";
    return $url;
}

// Function to get status badge class
function getStatusBadgeClass($status) {
    switch ($status) {
        case 'completed':
        case 'confirmed':
            return 'bg-success';
        case 'pending':
            return 'bg-warning';
        case 'processing':
            return 'bg-info';
        case 'rejected':
        case 'failed':
        case 'cancelled':
            return 'bg-danger';
        default:
            return 'bg-secondary';
    }
}

// Function to get status text
function getStatusText($status) {
    switch ($status) {
        case 'completed':
        case 'confirmed':
            return 'Completed';
        case 'pending':
            return 'Pending';
        case 'processing':
            return 'Processing';
        case 'rejected':
            return 'Rejected';
        case 'cancelled':
            return 'Cancelled';
        case 'failed':
            return 'Failed';
        default:
            return ucfirst($status);
    }
}

// Function to get transaction icon
function getTransactionIcon($type) {
    switch ($type) {
        case 'deposit':
            return 'fi fi-rr-download text-success';
        case 'withdrawal':
            return 'fi fi-rr-upload text-danger';
        case 'credit':
            return 'fi fi-rr-plus text-success';
        case 'debit':
            return 'fi fi-rr-minus text-danger';
        case 'profit':
            return 'fi fi-rr-chart-line-up text-success';
        case 'fee':
            return 'fi fi-rr-bank text-warning';
        default:
            return 'fi fi-rr-exchange text-info';
    }
}

// Calculate total withdrawable balance
$total_withdrawable = $availableBalance + ($funds_locked == 0 ? $fundBalance : 0) + $referral_balance;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <style>
    .wallet-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
        color: white;
        border-radius: 15px;
        border: none;
    }
    .balance-amount {
        font-size: 2.5rem;
        font-weight: bold;
        margin: 10px 0;
    }
    .quick-action-card {
        border: none;
        border-radius: 10px;
        transition: all 0.3s ease;
        text-align: center;
        padding: 20px;
        margin-bottom: 20px;
        cursor: pointer;
    }
    .quick-action-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 15px rgba(0,0,0,0.1);
    }
    .action-deposit { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; }
    .action-withdraw { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); color: white; }
    .action-history { background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); }
    .usdt-icon {
        width: 32px;
        height: 32px;
        margin-right: 10px;
    }
    .deposit-address-box {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 20px;
        margin: 20px 0;
    }
    .address-text {
        font-family: monospace;
        font-size: 14px;
        word-break: break-all;
        background: white;
        padding: 15px;
        border-radius: 8px;
        border: 2px dashed #dee2e6;
    }
    .qr-code-container {
        text-align: center;
        margin: 20px 0;
    }
    .qr-code-img {
        width: 200px;
        height: 200px;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 10px;
        background: white;
    }
    .network-badge {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 5px 15px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }
    .pending-deposit {
        background: #fff3cd;
        border-left: 4px solid #ffc107;
        padding: 15px;
        margin: 10px 0;
        border-radius: 8px;
    }
    .deposit-instruction {
        background: #d1ecf1;
        border-left: 4px solid #0dcaf0;
        padding: 15px;
        margin: 10px 0;
        border-radius: 8px;
    }
    .file-upload-box {
        border: 2px dashed #dee2e6;
        border-radius: 10px;
        padding: 30px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    .file-upload-box:hover {
        border-color: #667eea;
        background: #f8f9fa;
    }
    .file-upload-box.dragover {
        border-color: #667eea;
        background: #e7f3ff;
    }
    .withdrawal-fee-badge {
        background: #dc3545;
        color: white;
        padding: 3px 10px;
        border-radius: 15px;
        font-size: 11px;
        margin-left: 5px;
    }
    .transaction-type-deposit { color: #28a745; }
    .transaction-type-withdrawal { color: #dc3545; }
    .transaction-type-profit { color: #198754; }
    .transaction-type-fee { color: #fd7e14; }

    /* Balance source selector */
    .balance-source-option {
        border: 2px solid #e9ecef;
        border-radius: 10px;
        padding: 15px;
        margin-bottom: 10px;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    .balance-source-option:hover {
        border-color: #007bff;
        background-color: #f8f9fa;
    }
    .balance-source-option.selected {
        border-color: #007bff;
        background-color: #e7f3ff;
    }
    .balance-source-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        flex-shrink: 0;
    }
    .source-available { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
    .source-fund { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
    .source-referral { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
    .balance-source-info {
        flex: 1;
    }
    .balance-source-amount {
        font-weight: bold;
        font-size: 1.2rem;
    }
    .balance-source-label {
        color: #6c757d;
        font-size: 0.875rem;
    }
    
    /* Withdrawal summary */
    .withdrawal-summary {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 20px;
        margin: 20px 0;
    }
    .summary-item {
        display: flex;
        justify-content: space-between;
        padding: 8px 0;
        border-bottom: 1px solid #dee2e6;
    }
    .summary-item:last-child {
        border-bottom: none;
        font-weight: bold;
        font-size: 1.1rem;
    }
    .summary-label {
        color: #6c757d;
    }
    .summary-value {
        font-weight: 600;
    }
    
    /* Theme-aware styles for modals */
    .modal-content {
        background-color: var(--bs-modal-bg, var(--bs-body-bg)) !important;
        border-color: var(--bs-modal-border-color, var(--bs-border-color));
    }
    .modal-body {
        background-color: var(--bs-body-bg) !important;
    }
    .modal-header {
        background-color: var(--bs-modal-header-bg, var(--bs-secondary-bg));
        border-bottom-color: var(--bs-modal-header-border-color, var(--bs-border-color));
        color: var(--bs-modal-header-color, var(--bs-heading-color));
    }
    .modal-title {
        color: var(--bs-modal-title-color, var(--bs-heading-color));
    }
    .modal-footer {
        background-color: var(--bs-modal-footer-bg, var(--bs-secondary-bg));
        border-top-color: var(--bs-modal-footer-border-color, var(--bs-border-color));
    }
    </style>
</head>
<body class="dashboard">
    <div id="main-wrapper">
        <?php include('includes/header.php');?>
        <?php include('includes/sidebar.php');?>

        <div class="content-body">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title">
                            <div class="row align-items-center justify-content-between">
                                <div class="col-xl-4">
                                    <div class="page-title-content">
                                        <h3>USDT Wallet</h3>
                                        <p class="mb-2">Manage your USDT cryptocurrency funds</p>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <div class="breadcrumbs">
                                        <a href="dashboard.php">Home</a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="#">USDT Wallet</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ($userVerified == 0) { ?>
                    <div class="col-md-6">
                        <div class="card border-warning shadow-sm mb-3">
                            <div class="card-body bg-warning">
                                <div class="row align-items-center">
                                    <!-- Icon column - hidden on mobile, visible on desktop -->
                                    <div class="col-auto d-none d-md-block">
                                        <div class="icon-circle bg-danger ">
                                            <i class="fas fa-user-clock text-white fa-lg"></i>
                                        </div>
                                    </div>
                                    
                                    <!-- Content column -->
                                    <div class="col-md-8 col-12">
                                        <div class="d-flex align-items-center mb-2">
                                            <!-- Mobile icon - visible only on mobile -->
                                            <div class="d-md-none me-2">
                                                <i class="fas fa-user-clock text-white fa-lg"></i>
                                            </div>
                                            <div>
                                                <span class="badge bg-danger text-dark mb-1">VERIFICATION REQUIRED</span>
                                                <h6 class="mb-0 fw-bold">Complete KYC Verification</h6>
                                                <p class="text-muted small mb-2 mt-1">Verify your identity to access withdrawals and all trading features.</p>
                                            </div>
                                        </div>
                                        <div class="d-flex flex-wrap align-items-center gap-2">
                                            <a href="kyc-verification.php" class="btn btn-primary btn-sm">
                                                <i class="fas fa-id-card-alt me-1"></i> Verify Now
                                            </a>
                                            <small class="text-muted">
                                                <i class="fas fa-lock me-1"></i>Secure process
                                            </small>
                                        </div>
                                    </div>
                                    
                                    <!-- Badges column - stack on mobile -->
                                    <div class="col-md-12 col-12 mt-3 mt-md-0">
                                        <div class="text-md-end">
                                            <div class="small text-muted mb-1 d-none d-md-block">Unlocks:</div>
                                            <div class="d-flex flex-wrap gap-1 justify-content-start justify-content-md-end">
                                                <span class="badge bg-light text-dark border">Withdrawals</span>
                                                <span class="badge bg-light text-dark border">Trading Limits</span>
                                                <span class="badge bg-light text-dark border mt-1 mt-md-0">All Features</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php } ?>

                <!-- USDT Balance Card -->
                <div class="row">
                    <div class="col-xl-8">
                        <div class="card wallet-card">
                            <div class="card-body wallet-card">
                                <div class="row align-items-center">
                                    <div class="col-md-8">
                                        <div class="d-flex align-items-center mb-2">
                                            <img src="https://cryptologos.cc/logos/tether-usdt-logo.svg?v=035" class="usdt-icon" alt="USDT">
                                            <span class="network-badge"><?php echo htmlspecialchars($usdt_network); ?> Network</span>
                                        </div>

                                        <p class="mb-1">Available Balance</p>
                                        <?php if ($funds_locked == 1) { ?>
                                            <div class="balance-amount">$ <?php echo number_format($availableBalance, 2); ?></div>
                                        <?php } elseif ($funds_locked == 0) {?>
                                            <div class="balance-amount">$ <?php echo number_format($availableBalance + $fundBalance, 2); ?></div>
                                         <?php } ?>
                                        
                                        <div class="d-flex gap-4 mt-3">
                                            <div>
                                                <small>Total Balance</small>
                                                <div class="fw-bold">$ <?php echo number_format($availableBalance + $fundBalance, 2); ?></div>
                                            </div>
                                            <div>
                                                <?php if ($funds_locked == 1) { ?>
                                                    <small>Locked Funds</small>
                                                    <div class="fw-bold">$ <?php echo number_format($fundBalance, 2); ?></div>
                                                 <?php } elseif ($funds_locked == 0) {?>
                                                    <small>Trading Funds</small>
                                                    <div class="fw-bold">$ <?php echo number_format($fundBalance, 2); ?></div>
                                                <?php } ?>
                                            </div>
                                             <div>
                                                <small>Referral Balance</small>
                                                <div class="fw-bold text-warning">$ <?php echo number_format($referral_balance, 2); ?></div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 text-end">
                                        <div class="mb-3">
                                            <span class="badge bg-success">Active</span>
                                        </div>
                                        <div class="btn-group">
                                            <button class="btn btn-warning btn-sm me-2" onclick="showDepositModal()">
                                                <i class="fi fi-rr-download me-1"></i> Deposit USDT
                                            </button>
                                            <button class="btn btn-light btn-sm text-danger" onclick="showWithdrawalModal()">
                                                <i class="fi fi-rr-upload me-1"></i> Withdraw
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Pending Deposits -->
                        <?php if (!empty($pending_deposits)): ?>
                        <div class="card mt-4">
                            <div class="card-header">
                                <h5 class="card-title mb-0">Pending Deposits</h5>
                            </div>
                            <div class="card-body">
                                <?php foreach($pending_deposits as $deposit): ?>
                                <div class="pending-deposit">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <h6 class="mb-1">Deposit: $<?php echo number_format($deposit['amount'], 2); ?></h6>
                                            <small class="text-muted">
                                                TXID: <?php echo substr($deposit['transaction_hash'], 0, 20) . '...'; ?> • 
                                                <?php echo date('M j, Y g:i A', strtotime($deposit['created_at'])); ?>
                                            </small>
                                        </div>
                                        <div>
                                            <span class="badge bg-warning">Pending Confirmation</span>
                                        </div>
                                    </div>
                                    <?php if (!empty($deposit['note'])): ?>
                                    <div class="mt-2">
                                        <small><strong>Note:</strong> <?php echo htmlspecialchars($deposit['note']); ?></small>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Quick Actions -->
                        <div class="row mt-4">
                            <div class="col-md-4 col-4">
                                <div class="quick-action-card action-deposit" onclick="showDepositModal()">
                                    <div class="action-icon mb-3">
                                        <i class="fi fi-rr-download fs-1"></i>
                                    </div>
                                    <h6>Deposit USDT</h6>
                                    <small>Add USDT to wallet</small>
                                </div>
                            </div>
                            <div class="col-md-4 col-4">
                                <div class="quick-action-card action-withdraw" onclick="showWithdrawalModal()">
                                    <div class="action-icon mb-3">
                                       <i class="fi fi-rr-upload fs-1"></i>
                                    </div>
                                    <h6>Withdraw USDT</h6>
                                    <small>Withdraw from your balances</small>
                                </div>
                            </div>
                            <div class="col-md-4 col-4">
                                <div class="quick-action-card action-history" onclick="viewTransactionHistory()">
                                    <div class="action-icon mb-3">
                                        <i class="fi fi-rr-list fs-1"></i>
                                    </div>
                                    <h6>Transaction History</h6>
                                    <small>View all transactions</small>
                                </div>
                            </div>
                        </div>

                        <!-- Recent Transactions -->
                        <div class="card mt-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0">Recent Transactions</h5>
                                <a href="transaction_history.php" class="btn btn-outline-primary btn-sm">View All</a>
                            </div>
                            <div class="card-body">
                                <?php if (!empty($transactions_history)): ?>
                                    <div class="transaction-list">
                                        <?php foreach($transactions_history as $transaction): 
                                            $type_class = '';
                                            switch($transaction['type']) {
                                                case 'deposit':
                                                case 'credit':
                                                case 'profit':
                                                    $type_class = 'transaction-type-deposit';
                                                    $sign = '+';
                                                    break;
                                                case 'withdrawal':
                                                case 'debit':
                                                    $type_class = 'transaction-type-withdrawal';
                                                    $sign = '-';
                                                    break;
                                                case 'fee':
                                                    $type_class = 'transaction-type-fee';
                                                    $sign = '-';
                                                    break;
                                                default:
                                                    $type_class = 'transaction-type-deposit';
                                                    $sign = '+';
                                            }
                                        ?>
                                        <div class="d-flex justify-content-between align-items-center py-3 border-bottom">
                                            <div class="d-flex align-items-center">
                                                <div class="transaction-icon me-3">
                                                    <i class="<?php echo getTransactionIcon($transaction['type']); ?> fs-4"></i>
                                                </div>
                                                <div>
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($transaction['description']); ?></h6>
                                                    <small class="text-muted">
                                                        <?php echo date('M j, Y g:i A', strtotime($transaction['created_at'])); ?>
                                                        • <?php echo ucfirst($transaction['type']); ?>
                                                    </small>
                                                </div>
                                            </div>
                                            <div class="text-end">
                                                <div class="fw-bold <?php echo $type_class; ?>">
                                                    <?php echo $sign; ?>$ <?php echo number_format($transaction['net_amount'], 2); ?>
                                                    <?php if ($transaction['type'] == 'withdrawal' && $transaction['fee'] > 0): ?>
                                                        <br><small class="text-muted">Fee: $<?php echo number_format($transaction['fee'], 2); ?></small>
                                                    <?php endif; ?>
                                                </div>
                                                <span class="badge <?php echo getStatusBadgeClass($transaction['status']); ?>">
                                                    <?php echo getStatusText($transaction['status']); ?>
                                                </span>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="text-center py-4">
                                        <i class="fi fi-rr-receipt fs-1 text-muted mb-3"></i>
                                        <p class="text-muted">No transactions yet</p>
                                        <button class="btn btn-primary" onclick="showDepositModal()">Make Your First Deposit</button>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- USDT Information Sidebar -->
                    <div class="col-xl-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">USDT Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="deposit-instruction">
                                    <h6 class="mb-2">Deposit Instructions:</h6>
                                    <ol class="mb-0 ps-3">
                                        <li class="mb-1">Send USDT to your address below</li>
                                        <li class="mb-1">Use <strong><?php echo htmlspecialchars($usdt_network); ?></strong> network only</li>
                                        <li class="mb-1">Minimum deposit: $10.00</li>
                                        <li class="mb-1">Upload receipt after sending</li>
                                        <li>Contact support if not credited within 30 minutes</li>
                                    </ol>
                                </div>
                                
                                <div class="mt-4">
                                    <h6>Current Network:</h6>
                                    <div class="d-flex align-items-center mb-3">
                                        <span class="network-badge"><?php echo htmlspecialchars($usdt_network); ?></span>
                                        <small class="text-muted ms-2">(Lowest fees)</small>
                                    </div>
                                    
                                    <h6>Withdrawal Settings:</h6>
                                    <div class="mb-2">
                                        <small class="text-muted">Minimum:</small>
                                        <div class="fw-bold">$ <?php echo number_format($min_withdrawal, 2); ?></div>
                                    </div>
                                    <div class="mb-2">
                                        <small class="text-muted">Maximum:</small>
                                        <div class="fw-bold">$ <?php echo number_format($max_withdrawal, 2); ?></div>
                                    </div>
                                    <div class="mb-3">
                                        <small class="text-muted">Withdrawal Fee:</small>
                                        <div class="fw-bold"><?php echo number_format($withdrawal_fee, 2); ?>% 
                                            <span class="withdrawal-fee-badge">Paid by user</span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="alert alert-warning mt-3">
                                    <small>
                                        <i class="fi fi-rr-exclamation me-1"></i>
                                        <strong>Important:</strong> Always verify the network before sending. 
                                        Sending via wrong network may result in permanent loss of funds.
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php include('includes/footer.php');?>
    </div>

    <!-- Modals -->
    <!-- Deposit USDT Modal (same as before, kept for reference) -->

    <div class="modal fade" id="depositModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content" >
                <div class="modal-header">
                    <h5 class="modal-title text-dark">Deposit USDT</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" style="background: #18212f !important;">
                    <!-- Step 1: Show Deposit Address -->
                    <div id="depositStep1">
                        <div class="deposit-address-box" >
                            <div class="text-center mb-4">
                                <h6 class="mb-3  text-dark">Send USDT to this address:</h6>
                                
                                <!-- Centered QR Code -->
                                <div class="d-flex justify-content-center mb-4">
                                    <div class="qr-code-wrapper">
                                        <img src="<?php echo generateQRCodeUrl($usdt_address); ?>" 
                                             alt="USDT Deposit QR Code" 
                                             class="qr-code-img">
                                    </div>
                                </div>
                                <p class="text-muted mb-4">Scan QR code with your wallet</p>
                            </div>
                            
                            <div class="mb-4">
                                <label class="form-label">Your USDT Address:</label>
                                <div class="input-group">
                                    <input type="text" 
                                           class="form-control address-text" 
                                           id="usdtAddress" 
                                           value="<?php echo htmlspecialchars($usdt_address); ?>" 
                                           readonly>
                                    <button class="btn btn-outline-secondary" type="button" onclick="copyAddress()">
                                        <i class="fi fi-rr-copy"></i>
                                    </button>
                                </div>
                                <small class="text-muted mt-2 d-block">Click the copy button to copy your deposit address</small>
                            </div>
                            
                            <div class="alert alert-warning">
                                <i class="fi fi-rr-exclamation me-2"></i>
                                <strong>Important:</strong> Send only via <strong><?php echo htmlspecialchars($usdt_network); ?></strong> network. 
                                Sending via other networks will result in permanent loss of funds.
                            </div>
                            
                            <div class="alert alert-info">
                                <i class="fi fi-rr-clock me-2"></i>
                                <strong>Processing Time:</strong> Deposits typically take 1-30 minutes to confirm after verification.
                            </div>
                        </div>
                        
                        <div class="text-center mt-4">
                            <button class="btn btn-primary btn-lg" onclick="showDepositStep2()">
                                <i class="fi fi-rr-check me-2"></i>
                                I've Sent USDT, Proceed to Verification
                                <i class="fi fi-rr-arrow-right ms-1"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Step 2: Upload Receipt -->
                    <div id="depositStep2" style="display: none;">
                        <div class="text-center mb-4">
                            <div class="deposit-step-icon mb-3">
                                <i class="fi fi-rr-document-signed fs-1 text-primary"></i>
                            </div>
                            <h5>Verify Your Deposit</h5>
                            <p class="text-muted">Submit proof of your USDT deposit for verification</p>
                        </div>
                        
                        <form id="depositReceiptForm" enctype="multipart/form-data">
                            <div class="mb-4">
                                <label class="form-label">Deposit Amount (USDT)</label>
                                <input type="number" 
                                       class="form-control form-control-lg" 
                                       name="deposit_amount" 
                                       min="10" 
                                       step="0.01" 
                                       placeholder="10.00" 
                                       required>
                                <div class="form-text">Minimum deposit: $10.00</div>
                            </div>
                            
                            <div class="mb-4">
                                <label class="form-label">Transaction Hash (Optional)</label>
                                <input type="text" 
                                       class="form-control" 
                                       name="transaction_hash" 
                                       placeholder="Enter transaction hash if available (optional)">
                                <div class="form-text">
                                    <i class="fi fi-rr-info me-1"></i>
                                    You can find this in your wallet transaction history. Not required but helps with faster verification.
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <label class="form-label">Upload Receipt/Screenshot</label>
                                <div class="file-upload-box" id="fileUploadBox" onclick="document.getElementById('receiptFile').click()">
                                    <div class="file-upload-icon mb-3">
                                        <i class="fi fi-rr-cloud-upload fs-1"></i>
                                    </div>
                                    <h6 class="mb-2">Click to upload or drag and drop</h6>
                                    <p class="text-muted mb-0">PNG, JPG, PDF up to 5MB</p>
                                    <input type="file" 
                                           id="receiptFile" 
                                           name="receipt" 
                                           accept=".jpg,.jpeg,.png,.pdf" 
                                           style="display: none;" 
                                           required>
                                </div>
                                <div id="fileName" class="mt-3 text-center">
                                    <span class="badge bg-secondary">No file selected</span>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <label class="form-label">Note (Optional)</label>
                                <textarea class="form-control" 
                                          name="note" 
                                          rows="3" 
                                          placeholder="Add any notes about this deposit (e.g., reference, time sent, etc.)"></textarea>
                            </div>
                            
                            <div class="alert alert-success">
                                <div class="d-flex">
                                    <i class="fi fi-rr-info mt-1 me-3"></i>
                                    <div>
                                        <strong>Verification Process:</strong>
                                        <ul class="mb-0 ps-3">
                                            <li>Submit your deposit details</li>
                                            <li>Our team will verify your transaction</li>
                                            <li>Funds will be credited within 30 minutes after verification</li>
                                            <li>You'll receive email confirmation</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-outline-secondary" onclick="showDepositStep1()">
                                    <i class="fi fi-rr-arrow-left me-1"></i> Back to Address
                                </button>
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="fi fi-rr-check me-1"></i>
                                    Submit for Verification
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Withdraw USDT Modal -->
    <div class="modal fade" id="withdrawalModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content bg-dark" style="background: #000000 !important;">
                <div class="modal-header">
                    <h5 class="modal-title">Withdraw USDT</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body bg-dark"  style="background: #000000 !important;">
                    <div class="text-center mb-4">
                        <div class="withdrawal-step-icon mb-3 text-center">
                            <center>
                                <img src="https://cryptologos.cc/logos/tether-usdt-logo.svg?v=035" class="usdt-icon" style="width:500px" alt="USDT">
                            </center>
                            
                        </div>
                        <h5>Withdraw USDT to External Wallet</h5>
                        <p class="text-muted">Select balance source and enter withdrawal details</p>
                    </div>
                    
                    <form id="withdrawalForm">
                        <!-- Step 1: Select Balance Source -->
                        <div id="withdrawalStep1">
                            <h6 class="mb-3">Select Balance Source:</h6>
                            
                            <!-- Available Balance Option -->
                            <div class="balance-source-option" data-source="available_balance" onclick="selectBalanceSource('available_balance')">
                                <div class="d-flex align-items-center">
                                    <div class="balance-source-icon source-available">
                                        <i class="fi fi-rr-wallet text-white"></i>
                                    </div>
                                    <div class="balance-source-info">
                                        <div class="balance-source-amount">$ <?php echo number_format($availableBalance, 2); ?></div>
                                        <div class="balance-source-label">Available Balance</div>
                                        <small class="text-muted">Immediate withdrawal - no restrictions</small>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="balance_source" value="available_balance" required>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Fund Balance Option (only if not locked) -->
                            <?php if ($funds_locked == 0): ?>
                            <div class="balance-source-option" data-source="fund_balance" onclick="selectBalanceSource('fund_balance')">
                                <div class="d-flex align-items-center">
                                    <div class="balance-source-icon source-fund">
                                        <i class="fi fi-rr-chart-line-up text-white"></i>
                                    </div>
                                    <div class="balance-source-info">
                                        <div class="balance-source-amount">$ <?php echo number_format($fundBalance, 2); ?></div>
                                        <div class="balance-source-label">Trading Funds</div>
                                        <small class="text-muted">Withdraw trading profits and capital</small>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="balance_source" value="fund_balance">
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Referral Balance Option -->
                            <?php if ($referral_balance > 0): ?>
                            <div class="balance-source-option" data-source="referral_balance" onclick="selectBalanceSource('referral_balance')">
                                <div class="d-flex align-items-center">
                                    <div class="balance-source-icon source-referral">
                                        <i class="fi fi-rr-users text-white"></i>
                                    </div>
                                    <div class="balance-source-info">
                                        <div class="balance-source-amount">$ <?php echo number_format($referral_balance, 2); ?></div>
                                        <div class="balance-source-label">Referral Earnings</div>
                                        <small class="text-muted">Withdraw your referral commissions</small>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="balance_source" value="referral_balance">
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <div class="alert alert-info mt-3">
                                <i class="fi fi-rr-info me-2"></i>
                                <strong class="text-dark">Note:</strong> Select the balance source you want to withdraw from. Each source may have different withdrawal conditions.
                            </div>
                            
                            <div class="text-center mt-4">
                                <button type="button" class="btn btn-primary btn-lg" onclick="showWithdrawalStep2()">
                                    <i class="fi fi-rr-arrow-right me-2"></i>
                                    Continue to Withdrawal Details
                                </button>
                            </div>
                        </div>
                        
                        <!-- Step 2: Withdrawal Details -->
                        <div id="withdrawalStep2" style="display: none;">
                            <div class="mb-4">
                                <label class="form-label">Selected Balance Source</label>
                                <div class="alert alert-info">
                                    <strong id="selectedSourceDisplay">Available Balance</strong>
                                    <div class="mt-1">
                                        <small>Available amount: <strong id="selectedBalanceAmount">$0.00</strong></small>
                                    </div>
                                    <button type="button" class="btn btn-sm btn-outline-primary mt-2" onclick="showWithdrawalStep1()">
                                        <i class="fi fi-rr-arrow-left me-1"></i> Change Source
                                    </button>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <label class="form-label">Withdrawal Amount (USDT)</label>
                                <input type="number" 
                                       class="form-control form-control-lg" 
                                       name="amount" 
                                       id="withdrawalAmount"
                                       min="<?php echo $min_withdrawal; ?>" 
                                       step="0.01" 
                                       placeholder="10.00" 
                                       required>
                                <div class="form-text">
                                    Minimum: $<?php echo number_format($min_withdrawal, 2); ?> • 
                                    Maximum: Based on selected balance
                                </div>
                            </div>
                            
                            <!-- Withdrawal Summary -->
                            <div class="withdrawal-summary">
                                <h6 class="mb-3">Withdrawal Summary</h6>
                                <div class="summary-item">
                                    <span class="summary-label">Withdrawal Amount:</span>
                                    <span id="summaryAmount" class="summary-value">$0.00</span>
                                </div>
                                <div class="summary-item">
                                    <span class="summary-label">Network Fee (<?php echo number_format($withdrawal_fee, 2); ?>%):</span>
                                    <span id="summaryFee" class="summary-value text-danger">-$0.00</span>
                                </div>
                                <div class="summary-item">
                                    <span class="summary-label">You Will Receive:</span>
                                    <span id="summaryReceive" class="summary-value text-success">$0.00</span>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <label class="form-label text-dark">Destination USDT Address</label>
                                <input type="text" 
                                       class="form-control" 
                                       name="destination_address" 
                                       placeholder="Enter your external USDT address" 
                                       required>
                                <div class="form-text">
                                    <i class="fi fi-rr-shield-check me-1"></i>
                                    Make sure this is a <strong><?php echo htmlspecialchars($usdt_network); ?></strong> network address
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="confirmNetwork" required>
                                    <label class="form-check-label" for="confirmNetwork">
                                        <strong>Network Confirmation:</strong> I confirm this is a <strong><?php echo htmlspecialchars($usdt_network); ?></strong> network address
                                    </label>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="confirmIrreversible" required>
                                    <label class="form-check-label" for="confirmIrreversible">
                                        <strong>Irreversible Transaction:</strong> I understand that USDT withdrawals cannot be reversed
                                    </label>
                                </div>
                            </div>
                            
                            <div class="alert alert-warning">
                                <div class="d-flex">
                                    <i class="fi fi-rr-exclamation mt-1 me-3"></i>
                                    <div>
                                        <strong class=""text-dark>Important Information:</strong>
                                        <ul class="mb-0 ps-3">
                                            <li>Withdrawals are processed within 24 hours</li>
                                            <li>Double-check the destination address</li>
                                            <li>Transactions cannot be reversed</li>
                                            <li>Network fees are non-refundable</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between mt-4">
                                <button type="button" class="btn btn-outline-secondary" onclick="showWithdrawalStep1()">
                                    <i class="fi fi-rr-arrow-left me-1"></i> Back
                                </button>
                                <button type="button" class="btn btn-primary btn-lg" id="submitWithdrawal" onclick="submitWithdrawal()" disabled>
                                    <i class="fi fi-rr-check me-1"></i>
                                    Confirm Withdrawal
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    
    <script>
    // Global variables
    let selectedSource = '';
    let selectedBalance = 0;
    
    // Balance source data
    const balanceSources = {
        'available_balance': <?php echo $availableBalance; ?>,
        'fund_balance': <?php echo $funds_locked == 0 ? $fundBalance : 0; ?>,
        'referral_balance': <?php echo $referral_balance; ?>
    };
    
    // Source labels
    const sourceLabels = {
        'available_balance': 'Available Balance',
        'fund_balance': 'Trading Funds',
        'referral_balance': 'Referral Earnings'
    };
    
    // Withdrawal Functions
    function showWithdrawalModal() {
        const modal = new bootstrap.Modal(document.getElementById('withdrawalModal'));
        modal.show();
        showWithdrawalStep1();
    }
    
    function selectBalanceSource(source) {
        // Remove selected class from all options
        $('.balance-source-option').removeClass('selected');
        
        // Add selected class to clicked option
        $(`.balance-source-option[data-source="${source}"]`).addClass('selected');
        
        // Set the radio button as checked
        $(`input[name="balance_source"][value="${source}"]`).prop('checked', true);
        
        // Update global variables
        selectedSource = source;
        selectedBalance = balanceSources[source];
    }
    
    function showWithdrawalStep1() {
        $('#withdrawalStep1').show();
        $('#withdrawalStep2').hide();
    }
    
    function showWithdrawalStep2() {
        const selectedSource = $('input[name="balance_source"]:checked').val();
        
        if (!selectedSource) {
            alert('Please select a balance source to withdraw from.');
            return;
        }
        
        // Update display
        $('#selectedSourceDisplay').text(sourceLabels[selectedSource]);
        $('#selectedBalanceAmount').text('$' + balanceSources[selectedSource].toFixed(2));
        
        // Set max withdrawal amount
        const maxAmount = Math.min(balanceSources[selectedSource], <?php echo $max_withdrawal; ?>);
        $('#withdrawalAmount').attr('max', maxAmount);
        
        // Reset and calculate
        $('#withdrawalAmount').val('');
        calculateWithdrawal();
        
        // Show step 2
        $('#withdrawalStep1').hide();
        $('#withdrawalStep2').show();
    }
    
    function calculateWithdrawal() {
        const amount = parseFloat($('#withdrawalAmount').val()) || 0;
        const feePercent = <?php echo $withdrawal_fee; ?>;
        const minAmount = <?php echo $min_withdrawal; ?>;
        const maxAmount = Math.min(selectedBalance, <?php echo $max_withdrawal; ?>);
        
        // Update amount display
        $('#summaryAmount').text('$' + amount.toFixed(2));
        
        // Validate amount
        let isValid = true;
        let errorMessage = '';
        
        if (amount < minAmount) {
            errorMessage = 'Minimum: $' + minAmount.toFixed(2);
            isValid = false;
        } else if (amount > maxAmount) {
            errorMessage = 'Maximum: $' + maxAmount.toFixed(2);
            isValid = false;
        } else if (amount > selectedBalance) {
            errorMessage = 'Insufficient balance in selected source';
            isValid = false;
        }
        
        // Highlight input if invalid
        const $input = $('#withdrawalAmount');
        const $helpText = $input.next('.form-text');
        
        if (!isValid) {
            $input.addClass('is-invalid');
            $helpText.html('<span class="text-danger">' + errorMessage + '</span>');
        } else {
            $input.removeClass('is-invalid');
            $helpText.html('Minimum: $' + minAmount.toFixed(2) + ' • Maximum: $' + maxAmount.toFixed(2));
        }
        
        // Calculate fee and receive amount
        const fee = amount * (feePercent / 100);
        const receive = amount - fee;
        
        $('#summaryFee').text('-$' + fee.toFixed(2));
        $('#summaryReceive').text('$' + receive.toFixed(2));
        
        updateWithdrawalButton();
    }
    
    function updateWithdrawalButton() {
        const amount = parseFloat($('#withdrawalAmount').val()) || 0;
        const minAmount = <?php echo $min_withdrawal; ?>;
        const maxAmount = Math.min(selectedBalance, <?php echo $max_withdrawal; ?>);
        const confirmNetwork = $('#confirmNetwork').is(':checked');
        const confirmIrreversible = $('#confirmIrreversible').is(':checked');
        const hasAddress = $('input[name="destination_address"]').val().trim().length > 0;
        
        const isValid = amount >= minAmount && 
                       amount <= maxAmount && 
                       amount <= selectedBalance && 
                       confirmNetwork && 
                       confirmIrreversible && 
                       hasAddress;
        
        const $button = $('#submitWithdrawal');
        $button.prop('disabled', !isValid);
        
        // Update button appearance based on validation
        if (isValid) {
            $button.removeClass('btn-secondary').addClass('btn-primary');
        } else {
            $button.removeClass('btn-primary').addClass('btn-secondary');
        }
    }
    
    function submitWithdrawal() {
        const formData = $('#withdrawalForm').serialize();
        const selectedSource = $('input[name="balance_source"]:checked').val();
        
        $.ajax({
            url: 'process_withdrawal.php',
            method: 'POST',
            data: formData + '&balance_source=' + selectedSource,
            success: function(response) {
                try {
                    const result = JSON.parse(response);
                    if (result.success) {
                        alert('Withdrawal request submitted successfully! It will be processed within 24 hours.');
                        bootstrap.Modal.getInstance(document.getElementById('withdrawalModal')).hide();
                        location.reload();
                    } else {
                        alert('Error: ' + result.message);
                    }
                } catch (e) {
                    alert('Server error. Please try again.');
                }
            },
            error: function() {
                alert('Network error. Please try again.');
            }
        });
    }
    
    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        // Withdrawal amount calculation
        $('#withdrawalAmount').on('input', function() {
            calculateWithdrawal();
        });
        
        // Network confirmation
        $('#confirmNetwork').on('change', function() {
            updateWithdrawalButton();
        });
        
        // Irreversible confirmation
        $('#confirmIrreversible').on('change', function() {
            updateWithdrawalButton();
        });
        
        // Destination address validation
        $('input[name="destination_address"]').on('input', function() {
            updateWithdrawalButton();
        });
        
        // Auto-select first available balance source
        if ($('input[name="balance_source"]').length > 0) {
            const firstSource = $('input[name="balance_source"]').first().val();
            selectBalanceSource(firstSource);
        }
    });
    
    // Deposit Functions (kept from previous code)
    function showDepositModal() {
        const modal = new bootstrap.Modal(document.getElementById('depositModal'));
        modal.show();
        showDepositStep1();
    }
    
    function viewTransactionHistory() {
        window.location.href = 'transaction_history.php';
    }
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>