<?php
require_once 'functions.php';
requireAuth();

$user = getCurrentUser();
$db = getDB();

// Get active crypto wallets
$wallets = $db->query("SELECT * FROM crypto_wallets WHERE is_active = 1 ORDER BY coin_name");

// Get user's deposit history - FIXED: Use prepared statement instead of passing array to query()
$deposits = null;
$stmt = $db->prepare("
    SELECT cd.*, cw.coin_name, cw.coin_symbol, cw.network 
    FROM crypto_deposits cd 
    JOIN crypto_wallets cw ON cd.wallet_id = cw.id 
    WHERE cd.user_id = ? 
    ORDER BY cd.created_at DESC 
    LIMIT 20
");
if ($stmt) {
    $stmt->bind_param("i", $user['id']);
    $stmt->execute();
    $deposits = $stmt->get_result();
    $stmt->close();
}

$flash = getFlash();

/**
 * Fetch live crypto prices from CoinGecko API
 */
function fetchLiveRates(array $coinIds): array {
    if (empty($coinIds)) return [];
    
    $ids = implode(',', $coinIds);
    $url = "https://api.coingecko.com/api/v3/simple/price?ids=" . urlencode($ids) . "&vs_currencies=usd";
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200 && $response) {
        $data = json_decode($response, true);
        if (is_array($data)) {
            $rates = [];
            foreach ($data as $coinId => $info) {
                if (isset($info['usd']) && $info['usd'] > 0) {
                    $rates[$coinId] = (float)$info['usd'];
                }
            }
            return $rates;
        }
    }
    
    return [];
}

// Map coin names to CoinGecko IDs
$coinGeckoIds = [
    'bitcoin' => 'bitcoin',
    'ethereum' => 'ethereum',
    'tether' => 'tether',
    'litecoin' => 'litecoin',
    'bitcoin_cash' => 'bitcoin-cash',
    'dogecoin' => 'dogecoin',
    'cardano' => 'cardano',
    'solana' => 'solana',
    'polkadot' => 'polkadot',
    'ripple' => 'ripple',
    'binancecoin' => 'binancecoin',
    'usd_coin' => 'usd-coin',
    'tron' => 'tron',
    'chainlink' => 'chainlink',
    'polygon' => 'matic-network',
    'avalanche' => 'avalanche-2',
    'uniswap' => 'uniswap',
    'cosmos' => 'cosmos',
    'stellar' => 'stellar',
    'monero' => 'monero',
];

// Collect CoinGecko IDs
$apiIds = [];
$walletMap = [];

$wallets->data_seek(0);
while ($wallet = $wallets->fetch_assoc()) {
    $key = strtolower($wallet['coin_name']);
    $cgId = $coinGeckoIds[$key] ?? $key;
    $apiIds[] = $cgId;
    $walletMap[$key] = ['cg_id' => $cgId, 'wallet' => $wallet];
}

// Fetch live rates
$liveRates = fetchLiveRates($apiIds);

// Get rate with fallback chain
function getRate(string $key, array $liveRates, array $walletMap): float {
    $cgId = $walletMap[$key]['cg_id'] ?? $key;
    if (isset($liveRates[$cgId]) && $liveRates[$cgId] > 0) {
        return $liveRates[$cgId];
    }
    $wallet = $walletMap[$key]['wallet'] ?? [];
    $dbRate = (float)($wallet['rate'] ?? 0);
    if ($dbRate > 0) return $dbRate;
    
    $defaults = [
        'bitcoin' => 65000, 'ethereum' => 3500, 'tether' => 1, 'litecoin' => 80,
        'bitcoin_cash' => 450, 'dogecoin' => 0.16, 'cardano' => 0.45, 'solana' => 150,
        'polkadot' => 7, 'ripple' => 0.62, 'binancecoin' => 600, 'usd_coin' => 1,
        'tron' => 0.12, 'chainlink' => 18, 'polygon' => 0.7, 'avalanche' => 35,
        'uniswap' => 10, 'cosmos' => 8, 'stellar' => 0.11, 'monero' => 170,
    ];
    return $defaults[$key] ?? 1;
}

