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

// Ensure tables exist
try {
    $db->exec("CREATE TABLE IF NOT EXISTS mbanking_operators (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), code VARCHAR(20), logo_emoji VARCHAR(10) DEFAULT '💳', color VARCHAR(20) DEFAULT '#1a3c8f', send_charge_type VARCHAR(10) DEFAULT 'percent', send_charge DECIMAL(8,4) DEFAULT 0, send_cashback DECIMAL(8,4) DEFAULT 0, send_cashback_type VARCHAR(10) DEFAULT 'fixed', send_min DECIMAL(10,2) DEFAULT 0, send_max DECIMAL(10,2) DEFAULT 0, merchant_charge_type VARCHAR(10) DEFAULT 'percent', merchant_charge DECIMAL(8,4) DEFAULT 0, merchant_cashback DECIMAL(8,4) DEFAULT 0, merchant_cashback_type VARCHAR(10) DEFAULT 'fixed', merchant_min DECIMAL(10,2) DEFAULT 0, merchant_max DECIMAL(10,2) DEFAULT 0, cashout_charge_type VARCHAR(10) DEFAULT 'percent', cashout_charge DECIMAL(8,4) DEFAULT 1.85, cashout_cashback DECIMAL(8,4) DEFAULT 0, cashout_cashback_type VARCHAR(10) DEFAULT 'fixed', cashout_min DECIMAL(10,2) DEFAULT 0, cashout_max DECIMAL(10,2) DEFAULT 0, is_active TINYINT(1) DEFAULT 1, send_enabled TINYINT(1) DEFAULT 1, merchant_enabled TINYINT(1) DEFAULT 1, cashout_enabled TINYINT(1) DEFAULT 1, instructions TEXT)");
    $db->exec("CREATE TABLE IF NOT EXISTS mbanking_requests (id INT AUTO_INCREMENT PRIMARY KEY, user_id INT, operator_id INT, service_type VARCHAR(20), recipient_number VARCHAR(30), amount DECIMAL(10,2), charge DECIMAL(10,2) DEFAULT 0, cashback DECIMAL(10,2) DEFAULT 0, net_amount DECIMAL(10,2), balance_before DECIMAL(10,2), balance_after DECIMAL(10,2), reference VARCHAR(50), status VARCHAR(20) DEFAULT 'pending', note TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
} catch(Exception $e) {}

// User preferred currency
$_mb_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']]); $_mb_uc = $s->fetch() ?: null;
} catch(Exception $e) {}

$error=''; $success='';

