<?php
require_once 'includes/config.php';
require_once 'includes/telegram.php';
requireLogin();
require_once 'includes/service_check.php';
checkServiceEnabled('deposit');
$user = getCurrentUser();
$db   = getDB();

// User preferred currency
$_dep_uc = null;
try {
    $s = $db->prepare("SELECT c.* FROM users u JOIN currencies c ON u.preferred_currency=c.code WHERE u.id=? AND c.is_active=1 AND c.code<>'BDT'");
    $s->execute([$user['id']]);
    $_dep_uc = $s->fetch() ?: null;
} catch(Exception $e) { $_dep_uc = null; }

// Payment methods from settings
$methods = [
    'bkash'  => ['label'=>'bKash',  'icon'=>'fas fa-mobile-alt', 'color'=>'#E2136E', 'num'=> getSetting('bkash_number')  ?: ''],
    'nagad'  => ['label'=>'Nagad',  'icon'=>'fas fa-mobile-alt', 'color'=>'#F05829', 'num'=> getSetting('nagad_number')  ?: ''],
    'rocket' => ['label'=>'Rocket', 'icon'=>'fas fa-rocket',     'color'=>'#8C3494', 'num'=> getSetting('rocket_number') ?: ''],
    'bank'   => ['label'=>'Bank',   'icon'=>'fas fa-university', 'color'=>'#1a3c8f', 'num'=> getSetting('bank_account')  ?: ''],
];

$success = ''; $error = '';
if (isset($_GET['success'])) $success = "Deposit request submitted! Balance will be added after admin approval.";
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = floatval($_POST['amount'] ?? 0);
    $method = sanitize($_POST['method'] ?? '');
    $sender = sanitize($_POST['sender_number'] ?? '');
    $ref    = sanitize($_POST['transaction_ref'] ?? '');
    $minDep = floatval(getSetting('min_deposit') ?: 50);

    if ($amount < $minDep) {
        $error = "Minimum deposit amount is " . CURRENCY . number_format($minDep,0);
    } elseif (!$method) {
        $error = "Please select a payment method";
    } elseif (!$ref) {
        $error = "Please enter Transaction Reference";
    } else {
        $proof = null;
        if (isset($_FILES['proof']) && $_FILES['proof']['error'] === 0) {
            $ext = strtolower(pathinfo($_FILES['proof']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png'])) {
                $proof = 'uploads/' . uniqid() . '.' . $ext;
                move_uploaded_file($_FILES['proof']['tmp_name'], $proof);
            }
        }
        $db->prepare("INSERT INTO deposits (user_id,amount,method,sender_number,transaction_ref,proof_image) VALUES (?,?,?,?,?,?)")
           ->execute([$user['id'],$amount,$method,$sender,$ref,$proof]);
        notifyPending('deposit', $user['name'], [
            '💰 Amount' => CURRENCY.number_format($amount,2),
            '🏦 Method' => strtoupper($method),
            '📞 Sender' => $sender ?: '-',
            '🔖 Ref'    => $ref,
        ]);
        header('Location: deposit.php?success=1'); exit;
    }
}

