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

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

$fiat_currencies = [
    'USD' => ['name' => 'US Dollar', 'symbol' => '$', 'rate' => 1.0, 'region' => 'Americas'],
    'EUR' => ['name' => 'Euro', 'symbol' => '€', 'rate' => 0.92, 'region' => 'Europe'],
    'CNY' => ['name' => 'Chinese Yuan', 'symbol' => '¥', 'rate' => 7.21, 'region' => 'Asia'],
    'JPY' => ['name' => 'Japanese Yen', 'symbol' => '¥', 'rate' => 149.5, 'region' => 'Asia'],
    'KRW' => ['name' => 'South Korean Won', 'symbol' => '₩', 'rate' => 1335.0, 'region' => 'Asia'],
    'GBP' => ['name' => 'British Pound', 'symbol' => '£', 'rate' => 0.79, 'region' => 'Europe'],
    'RUB' => ['name' => 'Russian Ruble', 'symbol' => '₽', 'rate' => 92.4, 'region' => 'Europe'],
    'HKD' => ['name' => 'Hong Kong Dollar', 'symbol' => 'HK$', 'rate' => 7.82, 'region' => 'Asia'],
    'SGD' => ['name' => 'Singapore Dollar', 'symbol' => 'S$', 'rate' => 1.34, 'region' => 'Asia'],
    'AUD' => ['name' => 'Australian Dollar', 'symbol' => 'A$', 'rate' => 1.53, 'region' => 'Oceania'],
    'CAD' => ['name' => 'Canadian Dollar', 'symbol' => 'C$', 'rate' => 1.35, 'region' => 'Americas'],
    'BRL' => ['name' => 'Brazilian Real', 'symbol' => 'R$', 'rate' => 4.98, 'region' => 'Americas'],
    'INR' => ['name' => 'Indian Rupee', 'symbol' => '₹', 'rate' => 83.0, 'region' => 'Asia'],
    'VND' => ['name' => 'Vietnamese Dong', 'symbol' => '₫', 'rate' => 24500.0, 'region' => 'Asia'],
    'THB' => ['name' => 'Thai Baht', 'symbol' => '฿', 'rate' => 35.8, 'region' => 'Asia'],
    'MYR' => ['name' => 'Malaysian Ringgit', 'symbol' => 'RM', 'rate' => 4.77, 'region' => 'Asia'],
    'IDR' => ['name' => 'Indonesian Rupiah', 'symbol' => 'Rp', 'rate' => 15600.0, 'region' => 'Asia'],
    'PHP' => ['name' => 'Philippine Peso', 'symbol' => '₱', 'rate' => 56.1, 'region' => 'Asia'],
    'AED' => ['name' => 'UAE Dirham', 'symbol' => 'د.إ', 'rate' => 3.67, 'region' => 'Middle East'],
    'TRY' => ['name' => 'Turkish Lira', 'symbol' => '₺', 'rate' => 31.0, 'region' => 'Europe/Asia'],
];

// Group by region for better UI
$grouped_fiat = [];
foreach ($fiat_currencies as $code => $data) {
    $grouped_fiat[$data['region']][$code] = $data;
}

// Handle Receipt Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['receipt'])) {
    $amount = $_POST['amount'] ?? 0;
    $currency = $_POST['currency'] ?? 'USDT';
    
    $target_dir = "uploads/receipts/";
    if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
    
    $file_ext = pathinfo($_FILES["receipt"]["name"], PATHINFO_EXTENSION);
    $file_name = time() . "_" . $user['id'] . "." . $file_ext;
    $target_file = $target_dir . $file_name;
    
    if (move_uploaded_file($_FILES["receipt"]["tmp_name"], $target_file)) {
        // Save to DB
        $stmt = db()->prepare("INSERT INTO deposits (user_id, amount, currency, receipt_url, status) VALUES (?, ?, ?, ?, 'pending')");
        $stmt->execute([$user['id'], $amount, $currency, $target_file]);
        
        // Notify admin via chat (simulated message)
        $msg = "New deposit request: $amount $currency. UID: " . ($user['uid'] ?? '000000');
        $stmt = db()->prepare("INSERT INTO chat_messages (user_id, message, attachment_url) VALUES (?, ?, ?)");
        $stmt->execute([$user['id'], $msg, $target_file]);
        
        echo "<script>alert('" . mt('Receipt uploaded successfully. Waiting for admin approval.') . "'); window.location.href='profile.php';</script>";
        exit;
    }
}
?>