function isLiveRate(string $key, array $liveRates, array $walletMap): bool {
    $cgId = $walletMap[$key]['cg_id'] ?? $key;
    return isset($liveRates[$cgId]) && $liveRates[$cgId] > 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Crypto Deposit - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        /* ── Modal Overlay ── */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.6);
            z-index: 1000;
            justify-content: center;
            align-items: center;
            padding: 20px;
            backdrop-filter: blur(4px);
        }

        .modal-overlay.active {
            display: flex;
        }

        .modal-box {
            background: var(--white);
            border-radius: var(--border-radius-lg);
            width: 100%;
            max-width: 900px;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
            animation: modalSlideIn 0.3s ease;
            box-shadow: var(--shadow-lg);
        }

        @keyframes modalSlideIn {
            from { opacity: 0; transform: translateY(-30px) scale(0.95); }
            to { opacity: 1; transform: translateY(0) scale(1); }
        }

        .modal-close {
            position: absolute;
            top: 16px;
            right: 16px;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: var(--gray-100);
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            color: var(--gray);
            transition: var(--transition);
            z-index: 10;
        }

        .modal-close:hover {
            background: var(--gray-200);
            color: var(--secondary);
        }

        /* ── Normal Responsive Grid ── */
        .crypto-select-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
        }

        @media (max-width: 767px) {
            .crypto-select-grid {
                grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
                gap: 16px;
            }
        }

        @media (max-width: 480px) {
            .crypto-select-grid {
                grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
                gap: 12px;
            }
        }

        .crypto-select-card {
            background: var(--white);
            border: 2px solid var(--gray-200);
            border-radius: var(--border-radius-lg);
            padding: 28px 20px;
            text-align: center;
            cursor: pointer;
            transition: var(--transition);
            position: relative;
            overflow: hidden;
        }

        .crypto-select-card:hover {
            border-color: var(--primary);
            box-shadow: var(--shadow-lg);
            transform: translateY(-4px);
        }

        .crypto-select-card.active {
            border-color: var(--primary);
            background: var(--primary-light);
            box-shadow: var(--shadow-lg);
        }

        .crypto-select-card.active .select-indicator {
            background: var(--danger);
            color: var(--white);
        }

        .crypto-select-card .coin-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 30px;
            margin: 0 auto 14px;
            font-weight: 700;
        }

        .crypto-select-card .coin-name {
            font-size: 16px;
            font-weight: 700;
            color: var(--secondary);
            margin-bottom: 4px;
            text-transform: capitalize;
        }

        .crypto-select-card .coin-symbol {
            font-size: 13px;
            color: var(--gray);
            font-family: 'Courier New', monospace;
            margin-bottom: 6px;
        }

        .live-rate-badge {
            display: inline-block;
            padding: 4px 10px;
            background: var(--success-light);
            color: var(--success);
            border-radius: 50px;
            font-size: 11px;
            font-weight: 700;
            font-family: 'Courier New', monospace;
            margin-bottom: 12px;
        }

        .live-rate-badge.stale {
            background: var(--warning-light);
            color: var(--warning);
        }

        /* ── RED DEPOSIT BUTTON ── */
        .select-indicator {
            display: inline-block;
            padding: 8px 20px;
            background: var(--danger);
            color: var(--white);
            border-radius: var(--border-radius);
            font-size: 13px;
            font-weight: 700;
            transition: var(--transition);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .select-indicator:hover {
            background: #dc2626;
            transform: scale(1.05);
        }

        /* ── Modal Content ── */
        .modal-header {
            padding: 24px 28px;
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .modal-header .panel-icon {
            width: 44px;
            height: 44px;
            border-radius: var(--border-radius);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 22px;
            font-weight: 700;
        }

        .modal-header .panel-title {
            font-size: 20px;
            font-weight: 700;
            color: var(--secondary);
            text-transform: capitalize;
        }

        .badge-row {
            display: flex;
            gap: 8px;
            margin-top: 4px;
            flex-wrap: wrap;
        }

        .net-badge {
            display: inline-flex;
            align-items: center;
            padding: 3px 10px;
            background: var(--info-light);
            color: var(--info);
            border-radius: 50px;
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
        }

        .min-badge {
            display: inline-flex;
            align-items: center;
            padding: 3px 10px;
            background: var(--warning-light);
            color: var(--warning);
            border-radius: 50px;
            font-size: 11px;
            font-weight: 700;
        }

        .rate-badge {
            display: inline-flex;
            align-items: center;
            padding: 3px 10px;
            background: var(--success-light);
            color: var(--success);
            border-radius: 50px;
            font-size: 11px;
            font-weight: 700;
            font-family: 'Courier New', monospace;
        }

        .rate-badge.stale {
            background: var(--warning-light);
            color: var(--warning);
        }

        .modal-body {
            padding: 28px;
        }

        .deposit-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 32px;
            align-items: start;
        }

        @media (max-width: 767px) {
            .deposit-grid {
                grid-template-columns: 1fr;
            }
        }

        /* ── QR & Address ── */
        .qr-wrap {
            text-align: center;
            padding: 24px;
            background: var(--gray-50);
            border-radius: var(--border-radius);
            margin-bottom: 20px;
        }

        .qr-box {
            width: 180px;
            height: 180px;
            background: var(--white);
            border-radius: var(--border-radius);
            padding: 12px;
            margin: 0 auto 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: var(--shadow-sm);
        }

        .qr-box svg {
            width: 100%;
            height: 100%;
        }

        .qr-caption {
            font-size: 13px;
            color: var(--gray);
        }

        .address-wrap {
            background: var(--gray-50);
            border: 2px dashed var(--gray-200);
            border-radius: var(--border-radius);
            padding: 16px;
            transition: var(--transition);
        }

        .address-wrap:hover {
            border-color: var(--primary);
        }

        .address-wrap label {
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            color: var(--gray);
            letter-spacing: 0.5px;
            display: block;
            margin-bottom: 8px;
        }

        .copy-row {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        .copy-row input {
            flex: 1;
            padding: 12px 14px;
            background: var(--white);
            border: 1px solid var(--gray-200);
            border-radius: var(--border-radius-sm);
            font-family: 'Courier New', monospace;
            font-size: 13px;
            color: var(--secondary);
            outline: none;
        }

        .copy-row button {
            padding: 12px 18px;
            background: var(--primary);
            color: var(--white);
            border: none;
            border-radius: var(--border-radius-sm);
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            white-space: nowrap;
        }

        .copy-row button:hover {
            background: var(--primary-dark);
        }

        .copy-row button.copied {
            background: var(--success);
        }

        /* ── Deposit Form ── */
        .deposit-form-group {
            margin-bottom: 20px;
        }

        .deposit-form-group label {
            display: block;
            font-size: 12px;
            font-weight: 700;
            text-transform: uppercase;
            color: var(--gray);
            letter-spacing: 0.5px;
            margin-bottom: 6px;
        }

        .deposit-form-group input {
            width: 100%;
            padding: 14px 16px;
            background: var(--white);
            border: 2px solid var(--gray-200);
            border-radius: var(--border-radius);
            color: var(--secondary);
            font-size: 18px;
            font-weight: 600;
            transition: var(--transition);
            outline: none;
        }

        .deposit-form-group input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px var(--primary-light);
        }

        .deposit-form-group .hint {
            margin-top: 6px;
            font-size: 12px;
            color: var(--gray);
        }

        /* ── RED SUBMIT BUTTON ── */
        .submit-deposit-btn {
            width: 100%;
            padding: 16px;
            background: var(--danger);
            color: var(--white);
            border: none;
            border-radius: var(--border-radius);
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            transition: var(--transition);
            margin-top: 8px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .submit-deposit-btn:hover {
            background: #dc2626;
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(239, 68, 68, 0.4);
        }

        .submit-deposit-btn:active {
            transform: translateY(0);
        }

        /* ── Live Price Display ── */
        .live-price-banner {
            background: linear-gradient(135deg, var(--success-light) 0%, var(--primary-light) 100%);
            border: 1px solid var(--success);
            border-radius: var(--border-radius);
            padding: 16px 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .live-price-banner .price-label {
            font-size: 13px;
            color: var(--gray);
            font-weight: 600;
        }

        .live-price-banner .price-value {
            font-size: 20px;
            font-weight: 800;
            font-family: 'Courier New', monospace;
            color: var(--success);
        }

        .live-price-banner .price-pulse {
            width: 10px;
            height: 10px;
            background: var(--success);
            border-radius: 50%;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.5; transform: scale(1.2); }
        }

        /* ── Calculation Box ── */
        .calc-box {
            background: var(--primary-light);
            border: 1px solid var(--primary);
            border-radius: var(--border-radius);
            padding: 20px;
            margin: 20px 0;
        }

        .calc-line {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .calc-line:last-child {
            margin-bottom: 0;
            padding-top: 10px;
            border-top: 1px solid var(--primary);
        }

        .calc-line .calc-lbl {
            font-size: 13px;
            color: var(--gray);
        }

        .calc-line .calc-val {
            font-size: 15px;
            font-weight: 700;
            font-family: 'Courier New', monospace;
            color: var(--primary);
        }

        .calc-arrow {
            text-align: center;
            color: var(--gray);
            font-size: 18px;
            margin: 6px 0;
        }

        .crypto-amount-highlight {
            background: var(--success-light);
            border: 2px solid var(--success);
            border-radius: var(--border-radius);
            padding: 16px;
            margin: 16px 0;
            text-align: center;
        }

        .crypto-amount-highlight .highlight-label {
            font-size: 12px;
            color: var(--gray);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 8px;
        }

        .crypto-amount-highlight .highlight-value {
            font-size: 28px;
            font-weight: 800;
            font-family: 'Courier New', monospace;
            color: var(--success);
        }

        .crypto-amount-highlight .highlight-sub {
            font-size: 13px;
            color: var(--gray);
            margin-top: 4px;
        }

        /* ── Warning Box ── */
        .warning-box {
            margin-top: 20px;
            background: var(--warning-light);
            border: 1px solid var(--warning);
            border-radius: var(--border-radius);
            padding: 16px;
            display: flex;
            gap: 12px;
            align-items: start;
        }

        .warning-box .warning-icon {
            font-size: 20px;
            flex-shrink: 0;
        }

        .warning-box .warning-title {
            font-weight: 700;
            font-size: 14px;
            color: #92400E;
            margin-bottom: 4px;
        }

        .warning-box .warning-text {
            font-size: 13px;
            color: #92400E;
            line-height: 1.5;
        }

        /* ── Deposit History Table ── */
        .history-section {
            margin-top: 32px;
        }

        .history-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        .history-header h3 {
            font-size: 18px;
            font-weight: 700;
            color: var(--secondary);
        }

        .status-pill {
            display: inline-flex;
            align-items: center;
            padding: 4px 12px;
            border-radius: 50px;
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
        }

        .status-pill.pending {
            background: var(--warning-light);
            color: var(--warning);
        }

        .status-pill.completed {
            background: var(--success-light);
            color: var(--success);
        }

        .status-pill.failed {
            background: #fee2e2;
            color: #dc2626;
        }

        .history-table {
            width: 100%;
            border-collapse: collapse;
        }

        .history-table th {
            text-align: left;
            padding: 12px 16px;
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            color: var(--gray);
            letter-spacing: 0.5px;
            border-bottom: 2px solid var(--gray-200);
        }

        .history-table td {
            padding: 14px 16px;
            border-bottom: 1px solid var(--gray-100);
            font-size: 14px;
        }

        .history-table tr:hover {
            background: var(--gray-50);
        }

        .history-empty {
            text-align: center;
            padding: 40px;
            color: var(--gray);
        }

        .history-empty-icon {
            font-size: 48px;
            margin-bottom: 12px;
        }

        /* ── Modal Scrollbar ── */
        .modal-box::-webkit-scrollbar {
            width: 8px;
        }

        .modal-box::-webkit-scrollbar-track {
            background: var(--gray-100);
            border-radius: 0 var(--border-radius-lg) var(--border-radius-lg) 0;
        }

        .modal-box::-webkit-scrollbar-thumb {
            background: var(--gray-300);
            border-radius: 4px;
        }

        .modal-box::-webkit-scrollbar-thumb:hover {
            background: var(--gray);
        }

        /* ── Rate Refresh Indicator ── */
        .rate-refresh {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 12px;
            background: var(--gray-100);
            border-radius: 50px;
            font-size: 11px;
            color: var(--gray);
            margin-left: 8px;
        }

        .rate-refresh .pulse {
            width: 8px;
            height: 8px;
            background: var(--success);
            border-radius: 50%;
            animation: pulse 2s infinite;
        }
    </style>
</head>
<body>
    <?php include 'includes/client-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/client-header.php'; ?>
        
        <div class="page-content">
            <div class="page-header">
                <h2>Crypto Deposit</h2>
                <p>Deposit cryptocurrency to your account with live market prices</p>
            </div>
            
            <?php if ($flash): ?>
                <div class="alert alert-<?php echo $flash['type']; ?> fade-in">
                    <span><?php echo $flash['type'] === 'success' ? '✓' : '⚠'; ?></span> <?php echo e($flash['message']); ?>
                </div>
            <?php endif; ?>
            
            <!-- Available Cryptocurrencies -->
            <div class="card" style="margin-bottom: 24px;">
                <div class="card-header">
                    <span class="card-title">Select Cryptocurrency</span>
                    <div style="display: flex; align-items: center;">
                        <span style="color: var(--gray); font-size: 13px; margin-right: 8px;"><?php echo $wallets->num_rows; ?> available</span>
                        <?php 
                        $apiStatus = !empty($liveRates) ? 'live' : 'cached';
                        $statusText = $apiStatus === 'live' ? 'Live Market' : 'Using Cached';
                        ?>
                        <span class="rate-refresh">
                            <span class="pulse"></span>
                            <?php echo $statusText; ?>
                        </span>
                    </div>
                </div>
                <div class="card-body" style="padding: 32px 28px;">
                    <div class="crypto-select-grid">
                        <?php 
                        $cryptoIcons = [
                            'bitcoin' => '₿', 'ethereum' => 'Ξ', 'tether' => '₮', 'litecoin' => 'Ł',
                            'bitcoin_cash' => 'BCH', 'dogecoin' => 'Ð', 'cardano' => 'ADA', 'solana' => 'SOL',
                            'polkadot' => 'DOT', 'ripple' => 'XRP', 'binancecoin' => 'BNB', 'usd_coin' => 'USDC',
                            'tron' => 'TRX', 'chainlink' => 'LINK', 'polygon' => 'MATIC', 'avalanche' => 'AVAX',
                            'uniswap' => 'UNI', 'cosmos' => 'ATOM', 'stellar' => 'XLM', 'monero' => 'XMR',
                        ];
                        $cryptoColors = [
                            'bitcoin' => '#F7931A', 'ethereum' => '#627EEA', 'tether' => '#26A17B', 'litecoin' => '#BFBBBB',
                            'bitcoin_cash' => '#8DC351', 'dogecoin' => '#C2A633', 'cardano' => '#0033AD', 'solana' => '#00FFA3',
                            'polkadot' => '#E6007A', 'ripple' => '#23292F', 'binancecoin' => '#F3BA2F', 'usd_coin' => '#2775CA',
                            'tron' => '#FF060A', 'chainlink' => '#2A5ADA', 'polygon' => '#8247E5', 'avalanche' => '#E84142',
                            'uniswap' => '#FF007A', 'cosmos' => '#2E3148', 'stellar' => '#08B5E5', 'monero' => '#FF6600',
                        ];
                        
                        $wallets->data_seek(0);
                        while ($wallet = $wallets->fetch_assoc()): 
                            $key = strtolower($wallet['coin_name']);
                            $icon = $cryptoIcons[$key] ?? '💎';
                            $color = $cryptoColors[$key] ?? '#6366f1';
                            $rate = getRate($key, $liveRates, $walletMap);
                            $live = isLiveRate($key, $liveRates, $walletMap);
                        ?>
                        <div class="crypto-select-card" onclick="openModal('<?php echo e($key); ?>')" id="card-<?php echo e($key); ?>">
                            <div class="coin-icon" style="background: <?php echo e($color); ?>20; color: <?php echo e($color); ?>;">
                                <span><?php echo $icon; ?></span>
                            </div>
                            <div class="coin-name"><?php echo e($wallet['coin_name']); ?></div>
                            <div class="coin-symbol"><?php echo e($wallet['coin_symbol'] ?? strtoupper($key)); ?></div>
                            <div class="live-rate-badge <?php echo $live ? '' : 'stale'; ?>">
                                $<?php echo number_format($rate, 2); ?> USD
                            </div>
                            <span class="select-indicator">Click to Deposit</span>
                        </div>
                        <?php endwhile; ?>
                    </div>
                </div>
            </div>

            <!-- Deposit History -->
            <div class="card history-section">
                <div class="history-header" style="padding: 24px 28px; border-bottom: 1px solid var(--gray-200);">
                    <h3>📋 Your Deposit History</h3>
                    <a href="transactions.php" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body" style="padding: 0;">
                    <?php if ($deposits && $deposits->num_rows > 0): ?>
                        <div class="responsive-table-wrapper">
                            <table class="history-table">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Coin</th>
                                        <th>Amount (USD)</th>
                                        <th>Crypto Amount</th>
                                        <th>Rate</th>
                                        <th>Status</th>
                                        <th>Reference</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($dep = $deposits->fetch_assoc()): ?>
                                    <tr>
                                        <td><?php echo date('M d, Y H:i', strtotime($dep['created_at'])); ?></td>
                                        <td>
                                            <strong><?php echo e($dep['coin_symbol']); ?></strong>
                                            <div style="font-size: 12px; color: var(--gray);"><?php echo e($dep['network']); ?></div>
                                        </td>
                                        <td style="font-weight: 700;">$<?php echo number_format($dep['fiat_amount'], 2); ?></td>
                                        <td style="font-family: 'Courier New', monospace;">
                                            <?php echo number_format($dep['crypto_amount'], 8); ?> <?php echo e($dep['coin_symbol']); ?>
                                        </td>
                                        <td style="font-size: 12px; color: var(--gray);">
                                            $<?php echo number_format($dep['rate_used'], 2); ?>/<?php echo e($dep['coin_symbol']); ?>
                                        </td>
                                        <td>
                                            <span class="status-pill <?php echo e($dep['status']); ?>">
                                                <?php echo ucfirst(e($dep['status'])); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <code style="font-size: 11px;"><?php echo e(substr($dep['reference'], 0, 12)); ?>...</code>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="history-empty">
                            <div class="history-empty-icon">📭</div>
                            <h4>No Deposits Yet</h4>
                            <p>Your crypto deposit history will appear here once you make your first deposit.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Modal Deposit Forms -->
            <?php 
            $wallets->data_seek(0);
            while ($wallet = $wallets->fetch_assoc()): 
                $key = strtolower($wallet['coin_name']);
                $rate = getRate($key, $liveRates, $walletMap);
                $color = $cryptoColors[$key] ?? '#6366f1';
                $icon = $cryptoIcons[$key] ?? '💎';
                $minDeposit = isset($wallet['min_deposit']) ? (float)$wallet['min_deposit'] : 0;
                $address = $wallet['address'] ?? $wallet['wallet_address'] ?? '';
                $live = isLiveRate($key, $liveRates, $walletMap);
                $symbol = $wallet['coin_symbol'] ?? strtoupper($key);
            ?>
            <div class="modal-overlay" id="modal-<?php echo e($key); ?>" onclick="closeModalOnBackdrop(event, '<?php echo e($key); ?>')">
                <div class="modal-box" onclick="event.stopPropagation()">
                    <form action="process_deposit.php" method="POST">
                        <input type="hidden" name="coin_id" value="<?php echo $wallet['id']; ?>">
                        <input type="hidden" name="crypto_amount" id="crypto-amount-<?php echo e($key); ?>">
                        <input type="hidden" name="fiat_rate" id="fiat-rate-<?php echo e($key); ?>" value="<?php echo $rate; ?>">
                        <input type="hidden" name="wallet_address" value="<?php echo e($address); ?>">
                        
                        <button type="button" class="modal-close" onclick="closeModal('<?php echo e($key); ?>')">✕</button>
                        
                        <div class="modal-header">
                            <div class="panel-icon" style="background: <?php echo e($color); ?>20; color: <?php echo e($color); ?>;">
                                <span><?php echo $icon; ?></span>
                            </div>
                            <div>
                                <div class="panel-title"><?php echo e($wallet['coin_name']); ?> Deposit</div>
                                <div class="badge-row">
                                    <span class="net-badge"><?php echo e($wallet['network'] ?? 'Mainnet'); ?></span>
                                    <?php if ($minDeposit > 0): ?>
                                    <span class="min-badge">Min: $<?php echo number_format($minDeposit, 2); ?></span>
                                    <?php endif; ?>
                                    <span class="rate-badge <?php echo $live ? '' : 'stale'; ?>">
                                        1 <?php echo e($symbol); ?> = $<?php echo number_format($rate, 2); ?> USD
                                        <?php echo $live ? '● Live' : '○ Cached'; ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="modal-body">
                            <div class="live-price-banner">
                                <div>
                                    <div class="price-label">Current Market Price</div>
                                    <div class="price-value">$<?php echo number_format($rate, 2); ?> USD per <?php echo e($symbol); ?></div>
                                </div>
                                <div class="price-pulse"></div>
                            </div>

                            <div class="deposit-grid">
                                <div>
                                    <div class="qr-wrap">
                                        <div class="qr-box">
                                            <svg width="156" height="156" viewBox="0 0 156 156">
                                                <rect width="156" height="156" fill="white"/>
                                                <rect x="14" y="14" width="38" height="38" fill="<?php echo e($color); ?>"/>
                                                <rect x="20" y="20" width="26" height="26" fill="white"/>
                                                <rect x="26" y="26" width="14" height="14" fill="<?php echo e($color); ?>"/>
                                                <rect x="104" y="14" width="38" height="38" fill="<?php echo e($color); ?>"/>
                                                <rect x="110" y="20" width="26" height="26" fill="white"/>
                                                <rect x="116" y="26" width="14" height="14" fill="<?php echo e($color); ?>"/>
                                                <rect x="14" y="104" width="38" height="38" fill="<?php echo e($color); ?>"/>
                                                <rect x="20" y="110" width="26" height="26" fill="white"/>
                                                <rect x="26" y="116" width="14" height="14" fill="<?php echo e($color); ?>"/>
                                                <rect x="62" y="14" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="88" y="14" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="62" y="38" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="62" y="62" width="80" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="62" y="88" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="88" y="88" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="114" y="88" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="62" y="114" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="88" y="114" width="38" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="136" y="114" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="62" y="140" width="38" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="114" y="140" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="136" y="140" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="14" y="62" width="38" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="14" y="88" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="38" y="88" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="14" y="114" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="38" y="140" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                                <rect x="62" y="140" width="12" height="12" fill="<?php echo e($color); ?>"/>
                                            </svg>
                                        </div>
                                        <p class="qr-caption">Scan QR code to deposit</p>
                                    </div>
                                    
                                    <div class="address-wrap">
                                        <label>Deposit Address</label>
                                        <div class="copy-row">
                                            <input type="text" value="<?php echo e($address); ?>" readonly id="addr-<?php echo e($key); ?>">
                                            <button type="button" onclick="copyAddress('<?php echo e($key); ?>', this)">Copy</button>
                                        </div>
                                    </div>
                                </div>

                                <div>
                                    <div class="deposit-form-group">
                                        <label>Amount (USD)</label>
                                        <input type="number" 
                                               name="fiat_amount" 
                                               step="0.01" 
                                               min="0.01"
                                               required 
                                               placeholder="0.00" 
                                               id="fiat-<?php echo e($key); ?>"
                                               oninput="calculateDeposit(this, '<?php echo e($key); ?>')">
                                        <div class="hint">
                                            Enter deposit amount in USD
                                            <?php if ($minDeposit > 0): ?>
                                            <span style="color: var(--warning); font-weight: 600;">(Minimum: $<?php echo number_format($minDeposit, 2); ?>)</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    <div class="crypto-amount-highlight" id="highlight-<?php echo e($key); ?>" style="display: none;">
                                        <div class="highlight-label">You will send</div>
                                        <div class="highlight-value" id="highlight-value-<?php echo e($key); ?>">0.00000000 <?php echo e($symbol); ?></div>
                                        <div class="highlight-sub">Based on market price of $<?php echo number_format($rate, 2); ?> per <?php echo e($symbol); ?></div>
                                    </div>

                                    <div class="calc-box">
                                        <div class="calc-line">
                                            <span class="calc-lbl">You will send</span>
                                            <span class="calc-val" id="calc-crypto-<?php echo e($key); ?>">0.00000000 <?php echo e($symbol); ?></span>
                                        </div>
                                        <div class="calc-arrow">↓</div>
                                        <div class="calc-line">
                                            <span class="calc-lbl">Coin</span>
                                            <span class="calc-val" style="font-size: 14px;"><?php echo e($symbol); ?></span>
                                        </div>
                                        <div class="calc-line">
                                            <span class="calc-lbl">Market Price</span>
                                            <span class="calc-val" style="font-size: 14px;">$<?php echo number_format($rate, 2); ?> / <?php echo e($symbol); ?></span>
                                        </div>
                                        <div class="calc-line">
                                            <span class="calc-lbl">Your Deposit</span>
                                            <span class="calc-val" id="calc-usd-<?php echo e($key); ?>">$0.00 USD</span>
                                        </div>
                                    </div>

                                    <button type="submit" class="submit-deposit-btn">Submit Deposit Request</button>

                                    <div class="warning-box">
                                        <span class="warning-icon">⚠️</span>
                                        <div>
                                            <div class="warning-title">Important Notice</div>
                                            <div class="warning-text">
                                                Please verify the wallet address and network before sending. 
                                                Sending to the wrong address or network will result in permanent loss of funds. 
                                                Deposits are credited after network confirmation (typically 3-6 confirmations).
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
    </div>
    
    <script src="assets/js/main.js"></script>
    <script>
        const cryptoRates = <?php 
            $ratesObj = [];
            $wallets->data_seek(0);
            while ($w = $wallets->fetch_assoc()) {
                $k = strtolower($w['coin_name']);
                $ratesObj[$k] = getRate($k, $liveRates, $walletMap);
            }
            echo json_encode($ratesObj);
        ?>;
        
        const cryptoSymbols = <?php 
            $symObj = [];
            $wallets->data_seek(0);
            while ($w = $wallets->fetch_assoc()) {
                $k = strtolower($w['coin_name']);
                $symObj[$k] = $w['coin_symbol'] ?? strtoupper($k);
            }
            echo json_encode($symObj);
        ?>;

        let currentModal = null;

        function openModal(key) {
            if (currentModal) closeModal(currentModal);
            const modal = document.getElementById('modal-' + key);
            if (modal) {
                modal.classList.add('active');
                document.body.style.overflow = 'hidden';
                currentModal = key;
                document.querySelectorAll('.crypto-select-card').forEach(c => c.classList.remove('active'));
                document.getElementById('card-' + key)?.classList.add('active');
            }
        }

        function closeModal(key) {
            const modal = document.getElementById('modal-' + key);
            if (modal) {
                modal.classList.remove('active');
                document.body.style.overflow = '';
                currentModal = null;
                document.getElementById('card-' + key)?.classList.remove('active');
            }
        }

        function closeModalOnBackdrop(event, key) {
            if (event.target === event.currentTarget) closeModal(key);
        }

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && currentModal) closeModal(currentModal);
        });

        function calculateDeposit(input, key) {
            const rate = cryptoRates[key] || 1;
            const symbol = cryptoSymbols[key] || key.toUpperCase();
            const fiat = parseFloat(input.value) || 0;
            const crypto = fiat / rate;

            // Visual feedback for minimum deposit
            const minDeposit = <?php echo json_encode($minDeposit); ?>;
            if (fiat > 0 && fiat < minDeposit) {
                input.style.borderColor = 'var(--warning)';
                input.style.boxShadow = '0 0 0 3px var(--warning-light)';
            } else {
                input.style.borderColor = '';
                input.style.boxShadow = '';
            }

            const highlight = document.getElementById('highlight-' + key);
            const highlightValue = document.getElementById('highlight-value-' + key);
            if (highlight && highlightValue) {
                highlight.style.display = fiat > 0 ? 'block' : 'none';
                if (fiat > 0) highlightValue.innerText = crypto.toFixed(8) + ' ' + symbol;
            }

            const cryptoEl = document.getElementById('calc-crypto-' + key);
            if (cryptoEl) cryptoEl.innerText = crypto.toFixed(8) + ' ' + symbol;

            const usdEl = document.getElementById('calc-usd-' + key);
            if (usdEl) usdEl.innerText = '$' + fiat.toFixed(2) + ' USD';

            const hidden = document.getElementById('crypto-amount-' + key);
            if (hidden) hidden.value = crypto.toFixed(8);
            
            const rateHidden = document.getElementById('fiat-rate-' + key);
            if (rateHidden) rateHidden.value = rate;
        }

        function copyAddress(key, btn) {
            const input = document.getElementById('addr-' + key);
            if (!input) return;
            navigator.clipboard.writeText(input.value).then(() => {
                const original = btn.innerText;
                btn.innerText = 'Copied!';
                btn.classList.add('copied');
                setTimeout(() => {
                    btn.innerText = original;
                    btn.classList.remove('copied');
                }, 2000);
            });
        }
    </script>
</body>
</html>