if ($_SERVER['REQUEST_METHOD']==='POST') {
    $opId    = intval($_POST['operator_id']??0);
    $svcType = sanitize($_POST['service_type']??'');
    $recNum  = sanitize($_POST['recipient_number']??'');
    $amount  = floatval($_POST['amount']??0);

    $op = $db->prepare("SELECT * FROM mbanking_operators WHERE id=? AND is_active=1");
    $op->execute([$opId]); $op = $op->fetch();

    if (!$op) { $error = 'Operator not found!'; }
    elseif (!in_array($svcType,['send','merchant','cashout'])) { $error = 'Invalid service type!'; }
    elseif (strlen($recNum) < 10) { $error = 'Please enter valid recipient number!'; }
    elseif ($amount <= 0) { $error = 'Please enter valid amount!'; }
    else {
        $enabled = $op[$svcType.'_enabled'];
        $chType  = $op[$svcType.'_charge_type'];
        $chRate  = floatval($op[$svcType.'_charge']);
        $cbType  = $op[$svcType.'_cashback_type'];
        $cbRate  = floatval($op[$svcType.'_cashback']);
        $minAmt  = floatval($op[$svcType.'_min']);
        $maxAmt  = floatval($op[$svcType.'_max']);

        if (!$enabled) { $error = 'This service is not available!'; }
        elseif ($minAmt > 0 && $amount < $minAmt) { $error = 'Min amount: '.CURRENCY.number_format($minAmt,0); }
        elseif ($maxAmt > 0 && $amount > $maxAmt) { $error = 'Max amount: '.CURRENCY.number_format($maxAmt,0); }
        else {
            $charge   = $chType==='percent' ? round($amount*$chRate/100,2) : $chRate;
            $cashback = $cbType==='percent' ? round($amount*$cbRate/100,2) : $cbRate;
            $netDeduct = $amount + $charge;

            if ($user['balance'] < $netDeduct) {
                $error = 'Insufficient balance! Need: '.CURRENCY.number_format($netDeduct,2).' | Have: '.CURRENCY.number_format($user['balance'],2);
            } else {
                $ref = 'MB'.strtoupper(substr(uniqid(),7));
                $balBefore = $user['balance'];
                $balAfter  = $balBefore - $netDeduct;

                $db->beginTransaction();
                try {
                    $db->prepare("UPDATE users SET balance=balance-? WHERE id=?")->execute([$netDeduct,$user['id']]);
                    $db->prepare("INSERT INTO mbanking_requests (user_id,operator_id,service_type,recipient_number,amount,charge,cashback,net_amount,balance_before,balance_after,reference,status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)")->execute([$user['id'],$opId,$svcType,$recNum,$amount,$charge,$cashback,$netDeduct,$balBefore,$balAfter,$ref,'pending']);
                    $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,?,?,?,?,?,?,?)")->execute([$user['id'],'mbanking',$amount,$charge,$netDeduct,$balBefore,$balAfter,$ref,'pending',ucfirst($svcType).' via '.$op['name'].': '.$recNum]);
                    $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'info')")->execute([$user['id'],'🏦 mBanking Request Sent!',ucfirst($svcType).' ৳'.number_format($amount,2).' via '.$op['name'].'. Ref: '.$ref]);
                    notifyPending('mbanking', $user['name'], [
                        '🏦 Service' => ucfirst($svcType).' via '.$op['name'],
                        '📱 Recipient'=> $recNum,
                        '💰 Amount'  => CURRENCY.number_format($amount,2),
                        '💳 Charge'  => CURRENCY.number_format($charge,2),
                        '🔖 Ref'     => $ref,
                    ]);
                    $db->commit();
                    $success = "✅ Request submitted! Ref: $ref | Charge: ".CURRENCY.number_format($charge,2).($cashback>0?" | Cashback: ".CURRENCY.number_format($cashback,2)." (after approval)":'');
                    $user = getCurrentUser();
                } catch(Exception $e) { $db->rollBack(); $error = 'Error: '.$e->getMessage(); }
            }
        }
    }
}

$operators = $db->query("SELECT * FROM mbanking_operators WHERE is_active=1 ORDER BY id")->fetchAll();
$recentReqs = $db->prepare("SELECT r.*, mo.name as op_name, mo.logo_emoji, mo.logo_img, mo.color FROM mbanking_requests r JOIN mbanking_operators mo ON r.operator_id=mo.id WHERE r.user_id=? ORDER BY r.created_at DESC LIMIT 10");
$recentReqs->execute([$user['id']]); $recentList = $recentReqs->fetchAll();
?>
<!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>mBanking - <?= 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}
.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;flex:1}
.hdr-bal{background:rgba(255,255,255,0.15);color:white;padding:6px 12px;border-radius:10px;font-size:13px;font-weight:700}
.content{max-width:480px;margin:0 auto;padding:16px 16px}
.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}

