<?php
require_once 'db/config.php';
require_once 'includes/currency_helper.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id'])) { 
    header("Location: login.php"); 
    exit; 
}

$db = db();

include 'header.php';

$fiat_rates = get_fiat_rates();
$fiat_currencies_info = [
    'USD' => ['name' => '美元', 'flag' => '🇺🇸'],
    'EUR' => ['name' => '欧元', 'flag' => '🇪🇺'],
    'GBP' => ['name' => '英镑', 'flag' => '🇬🇧'],
    'CNY' => ['name' => '人民币', 'flag' => '🇨🇳'],
    'HKD' => ['name' => '港币', 'flag' => '🇭🇰'],
    'JPY' => ['name' => '日元', 'flag' => '🇯🇵'],
    'KRW' => ['name' => '韩元', 'flag' => '🇰🇷'],
    'SGD' => ['name' => '新加坡元', 'flag' => '🇸🇬'],
    'TWD' => ['name' => '台币', 'flag' => '🇹🇼'],
    'THB' => ['name' => '泰铢', 'flag' => '🇹🇭'],
    'VND' => ['name' => '越南盾', 'flag' => '🇻🇳'],
    'IDR' => ['name' => '印尼盾', 'flag' => '🇮🇩'],
    'MYR' => ['name' => '马来西亚林吉特', 'flag' => '🇲🇾'],
];
?>