$deposits = $db->prepare("SELECT * FROM deposits WHERE user_id=? ORDER BY created_at DESC LIMIT 10");
$deposits->execute([$user['id']]);
$deposits = $deposits->fetchAll();
$minDep = floatval(getSetting('min_deposit') ?: 50);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
    <title>Add Balance - <?= SITE_NAME ?></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        *{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}
        :root{
            --primary:<?= getSetting('color_primary') ?: '#1a3c8f' ?>;
            --secondary:<?= getSetting('color_secondary') ?: '#f5a623' ?>;
            --dark:<?= getSetting('color_dark') ?: '#0d1f4e' ?>;
        }
        body{font-family:'Segoe UI',sans-serif;background:#f5f7fa;padding-bottom:90px}

        /* Header */
        .hdr{background:linear-gradient(135deg,var(--dark),var(--primary));padding:0 18px;position:sticky;top:0;z-index:50}
        .hdr-in{display:flex;align-items:center;gap:12px;height:58px;max-width:480px;margin:0 auto}
        .back-btn{width:36px;height:36px;background:rgba(255,255,255,0.15);border:none;color:white;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:17px;cursor:pointer;flex-shrink:0}
        .hdr-title{color:white;font-size:18px;font-weight:700}

        /* Balance Hero */
        .hero{background:linear-gradient(135deg,var(--dark),var(--primary));padding:0 18px 18px}
        .hero-in{max-width:480px;margin:0 auto}
        .bal-card{background:rgba(255,255,255,0.12);border-radius:14px;padding:16px 18px;display:flex;align-items:center;justify-content:space-between}
        .bal-left .lbl{color:rgba(255,255,255,0.65);font-size:12px;font-weight:600;margin-bottom:4px}
        .bal-left .amt{color:white;font-size:26px;font-weight:800}
        .bal-left .dual{color:rgba(255,255,255,0.55);font-size:12px;margin-top:2px}
        .bal-icon{width:46px;height:46px;background:rgba(255,255,255,0.15);border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:22px;color:rgba(255,255,255,0.7)}

        /* Content */
        .content{max-width:480px;margin:0 auto;padding:16px 18px}

        /* Card */
        .card{background:white;border-radius:16px;padding:18px;margin-bottom:14px;box-shadow:0 2px 10px rgba(0,0,0,0.06)}
        .card-title{font-size:14px;font-weight:700;color:var(--dark);margin-bottom:14px;display:flex;align-items:center;gap:8px}

        /* Alert */
        .alert{padding:12px 15px;border-radius:12px;margin-bottom:14px;font-size:13px;font-weight:600;display:flex;align-items:center;gap:8px}
        .alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
        .alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7}

        /* Methods */
        .method-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:14px}
        .method-item{border:2px solid #e8ecf4;border-radius:13px;padding:14px 10px;text-align:center;cursor:pointer;transition:0.2s;background:#f8fafc}
        .method-item:active{transform:scale(0.96)}
        .method-item.active{border-color:var(--primary);background:#eef2ff}
        .method-item i{font-size:22px;display:block;margin-bottom:6px}
        .method-item span{font-size:12px;font-weight:700;color:#333;display:block}
        .method-item.active span{color:var(--primary)}

        /* Pay info */
        .pay-info{background:#eef2ff;border-radius:12px;padding:13px 15px;margin-bottom:14px;display:none}
        .pay-info .pi-lbl{font-size:11px;color:#666;font-weight:600;text-transform:uppercase;margin-bottom:4px}
        .pay-info .pi-num{font-size:16px;font-weight:800;color:var(--primary)}
        .pay-info .pi-copy{background:var(--primary);color:white;border:none;padding:5px 12px;border-radius:8px;font-size:11px;font-weight:700;cursor:pointer;margin-top:8px}

        /* Form */
        .fg{margin-bottom:13px}
        .fg label{display:block;font-size:12px;font-weight:700;color:#555;margin-bottom:6px;text-transform:uppercase;letter-spacing:0.4px}
        .inp-wrap{position:relative}
        .inp-wrap i{position:absolute;left:13px;top:50%;transform:translateY(-50%);color:#aaa;font-size:14px;pointer-events:none}
        .inp-wrap input,.inp-wrap select{width:100%;padding:12px 13px 12px 38px;border:2px solid #e8ecf4;border-radius:12px;font-size:14px;outline:none;transition:0.2s;background:white}
        .inp-wrap input:focus{border-color:var(--primary)}
        .amt-dual{font-size:11px;color:#b7791f;margin-top:4px;font-weight:600;min-height:16px}

        /* Quick amounts */
        .quick{display:flex;gap:7px;flex-wrap:wrap;margin-top:8px}
        .qbtn{padding:7px 13px;border:2px solid #e8ecf4;border-radius:9px;background:white;font-size:13px;font-weight:600;cursor:pointer;color:#555;transition:0.2s}
        .qbtn:active,.qbtn.sel{border-color:var(--primary);background:#eef2ff;color:var(--primary)}

        /* Submit */
        .submit-btn{width:100%;padding:15px;background:linear-gradient(135deg,var(--primary),#2856c8);color:white;border:none;border-radius:14px;font-size:15px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;margin-top:4px}
        .submit-btn:disabled{background:#c8d0db;cursor:not-allowed}

        /* History */
        .hist-item{display:flex;align-items:center;gap:12px;padding:12px 0;border-bottom:1px solid #f5f5f5}
        .hist-item:last-child{border:none}
        .hist-ic{width:40px;height:40px;border-radius:10px;background:#f0f4ff;display:flex;align-items:center;justify-content:center;font-size:16px;color:var(--primary);flex-shrink:0}
        .hist-info{flex:1}
        .hist-name{font-size:13px;font-weight:700;color:#333}
        .hist-sub{font-size:11px;color:#aaa;margin-top:2px}
        .hist-right{text-align:right}
        .hist-amt{font-size:14px;font-weight:800;color:#38a169}
        .hist-dual{font-size:10px;color:#aaa;margin-top:1px}
        .badge{display:inline-block;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:700;margin-top:3px}
        .badge-pending{background:#fffaf0;color:#d69e2e}
        .badge-approved{background:#f0fff4;color:#38a169}
        .badge-rejected{background:#fff5f5;color:#e53e3e}
    </style>
</head>
<body>

<div class="hdr">
    <div class="hdr-in">
        <button class="back-btn" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
        <div class="hdr-title">Add Balance</div>
    </div>
</div>

<!-- Balance Hero -->
<div class="hero">
    <div class="hero-in">
        <div class="bal-card">
            <div class="bal-left">
                <div class="lbl">CURRENT BALANCE</div>
                <div class="amt"><?= CURRENCY ?> <?= number_format($user['balance'],2) ?></div>
                <?php if($_dep_uc): ?>
                <div class="dual">≈ <?= htmlspecialchars($_dep_uc['symbol']) ?><?= number_format($user['balance']*floatval($_dep_uc['rate']),2) ?> <?= $_dep_uc['code'] ?></div>
                <?php endif; ?>
            </div>
            <div class="bal-icon"><i class="fas fa-wallet"></i></div>
        </div>
    </div>
</div>

<div class="content">
    <?php if($error): ?><div class="alert alert-err"><i class="fas fa-times-circle"></i> <?= htmlspecialchars($error) ?></div><?php endif; ?>
    <?php if($success): ?><div class="alert alert-ok"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?></div><?php endif; ?>

    <!-- Payment Method -->
    <div class="card">
        <div class="card-title"><i class="fas fa-credit-card" style="color:var(--primary)"></i> Select Payment Method</div>
        <div class="method-grid">
            <?php foreach($methods as $key => $m): ?>
            <div class="method-item" onclick="selectMethod('<?= $key ?>','<?= addslashes($m['num']) ?>',this)">
                <i class="<?= $m['icon'] ?>" style="color:<?= $m['color'] ?>"></i>
                <span><?= $m['label'] ?></span>
            </div>
            <?php endforeach; ?>
            <?php if(!empty(getSetting('bkash_app_key'))): ?>
            <div class="method-item bkash" id="bkMethodCard" onclick="selectBkash(this)" style="border-color:#E2136E;background:#fff5f8;position:relative;grid-column:1/-1">
                <div style="display:flex;align-items:center;gap:12px">
                    <i class="fas fa-mobile-alt" style="color:#E2136E;font-size:22px"></i>
                    <div style="text-align:left">
                        <div style="font-size:13px;font-weight:800;color:#E2136E">Pay with bKash</div>
                        <div style="font-size:11px;color:#aaa">Instant ⚡ No approval needed</div>
                    </div>
                    <span style="margin-left:auto;background:#E2136E;color:white;font-size:10px;font-weight:700;padding:3px 9px;border-radius:20px">AUTO</span>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- bKash Expanded Section -->
        <?php if(!empty(getSetting('bkash_app_key'))): ?>
        <div id="bkashSection" style="display:none;border-top:2px solid #fce4ec;margin-top:12px;padding-top:16px">
            <div style="font-size:12px;font-weight:700;color:#E2136E;margin-bottom:10px;text-transform:uppercase;letter-spacing:0.5px">⚡ bKash Payment Amount</div>
            <div style="position:relative;margin-bottom:10px">
                <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);font-size:16px;font-weight:700;color:#E2136E;pointer-events:none">৳</span>
                <input type="number" id="bkAmtInput" placeholder="Min ৳<?= number_format($minDep,0) ?>" step="1" min="<?= $minDep ?>"
                    oninput="onBkAmt(this.value)"
                    style="width:100%;padding:13px 13px 13px 36px;border:2px solid #fce4ec;border-radius:12px;font-size:22px;font-weight:800;outline:none;color:#E2136E;background:#fff5f8">
            </div>
            <div style="display:flex;gap:7px;flex-wrap:wrap;margin-bottom:10px">
                <?php foreach([100,200,500,1000,2000,5000] as $q): ?>
                <button type="button" onclick="setBkAmt(<?= $q ?>,this)"
                    style="padding:7px 14px;border:2px solid #fce4ec;border-radius:9px;background:white;font-size:13px;font-weight:600;cursor:pointer;color:#E2136E;transition:0.2s">
                    ৳<?= $q ?>
                </button>
                <?php endforeach; ?>
            </div>
            <?php if($_dep_uc): ?>
            <div id="bkDual" style="font-size:12px;color:#b7791f;margin-bottom:10px;font-weight:600"></div>
            <?php endif; ?>
            <button type="button" id="bkashBtn" onclick="payBkash()"
                style="width:100%;padding:15px;background:#E2136E;color:white;border:none;border-radius:14px;font-size:15px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:10px;opacity:0.5;pointer-events:none;transition:0.2s">
                <i class="fas fa-mobile-alt"></i> Pay with bKash
            </button>
        </div>
        <?php endif; ?>

        <div class="pay-info" id="payInfo">
            <div class="pi-lbl">Send money to</div>
            <div class="pi-num" id="payNum">-</div>
            <button class="pi-copy" onclick="copyNum()"><i class="fas fa-copy"></i> Copy</button>
        </div>

        <form method="POST" enctype="multipart/form-data" id="depForm">
            <input type="hidden" name="method" id="methodInput">
            <input type="hidden" name="amount" id="amtBDT">

            <!-- Currency Toggle -->
            <?php if($_dep_uc): ?>
            <div style="display:flex;background:#f0f4ff;border-radius:12px;padding:4px;margin-bottom:14px;gap:4px">
                <button type="button" id="btnBDT" onclick="setCurMode('bdt')"
                    style="flex:1;padding:10px;border:none;border-radius:9px;font-size:13px;font-weight:700;cursor:pointer;background:var(--primary);color:white;transition:0.2s">
                    ৳ BDT
                </button>
                <button type="button" id="btnUC" onclick="setCurMode('uc')"
                    style="flex:1;padding:10px;border:none;border-radius:9px;font-size:13px;font-weight:700;cursor:pointer;background:none;color:#888;transition:0.2s">
                    <?= htmlspecialchars($_dep_uc['symbol']) ?> <?= $_dep_uc['code'] ?>
                </button>
            </div>
            <?php endif; ?>

            <div class="fg">
                <label id="amtLabel">Amount (BDT)</label>
                <div class="inp-wrap" style="position:relative">
                    <span id="amtPrefix" style="position:absolute;left:14px;top:50%;transform:translateY(-50%);font-size:16px;font-weight:700;color:#aaa;pointer-events:none">৳</span>
                    <input type="number" id="amtInput" placeholder="Min <?= CURRENCY ?><?= number_format($minDep,0) ?>" step="0.01" oninput="onAmt(this.value)"
                        style="width:100%;padding:14px 14px 14px 38px;border:2px solid #e8ecf4;border-radius:12px;font-size:20px;font-weight:800;outline:none;color:var(--primary)" required>
                </div>
                <!-- Convert result -->
                <div id="convertBox" style="display:none;background:#f0fff4;border-radius:10px;padding:10px 14px;margin-top:8px;font-size:13px;color:#276749;font-weight:600;display:flex;align-items:center;justify-content:space-between">
                    <span>Will be deposited as:</span>
                    <span id="convertResult" style="font-size:16px;font-weight:800">৳0</span>
                </div>
                <div class="quick" style="margin-top:10px">
                    <?php if($_dep_uc): ?>
                    <div id="quickBDT">
                        <?php foreach([100,200,500,1000,2000,5000] as $q): ?>
                        <button type="button" class="qbtn" onclick="setAmt(<?= $q ?>,this)"><?= CURRENCY ?><?= $q ?></button>
                        <?php endforeach; ?>
                    </div>
                    <div id="quickUC" style="display:none">
                        <?php
                        $rate = floatval($_dep_uc['rate']);
                        $sym  = htmlspecialchars($_dep_uc['symbol']);
                        $ucAmts = $rate > 0 ? [1, 5, 10, 20, 50, 100] : [];
                        foreach($ucAmts as $q): ?>
                        <button type="button" class="qbtn" onclick="setAmt(<?= $q ?>,this)"><?= $sym ?><?= $q ?></button>
                        <?php endforeach; ?>
                    </div>
                    <?php else: ?>
                    <?php foreach([100,200,500,1000,2000,5000] as $q): ?>
                    <button type="button" class="qbtn" onclick="setAmt(<?= $q ?>,this)"><?= CURRENCY ?><?= $q ?></button>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <div class="fg">
                <label>Sender Number</label>
                <div class="inp-wrap">
                    <i class="fas fa-phone"></i>
                    <input type="text" name="sender_number" placeholder="Your mobile number">
                </div>
            </div>

            <div class="fg">
                <label>Transaction Reference / TrxID</label>
                <div class="inp-wrap">
                    <i class="fas fa-hashtag"></i>
                    <input type="text" name="transaction_ref" placeholder="Transaction ID" required>
                </div>
            </div>

            <div class="fg">
                <label>Payment Screenshot (Optional)</label>
                <input type="file" name="proof" accept="image/*" style="width:100%;padding:10px 12px;border:2px solid #e8ecf4;border-radius:12px;font-size:13px;background:white">
            </div>

            <button type="submit" class="submit-btn" id="submitBtn" disabled>
                <i class="fas fa-paper-plane"></i> Submit Deposit Request
            </button>


        </form>
    </div>

    <!-- Deposit History -->
    <?php if (!empty($deposits)): ?>
    <div class="card">
        <div class="card-title"><i class="fas fa-history" style="color:#805ad5"></i> Deposit History</div>
        <?php foreach($deposits as $d): ?>
        <div class="hist-item">
            <div class="hist-ic"><i class="fas fa-plus-circle"></i></div>
            <div class="hist-info">
                <div class="hist-name"><?= strtoupper($d['method']) ?></div>
                <div class="hist-sub"><?= date('d M Y, h:i A', strtotime($d['created_at'])) ?> • Ref: <?= $d['transaction_ref'] ?></div>
            </div>
            <div class="hist-right">
                <div class="hist-amt">+<?= CURRENCY ?><?= number_format($d['amount'],2) ?></div>
                <?php if($_dep_uc): ?>
                <div class="hist-dual">≈ <?= htmlspecialchars($_dep_uc['symbol']) ?><?= number_format($d['amount']*floatval($_dep_uc['rate']),2) ?> <?= $_dep_uc['code'] ?></div>
                <?php endif; ?>
                <span class="badge badge-<?= $d['status'] ?>"><?= ucfirst($d['status']) ?></span>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<?php include 'includes/bottom_nav.php'; ?>

<script>
const UC_RATE  = <?= $_dep_uc ? floatval($_dep_uc['rate']) : 0 ?>;
const UC_SYM   = "<?= $_dep_uc ? addslashes(htmlspecialchars($_dep_uc['symbol'])) : '' ?>";
const UC_CODE  = "<?= $_dep_uc ? $_dep_uc['code'] : '' ?>";
const BDT_RATE = <?= ($_dep_uc && floatval($_dep_uc['rate']) > 0) ? round(1/floatval($_dep_uc['rate']),4) : 0 ?>;
const MIN_DEP  = <?= $minDep ?>;

let curPayNum = '';
let curMode   = 'bdt';

function setCurMode(mode) {
    curMode = mode;
    const isBdt = (mode === 'bdt');
    const btnBDT = document.getElementById('btnBDT');
    const btnUC  = document.getElementById('btnUC');
    if (btnBDT) { btnBDT.style.background = isBdt ? 'var(--primary)' : 'none'; btnBDT.style.color = isBdt ? 'white' : '#888'; }
    if (btnUC)  { btnUC.style.background  = !isBdt ? 'var(--primary)' : 'none'; btnUC.style.color  = !isBdt ? 'white' : '#888'; }
    const qBDT = document.getElementById('quickBDT');
    const qUC  = document.getElementById('quickUC');
    if (qBDT) qBDT.style.display = isBdt ? 'flex' : 'none';
    if (qUC)  qUC.style.display  = !isBdt ? 'flex' : 'none';
    document.getElementById('amtPrefix').textContent = isBdt ? '৳' : UC_SYM;
    document.getElementById('amtLabel').textContent  = isBdt ? 'Amount (BDT)' : 'Amount (' + UC_CODE + ')';
    document.getElementById('amtInput').value = '';
    document.getElementById('amtInput').placeholder = isBdt ? 'Min ৳<?= number_format($minDep,0) ?>' : 'Enter ' + UC_CODE + ' amount';
    document.getElementById('convertBox').style.display = 'none';
    document.getElementById('amtBDT').value = '';
    document.querySelectorAll('.qbtn').forEach(b => b.classList.remove('sel'));
    checkReady();
}

function selectBkash(el) {
    // Deselect all methods
    document.querySelectorAll('.method-item').forEach(m => m.classList.remove('active'));
    el.classList.add('active');
    // Hide manual form, show bKash section
    document.getElementById('payInfo').style.display = 'none';
    document.getElementById('bkashSection').style.display = 'block';
    document.getElementById('methodInput').value = '';
    // Scroll to bKash section
    document.getElementById('bkashSection').scrollIntoView({behavior:'smooth', block:'nearest'});
    // Disable manual submit
    document.getElementById('submitBtn').disabled = true;
}

function selectMethod(method, num, el) {
    // Hide bKash section if open
    const bkSec = document.getElementById('bkashSection');
    if (bkSec) bkSec.style.display = 'none';
    const bkCard = document.getElementById('bkMethodCard');
    if (bkCard) bkCard.classList.remove('active');
    document.querySelectorAll('.method-item').forEach(m => m.classList.remove('active'));
    el.classList.add('active');
    document.getElementById('methodInput').value = method;
    curPayNum = num;
    document.getElementById('payNum').textContent = num || '-';
    document.getElementById('payInfo').style.display = num ? 'block' : 'none';
    checkReady();
}

function copyNum() {
    navigator.clipboard?.writeText(curPayNum).then(() => {
        const btn = document.querySelector('.pi-copy');
        const orig = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-check"></i> Copied!';
        setTimeout(() => btn.innerHTML = orig, 2000);
    });
}

function setAmt(v, btn) {
    document.getElementById('amtInput').value = v;
    document.querySelectorAll('.qbtn').forEach(b => b.classList.remove('sel'));
    if (btn) btn.classList.add('sel');
    calcAmt(v);
    checkReady();
}

function onAmt(v) {
    document.querySelectorAll('.qbtn').forEach(b => b.classList.remove('sel'));
    calcAmt(parseFloat(v) || 0);
    checkReady();
}

function calcAmt(inputVal) {
    const box    = document.getElementById('convertBox');
    const result = document.getElementById('convertResult');
    if (curMode === 'bdt' || !UC_RATE) {
        document.getElementById('amtBDT').value = inputVal || '';
        if (UC_RATE && inputVal > 0) {
            box.style.display = 'flex';
            result.textContent = '৳' + inputVal.toFixed(2) + ' ≈ ' + UC_SYM + (inputVal * UC_RATE).toFixed(2) + ' ' + UC_CODE;
        } else { box.style.display = 'none'; }
    } else {
        const bdtVal = inputVal > 0 ? Math.round(inputVal * BDT_RATE * 100) / 100 : 0;
        document.getElementById('amtBDT').value = bdtVal || '';
        if (inputVal > 0) {
            box.style.display = 'flex';
            result.textContent = UC_SYM + inputVal.toFixed(2) + ' ' + UC_CODE + ' = ৳' + bdtVal.toFixed(2) + ' BDT';
        } else { box.style.display = 'none'; }
    }
}

function checkReady() {
    const rawInput = parseFloat(document.getElementById('amtInput').value) || 0;
    const bdtAmt   = parseFloat(document.getElementById('amtBDT').value) || 0;
    const method   = document.getElementById('methodInput').value;
    const valid    = bdtAmt >= MIN_DEP && method;
    const btn      = document.getElementById('submitBtn');
    btn.disabled   = !valid;
    if (valid && curMode === 'uc' && UC_CODE) {
        btn.innerHTML = '<i class="fas fa-paper-plane"></i> Submit — ' + UC_SYM + rawInput.toFixed(2) + ' ' + UC_CODE + ' = ৳' + bdtAmt.toFixed(2);
    } else {
        btn.innerHTML = '<i class="fas fa-paper-plane"></i> Submit Deposit Request';
    }
}

function setBkAmt(v, btn) {
    document.getElementById('bkAmtInput').value = v;
    document.querySelectorAll('#bkashBtn').forEach(()=>{});
    // highlight btn
    document.querySelectorAll('[onclick^="setBkAmt"]').forEach(b => b.style.borderColor = '#e8ecf4');
    if(btn) btn.style.borderColor = '#E2136E';
    onBkAmt(v);
}

function onBkAmt(v) {
    const amt = parseFloat(v) || 0;
    const btn = document.getElementById('bkashBtn');
    if (amt >= MIN_DEP) {
        btn.style.opacity = '1';
        btn.style.pointerEvents = 'auto';
        btn.innerHTML = '<i class="fas fa-mobile-alt"></i> Pay ৳' + amt.toFixed(0) + ' with bKash';
    } else {
        btn.style.opacity = '0.5';
        btn.style.pointerEvents = 'none';
        btn.innerHTML = '<i class="fas fa-mobile-alt"></i> Pay with bKash';
    }
    // Show dual currency
    const dual = document.getElementById('bkDual');
    if (dual && UC_RATE && amt > 0) {
        dual.textContent = '≈ ' + UC_SYM + (amt * UC_RATE).toFixed(2) + ' ' + UC_CODE;
    } else if (dual) {
        dual.textContent = '';
    }
}

function payBkash() {
    const bdtAmt = parseFloat(document.getElementById('bkAmtInput').value) || 0;
    if (bdtAmt < MIN_DEP) { alert('Please enter amount first'); return; }

    const btn = document.getElementById('bkashBtn');
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Creating payment...';
    btn.disabled = true;

    fetch('api/bkash_payment.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({action: 'create', amount: bdtAmt})
    })
    .then(r => r.json())
    .then(d => {
        if (d.success) {
            sessionStorage.setItem('bkash_ref', d.ref);
            sessionStorage.setItem('bkash_amount', bdtAmt);
            window.location.href = d.bkash_url;
        } else {
            alert('❌ ' + d.message);
            btn.innerHTML = '<i class="fas fa-mobile-alt"></i> Pay with bKash';
            btn.disabled = false;
        }
    })
    .catch(() => {
        alert('❌ Connection error!');
        btn.innerHTML = '<i class="fas fa-mobile-alt"></i> Pay with bKash';
        btn.disabled = false;
    });
}

// Auto-execute after bKash callback
window.addEventListener('load', function() {
    const params = new URLSearchParams(window.location.search);
    if (params.get('bkash') === 'execute') {
        const paymentID = params.get('paymentID');
        const ref       = params.get('ref') || sessionStorage.getItem('bkash_ref');
        if (paymentID && ref) {
            document.body.innerHTML += '<div style="position:fixed;inset:0;background:rgba(255,255,255,0.9);z-index:9999;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px"><div style="width:50px;height:50px;border:4px solid #E2136E;border-top-color:transparent;border-radius:50%;animation:spin 0.8s linear infinite"></div><div style="font-size:15px;font-weight:700;color:#E2136E">Processing bKash Payment...</div></div><style>@keyframes spin{to{transform:rotate(360deg)}}</style>';
            fetch('api/bkash_payment.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({action: 'execute', paymentID, ref})
            })
            .then(r => r.json())
            .then(d => {
                if (d.success) {
                    window.location.href = 'dashboard.php?bkash=success&amount=' + d.amount;
                } else {
                    alert('❌ ' + d.message);
                    window.location.href = 'deposit.php?bkash=failed';
                }
            });
        }
    }
    if (params.get('bkash') === 'failed') {
        alert('❌ bKash payment failed or cancelled.');
    }
});

</script>
<script>document.addEventListener("DOMContentLoaded",function(){ if(window.pageReady) window.pageReady(); });</script>
</body>
</html>
