<?php
include 'header.php';

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

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

$db = db();

// Check for existing pending orders to force workflow
$stmt = $db->prepare("SELECT id FROM fiat_orders WHERE user_id = ? AND status IN ('matching', 'matched', 'submitting') ORDER BY id DESC LIMIT 1");
$stmt->execute([$_SESSION['user_id']]);
$pending_order = $stmt->fetch();
if ($pending_order) {
    header("Location: chat.php");
    exit;
}

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

$fiat_rates = get_fiat_rates();
$fiat_currencies_info = [
    'USD' => 'US Dollar',
    'EUR' => 'Euro',
    'GBP' => 'British Pound',
    'CNY' => 'Chinese Yuan',
    'HKD' => 'Hong Kong Dollar',
    'JPY' => 'Japanese Yen',
    'KRW' => 'Korean Won',
    'SGD' => 'Singapore Dollar',
    'TWD' => 'Taiwan Dollar',
    'THB' => 'Thai Baht',
    'VND' => 'Vietnamese Dong',
    'IDR' => 'Indonesian Rupiah',
    'MYR' => 'Malaysian Ringgit',
];
?>

<main style="padding: 40px 20px; background: #0b0e11; min-height: calc(100vh - 64px);">
    <div style="max-width: 1000px; margin: 0 auto;">
        
        <a href="profile.php" class="back-btn"><i class="fas fa-arrow-left"></i> <?php echo __('nav_profile'); ?></a>

        <div style="margin-bottom: 40px;">
            <h1 style="font-size: 2.5rem; font-weight: bold; margin-bottom: 10px;"><?php echo __('deposit_assets', '充值资产'); ?></h1>
            <p style="color: var(--text-muted);"><?php echo __('deposit_method_tip', '请选择您偏好的充值方式'); ?></p>
        </div>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-bottom: 40px;">
            <div id="card-fiat" style="background: var(--card-bg); padding: 35px; border-radius: 24px; border: 2px solid var(--primary-color); cursor: pointer;" onclick="switchMethod('fiat')">
                <div style="display: flex; align-items: center; gap: 20px; margin-bottom: 25px;">
                    <div style="width: 60px; height: 60px; background: rgba(0, 82, 255, 0.1); border-radius: 16px; display: flex; align-items: center; justify-content: center; color: var(--primary-color); font-size: 24px;">
                        <i class="fas fa-university"></i>
                    </div>
                    <div>
                        <h3 style="margin: 0;"><?php echo __('fiat_deposit', '法币充值'); ?></h3>
                        <p style="margin: 5px 0 0; color: var(--text-muted); font-size: 14px;"><?php echo __('bank_transfer', '银行转账 / OTC'); ?></p>
                    </div>
                </div>
                <div style="color: var(--text-muted); font-size: 13px; line-height: 2;">
                    <div style="display: flex; align-items: center; gap: 10px;"><i class="fas fa-check-circle" style="color: var(--success-color); font-size: 12px;"></i> Support 20+ Global Currencies</div>
                    <div style="display: flex; align-items: center; gap: 10px;"><i class="fas fa-check-circle" style="color: var(--success-color); font-size: 12px;"></i> Secure Bank-Grade Processing</div>
                </div>
            </div>

            <div id="card-usdt" style="background: var(--card-bg); padding: 35px; border-radius: 24px; border: 2px solid transparent; cursor: pointer;" onclick="switchMethod('usdt')">
                <div style="display: flex; align-items: center; gap: 20px; margin-bottom: 25px;">
                    <div style="width: 60px; height: 60px; background: rgba(14, 203, 129, 0.1); border-radius: 16px; display: flex; align-items: center; justify-content: center; color: var(--success-color); font-size: 24px;">
                        <i class="fas fa-coins"></i>
                    </div>
                    <div>
                        <h3 style="margin: 0;"><?php echo __('crypto_deposit', '数字货币充值'); ?></h3>
                        <p style="margin: 5px 0 0; color: var(--text-muted); font-size: 14px;">Blockchain Transfer</p>
                    </div>
                </div>
                <div style="color: var(--text-muted); font-size: 13px; line-height: 2;">
                    <div style="display: flex; align-items: center; gap: 10px;"><i class="fas fa-check-circle" style="color: var(--success-color); font-size: 12px;"></i> USDT (TRC20, ERC20, BEP20)</div>
                    <div style="display: flex; align-items: center; gap: 10px;"><i class="fas fa-check-circle" style="color: var(--success-color); font-size: 12px;"></i> Low Service Fees</div>
                </div>
            </div>
        </div>

        <div id="fiat-section" style="background: var(--card-bg); padding: 40px; border-radius: 24px; border: 1px solid var(--border-color);">
            <form action="matching.php" method="POST" id="fiat-form">
                <input type="hidden" name="type" value="fiat">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-bottom: 30px;">
                    <div>
                        <label style="display: block; margin-bottom: 12px; color: var(--text-muted); font-size: 14px;"><?php echo __('select_currency', '选择币种'); ?></label>
                        <select name="currency" id="currency-select" style="width: 100%; padding: 15px; background: #161a1e; border: 1px solid var(--border-color); color: white; border-radius: 12px; font-size: 1rem; outline: none;">
                            <?php foreach ($fiat_rates as $code => $rate): ?>
                                <option value="<?php echo $code; ?>" data-rate="<?php echo $rate; ?>"><?php echo $code; ?> - <?php echo $fiat_currencies_info[$code] ?? $code; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label style="display: block; margin-bottom: 12px; color: var(--text-muted); font-size: 14px;"><?php echo __('deposit_amount', '充值金额'); ?></label>
                        <input type="number" name="amount" id="amount-input" placeholder="Min. 100" required style="width: 100%; padding: 15px; background: #161a1e; border: 1px solid var(--border-color); color: white; border-radius: 12px; font-size: 1.2rem; font-weight: bold; outline: none;">
                    </div>
                </div>
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 30px;">
                    <div id="rate-display" style="padding: 20px; background: #161a1e; border-radius: 12px; border: 1px dashed var(--border-color); display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center;">
                        <div style="color: var(--text-muted); font-size: 12px; margin-bottom: 5px;">Real-time Exchange Rate</div>
                        <div style="font-weight: bold; font-size: 1.1rem;"><span id="rate-value">...</span> <span id="rate-currency">...</span> = 1 USDT</div>
                    </div>
                    <div id="result-display" style="padding: 20px; background: rgba(79, 172, 254, 0.05); border-radius: 12px; border: 1px solid rgba(79, 172, 254, 0.2); display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center;">
                        <div style="color: var(--primary-color); font-size: 12px; margin-bottom: 5px;">You will receive</div>
                        <div style="font-weight: 800; font-size: 1.5rem; color: var(--primary-color);"><span id="receive-amount">0.00</span> USDT</div>
                    </div>
                </div>

                <div style="margin-top: 30px; padding: 25px; background: rgba(0,82,255,0.03); border-radius: 16px; border: 1px solid rgba(0,82,255,0.1); margin-bottom: 30px;">
                    <div style="display: flex; align-items: center; gap: 10px; color: var(--primary-color); margin-bottom: 10px; font-weight: bold;">
                        <i class="fas fa-info-circle"></i> Instructions
                    </div>
                    <p style="color: var(--text-muted); font-size: 14px; margin: 0; line-height: 1.6;">
                        Please complete the payment within the time limit after matching. Once submitted, our customer service will verify your deposit.
                    </p>
                </div>
                <button type="submit" class="btn-primary" style="width: 100%; padding: 18px; font-size: 1.1rem; border-radius: 12px;">Order Confirmation / 订单确认</button>
            </form>
        </div>

        <div id="usdt-section" style="background: var(--card-bg); padding: 40px; border-radius: 24px; border: 1px solid var(--border-color); display: none;">
            <form action="matching.php" method="POST" id="usdt-form">
                <input type="hidden" name="type" value="usdt">
                <div style="margin-bottom: 30px;">
                    <label style="display: block; margin-bottom: 15px; color: var(--text-muted); font-size: 14px;">Select Network</label>
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px;">
                        <label class="network-label active">
                            <input type="radio" name="network" value="TRC20" checked style="display: none;">
                            <div style="font-weight: bold;">TRC20</div>
                            <div style="font-size: 11px; opacity: 0.7; margin-top: 4px;">≈ 2 Mins</div>
                        </label>
                        <label class="network-label">
                            <input type="radio" name="network" value="ERC20" style="display: none;">
                            <div style="font-weight: bold;">ERC20</div>
                            <div style="font-size: 11px; opacity: 0.7; margin-top: 4px;">≈ 5 Mins</div>
                        </label>
                        <label class="network-label">
                            <input type="radio" name="network" value="BEP20" style="display: none;">
                            <div style="font-weight: bold;">BEP20</div>
                            <div style="font-size: 11px; opacity: 0.7; margin-top: 4px;">≈ 1 Min</div>
                        </label>
                    </div>
                </div>
                <div style="margin-bottom: 35px;">
                    <label style="display: block; margin-bottom: 12px; color: var(--text-muted); font-size: 14px;">Deposit Amount (USDT)</label>
                    <input type="number" name="amount" placeholder="Min. 10" required style="width: 100%; padding: 15px; background: #161a1e; border: 1px solid var(--border-color); color: white; border-radius: 12px; font-size: 1.2rem; font-weight: bold; outline: none;">
                </div>
                <button type="submit" class="btn-primary" style="width: 100%; padding: 18px; font-size: 1.1rem; border-radius: 12px; background: var(--success-color);">Order Confirmation / 订单确认</button>
            </form>
        </div>

    </div>
