<?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();
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();


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' => '🇲🇾'],
];

$error = '';
?>

<style>
    .withdraw-container { padding: 40px 0; background: #0b0e11; min-height: 100vh; }
    .withdraw-card { background: var(--card-bg); border-radius: 24px; border: 1px solid var(--border-color); overflow: hidden; padding: 40px; }
    .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(--danger-color); background: rgba(246, 70, 93, 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; }
    
    .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; }
    
    .safety-alert { background: rgba(246, 70, 93, 0.1); border: 1px solid rgba(246, 70, 93, 0.2); padding: 20px; border-radius: 16px; color: var(--danger-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="withdraw-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>

        <?php if($error): ?>
            <div class="safety-alert">
                <i class="fas fa-exclamation-circle" style="font-size: 24px;"></i>
                <div style="font-weight: 700;"><?php echo $error; ?></div>
            </div>
        <?php endif; ?>

        <div class="responsive-grid">
            <div>
                <div class="withdraw-card">
                    <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" onclick="switchWithdrawMethod('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 active" onclick="switchWithdrawMethod('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;">区块链转账</div>
                        </div>
                    </div>

                    <form action="matching.php" method="POST" id="withdraw-form">
                        <input type="hidden" name="order_type" value="withdrawal">
                        <input type="hidden" name="type" id="withdraw-type" value="usdt">
                        
                        <h3 style="margin-bottom: 25px; font-weight: 800;">2. 提现详情</h3>
                        
                        <!-- Fiat Options -->
                        <div id="fiat-options" style="display: none;">
                            <div style="margin-bottom: 25px;">
                                <label style="display: block; color: var(--text-muted); font-size: 13px; margin-bottom: 8px;">接收币种</label>
                                <select name="currency" id="fiat-currency" onchange="updateWithdrawRate()" 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>

                        <!-- USDT Options -->
                        <div id="usdt-options">
                            <div style="margin-bottom: 25px;">
                                <label style="display: block; color: var(--text-muted); font-size: 13px; margin-bottom: 8px;">网络</label>
                                <select name="network" style="width: 100%; padding: 16px; background: #161a1e; border: 1px solid var(--border-color); color: white; border-radius: 16px; outline: none; font-weight: 600;">
                                    <option value="TRC20">USDT - TRC20 (快速 & 低手续费)</option>
                                    <option value="ERC20">USDT - ERC20</option>
                                    <option value="BEP20">USDT - BEP20 (BSC)</option>
                                </select>
                            </div>
                        </div>

                        <!-- Amount & Password -->
                        <div style="margin-bottom: 25px;">
                            <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" id="amount-input" oninput="updateWithdrawRate()" placeholder="最小 10.00" step="0.01" required>
                                <span onclick="document.getElementById('amount-input').value = '<?php echo $user['balance']; ?>'; updateWithdrawRate();" style="color: var(--primary-color); font-weight: 800; cursor: pointer; white-space: nowrap;">全部</span>
                            </div>
                            <div style="display: flex; justify-content: space-between; margin-top: 10px; font-size: 13px;">
                                <span style="color: var(--text-muted);">可用余额: <strong style="color: white;"><?php echo number_format($user['balance'], 2); ?> USDT</strong></span>
                                <span id="fiat-equiv-display" style="color: var(--success-color); font-weight: 800; display: none;">≈ <span id="fiat-val">0.00</span> <span id="fiat-code">USD</span></span>
                            </div>
                        </div>

                        <div style="margin-bottom: 35px;">
                            <label style="display: block; color: var(--text-muted); font-size: 13px; margin-bottom: 8px;">交易密码</label>
                            <div class="input-group-custom">
                                <input type="password" name="trading_password" placeholder="6 位安全密码" required style="letter-spacing: 5px;">
                            </div>
                        </div>

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

            <div class="sidebar-area">
                <div class="withdraw-card" style="padding: 30px;">
                    <h4 style="font-weight: 800; margin-bottom: 25px;"><i class="fas fa-shield-check" style="color: var(--success-color);"></i> 提现安全说明</h4>
                    <div style="font-size: 13px; color: var(--text-muted); line-height: 1.8;">
                        <p style="margin-bottom: 15px;">为了您的账户安全，提现申请将由人工审核，您将自动弹出在线客服界面完成后续步骤。</p>
                        <p style="margin-bottom: 15px;">发起申请后，请按照客服要求提供您的收款账户信息。</p>
                        <div style="background: rgba(255, 255, 255, 0.03); padding: 15px; border-radius: 12px; border-left: 3px solid var(--primary-color);">
                            请确保您的收款账户信息 100% 正确。资金一旦发出，将无法追回。
                        </div>
                    </div>
                </div>

                <div class="withdraw-card" style="padding: 30px; margin-top: 20px;">
                    <h4 style="font-weight: 800; margin-bottom: 20px;"><i class="fas fa-history"></i> 帮助与支持</h4>
                    <div style="font-size: 13px; color: var(--text-muted);">
                        提现过程中遇到问题？联系我们的 24/7 在线客服。
                        <div style="margin-top: 20px;">
                            <a href="javascript:void(0)" onclick="openCSChat()" class="btn" style="width: 100%; background: #2b3139; color: white; border-radius: 10px; padding: 10px; text-decoration: none; display: block; text-align: center;">联系客服</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function switchWithdrawMethod(method) {
        document.getElementById('fiat-options').style.display = method === 'fiat' ? 'block' : 'none';
        document.getElementById('usdt-options').style.display = method === 'usdt' ? 'block' : 'none';
        document.getElementById('method-fiat').classList.toggle('active', method === 'fiat');
        document.getElementById('method-usdt').classList.toggle('active', method === 'usdt');
        document.getElementById('withdraw-type').value = method;
        document.getElementById('fiat-equiv-display').style.display = method === 'fiat' ? 'block' : 'none';
        updateWithdrawRate();
    }

    function updateWithdrawRate() {
        const amount = parseFloat(document.getElementById('amount-input').value) || 0;
        const select = document.getElementById('fiat-currency');
        const rate = parseFloat(select.options[select.selectedIndex].getAttribute('data-rate'));
        const code = select.value;
        
        document.getElementById('fiat-val').innerText = (amount * rate).toFixed(2);
        document.getElementById('fiat-code').innerText = code;
    }

    updateWithdrawRate();

    // AJAX Form Submission
    const withdrawForm = document.getElementById('withdraw-form');
    if (withdrawForm) {
        withdrawForm.onsubmit = async (e) => {
            e.preventDefault();
            const btn = document.getElementById('submit-btn');
            const originalText = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';

            try {
                const formData = new FormData(withdrawForm);
                const resp = await fetch('matching.php', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                });
                
                // For withdrawals, matching.php might return plain text if balance is insufficient
                const text = await resp.text();
                let res;
                try {
                    res = JSON.parse(text);
                } catch (e) {
                    alert(text || '提交失败，请检查余额或密码');
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                    return;
                }

                if (res.success) {
                    // Trigger chat popup
                    if (typeof openCSChat === 'function') {
                        openCSChat();
                        withdrawForm.style.opacity = '0.5';
                        withdrawForm.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'; ?>