<?php
require_once '../includes/config.php';
require_once '../includes/telegram.php';
requireAdmin();
$db = getDB();

// Auto-create tables
try {
    $db->exec("CREATE TABLE IF NOT EXISTS mbanking_operators (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, code VARCHAR(20) NOT NULL UNIQUE, logo_emoji VARCHAR(10) DEFAULT NULL, 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, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
} catch(Exception $e) { die("Table create error: ".$e->getMessage()); }

try {
    $db->exec("CREATE TABLE IF NOT EXISTS mbanking_requests (id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, operator_id INT NOT NULL, service_type VARCHAR(20) NOT NULL DEFAULT 'send', recipient_number VARCHAR(30), amount DECIMAL(10,2) NOT NULL, charge DECIMAL(10,2) DEFAULT 0, cashback DECIMAL(10,2) DEFAULT 0, net_amount DECIMAL(10,2) NOT NULL, 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, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)");
} catch(Exception $e) { die("Table create error: ".$e->getMessage()); }

// Insert defaults
$cnt = $db->query("SELECT COUNT(*) FROM mbanking_operators")->fetchColumn();
if (!$cnt) {
    $defaults = [
        ['bKash','bkash','💗','#E2136E', 'percent',1.5,0,'fixed',50,25000, 'percent',0,0,'fixed',50,200000, 'percent',1.85,0,'fixed',1000,25000],
        ['Nagad','nagad','🟠','#F05829', 'percent',1.5,0,'fixed',50,25000, 'percent',0,0,'fixed',50,200000, 'percent',1.5,0,'fixed',1000,25000],
        ['Rocket','rocket','🚀','#8C3494', 'percent',1.8,0,'fixed',50,25000, 'percent',0,0,'fixed',50,200000, 'percent',2.0,0,'fixed',1000,25000],
        ['Upay','upay','🔵','#0066CC',   'percent',1.5,0,'fixed',50,25000, 'percent',0,0,'fixed',50,200000, 'percent',1.8,0,'fixed',1000,25000],
    ];
    $ins = $db->prepare("INSERT INTO mbanking_operators (name,code,logo_emoji,color,send_charge_type,send_charge,send_cashback,send_cashback_type,send_min,send_max,merchant_charge_type,merchant_charge,merchant_cashback,merchant_cashback_type,merchant_min,merchant_max,cashout_charge_type,cashout_charge,cashout_cashback,cashout_cashback_type,cashout_min,cashout_max) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    foreach ($defaults as $d) $ins->execute($d);
}

$msg = null;
if (isset($_GET['ok'])) $msg = ['ok'=>true,'text'=>'✅ Saved successfully!'];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add' || $action === 'edit') {
        $f = $_POST;
        // Handle logo image upload
        $logoImg = $f['existing_logo'] ?? null;
        if (!empty($_FILES['logo_img']['name'])) {
            $uploadDir = '../assets/img/mbanking/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
            $ext      = strtolower(pathinfo($_FILES['logo_img']['name'], PATHINFO_EXTENSION));
            $allowed  = ['jpg','jpeg','png','gif','webp','svg'];
            if (in_array($ext, $allowed)) {
                $filename = 'mb_'.strtolower(preg_replace('/[^a-z0-9]/','_',$f['code']??'op')).'_'.time().'.'.$ext;
                if (move_uploaded_file($_FILES['logo_img']['tmp_name'], $uploadDir.$filename)) {
                    $logoImg = 'assets/img/mbanking/'.$filename;
                }
            }
        }
        $data = [
            $f['name'], $f['code'], $logoImg, $f['color']??'#1a3c8f',
            $f['send_charge_type']??'percent', floatval($f['send_charge']??0), floatval($f['send_cashback']??0), $f['send_cashback_type']??'fixed', floatval($f['send_min']??0), floatval($f['send_max']??0),
            $f['merchant_charge_type']??'percent', floatval($f['merchant_charge']??0), floatval($f['merchant_cashback']??0), $f['merchant_cashback_type']??'fixed', floatval($f['merchant_min']??0), floatval($f['merchant_max']??0),
            $f['cashout_charge_type']??'percent', floatval($f['cashout_charge']??0), floatval($f['cashout_cashback']??0), $f['cashout_cashback_type']??'fixed', floatval($f['cashout_min']??0), floatval($f['cashout_max']??0),
            intval($f['send_enabled']??1), intval($f['merchant_enabled']??1), intval($f['cashout_enabled']??1),
            trim($f['instructions']??''), intval($f['is_active']??1),
        ];
        if ($action === 'add') {
            try {
                $db->prepare("INSERT INTO mbanking_operators (name,code,logo_emoji,color,send_charge_type,send_charge,send_cashback,send_cashback_type,send_min,send_max,merchant_charge_type,merchant_charge,merchant_cashback,merchant_cashback_type,merchant_min,merchant_max,cashout_charge_type,cashout_charge,cashout_cashback,cashout_cashback_type,cashout_min,cashout_max,send_enabled,merchant_enabled,cashout_enabled,instructions,is_active) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")->execute($data);
                $msg = ['ok'=>true,'text'=>'Added!'];
                header('Location: mbanking.php?ok=1'); exit;
            } catch(Exception $e) { $msg = ['ok'=>false,'text'=>'Code already exists!']; }
        } else {
            $id = intval($f['id']);
            $db->prepare("UPDATE mbanking_operators SET name=?,code=?,logo_emoji=?,color=?,send_charge_type=?,send_charge=?,send_cashback=?,send_cashback_type=?,send_min=?,send_max=?,merchant_charge_type=?,merchant_charge=?,merchant_cashback=?,merchant_cashback_type=?,merchant_min=?,merchant_max=?,cashout_charge_type=?,cashout_charge=?,cashout_cashback=?,cashout_cashback_type=?,cashout_min=?,cashout_max=?,send_enabled=?,merchant_enabled=?,cashout_enabled=?,instructions=?,is_active=? WHERE id=?")->execute(array_merge($data, [$id]));
            $msg = ['ok'=>true,'text'=>'Updated!'];
            header('Location: mbanking.php?ok=1'); exit;
        }
    }
    if ($action === 'toggle') { $db->prepare("UPDATE mbanking_operators SET is_active=1-is_active WHERE id=?")->execute([intval($_POST['id'])]); $msg=['ok'=>true,'text'=>'Status changed!']; }
    header('Location: mbanking.php?ok=1'); exit;
    if ($action === 'delete') { $db->prepare("DELETE FROM mbanking_operators WHERE id=?")->execute([intval($_POST['id'])]); $msg=['ok'=>true,'text'=>'Deleted!']; }
    header('Location: mbanking.php?ok=1'); exit;

    // Request actions
    if (in_array($action,['approve','reject'])) {
        $id   = intval($_POST['req_id']);
        $note = trim($_POST['note']??'');
        $stmt = $db->prepare("SELECT r.*, u.balance as ubal, u.name as uname FROM mbanking_requests r JOIN users u ON r.user_id=u.id WHERE r.id=?");
        $stmt->execute([$id]);
        $req = $stmt->fetch();

        if ($req && $req['status']==='pending') {
            $db->beginTransaction();
            try {
                if ($action === 'approve') {
                    $db->prepare("UPDATE mbanking_requests SET status='success', note=?, updated_at=NOW() WHERE id=?")->execute([$note?:'Approved', $id]);
                    $db->prepare("UPDATE transactions SET status='success', note=? WHERE reference=? AND type='mbanking'")->execute([$note?:'Approved', $req['reference']]);

                    // Cashback
                    if ($req['cashback'] > 0) {
                        $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$req['cashback'], $req['user_id']]);
                        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")->execute([$req['user_id'],'💰 mBanking Cashback!','৳'.number_format($req['cashback'],2).' cashback added. Ref: '.$req['reference']]);
                    }
                    $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")->execute([$req['user_id'],'✅ mBanking Success!', $req['service_type'].' ৳'.number_format($req['amount'],2).' completed. Ref: '.$req['reference']]);
                    notifyUser($req['user_id'], 'mBanking সফল! 🏦', ['🏦 Service'=>ucfirst($req['service_type']), '📱 Recipient'=>$req['recipient_number'], '💰 Amount'=>CURRENCY.number_format($req['amount'],2), '💳 Charge'=>CURRENCY.number_format($req['charge'],2), '🔖 Ref'=>$req['reference']]);
                    $msg = ['ok'=>true,'text'=>'✅ Approved!'];
                    header('Location: mbanking.php?ok=1'); exit;

                } else {
                    $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$req['net_amount'], $req['user_id']]);
                    $db->prepare("UPDATE mbanking_requests SET status='failed', note=?, updated_at=NOW() WHERE id=?")->execute([$note?:'Rejected', $id]);
                    $db->prepare("UPDATE transactions SET status='failed', note=? WHERE reference=? AND type='mbanking'")->execute([$note?:'Rejected & refunded', $req['reference']]);
                    $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'warning')")->execute([$req['user_id'],'❌ mBanking Rejected','৳'.number_format($req['net_amount'],2).' refunded. Ref: '.$req['reference']]);
                    notifyUser($req['user_id'], 'mBanking Rejected ❌', ['💰 Refunded'=>CURRENCY.number_format($req['net_amount'],2), '🔖 Ref'=>$req['reference'], '📝 Note'=>$note], 'warning');
                    $msg = ['ok'=>true,'text'=>'❌ Rejected & Refunded!'];
                    header('Location: mbanking.php?ok=1'); exit;
                }
                $db->commit();
            } catch(Exception $e) { $db->rollBack(); $msg=['ok'=>false,'text'=>$e->getMessage()]; }
        }
    }
}