</main>

<style>
    .network-label { padding: 20px; background: #161a1e; border: 1px solid var(--border-color); border-radius: 16px; cursor: pointer; text-align: center; transition: 0.2s; }
    .network-label.active { border-color: var(--success-color); background: rgba(14,203,129,0.05); color: var(--success-color); }
</style>

<script>
    function switchMethod(method) {
        if(method === 'fiat') {
            document.getElementById('fiat-section').style.display = 'block';
            document.getElementById('usdt-section').style.display = 'none';
            document.getElementById('card-fiat').style.borderColor = 'var(--primary-color)';
            document.getElementById('card-usdt').style.borderColor = 'transparent';
        } else {
            document.getElementById('fiat-section').style.display = 'none';
            document.getElementById('usdt-section').style.display = 'block';
            document.getElementById('card-fiat').style.borderColor = 'transparent';
            document.getElementById('card-usdt').style.borderColor = 'var(--success-color)';
        }
    }

    const select = document.getElementById('currency-select');
    const amountInput = document.getElementById('amount-input');
    const rateVal = document.getElementById('rate-value');
    const rateCur = document.getElementById('rate-currency');
    const receiveAmount = document.getElementById('receive-amount');

    function calculate() {
        const option = select.options[select.selectedIndex];
        const rate = parseFloat(option.getAttribute('data-rate'));
        const amount = parseFloat(amountInput.value) || 0;
        
        rateVal.innerText = rate.toFixed(4);
        rateCur.innerText = select.value;
        
        if (rate > 0) {
            receiveAmount.innerText = (amount / rate).toFixed(2);
        } else {
            receiveAmount.innerText = '0.00';
        }
    }

    select.onchange = calculate;
    amountInput.oninput = calculate;
    calculate();

    document.querySelectorAll('.network-label').forEach(label => {
        label.onclick = function() {
            document.querySelectorAll('.network-label').forEach(l => l.classList.remove('active'));
            this.classList.add('active');
            this.querySelector('input').checked = true;
        };
    });
</script>

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