<?php
require_once 'includes/header.php';

if (!$user) {
    header('Location: login.php');
    exit;
}

$currency = $_POST['fiat_currency'] ?? 'USD';
$amount = $_POST['amount'] ?? 0;
$order_id = strtoupper(substr(md5(time() . ($user['id'] ?? 0)), 0, 10));

// Rates mapping
$rates = [
    'USD' => 1.0, 'EUR' => 0.92, 'CNY' => 7.21, 'JPY' => 149.5, 'KRW' => 1335.0, 
    'GBP' => 0.79, 'RUB' => 92.4, 'HKD' => 7.82, 'SGD' => 1.34, 'AUD' => 1.53,
    'CAD' => 1.35, 'BRL' => 4.98, 'INR' => 83.0, 'VND' => 24500.0, 'THB' => 35.8,
    'MYR' => 4.77, 'IDR' => 15600.0, 'PHP' => 56.1, 'AED' => 3.67, 'TRY' => 31.0
];
$rate = $rates[$currency] ?? 1.0;
$usdt_amount = $amount / $rate;
?>

<div class="container my-5 py-5">
    <div class="row justify-content-center">
        <div class="col-md-9 col-lg-7">
            <div class="card bg-dark border-secondary shadow-lg overflow-hidden" style="border-radius: 24px;">
                <!-- Header / Order Status -->
                <div class="p-4 border-bottom border-secondary d-flex justify-content-between align-items-center bg-secondary bg-opacity-10">
                    <div>
                        <h5 class="fw-bold text-white mb-0"><?php echo mt('Deposit'); ?>: <?php echo number_format((float)$amount, 2); ?> <?php echo $currency; ?></h5>
                        <div class="small text-muted mt-1"><?php echo mt('Order ID'); ?>: #<?php echo $order_id; ?></div>
                    </div>
                    <div class="text-end">
                        <div class="text-primary fw-bold fs-4" id="timer">15:00</div>
                    </div>
                </div>

                <div class="row g-0" style="min-height: 550px;">
                    <!-- Left: Chat/Matching Status -->
                    <div class="col-md-5 border-end border-secondary p-4 d-flex flex-column bg-black bg-opacity-25">
                        <h6 class="text-white fw-bold mb-4 d-flex align-items-center">
                            <span class="spinner-grow spinner-grow-sm text-success me-2"></span>
                            <?php echo mt('Customer Service'); ?>
                        </h6>
                        
                        <div id="chat-messages" class="flex-grow-1 overflow-auto small mb-3 px-1" style="max-height: 350px;">
                            <div class="mb-3">
                                <span class="badge bg-secondary mb-1">System</span>
                                <div class="p-2 bg-dark rounded border border-secondary text-muted" style="font-size: 0.75rem;">
                                    <?php echo mt('Establishing secure connection with liquidity provider...'); ?>
                                </div>
                            </div>
                        </div>

                        <div id="matching-status" class="text-center py-3 border-top border-secondary mt-auto">
                            <div class="spinner-border spinner-border-sm text-primary mb-2"></div>
                            <div class="small text-muted" style="font-size: 0.7rem;"><?php echo mt('Awaiting merchant confirmation...'); ?></div>
                        </div>
                    </div>

                    <!-- Right: Payment Details -->
                    <div class="col-md-7 p-4 position-relative">
                        <div id="lock-overlay" class="position-absolute top-0 start-0 w-100 h-100 d-flex flex-column align-items-center justify-content-center bg-dark" style="z-index: 5; transition: opacity 0.5s;">
                            <div class="text-center">
                                <i class="fas fa-user-clock fa-3x text-secondary mb-3"></i>
                                <h6 class="text-white mb-2"><?php echo mt('Matching in progress'); ?></h6>
                                <p class="text-muted small px-4"><?php echo mt('The specialized account for this transaction will be provided by our agent shortly.'); ?></p>
                            </div>
                        </div>

                        <div id="payment-details" class="d-none">
                            <div class="alert alert-primary bg-primary bg-opacity-10 border-primary text-white p-3 rounded-4 mb-4 small">
                                <i class="fas fa-info-circle me-2"></i> <?php echo mt('Transfer the exact amount. Upload proof below.'); ?>
                            </div>

                            <div class="p-3 bg-secondary bg-opacity-10 rounded-4 mb-4 border border-secondary small">
                                <div class="mb-3">
                                    <label class="text-muted mb-1 d-block"><?php echo mt('Bank Name'); ?></label>
                                    <div class="d-flex justify-content-between">
                                        <span class="fw-bold text-white" id="bank-name">--</span>
                                        <span class="text-primary pointer" onclick="copyText('bank-name')"><?php echo mt('Copy'); ?></span>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label class="text-muted mb-1 d-block"><?php echo mt('Account Number'); ?></label>
                                    <div class="d-flex justify-content-between">
                                        <span class="fw-bold text-white" id="account-num">--</span>
                                        <span class="text-primary pointer" onclick="copyText('account-num')"><?php echo mt('Copy'); ?></span>
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label class="text-muted mb-1 d-block"><?php echo mt('Beneficiary'); ?></label>
                                    <div class="d-flex justify-content-between">
                                        <span class="fw-bold text-white" id="beneficiary-name">--</span>
                                        <span class="text-primary pointer" onclick="copyText('beneficiary-name')"><?php echo mt('Copy'); ?></span>
                                    </div>
                                </div>
                                <div class="mb-0">
                                    <label class="text-muted mb-1 d-block"><?php echo mt('Reference'); ?></label>
                                    <div class="d-flex justify-content-between">
                                        <span class="fw-bold text-warning" id="ref-code"><?php echo $order_id; ?></span>
                                        <span class="text-primary pointer" onclick="copyText('ref-code')"><?php echo mt('Copy'); ?></span>
                                    </div>
                                </div>
                            </div>

                            <form id="proof-form">
                                <div class="mb-3">
                                    <div class="upload-area border border-dashed border-secondary rounded-4 p-4 text-center position-relative" id="drop-area">
                                        <input type="file" class="position-absolute w-100 h-100 top-0 start-0 opacity-0" style="cursor: pointer;" id="file-input">
                                        <i class="fas fa-camera text-muted mb-2"></i>
                                        <div class="small text-muted"><?php echo mt('Upload Proof'); ?></div>
                                        <div id="preview" class="mt-2 d-none">
                                            <span class="badge bg-success"><?php echo mt('Selected'); ?></span>
                                        </div>
                                    </div>
                                </div>
                                <button type="button" class="btn btn-primary w-100 py-3 rounded-3 fw-bold shadow-glow" onclick="completeOrder()">
                                    <?php echo mt('Transfer Completed'); ?>
                                </button>
                            </form>
                        </div>

                        <!-- Success Screen -->
                        <div id="success-step" class="d-none text-center py-5">
                            <i class="fas fa-check-circle text-success mb-3" style="font-size: 4rem;"></i>
                            <h4 class="text-white fw-bold mb-3"><?php echo mt('Success'); ?></h4>
                            <p class="text-muted small"><?php echo mt('Your transfer is being reviewed. ETA: 10-20 mins.'); ?></p>
                            <a href="profile.php" class="btn btn-outline-light px-4 mt-3"><?php echo mt('Back to Wallet'); ?></a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let seconds = 900;