<style>
    .deposit-container { padding: 40px 0; background: #0b0e11; min-height: 100vh; }
    .deposit-card { background: var(--card-bg); border-radius: 24px; border: 1px solid var(--border-color); overflow: hidden; }
    .method-card { padding: 30px; border-radius: 20px; border: 2px solid transparent; cursor: pointer; transition: 0.3s; background: rgba(255,255,255,0.02); }
    .method-card:hover { background: rgba(255,255,255,0.05); }
    .method-card.active { border-color: var(--primary-color); background: rgba(240, 185, 11, 0.05); }
    .method-card .icon-box { width: 50px; height: 50px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 20px; margin-bottom: 15px; }
    
    .instruction-item { display: flex; gap: 15px; margin-bottom: 20px; }
    .instruction-number { width: 24px; height: 24px; background: var(--primary-color); color: #000; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 12px; flex-shrink: 0; }
    
    .input-group-custom { background: #161a1e; border: 1px solid var(--border-color); border-radius: 16px; padding: 15px 20px; display: flex; align-items: center; gap: 15px; transition: 0.3s; }
    .input-group-custom:focus-within { border-color: var(--primary-color); }
    .input-group-custom input { background: none; border: none; color: white; font-size: 1.2rem; font-weight: 700; width: 100%; outline: none; }
    
    .safe-banner { background: rgba(14, 203, 129, 0.1); border: 1px solid rgba(14, 203, 129, 0.2); padding: 20px; border-radius: 16px; color: var(--success-color); display: flex; gap: 15px; align-items: center; margin-bottom: 30px; }

    @media (max-width: 576px) {
        .method-card { padding: 20px 15px; }
        .method-card .icon-box { width: 40px; height: 40px; font-size: 16px; }
        .method-card div:nth-child(2) { font-size: 0.95rem !important; }
    }
</style>

<div class="deposit-container">
    <div class="container" style="max-width: 1100px;">
        <div style="margin-bottom: 30px;">
            <a href="profile.php" class="back-btn" style="color: var(--text-muted); text-decoration: none; font-size: 14px;"><i class="fas fa-arrow-left"></i> 个人中心</a>
            <h1 style="font-size: 2.2rem; font-weight: 800; margin-top: 10px;">充值</h1>
            <p style="color: var(--text-muted);">通过多种通道安全地为您的账户充值</p>
        </div>

        <div class="safe-banner">
            <i class="fas fa-shield-check" style="font-size: 24px;"></i>
            <div>
                <div style="font-weight: 800;">安全保障</div>
                <div style="font-size: 13px; opacity: 0.8;">所有交易均经过加密处理，24/7 全天候监控。您的资金受到我们的安全资产基金保护。</div>
            </div>
        </div>

        <div class="responsive-grid">
            <div>
                <div class="deposit-card" style="padding: 40px;">
                    <h3 style="margin-bottom: 25px; font-weight: 800;">1. 选择充值方式</h3>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 40px;">
                        <div id="method-fiat" class="method-card active" onclick="switchDepositMethod('fiat')">
                            <div class="icon-box" style="background: rgba(79,172,254,0.1); color: #4facfe;"><i class="fas fa-university"></i></div>
                            <div style="font-weight: 800; font-size: 1.1rem;">法币充值</div>
                            <div style="color: var(--text-muted); font-size: 11px; margin-top: 4px;">银行转账 / OTC</div>
                        </div>
                        <div id="method-usdt" class="method-card" onclick="switchDepositMethod('usdt')">
                            <div class="icon-box" style="background: rgba(14,203,129,0.1); color: var(--success-color);"><i class="fas fa-coins"></i></div>
                            <div style="font-weight: 800; font-size: 1.1rem;">USDT 充值</div>
                            <div style="color: var(--text-muted); font-size: 11px; margin-top: 4px;">TRC20, ERC20...</div>
                        </div>
                    </div>

                    <div id="fiat-form-section">
                        <h3 style="margin-bottom: 25px; font-weight: 800;">2. 订单详情</h3>
                        <form id="fiat-deposit-form" action="matching.php" method="POST">
                            <input type="hidden" name="order_type" value="deposit">
                            <input type="hidden" name="type" value="fiat">
                            <div style="display: flex; flex-direction: column; gap: 20px; margin-bottom: 25px;">
                                <div>
                                    <label style="display: block; color: var(--text-muted); font-size: 13px; margin-bottom: 8px;">充值币种</label>
                                    <select name="currency" id="fiat-select" onchange="updateExchangeRate()" style="width: 100%; padding: 16px; background: #161a1e; border: 1px solid var(--border-color); color: white; border-radius: 16px; outline: none; font-weight: 600;">
                                        <?php foreach ($fiat_rates as $code => $rate): ?>
                                        <option value="<?php echo $code; ?>" data-rate="<?php echo $rate; ?>">
                                            <?php echo ($fiat_currencies_info[$code]['flag'] ?? '') . ' ' . $code . ' - ' . ($fiat_currencies_info[$code]['name'] ?? $code); ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <label style="display: block; color: var(--text-muted); font-size: 13px; margin-bottom: 8px;">充值金额</label>
                                    <div class="input-group-custom">
                                        <input type="number" name="amount" id="fiat-amount" placeholder="0.00" required oninput="updateExchangeRate()">
                                        <span id="fiat-symbol-display" style="font-weight: 800; color: var(--text-muted);">USD</span>
                                    </div>
                                </div>
                            </div>

                            <div style="background: rgba(255,255,255,0.03); padding: 25px; border-radius: 20px; margin-bottom: 30px; border: 1px dashed var(--border-color);">
                                <div style="display: flex; justify-content: space-between; margin-bottom: 10px; font-size: 14px;">
                                    <span style="color: var(--text-muted);">实时汇率</span>
                                    <span style="font-weight: 700;">1 USDT ≈ <span id="rate-text">--</span> <span class="current-fiat-code">USD</span></span>
                                </div>
                                <div style="display: flex; justify-content: space-between; align-items: center; border-top: 1px solid rgba(255,255,255,0.05); pt: 15px; margin-top: 15px; padding-top: 15px;">
                                    <span style="font-weight: 800; font-size: 1.1rem;">预计收到</span>
                                    <span style="font-weight: 800; font-size: 1.4rem; color: var(--primary-color);"><span id="receive-text">0.00</span> USDT</span>
                                </div>
                            </div>

                            <button type="submit" class="btn-primary submit-btn" style="width: 100%; padding: 20px; border-radius: 16px; font-size: 1.1rem; font-weight: 800;">
                                发起充值请求
                            </button>
                        </form>
                    </div>

                    <div id="usdt-form-section" style="display: none;">
                        <h3 style="margin-bottom: 25px; font-weight: 800;">2. 订单详情</h3>
                        <form id="usdt-deposit-form" action="matching.php" method="POST">
                            <input type="hidden" name="order_type" value="deposit">
                            <input type="hidden" name="type" value="usdt">
                            <input type="hidden" name="currency" value="USDT">
                            
                            <label style="display: block; color: var(--text-muted); font-size: 13px; margin-bottom: 12px;">选择网络</label>
                            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 25px;">
                                <label class="network-opt"><input type="radio" name="network" value="TRC20" checked style="display:none;"><div class="network-box">TRC20</div></label>
                                <label class="network-opt"><input type="radio" name="network" value="ERC20" style="display:none;"><div class="network-box">ERC20</div></label>
                                <label class="network-opt"><input type="radio" name="network" value="BEP20" style="display:none;"><div class="network-box">BEP20</div></label>
                            </div>

                            <div style="margin-bottom: 30px;">
                                <label style="display: block; color: var(--text-muted); font-size: 13px; margin-bottom: 8px;">充值金额 (USDT)</label>
                                <div class="input-group-custom">
                                    <input type="number" name="amount" placeholder="最小 10 USDT" required>
                                    <span style="font-weight: 800; color: var(--text-muted);">USDT</span>
                                </div>
                            </div>

                            <button type="submit" class="btn-primary submit-btn" style="width: 100%; padding: 20px; border-radius: 16px; font-size: 1.1rem; font-weight: 800; background: var(--success-color);">
                                发起充值请求
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="sidebar-area">
                <div class="deposit-card" style="padding: 30px;">
                    <h4 style="font-weight: 800; margin-bottom: 25px;"><i class="fas fa-info-circle" style="color: var(--primary-color);"></i> 充值步骤说明</h4>
                    <div class="instruction-item">
                        <div class="instruction-number">1</div>
                        <div style="font-size: 14px; color: var(--text-muted);">
                            <strong style="color: white; display: block; margin-bottom: 4px;">发起充值申请</strong>
                            输入您想要充值的金额并点击确认。
                        </div>
                    </div>
                    <div class="instruction-item">
                        <div class="instruction-number">2</div>
                        <div style="font-size: 14px; color: var(--text-muted);">
                            <strong style="color: white; display: block; margin-bottom: 4px;">联系在线客服</strong>
                            您将自动弹出客服聊天界面，客服将为您匹配唯一的收款账户。
                        </div>
                    </div>
                    <div class="instruction-item">
                        <div class="instruction-number">3</div>
                        <div style="font-size: 14px; color: var(--text-muted);">
                            <strong style="color: white; display: block; margin-bottom: 4px;">完成转账并上传凭证</strong>
                            按照客服提供的账户进行转账，并在聊天窗口中上传付款凭证截图。
                        </div>
                    </div>
                    <div class="instruction-item">
                        <div class="instruction-number">4</div>
                        <div style="font-size: 14px; color: var(--text-muted);">
                            <strong style="color: white; display: block; margin-bottom: 4px;">资金到账</strong>
                            客服确认凭证后，USDT 将立即存入您的账户余额。
                        </div>
                    </div>
                </div>

                <div class="deposit-card" style="padding: 30px; margin-top: 20px; border-color: rgba(246,70,93,0.2);">
                    <h4 style="font-weight: 800; margin-bottom: 20px; color: var(--danger-color);"><i class="fas fa-exclamation-triangle"></i> 重要安全提示</h4>
                    <ul style="padding-left: 18px; color: var(--text-muted); font-size: 13px; line-height: 1.8;">
                        <li>请务必只使用客服在聊天窗口中提供的账户。</li>
                        <li>银行转账备注中请勿提及任何加密货币相关术语。</li>
                        <li>转账账户必须与您的实名认证身份一致。</li>
                        <li>如有任何疑问，请保持在聊天窗口中，直至问题解决。</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .network-box { padding: 15px; background: #161a1e; border: 1px solid var(--border-color); border-radius: 12px; text-align: center; font-weight: 700; cursor: pointer; transition: 0.3s; font-size: 13px; }
    .network-opt input:checked + .network-box { border-color: var(--success-color); background: rgba(14,203,129,0.05); color: var(--success-color); }
</style>

<script>
    function switchDepositMethod(method) {
        document.getElementById('fiat-form-section').style.display = method === 'fiat' ? 'block' : 'none';
        document.getElementById('usdt-form-section').style.display = method === 'usdt' ? 'block' : 'none';
        document.getElementById('method-fiat').classList.toggle('active', method === 'fiat');
        document.getElementById('method-usdt').classList.toggle('active', method === 'usdt');
    }

    function updateExchangeRate() {
        const select = document.getElementById('fiat-select');
        const rate = parseFloat(select.options[select.selectedIndex].getAttribute('data-rate'));
        const code = select.value;
        const amount = parseFloat(document.getElementById('fiat-amount').value) || 0;

        document.getElementById('rate-text').innerText = rate.toFixed(2);
        document.querySelectorAll('.current-fiat-code').forEach(el => el.innerText = code);
        document.getElementById('fiat-symbol-display').innerText = code;
        
        const receive = amount / rate;
        document.getElementById('receive-text').innerText = receive.toFixed(2);
    }

    updateExchangeRate();

    // AJAX Form Submission
    const forms = ['fiat-deposit-form', 'usdt-deposit-form'];
    forms.forEach(id => {
        const form = document.getElementById(id);
        if (form) {
            form.onsubmit = async (e) => {
                e.preventDefault();
                const btn = form.querySelector('.submit-btn');
                const originalText = btn.innerHTML;
                btn.disabled = true;
                btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';

                try {
                    const formData = new FormData(form);
                    const resp = await fetch('matching.php', {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    });
                    const res = await resp.json();
                    if (res.success) {
                        // Trigger chat popup
                        if (typeof openCSChat === 'function') {
                            openCSChat();
                            // Optional: Disable forms to prevent double submission
                            form.style.opacity = '0.5';
                            form.style.pointerEvents = 'none';
                            btn.innerHTML = '<i class="fas fa-check"></i> 请求已发送';
                        } else {
                            window.location.href = 'chat.php';
                        }
                    } else {
                        alert(res.error || '提交失败，请稍后重试');
                        btn.disabled = false;
                        btn.innerHTML = originalText;
                    }
                } catch (e) {
                    console.error(e);
                    alert('网络错误，请稍后重试');
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                }
            };
        }
    });
</script>

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