/* Operator Grid */
.op-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:16px}
.op-btn{background:white;border:2px solid #e8ecf4;border-radius:14px;padding:12px 8px;text-align:center;cursor:pointer;transition:0.2s;-webkit-tap-highlight-color:transparent}
.op-btn:active{transform:scale(0.95)}
.op-btn.sel{border-width:2px}
.op-btn *{pointer-events:none}
.op-emoji{font-size:24px;display:block;margin-bottom:5px}
.op-name{font-size:11px;font-weight:700;color:#333}

/* Service tabs */
.svc-tabs{display:flex;gap:8px;margin-bottom:16px}
.svc-tab{flex:1;padding:12px 6px;border:2px solid #e8ecf4;border-radius:13px;background:white;cursor:pointer;text-align:center;transition:0.2s;-webkit-tap-highlight-color:transparent}
.svc-tab.active{border-width:2px}
.svc-tab .svc-icon{font-size:20px;display:block;margin-bottom:4px}
.svc-tab .svc-lbl{font-size:11px;font-weight:700;color:#555}
.svc-tab .svc-charge{font-size:10px;color:#aaa;margin-top:2px}
.svc-tab.active .svc-lbl,.svc-tab.active .svc-charge{color:white}
.svc-tab.disabled{opacity:0.4;cursor:not-allowed}

/* Form */
.form-card{background:white;border-radius:16px;padding:16px;margin-bottom:14px;box-shadow:0 2px 10px rgba(0,0,0,0.06);display:none}
.form-card.show{display:block}
.fg{margin-bottom:13px}
.fg label{font-size:12px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:0.4px;display:block;margin-bottom:6px}
.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{width:100%;padding:13px 13px 13px 40px;border:2px solid #e8ecf4;border-radius:12px;font-size:16px;font-weight:700;outline:none;transition:0.2s;color:var(--primary)}
.inp-wrap input:focus{border-color:var(--primary)}

/* Charge preview */
.charge-box{background:#f8fafc;border-radius:12px;padding:13px 15px;margin-top:10px;display:none}
.charge-row{display:flex;justify-content:space-between;font-size:13px;padding:5px 0;border-bottom:1px solid #f0f0f0}
.charge-row:last-child{border:none;font-weight:800;font-size:15px}
.charge-row.cashback{color:#38a169}

.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}
.submit-btn:disabled{background:#c8d0db;cursor:not-allowed}

/* Instructions */
.inst-box{background:#fffaf0;border:1px solid #fbd38d;border-radius:10px;padding:10px 12px;font-size:12px;color:#744210;margin-bottom:12px;display:none}

/* History */
.hist-item{background:white;border-radius:12px;padding:13px;margin-bottom:8px;box-shadow:0 1px 6px rgba(0,0,0,0.05);display:flex;align-items:center;gap:12px}
.hist-ic{width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0}
.hist-info{flex:1}
.hist-name{font-size:13px;font-weight:700;color:#222}
.hist-sub{font-size:11px;color:#aaa;margin-top:2px}
.hist-right{text-align:right}
.hist-amt{font-size:14px;font-weight:800;color:#e53e3e}
.hist-stat{font-size:11px;font-weight:700;padding:2px 8px;border-radius:20px;margin-top:2px;display:inline-block}
.s-pending{background:#fffaf0;color:#d69e2e}.s-success{background:#f0fff4;color:#38a169}.s-failed{background:#fff5f5;color:#e53e3e}
.sec-title{font-size:14px;font-weight:700;color:var(--dark);margin-bottom:12px;display:flex;align-items:center;gap:8px}
</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">🏦 mBanking</div>
        <div class="hdr-bal"><?= CURRENCY ?><?= number_format($user['balance'],0) ?></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; ?>

<!-- Balance -->
<div style="background:linear-gradient(135deg,var(--dark),var(--primary));border-radius:16px;padding:16px 18px;margin-bottom:16px;color:white">
    <div style="font-size:11px;opacity:0.7;font-weight:600;margin-bottom:4px">AVAILABLE BALANCE</div>
    <div style="font-size:26px;font-weight:800"><?= CURRENCY ?><?= number_format($user['balance'],2) ?></div>
    <?php if($_mb_uc): ?><div style="font-size:12px;opacity:0.6;margin-top:2px">≈ <?= htmlspecialchars($_mb_uc['symbol']) ?><?= number_format($user['balance']*floatval($_mb_uc['rate']),2) ?> <?= $_mb_uc['code'] ?></div><?php endif; ?>
</div>

<?php if(empty($operators)): ?>
<div style="text-align:center;padding:40px;color:#aaa;background:white;border-radius:14px"><i class="fas fa-bank" style="font-size:36px;display:block;margin-bottom:10px;color:#ddd"></i>No mBanking services available</div>
<?php else: ?>

<!-- Operator Select -->
<div style="font-size:12px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:10px">Select Operator</div>
<div class="op-grid">
<?php foreach($operators as $op): ?>
<div class="op-btn" 
    id="opBtn<?= $op['id'] ?>"
    data-id="<?= $op['id'] ?>"
    data-color="<?= htmlspecialchars($op['color']) ?>"
    data-op="<?= htmlspecialchars(json_encode($op, JSON_UNESCAPED_UNICODE)) ?>"
    style="border-color:#e8ecf4">
    <?php if($op['logo_img']): ?>
    <img src="<?= htmlspecialchars($op['logo_img']) ?>" style="width:40px;height:40px;object-fit:contain;margin-bottom:5px;border-radius:8px">
    <?php else: ?>
    <div style="width:40px;height:40px;border-radius:10px;background:<?= $op['color'] ?>22;display:flex;align-items:center;justify-content:center;margin:0 auto 5px;font-size:13px;font-weight:800;color:<?= $op['color'] ?>"><?= strtoupper(substr($op['name'],0,2)) ?></div>
    <?php endif; ?>
    <span class="op-name"><?= htmlspecialchars($op['name']) ?></span>
</div>
<?php endforeach; ?>
</div>

<!-- Service Select -->
<div id="svcSection" style="display:none">
    <div style="font-size:12px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:10px">Select Service</div>
    <div class="svc-tabs">
        <div class="svc-tab" id="svcSend" onclick="selectSvc('send')">
            <span class="svc-icon">💸</span>
            <span class="svc-lbl">Send Money</span>
            <span class="svc-charge" id="chargeSend">—</span>
        </div>
        <div class="svc-tab" id="svcMerchant" onclick="selectSvc('merchant')">
            <span class="svc-icon">🏪</span>
            <span class="svc-lbl">Merchant</span>
            <span class="svc-charge" id="chargeMerchant">—</span>
        </div>
        <div class="svc-tab" id="svcCashout" onclick="selectSvc('cashout')">
            <span class="svc-icon">💵</span>
            <span class="svc-lbl">Cash Out</span>
            <span class="svc-charge" id="chargeCashout">—</span>
        </div>
    </div>
</div>

<!-- Form -->
<div class="form-card" id="formCard">
    <div class="inst-box" id="instBox"></div>
    <form method="POST">
        <input type="hidden" name="operator_id" id="fOpId">
        <input type="hidden" name="service_type" id="fSvcType">
        <div class="fg">
            <label id="recipientLabel">Recipient Number</label>
            <div class="inp-wrap">
                <i class="fas fa-mobile-alt"></i>
                <input type="tel" name="recipient_number" id="fRecipient" placeholder="01XXXXXXXXX" maxlength="20" oninput="calcCharge()">
            </div>
        </div>
        <div class="fg">
            <label>Amount (BDT)</label>
            <div class="inp-wrap">
                <i class="fas fa-taka-sign"></i>
                <input type="number" name="amount" id="fAmount" placeholder="Enter amount" step="1" min="1" oninput="calcCharge()">
            </div>
        </div>
        <!-- Charge Preview -->
        <div class="charge-box" id="chargeBox">
            <div class="charge-row"><span>Send Amount</span><span id="cpAmt">—</span></div>
            <div class="charge-row"><span id="cpChargeLbl">Charge</span><span id="cpCharge" style="color:#e53e3e">—</span></div>
            <div class="charge-row cashback" id="cpCashbackRow" style="display:none"><span>💰 Cashback</span><span id="cpCashback">—</span></div>
            <div class="charge-row" style="border-top:2px solid #e8ecf4;margin-top:4px;padding-top:8px"><span>Total Deducted</span><span id="cpTotal" style="color:#e53e3e">—</span></div>
            <?php if($_mb_uc): ?><div style="font-size:11px;color:#aaa;margin-top:6px;text-align:right" id="cpDual"></div><?php endif; ?>
        </div>
        <button type="submit" class="submit-btn" id="submitBtn" disabled style="margin-top:14px">
            <i class="fas fa-paper-plane"></i> Submit Request
        </button>
    </form>
</div>
<?php endif; ?>

<!-- Recent Requests -->
<?php if(!empty($recentList)): ?>
<div style="margin-top:20px">
    <div class="sec-title"><i class="fas fa-history" style="color:#805ad5"></i> Recent Requests</div>
    <?php foreach($recentList as $r):
        $svcIcons = ['send'=>'💸','merchant'=>'🏪','cashout'=>'💵'];
    ?>
    <div class="hist-item" onclick="toggleHist(<?= $r['id'] ?>)" style="cursor:pointer">
        <div class="hist-ic" style="background:<?= $r['color'] ?>22;display:flex;align-items:center;justify-content:center">
            <?php if($r['logo_img']): ?><img src="<?= htmlspecialchars($r['logo_img']) ?>" style="width:26px;height:26px;object-fit:contain"><?php else: ?><span style="font-size:11px;font-weight:800;color:<?= $r['color'] ?>"><?= strtoupper(substr($r['op_name'],0,2)) ?></span><?php endif; ?>
        </div>
        <div class="hist-info">
            <div class="hist-name"><?= $svcIcons[$r['service_type']]??'🏦' ?> <?= ucfirst($r['service_type']) ?> — <?= htmlspecialchars($r['op_name']) ?></div>
            <div class="hist-sub"><?= $r['recipient_number'] ?> · <?= date('d M, h:i A',strtotime($r['created_at'])) ?></div>
        </div>
        <div class="hist-right">
            <div class="hist-amt">-<?= CURRENCY ?><?= number_format($r['net_amount'],2) ?></div>
            <span class="hist-stat s-<?= $r['status'] ?>"><?= ucfirst($r['status']) ?></span>
        </div>
    </div>
    <!-- Expandable detail -->
    <div id="hdet<?= $r['id'] ?>" style="display:none;background:#f8fafc;border-radius:0 0 12px 12px;padding:12px 14px;margin-top:-4px;margin-bottom:8px;font-size:12px">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:6px;margin-bottom:8px">
            <div><span style="color:#aaa">Amount:</span> <b><?= CURRENCY ?><?= number_format($r['amount'],2) ?></b></div>
            <div><span style="color:#aaa">Charge:</span> <b style="color:#e53e3e"><?= CURRENCY ?><?= number_format($r['charge'],2) ?></b></div>
            <?php if($r['cashback']>0): ?>
            <div><span style="color:#aaa">Cashback:</span> <b style="color:#38a169">+<?= CURRENCY ?><?= number_format($r['cashback'],2) ?></b></div>
            <?php endif; ?>
            <div><span style="color:#aaa">Net:</span> <b><?= CURRENCY ?><?= number_format($r['net_amount'],2) ?></b></div>
            <div style="grid-column:1/-1"><span style="color:#aaa">Ref:</span> <b style="font-family:monospace"><?= $r['reference'] ?></b></div>
        </div>
        <?php if($r['note']): ?>
        <div style="background:white;border-radius:8px;padding:8px 10px;border-left:3px solid <?= $r['status']==='success'?'#38a169':($r['status']==='failed'?'#e53e3e':'#d69e2e') ?>">
            <b>📝 Note:</b> <?= htmlspecialchars($r['note']) ?>
        </div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>
</div>

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

<script>
const UC_RATE = <?= $_mb_uc ? floatval($_mb_uc['rate']) : 0 ?>;
const UC_SYM  = "<?= $_mb_uc ? addslashes(htmlspecialchars($_mb_uc['symbol'])) : '' ?>";
const UC_CODE = "<?= $_mb_uc ? $_mb_uc['code'] : '' ?>";

let curOp  = null;
let curSvc = null;

// Use event delegation for op-btn clicks
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.op-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const id    = this.dataset.id;
            const color = this.dataset.color;
            const op    = JSON.parse(this.dataset.op);
            selectOp(id, color, op);
        });
    });
});

function selectOp(id, color, op) {
    curOp = op;
    // Highlight selected
    document.querySelectorAll('.op-btn').forEach(b => { b.style.borderColor='#e8ecf4'; b.style.background='white'; });
    const btn = document.getElementById('opBtn'+id);
    btn.style.borderColor = color;
    btn.style.background  = color+'11';

    // Show service tabs
    document.getElementById('svcSection').style.display = 'block';
    document.getElementById('formCard').classList.remove('show');
    curSvc = null;

    // Update charges on tabs
    const svcs = ['send','merchant','cashout'];
    svcs.forEach(s => {
        const tab = document.getElementById('svc'+s.charAt(0).toUpperCase()+s.slice(1));
        const chEl = document.getElementById('charge'+s.charAt(0).toUpperCase()+s.slice(1));
        const enabled = op[s+'_enabled']==1;
        const charge  = op[s+'_charge'];
        const chType  = op[s+'_charge_type'];
        const cashback= op[s+'_cashback'];
        const cbType  = op[s+'_cashback_type'];

        if (!enabled) {
            tab.classList.add('disabled');
            tab.onclick = null;
            chEl.textContent = 'N/A';
        } else {
            tab.classList.remove('disabled');
            tab.onclick = function(){ selectSvc(s); };
            chEl.textContent = charge>0 ? (chType==='percent'?charge+'%':'৳'+charge)+' charge' : 'Free';
            if (cashback>0) chEl.textContent += ' +'+cashback+(cbType==='percent'?'%':'৳')+' cashback';
        }
    });
}

function selectSvc(svc) {
    if (!curOp || !curOp[svc+'_enabled']) return;
    curSvc = svc;

    // Highlight tab
    ['send','merchant','cashout'].forEach(s => {
        const tab = document.getElementById('svc'+s.charAt(0).toUpperCase()+s.slice(1));
        tab.classList.remove('active');
        tab.style.background = '';
        tab.style.borderColor = '';
    });
    const activeTab = document.getElementById('svc'+svc.charAt(0).toUpperCase()+svc.slice(1));
    activeTab.classList.add('active');
    activeTab.style.background = curOp.color;
    activeTab.style.borderColor = curOp.color;

    // Fill form
    document.getElementById('fOpId').value   = curOp.id;
    document.getElementById('fSvcType').value = svc;

    // Label
    const labels = {send:'Recipient Number', merchant:'Merchant Number / ID', cashout:'Agent Number'};
    document.getElementById('recipientLabel').textContent = labels[svc] || 'Recipient';

    // Instructions
    const instBox = document.getElementById('instBox');
    if (curOp.instructions) {
        instBox.textContent = '📌 ' + curOp.instructions;
        instBox.style.display = 'block';
    } else {
        instBox.style.display = 'none';
    }

    document.getElementById('formCard').classList.add('show');
    document.getElementById('fAmount').value = '';
    document.getElementById('fRecipient').value = '';
    document.getElementById('chargeBox').style.display = 'none';
    document.getElementById('submitBtn').disabled = true;

    // Scroll to form
    setTimeout(() => document.getElementById('formCard').scrollIntoView({behavior:'smooth',block:'nearest'}), 100);
}

function calcCharge() {
    if (!curOp || !curSvc) return;
    const amt  = parseFloat(document.getElementById('fAmount').value) || 0;
    const rec  = document.getElementById('fRecipient').value.trim();
    const box  = document.getElementById('chargeBox');

    if (amt <= 0) { box.style.display='none'; document.getElementById('submitBtn').disabled=true; return; }

    const chType  = curOp[curSvc+'_charge_type'];
    const chRate  = parseFloat(curOp[curSvc+'_charge'])||0;
    const cbType  = curOp[curSvc+'_cashback_type'];
    const cbRate  = parseFloat(curOp[curSvc+'_cashback'])||0;
    const minAmt  = parseFloat(curOp[curSvc+'_min'])||0;
    const maxAmt  = parseFloat(curOp[curSvc+'_max'])||0;

    const charge   = chType==='percent' ? amt*chRate/100 : chRate;
    const cashback = cbType==='percent' ? amt*cbRate/100 : cbRate;
    const total    = amt + charge;

    document.getElementById('cpAmt').textContent    = '৳'+amt.toFixed(2);
    document.getElementById('cpChargeLbl').textContent = chType==='percent' ? 'Charge ('+chRate+'%)' : 'Charge (Fixed)';
    document.getElementById('cpCharge').textContent = charge>0 ? '-৳'+charge.toFixed(2) : 'Free';
    document.getElementById('cpTotal').textContent  = '৳'+total.toFixed(2);

    if (cashback > 0) {
        document.getElementById('cpCashbackRow').style.display = 'flex';
        document.getElementById('cpCashback').textContent = '+৳'+cashback.toFixed(2)+' (after approval)';
    } else {
        document.getElementById('cpCashbackRow').style.display = 'none';
    }

    if (UC_RATE) {
        document.getElementById('cpDual').textContent = '≈ '+UC_SYM+(total*UC_RATE).toFixed(2)+' '+UC_CODE;
    }

    box.style.display = 'block';

    const valid = rec.length >= 10 && amt > 0 && (minAmt===0||amt>=minAmt) && (maxAmt===0||amt<=maxAmt);
    const submitBtn = document.getElementById('submitBtn');
    submitBtn.disabled = !valid;
    if (valid) {
        const svcNames = {send:'Send Money',merchant:'Merchant Pay',cashout:'Cash Out'};
        submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i> Submit '+svcNames[curSvc]+' — ৳'+total.toFixed(2);
    }
}
function toggleHist(id) {
    const d = document.getElementById('hdet'+id);
    if(d) d.style.display = d.style.display==='none' ? 'block' : 'none';
}
</script>
<script>document.addEventListener("DOMContentLoaded",function(){ if(window.pageReady) window.pageReady(); });</script>
</body>
</html>