const timerEl = document.getElementById('timer');
const chatBox = document.getElementById('chat-messages');

function addChatMessage(sender, msg, type = 'agent') {
    const div = document.createElement('div');
    div.className = 'mb-3';
    div.innerHTML = `
        <div class="d-flex justify-content-between align-items-center mb-1">
            <span class="badge ${type === 'agent' ? 'bg-primary' : 'bg-secondary'}" style="font-size: 0.65rem;">${sender}</span>
            <span class="text-muted" style="font-size: 0.6rem;">${new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
        </div>
        <div class="p-2 bg-dark rounded border border-secondary text-white-50" style="font-size: 0.8rem; line-height: 1.4;">
            ${msg}
        </div>
    `;
    chatBox.appendChild(div);
    chatBox.scrollTop = chatBox.scrollHeight;
}

function updateTimer() {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    timerEl.innerText = `${mins}:${secs < 10 ? '0' : ''}${secs}`;
    if (seconds > 0) {
        seconds--;
        setTimeout(updateTimer, 1000);
    }
}

function copyText(id) {
    const text = document.getElementById(id).innerText;
    navigator.clipboard.writeText(text);
    alert('<?php echo mt('Copy'); ?> OK');
}

// Simulated Professional Flow
setTimeout(() => addChatMessage('System', '<?php echo mt('A local merchant has been found. Matching account details...'); ?>'), 3000);
setTimeout(() => {
    addChatMessage('Live Agent', '<?php echo mt('Welcome! I am your dedicated matching assistant. I am currently verifying the liquidity provider for your deposit.'); ?>');
}, 8000);