<div class="container my-5 py-5">
    <div class="row justify-content-center">
        <div class="col-md-11 col-lg-10">
            <div class="text-center mb-5">
                <h1 class="fw-bold text-white mb-2"><?php echo mt('Deposit Assets'); ?></h1>
                <p class="text-muted"><?php echo mt('Choose your preferred method to fund your account'); ?></p>
            </div>

            <div class="card bg-dark border-secondary shadow-lg overflow-hidden" style="border-radius: 30px;">
                <div class="row g-0">
                    <div class="col-md-3 border-end border-secondary bg-secondary bg-opacity-10">
                        <div class="nav flex-column nav-pills p-3 h-100" id="deposit-tabs" role="tablist">
                            <button class="nav-link active mb-2 text-start p-3 rounded-4" id="crypto-tab" data-bs-toggle="pill" data-bs-target="#crypto-pane">
                                <i class="fas fa-coins me-2"></i> <?php echo mt('Crypto Deposit'); ?>
                            </button>
                            <button class="nav-link mb-2 text-start p-3 rounded-4" id="fiat-tab" data-bs-toggle="pill" data-bs-target="#fiat-pane">
                                <i class="fas fa-university me-2"></i> <?php echo mt('Fiat Deposit'); ?>
                            </button>
                        </div>
                    </div>

                    <div class="col-md-9 p-4 p-md-5">
                        <div class="tab-content">
                            <!-- Crypto Pane -->
                            <div class="tab-pane fade show active" id="crypto-pane">
                                <div class="d-flex justify-content-between align-items-center mb-4">
                                    <h3 class="fw-bold mb-0 text-white"><?php echo mt('Crypto Deposit'); ?></h3>
                                    <span class="badge bg-primary bg-opacity-10 text-primary px-3 py-2 rounded-pill"><?php echo mt('Instant'); ?></span>
                                </div>
                                
                                <div class="row g-4">
                                    <div class="col-md-6">
                                        <div class="mb-4">
                                            <label class="small text-muted mb-2"><?php echo mt('Select Currency'); ?></label>
                                            <select class="form-select bg-dark text-white border-secondary py-3 rounded-4" id="crypto-select">
                                                <option value="USDT">USDT (TRC20)</option>
                                                <option value="BTC">BTC (Bitcoin)</option>
                                                <option value="ETH">ETH (ERC20)</option>
                                            </select>
                                        </div>
                                        <div id="deposit-details">
                                            <div class="p-3 bg-secondary bg-opacity-10 rounded-4 border border-secondary mb-3">
                                                <div class="small text-muted mb-1"><?php echo mt('Network'); ?></div>
                                                <div class="fw-bold text-white" id="network-name">Tron (TRC20)</div>
                                            </div>
                                            <div class="p-3 bg-secondary bg-opacity-10 rounded-4 border border-secondary">
                                                <div class="small text-muted mb-1"><?php echo mt('Deposit Address'); ?></div>
                                                <div class="fw-bold text-white text-break font-monospace" id="deposit-addr">TWr8mP9PjH5pX9pX9pX9pX9pX9pX9pX9pX</div>
                                                <button class="btn btn-sm btn-primary mt-3 rounded-pill px-4" onclick="copyAddr()">
                                                    <i class="fas fa-copy me-1"></i> <?php echo mt('Copy'); ?>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="text-center mb-4">
                                            <div class="bg-white p-3 d-inline-block rounded-4 mb-3 shadow">
                                                <img src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=TWr8mP9PjH5pX9pX9pX9pX9pX9pX9pX9pX&color=0b0e11" alt="QR" width="150" id="deposit-qr">
                                            </div>
                                            <p class="small text-muted"><?php echo mt('Scan QR code to deposit'); ?></p>
                                        </div>
                                        
                                        <form method="POST" enctype="multipart/form-data" class="mt-2 bg-secondary bg-opacity-10 p-4 rounded-4 border border-secondary border-opacity-50">
                                            <input type="hidden" name="currency" id="h-currency" value="USDT">
                                            <div class="mb-3">
                                                <label class="small text-muted mb-2"><?php echo mt('Deposit Amount'); ?></label>
                                                <div class="input-group">
                                                    <input type="number" name="amount" class="form-control bg-dark text-white border-secondary rounded-start-4 py-2" placeholder="0.00" step="0.01" required>
                                                    <span class="input-group-text bg-dark border-secondary text-muted rounded-end-4" id="crypto-label">USDT</span>
                                                </div>
                                            </div>
                                            <div class="mb-4">
                                                <label class="small text-muted mb-2"><?php echo mt('Upload Proof'); ?></label>
                                                <input type="file" name="receipt" class="form-control bg-dark text-white border-secondary rounded-4 py-2" accept="image/*" required>
                                                <div class="small text-muted mt-2"><i class="fas fa-info-circle me-1"></i> <?php echo mt('Upload screenshot of your transaction'); ?></div>
                                            </div>
                                            <button type="submit" class="btn btn-primary w-100 py-3 rounded-4 fw-bold shadow">
                                                <i class="fas fa-upload me-2"></i> <?php echo mt('Submit Deposit'); ?>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>

                            <!-- Fiat Pane -->
                            <div class="tab-pane fade" id="fiat-pane">
                                <div class="d-flex justify-content-between align-items-center mb-4">
                                    <h3 class="fw-bold mb-0 text-white"><?php echo mt('Fiat Deposit'); ?></h3>
                                    <span class="badge bg-success bg-opacity-10 text-success px-3 py-2 rounded-pill"><?php echo mt('Regional Support'); ?></span>
                                </div>
                                
                                <form action="matching.php" method="POST" id="fiat-form">
                                    <div class="row g-4">
                                        <div class="col-md-7">
                                            <div class="mb-4">
                                                <label class="small text-muted mb-2"><?php echo mt('Select Fiat Currency'); ?></label>
                                                <select name="fiat_currency" id="fiat-currency" class="form-select bg-dark text-white border-secondary py-3 rounded-4 shadow-sm" onchange="updateRate()">
                                                    <?php foreach($grouped_fiat as $region => $coins): ?>
                                                        <optgroup label="<?php echo $region; ?>">
                                                            <?php foreach($coins as $code => $data): ?>
                                                                <option value="<?php echo $code; ?>" data-rate="<?php echo $data['rate']; ?>" data-symbol="<?php echo $data['symbol']; ?>">
                                                                    <?php echo $code; ?> - <?php echo $data['name']; ?>
                                                                </option>
                                                            <?php endforeach; ?>
                                                        </optgroup>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="mb-4">
                                                <label class="small text-muted mb-2"><?php echo mt('Amount'); ?></label>
                                                <div class="input-group">
                                                    <span class="input-group-text bg-dark border-secondary text-white rounded-start-4 px-3" id="currency-symbol">$</span>
                                                    <input type="number" name="amount" id="fiat-amount" class="form-control bg-dark text-white border-secondary py-3" placeholder="0.00" oninput="updateRate()" required>
                                                    <span class="input-group-text bg-dark border-secondary text-muted rounded-end-4" id="fiat-code">USD</span>
                                                </div>
                                            </div>
                                            
                                            <div class="alert alert-primary bg-primary bg-opacity-10 border-primary border-opacity-20 rounded-4 p-3 mb-0">
                                                <div class="d-flex">
                                                    <i class="fas fa-info-circle mt-1 me-3"></i>
                                                    <div class="small">
                                                        <?php echo mt('We will match you with a local merchant to facilitate your deposit in your local currency.'); ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-5">
                                            <div class="p-4 bg-secondary bg-opacity-10 border border-secondary rounded-4 h-100 d-flex flex-column justify-content-center text-center">
                                                <div class="small text-muted mb-2"><?php echo mt('Est. Arrival'); ?></div>
                                                <div class="display-5 fw-bold text-white mb-2"><span id="usdt-amount">0.00</span> <span class="fs-4">USDT</span></div>
                                                <div class="small text-muted"><?php echo mt('Processing Time: 10-30 mins'); ?></div>
                                                
                                                <hr class="my-4 border-secondary border-opacity-50">
                                                
                                                <div class="text-start small text-muted">
                                                    <div class="d-flex justify-content-between mb-2">
                                                        <span><?php echo mt('Exchange Rate'); ?>:</span>
                                                        <span id="display-rate">1 USDT ≈ 1.00 USD</span>
                                                    </div>
                                                    <div class="d-flex justify-content-between">
                                                        <span><?php echo mt('Service Fee'); ?>:</span>
                                                        <span class="text-success"><?php echo mt('Free'); ?></span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mt-5">
                                        <button type="submit" class="btn btn-primary btn-lg w-100 py-3 rounded-4 fw-bold shadow-lg">
                                            <?php echo mt('Confirm Deposit'); ?> <i class="fas fa-arrow-right ms-2"></i>
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="mt-4 row g-4">
                <div class="col-md-4">
                    <div class="p-4 rounded-4 bg-white bg-opacity-5 border border-white border-opacity-10 d-flex align-items-center gap-3">
                        <i class="fas fa-shield-check fa-2x text-primary"></i>
                        <div>
                            <h6 class="text-white mb-1"><?php echo mt('Secure Payment'); ?></h6>
                            <p class="small text-muted mb-0"><?php echo mt('All transactions are encrypted'); ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="p-4 rounded-4 bg-white bg-opacity-5 border border-white border-opacity-10 d-flex align-items-center gap-3">
                        <i class="fas fa-clock fa-2x text-primary"></i>
                        <div>
                            <h6 class="text-white mb-1"><?php echo mt('Fast Arrival'); ?></h6>
                            <p class="small text-muted mb-0"><?php echo mt('Most deposits arrive in mins'); ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="p-4 rounded-4 bg-white bg-opacity-5 border border-white border-opacity-10 d-flex align-items-center gap-3">
                        <i class="fas fa-headset fa-2x text-primary"></i>
                        <div>
                            <h6 class="text-white mb-1"><?php echo mt('24/7 Support'); ?></h6>
                            <p class="small text-muted mb-0"><?php echo mt('Live help for your deposit'); ?></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function copyAddr() {
    const addr = document.getElementById('deposit-addr').innerText;
    navigator.clipboard.writeText(addr);
    alert('<?php echo mt('Address copied to clipboard'); ?>');
}