$operators = $db->query("SELECT * FROM mbanking_operators ORDER BY is_active DESC, id")->fetchAll();
$requests  = $db->query("SELECT r.*, u.name as uname, mo.name as op_name, mo.logo_emoji, mo.logo_img, mo.color FROM mbanking_requests r JOIN users u ON r.user_id=u.id JOIN mbanking_operators mo ON r.operator_id=mo.id ORDER BY r.created_at DESC LIMIT 50")->fetchAll();
$stats = [
    'pending' => $db->query("SELECT COUNT(*) FROM mbanking_requests WHERE status='pending'")->fetchColumn(),
    'success' => $db->query("SELECT COUNT(*) FROM mbanking_requests WHERE status='success'")->fetchColumn(),
    'revenue' => $db->query("SELECT COALESCE(SUM(charge),0) FROM mbanking_requests WHERE status='success'")->fetchColumn(),
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>mBanking - Admin</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="../assets/css/admin.css">
<style>
.op-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:14px;margin-bottom:18px}
.op-card{background:white;border-radius:14px;box-shadow:0 2px 10px rgba(0,0,0,0.07);overflow:hidden;border-top:4px solid var(--c)}
.op-head{padding:14px 16px;display:flex;align-items:center;gap:12px}
.op-icon{width:46px;height:46px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:22px;flex-shrink:0}
.op-name{font-size:16px;font-weight:800;color:#222}
.op-code{font-size:11px;color:#aaa;font-family:monospace}
.svc-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px;padding:0 14px 14px}
.svc-item{background:#f8fafc;border-radius:10px;padding:8px 10px;text-align:center}
.svc-name{font-size:10px;color:#888;font-weight:700;text-transform:uppercase;margin-bottom:4px}
.svc-charge{font-size:13px;font-weight:800;color:#e53e3e}
.svc-cashback{font-size:11px;color:#38a169;font-weight:600;margin-top:2px}
.svc-off{opacity:0.4}
.op-foot{padding:10px 14px;background:#f8fafc;display:flex;gap:6px}
.card{background:white;border-radius:12px;box-shadow:0 2px 8px rgba(0,0,0,0.05);margin-bottom:16px;overflow:hidden}
.card-h{padding:13px 18px;border-bottom:1px solid #f5f5f5;font-size:14px;font-weight:700;display:flex;align-items:center;gap:8px}
.alert{padding:10px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7}
.stats-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:16px}
.stat-box{background:white;border-radius:10px;padding:14px;text-align:center;box-shadow:0 2px 6px rgba(0,0,0,0.05);border-top:3px solid var(--primary)}
.stat-box.yellow{border-color:#d69e2e}.stat-box.green{border-color:#38a169}
.stat-num{font-size:22px;font-weight:800;color:var(--dark)}.stat-lbl{font-size:11px;color:#888;font-weight:600}
.req-card{border:2px solid #f0f0f0;border-radius:12px;margin-bottom:8px;overflow:hidden}
.req-card.pending{border-color:#fbd38d}
.req-head{display:flex;align-items:center;gap:10px;padding:12px 14px;cursor:pointer;background:#fafafa}
.req-detail{display:none;padding:14px;border-top:1px solid #f5f5f5}
.req-detail.show{display:block}
.dg{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:12px}
.dg-item{background:#f8fafc;border-radius:8px;padding:8px 10px}
.dg-lbl{font-size:10px;color:#aaa;font-weight:700;text-transform:uppercase;margin-bottom:1px}
.dg-val{font-size:13px;font-weight:700;color:#333}
.btn{padding:7px 13px;border:none;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:5px}
.btn-primary{background:var(--primary);color:white}.btn-sm{padding:5px 10px;font-size:11px;border-radius:7px}
.btn-edit{background:#ebf8ff;color:#2b6cb0}.btn-del{background:#fff5f5;color:#e53e3e}
.btn-ok{background:#38a169;color:white}.btn-fail{background:#e53e3e;color:white}.btn-tog{background:#f5f5f5;color:#555}
.modal-ov{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:9999;align-items:center;justify-content:center}
.modal-ov.show{display:flex}
.modal-box{background:white;border-radius:14px;padding:20px;width:95%;max-width:600px;max-height:90vh;overflow-y:auto}
.modal-box h3{font-size:15px;font-weight:800;margin-bottom:14px;color:var(--dark)}
.frow{display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px}
.fg{display:flex;flex-direction:column;gap:3px;margin-bottom:8px}
.fg label{font-size:11px;font-weight:700;color:#888;text-transform:uppercase}
.fg input,.fg select,.fg textarea{padding:8px 10px;border:2px solid #e8ecf4;border-radius:8px;font-size:12px;outline:none;width:100%}
.fg input:focus,.fg select:focus{border-color:var(--primary)}
.svc-section{background:#f8fafc;border-radius:10px;padding:12px;margin-bottom:10px}
.svc-section h4{font-size:12px;font-weight:700;margin-bottom:8px;color:#555}
.gap-btn{display:flex;gap:8px;margin-top:12px}
.note-in{width:100%;padding:8px 10px;border:2px solid #e8ecf4;border-radius:8px;font-size:12px;outline:none;margin-bottom:8px}
</style>
</head>
<body>
<?php include '../includes/admin_sidebar.php'; ?>
<div class="main">
<div class="topbar">
    <div class="topbar-left">
        <button class="menu-toggle" onclick="openSidebar()"><i class="fas fa-bars"></i></button>
        <span class="topbar-title">🏦 mBanking Management</span>
    </div>
    <div class="topbar-right">
        <button class="btn btn-primary" onclick="openAdd()"><i class="fas fa-plus"></i> Add Operator</button>
    </div>
</div>
<div class="content">
<?php if($msg): ?>
<div class="alert <?= $msg['ok']?'alert-ok':'alert-err' ?>"><?= $msg['ok']?'✅':'❌' ?> <?= htmlspecialchars($msg['text']) ?></div>
<?php endif; ?>

<!-- Stats -->
<div class="stats-grid">
    <div class="stat-box yellow"><div class="stat-num"><?= $stats['pending'] ?></div><div class="stat-lbl">⏳ Pending</div></div>
    <div class="stat-box green"><div class="stat-num"><?= $stats['success'] ?></div><div class="stat-lbl">✅ Success</div></div>
    <div class="stat-box green"><div class="stat-num"><?= CURRENCY ?><?= number_format($stats['revenue'],2) ?></div><div class="stat-lbl">💰 Charge Collected</div></div>
</div>

<!-- Operators -->
<div class="op-grid">
<?php foreach($operators as $op): ?>
<div class="op-card <?= $op['is_active']?'':'opacity-50' ?>" style="--c:<?= $op['color'] ?>">
    <div class="op-head">
        <div class="op-icon" style="background:<?= $op['color'] ?>22;border:2px solid <?= $op['color'] ?>44">
            <?php if($op['logo_img']): ?>
            <img src="<?= htmlspecialchars('../'.$op['logo_img']) ?>" style="width:32px;height:32px;object-fit:contain;border-radius:6px">
            <?php else: ?>
            <span style="font-size:13px;font-weight:800;color:<?= $op['color'] ?>"><?= strtoupper(substr($op['name'],0,2)) ?></span>
            <?php endif; ?>
        </div>
        <div style="flex:1">
            <div class="op-name"><?= htmlspecialchars($op['name']) ?></div>
            <div class="op-code"><?= $op['code'] ?> · <?= $op['is_active']?'<span style="color:#38a169;font-weight:700">Active</span>':'<span style="color:#e53e3e">Inactive</span>' ?></div>
        </div>
    </div>
    <div class="svc-grid">
        <div class="svc-item <?= $op['send_enabled']?'':'svc-off' ?>">
            <div class="svc-name">Send</div>
            <div class="svc-charge"><?= $op['send_charge'] ?><?= $op['send_charge_type']==='percent'?'%':'৳' ?></div>
            <?php if($op['send_cashback']>0): ?><div class="svc-cashback">+<?= $op['send_cashback'] ?><?= $op['send_cashback_type']==='percent'?'%':'৳' ?> cash</div><?php endif; ?>
        </div>
        <div class="svc-item <?= $op['merchant_enabled']?'':'svc-off' ?>">
            <div class="svc-name">Merchant</div>
            <div class="svc-charge"><?= $op['merchant_charge'] ?><?= $op['merchant_charge_type']==='percent'?'%':'৳' ?></div>
            <?php if($op['merchant_cashback']>0): ?><div class="svc-cashback">+<?= $op['merchant_cashback'] ?><?= $op['merchant_cashback_type']==='percent'?'%':'৳' ?> cash</div><?php endif; ?>
        </div>
        <div class="svc-item <?= $op['cashout_enabled']?'':'svc-off' ?>">
            <div class="svc-name">Cash Out</div>
            <div class="svc-charge"><?= $op['cashout_charge'] ?><?= $op['cashout_charge_type']==='percent'?'%':'৳' ?></div>
            <?php if($op['cashout_cashback']>0): ?><div class="svc-cashback">+<?= $op['cashout_cashback'] ?><?= $op['cashout_cashback_type']==='percent'?'%':'৳' ?> cash</div><?php endif; ?>
        </div>
    </div>
    <div class="op-foot">
        <button class="btn btn-sm btn-edit" onclick='openEdit(<?= htmlspecialchars(json_encode($op),ENT_QUOTES) ?>)'><i class="fas fa-edit"></i> Edit</button>
        <form method="POST" style="display:inline"><input type="hidden" name="action" value="toggle"><input type="hidden" name="id" value="<?= $op['id'] ?>"><button type="submit" class="btn btn-sm btn-tog"><?= $op['is_active']?'Disable':'Enable' ?></button></form>
        <form method="POST" onsubmit="return confirm('Delete?')" style="display:inline"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= $op['id'] ?>"><button type="submit" class="btn btn-sm btn-del"><i class="fas fa-trash"></i></button></form>
    </div>
</div>
<?php endforeach; ?>
</div>

<!-- Requests -->
<div class="card">
    <div class="card-h"><i class="fas fa-list" style="color:var(--primary)"></i> mBanking Requests (<?= count($requests) ?>)</div>
    <?php if(empty($requests)): ?>
    <div style="text-align:center;padding:30px;color:#aaa">No requests yet</div>
    <?php else: ?>
    <?php foreach($requests as $r):
        $svcLabels = ['send'=>'💸 Send Money','merchant'=>'🏪 Merchant','cashout'=>'💵 Cash Out'];
    ?>
    <div class="req-card <?= $r['status'] ?>">
        <div class="req-head" onclick="toggleReq(<?= $r['id'] ?>)">
            <div style="width:36px;height:36px;border-radius:9px;background:<?= $r['color'] ?>22;display:flex;align-items:center;justify-content:center;flex-shrink:0">
                <?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:12px;font-weight:800;color:<?= $r['color'] ?>"><?= strtoupper(substr($r['op_name'],0,2)) ?></span><?php endif; ?>
            </div>
            <div style="flex:1">
                <div style="font-size:13px;font-weight:700"><?= $svcLabels[$r['service_type']]??$r['service_type'] ?> — <?= htmlspecialchars($r['op_name']) ?></div>
                <div style="font-size:11px;color:#aaa">👤 <?= htmlspecialchars($r['uname']) ?> · <?= $r['recipient_number'] ?> · <?= date('d M, h:i A',strtotime($r['created_at'])) ?></div>
            </div>
            <div style="text-align:right">
                <div style="font-size:15px;font-weight:800;color:var(--primary)"><?= CURRENCY ?><?= number_format($r['amount'],2) ?></div>
                <span style="font-size:10px;font-weight:700;padding:2px 7px;border-radius:20px;background:<?= $r['status']==='success'?'#f0fff4':($r['status']==='pending'?'#fffaf0':'#fff5f5') ?>;color:<?= $r['status']==='success'?'#276749':($r['status']==='pending'?'#d69e2e':'#c53030') ?>"><?= ucfirst($r['status']) ?></span>
            </div>
            <i class="fas fa-chevron-down" id="rch<?= $r['id'] ?>" style="color:#ddd;font-size:11px;margin-left:6px"></i>
        </div>
        <div class="req-detail" id="rdet<?= $r['id'] ?>">
            <div class="dg">
                <div class="dg-item"><div class="dg-lbl">Amount</div><div class="dg-val"><?= CURRENCY ?><?= number_format($r['amount'],2) ?></div></div>
                <div class="dg-item"><div class="dg-lbl">Charge</div><div class="dg-val" style="color:#e53e3e"><?= CURRENCY ?><?= number_format($r['charge'],2) ?></div></div>
                <div class="dg-item"><div class="dg-lbl">Cashback</div><div class="dg-val" style="color:#38a169"><?= CURRENCY ?><?= number_format($r['cashback'],2) ?></div></div>
                <div class="dg-item"><div class="dg-lbl">Net Deducted</div><div class="dg-val"><?= CURRENCY ?><?= number_format($r['net_amount'],2) ?></div></div>
                <div class="dg-item"><div class="dg-lbl">Recipient</div><div class="dg-val" style="font-family:monospace"><?= $r['recipient_number'] ?></div></div>
                <div class="dg-item"><div class="dg-lbl">Ref</div><div class="dg-val" style="font-family:monospace;font-size:11px"><?= $r['reference'] ?></div></div>
            </div>
            <?php if($r['note']): ?>
            <div style="background:#f8fafc;border-radius:9px;padding:10px 12px;margin-bottom:10px;font-size:12px;color:#555">
                <b>📝 Note:</b> <?= htmlspecialchars($r['note']) ?>
            </div>
            <?php endif; ?>
            <?php if($r['status']==='pending'): ?>
            <form method="POST" id="rf<?= $r['id'] ?>">
                <input type="hidden" name="req_id" value="<?= $r['id'] ?>">
                <input type="hidden" name="action" id="ra<?= $r['id'] ?>">
                <input type="text" name="note" class="note-in" placeholder="Note...">
                <div style="display:flex;gap:8px">
                    <button type="button" class="btn btn-ok" onclick="doReq(<?= $r['id'] ?>,'approve')"><i class="fas fa-check"></i> ✅ Approve</button>
                    <button type="button" class="btn btn-fail" onclick="doReq(<?= $r['id'] ?>,'reject')"><i class="fas fa-times"></i> ❌ Reject & Refund</button>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

</div>
</div>

<!-- Add/Edit Modal -->
<div class="modal-ov" id="opModal" onclick="if(event.target===this)closeModal()">
<div class="modal-box">
    <h3 id="mTitle">Add mBanking Operator</h3>
    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" id="mAction" value="add">
        <input type="hidden" name="id" id="mId">
        <input type="hidden" name="existing_logo" id="mExistLogo">

        <div class="frow" style="grid-template-columns:1fr 1fr">
            <div class="fg"><label>Name *</label><input name="name" id="mName" placeholder="bKash" required></div>
            <div class="fg"><label>Code</label><input name="code" id="mCode" placeholder="bkash"></div>
        </div>
        <div class="frow" style="grid-template-columns:1fr auto;align-items:end">
            <div class="fg">
                <label>Logo Image</label>
                <input type="file" name="logo_img" id="mLogoFile" accept="image/*" onchange="previewLogo(this)">
                <div style="margin-top:6px" id="mLogoPreview"></div>
            </div>
            <div class="fg"><label>Color</label><input type="color" name="color" id="mColor" value="#E2136E" style="height:38px;padding:3px;width:50px"></div>
        </div>

        <?php foreach([
            ['send','💸 Send Money','send'],
            ['merchant','🏪 Merchant Pay','merchant'],
            ['cashout','💵 Cash Out','cashout'],
        ] as [$svc,$label,$key]): ?>
        <div class="svc-section">
            <h4><?= $label ?> <label style="float:right;font-weight:normal;font-size:11px"><input type="checkbox" name="<?= $key ?>_enabled" id="m_<?= $key ?>_en" value="1" checked> Enabled</label></h4>
            <div class="frow">
                <div class="fg"><label>Charge</label><input type="number" name="<?= $key ?>_charge" id="m_<?= $key ?>_ch" step="0.01" min="0" placeholder="0" value="0"></div>
                <div class="fg"><label>Type</label><select name="<?= $key ?>_charge_type" id="m_<?= $key ?>_ct"><option value="percent">% Percent</option><option value="fixed">৳ Fixed</option></select></div>
                <div class="fg"><label>Min Amount</label><input type="number" name="<?= $key ?>_min" id="m_<?= $key ?>_min" placeholder="50"></div>
                <div class="fg"><label>Max Amount</label><input type="number" name="<?= $key ?>_max" id="m_<?= $key ?>_max" placeholder="25000"></div>
                <div class="fg"><label>Cashback</label><input type="number" name="<?= $key ?>_cashback" id="m_<?= $key ?>_cb" step="0.01" min="0" placeholder="0" value="0"></div>
                <div class="fg"><label>CB Type</label><select name="<?= $key ?>_cashback_type" id="m_<?= $key ?>_cbt"><option value="fixed">৳ Fixed</option><option value="percent">% Percent</option></select></div>
            </div>
        </div>
        <?php endforeach; ?>

        <div class="fg"><label>Instructions (shown to user)</label><textarea name="instructions" id="mInst" rows="2" placeholder="Send money to our bKash number: 01XXXXXXXXX"></textarea></div>
        <div class="fg"><label>Status</label><select name="is_active" id="mActive"><option value="1">✅ Active</option><option value="0">❌ Inactive</option></select></div>

        <div class="gap-btn">
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save</button>
            <button type="button" class="btn" style="background:#f5f5f5" onclick="closeModal()">Cancel</button>
        </div>
    </form>
</div>
</div>

<script>
function openAdd() {
    document.getElementById('mTitle').textContent = 'Add mBanking Operator';
    document.getElementById('mAction').value = 'add';
    document.getElementById('mId').value = '';
    ['mName','mCode','mEmoji','mInst'].forEach(id=>document.getElementById(id).value='');
    document.getElementById('mColor').value = '#1a3c8f';
    document.getElementById('mActive').value = '1';
    ['send','merchant','cashout'].forEach(s=>{
        ['ch','min','max','cb'].forEach(f=>document.getElementById('m_'+s+'_'+f).value='0');
        document.getElementById('m_'+s+'_ct').value='percent';
        document.getElementById('m_'+s+'_cbt').value='fixed';
        document.getElementById('m_'+s+'_en').checked=true;
    });
    document.getElementById('opModal').classList.add('show');
}
function openEdit(op) {
    document.getElementById('mTitle').textContent = 'Edit: '+op.name;
    document.getElementById('mAction').value = 'edit';
    document.getElementById('mId').value = op.id;
    document.getElementById('mName').value = op.name;
    document.getElementById('mCode').value = op.code;
    document.getElementById('mExistLogo').value = op.logo_img||'';
    const prev = document.getElementById('mLogoPreview');
    if(op.logo_img) prev.innerHTML = '<img src="../'+op.logo_img+'" style="width:50px;height:50px;object-fit:contain;border-radius:8px;border:2px solid #e8ecf4">';
    else prev.innerHTML = '';
    document.getElementById('mColor').value = op.color||'#1a3c8f';
    document.getElementById('mInst').value = op.instructions||'';
    document.getElementById('mActive').value = op.is_active;
    ['send','merchant','cashout'].forEach(s=>{
        document.getElementById('m_'+s+'_ch').value = op[s+'_charge']||0;
        document.getElementById('m_'+s+'_ct').value = op[s+'_charge_type']||'percent';
        document.getElementById('m_'+s+'_min').value = op[s+'_min']||0;
        document.getElementById('m_'+s+'_max').value = op[s+'_max']||0;
        document.getElementById('m_'+s+'_cb').value = op[s+'_cashback']||0;
        document.getElementById('m_'+s+'_cbt').value = op[s+'_cashback_type']||'fixed';
        document.getElementById('m_'+s+'_en').checked = op[s+'_enabled']==1;
    });
    document.getElementById('opModal').classList.add('show');
}
function closeModal(){document.getElementById('opModal').classList.remove('show');}
function previewLogo(input) {
    const prev = document.getElementById('mLogoPreview');
    if(input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = e => prev.innerHTML = '<img src="'+e.target.result+'" style="width:50px;height:50px;object-fit:contain;border-radius:8px;border:2px solid #e8ecf4">';
        reader.readAsDataURL(input.files[0]);
    }
}
function toggleReq(id){
    const d=document.getElementById('rdet'+id),c=document.getElementById('rch'+id);
    const s=d.classList.toggle('show');c.style.transform=s?'rotate(180deg)':'';
}
function doReq(id,action){
    if(!confirm(action==='approve'?'Approve?':'Reject & Refund?'))return;
    document.getElementById('ra'+id).value=action;
    document.getElementById('rf'+id).submit();
}
// Auto-expand pending
document.querySelectorAll('.req-card.pending').forEach(c=>{
    const id=c.querySelector('[id^="rdet"]')?.id?.replace('rdet','');
    if(id){document.getElementById('rdet'+id)?.classList.add('show');const ch=document.getElementById('rch'+id);if(ch)ch.style.transform='rotate(180deg)';}
});
</script>
</body>
</html>