setTimeout(() => {
    addChatMessage('Live Agent', '<?php echo mt('Matching successful. I have secured a high-priority account for your transaction. Please find the details on the right.'); ?>');
    
    // Unlock UI
    document.getElementById('lock-overlay').style.opacity = '0';
    setTimeout(() => {
        document.getElementById('lock-overlay').classList.add('d-none');
        document.getElementById('payment-details').classList.remove('d-none');
    }, 500);
    
    document.getElementById('matching-status').innerHTML = '<div class="badge bg-success bg-opacity-25 text-success border border-success px-3"><?php echo mt('Matched & Active'); ?></div>';
    
    // Fill bank info
    const banks = {
        'USD': { name: 'JPMorgan Chase Bank', account: '9120 4481 0029 3341', beneficiary: 'Global Assets Ltd.' },
        'CNY': { name: '中国工商银行', account: '6222 0812 0900 3381 922', beneficiary: '数字科技有限公司' },
        'EUR': { name: 'Deutsche Bank', account: 'DE89 1007 0000 0123 4567 89', beneficiary: 'EU Crypto Services' },
        'JPY': { name: 'Mizuho Bank', account: '109-2239481-001', beneficiary: 'テック・トレード株式会社' },
        'GBP': { name: 'Barclays Bank', account: '20-10-05 99384812', beneficiary: 'UK Digital Trade' }
    };
    const bank = banks['<?php echo $currency; ?>'] || banks['USD'];
    document.getElementById('bank-name').innerText = bank.name;
    document.getElementById('account-num').innerText = bank.account;
    document.getElementById('beneficiary-name').innerText = bank.beneficiary;
}, 15000); 

document.getElementById('file-input').addEventListener('change', function() {
    if (this.files.length > 0) document.getElementById('preview').classList.remove('d-none');
});

function completeOrder() {
    if (document.getElementById('file-input').files.length === 0) {
        alert('<?php echo mt('Please upload your payment receipt/screenshot first.'); ?>');
        return;
    }
    document.getElementById('payment-details').classList.add('d-none');
    document.getElementById('success-step').classList.remove('d-none');
    addChatMessage('Live Agent', '<?php echo mt('Thank you for the update. We have received your payment proof and are now verifying the transaction on the blockchain. Your balance will be updated shortly.'); ?>');
}

updateTimer();
</script>

<style>
    .upload-area { border-style: dashed !important; cursor: pointer; transition: 0.3s; }
    .upload-area:hover { border-color: #f0b90b !important; background: rgba(240,185,11,0.05); }
    .pointer { cursor: pointer; }
    .shadow-glow { box-shadow: 0 0 15px rgba(240,185,11,0.2); }
</style>

<?php require_once 'includes/footer.php'; ?>