function updateRate() {
    const select = document.getElementById('fiat-currency');
    const option = select.options[select.selectedIndex];
    const rate = parseFloat(option.getAttribute('data-rate'));
    const symbol = option.getAttribute('data-symbol');
    const code = select.value;
    const amount = parseFloat(document.getElementById('fiat-amount').value) || 0;
    
    document.getElementById('currency-symbol').innerText = symbol;
    document.getElementById('fiat-code').innerText = code;
    document.getElementById('usdt-amount').innerText = (amount / rate).toFixed(2);
    document.getElementById('display-rate').innerText = `1 USDT ≈ ${rate.toFixed(2)} ${code}`;
}

document.getElementById('crypto-select').addEventListener('change', function() {
    const val = this.value;
    document.getElementById('h-currency').value = val;
    document.getElementById('crypto-label').innerText = val;
    
    let addr = '';
    let network = '';
    
    if (val === 'BTC') {
        addr = '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa';
        network = 'Bitcoin';
    } else if (val === 'ETH') {
        addr = '0x742d35Cc6634C0532925a3b844Bc454e4438f44e';
        network = 'Ethereum (ERC20)';
    } else {
        addr = 'TWr8mP9PjH5pX9pX9pX9pX9pX9pX9pX9pX';
        network = 'Tron (TRC20)';
    }
    
    document.getElementById('deposit-addr').innerText = addr;
    document.getElementById('network-name').innerText = network;
    document.getElementById('deposit-qr').src = `https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${addr}&color=0b0e11`;
});

document.addEventListener('DOMContentLoaded', updateRate);
</script>

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