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

require_once '../includes/ecare.php';

$msg = null;
if (isset($_GET['ok'])) $msg = ['ok'=>true,'text'=>'✅ Saved successfully!'];

// Save recharge mode + operator settings
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Save mode settings
    if ($action === 'save_mode') {
        $mode = $_POST['recharge_mode'] ?? 'manual';
        $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['api_mode',$mode,$mode]);

        // Save per-operator API selection
        $ops = $db->query("SELECT id,code FROM operators WHERE status='active'")->fetchAll();
        foreach ($ops as $op) {
            $opApi = $_POST['op_api_'.$op['id']] ?? 'manual';
            $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['op_api_'.$op['id'],$opApi,$opApi]);
            // Keep old op_mode for compatibility
            $opMode = ($opApi === 'manual') ? 'manual' : 'auto';
            $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")->execute(['op_mode_'.$op['id'],$opMode,$opMode]);
        }
        $msg = ['ok'=>true,'text'=>'✅ Settings saved!'];
        header('Location: recharges.php?ok=1'); exit;
    }

    // Retry API with correct provider
    if ($action === 'retry_api') {
        $id   = intval($_POST['txn_id'] ?? 0);
        $note = sanitize($_POST['note'] ?? '');
        $txn  = $db->prepare("SELECT t.*, u.name as uname, u.balance, o.name as op_name, o.code as op_code, o.id as op_id FROM transactions t JOIN users u ON t.user_id=u.id LEFT JOIN operators o ON t.operator_id=o.id WHERE t.id=? AND t.type='topup'");
        $txn->execute([$id]); $t = $txn->fetch();

        if ($t) {
            $opId   = $t['op_id'] ?? 0;
            $opCode = $t['op_code'] ?? '';
            $opApi  = $_POST['use_api'] ?? getSetting('op_api_'.$opId) ?: 'ecare';
            $apiJson = ''; $apiStatus = 'pending'; $errMsg = '';

            if ($opApi === 'successtopup') {
                $res     = successTopupRecharge($t['phone_number'], $t['amount'], $opCode, $t['reference'], 'prepaid');
                $apiJson = json_encode($res, JSON_UNESCAPED_UNICODE);
                if (!empty($res['result']) && $res['result'] == 1) {
                    $apiStatus = 'success';
                } else {
                    $errMsg = $res['message'] ?? 'Failed';
                }
            } elseif ($opApi === 'ecare') {
                $ecareRef = $t['reference'] . substr(microtime(true)*1000, -4);
                $res      = ecareRecharge($t['phone_number'], $t['amount'], $opCode, 'prepaid', $ecareRef);
                $apiJson  = json_encode(array_merge($res['raw'] ?? [], ['ecare_ref' => $ecareRef]), JSON_UNESCAPED_UNICODE);
                if ($res['received']) {
                    $apiStatus = 'pending';
                    $errMsg    = 'RECEIVED — cron will confirm';
                } elseif ($res['result']) {
                    $apiStatus = 'success';
                } else {
                    $errMsg = $res['rc_status'].': '.($res['message'] ?? 'Failed');
                }
            } else {
                // Custom API by slug
                try {
                    require_once '../includes/custom_api.php';
                    $res = customApiCall($opApi, 'recharge', [
                        'phone'     => $t['phone_number'],
                        'amount'    => $t['amount'],
                        'operator'  => $opCode,
                        'reference' => $t['reference'],
                    ]);
                    $apiJson = json_encode($res, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
                    $success = $res['success'] ?? $res['status'] ?? false;
                    if($success === true || $success === 'success' || $success === 1 || $success === '1') {
                        $apiStatus = 'success';
                    } else {
                        $errMsg = $res['message'] ?? $res['error'] ?? $res['msg'] ?? 'Failed';
                        // Save response even on failure
                        $db->prepare("UPDATE transactions SET api_response=?, note=? WHERE id=?")
                           ->execute([$apiJson, '❌ '.$opApi.': '.$errMsg, $id]);
                    }
                } catch(Exception $e) {
                    $errMsg  = $e->getMessage();
                    $apiJson = json_encode(['error'=>$errMsg], JSON_UNESCAPED_UNICODE);
                    $db->prepare("UPDATE transactions SET api_response=?, note=? WHERE id=?")
                       ->execute([$apiJson, '❌ '.$opApi.' Error: '.$errMsg, $id]);
                }
            }

            if ($apiStatus === 'success') {
                $db->prepare("UPDATE transactions SET status='success', note=?, api_response=?, updated_at=NOW() WHERE id=?")
                   ->execute(['✅ '.strtoupper($opApi).' Success', $apiJson, $id]);
                require_once '../includes/commission.php';
                applyCommission($db, $t['user_id'], 'topup', $t['amount'], $t['reference']);
                $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
                   ->execute([$t['user_id'],'✅ Recharge Successful!',$t['phone_number'].' — '.CURRENCY.number_format($t['amount'],2).' completed.']);
                notifyUser($t['user_id'], 'রিচার্জ সফল! 📱', ['📱 নম্বর'=>$t['phone_number'], '💰 পরিমাণ'=>CURRENCY.number_format($t['amount'],2), '🔖 Ref'=>$t['reference']]);
                $msg = ['ok'=>true, 'text'=>'✅ '.strtoupper($opApi).' Success!'];
                header('Location: recharges.php?ok=1'); exit;
            } elseif ($opApi === 'ecare' && $errMsg === 'RECEIVED — cron will confirm') {
                $db->prepare("UPDATE transactions SET note=?, api_response=? WHERE id=?")
                   ->execute(['⏳ ECARE RECEIVED — cron status check pending', $apiJson, $id]);
                $msg = ['ok'=>true, 'text'=>'⏳ ECARE RECEIVED — cron will confirm in ~1 min'];
                header('Location: recharges.php?ok=1'); exit;
            } elseif ($opApi === 'manual') {
                $msg = ['ok'=>false, 'text'=>'This operator is set to Manual mode'];
            } else {
                $db->prepare("UPDATE transactions SET note=?, api_response=? WHERE id=?")
                   ->execute(['❌ '.$opApi.' Failed: '.$errMsg, $apiJson, $id]);
                $msg = ['ok'=>false, 'text'=>'❌ '.strtoupper($opApi).' Failed: '.$errMsg];
            }
        }
    }

    // Transaction actions
    if (in_array($action, ['success','processing','failed','retry_api'])) {
        $id   = intval($_POST['txn_id'] ?? 0);
        $note = sanitize($_POST['note'] ?? '');

        $txn = $db->prepare("SELECT t.*, u.name as uname, u.balance, o.name as op_name, o.code as op_code FROM transactions t JOIN users u ON t.user_id=u.id LEFT JOIN operators o ON t.operator_id=o.id WHERE t.id=? AND t.type='topup'");
        $txn->execute([$id]);
        $t = $txn->fetch();

        if ($t) {
            if ($action === 'success' && in_array($t['status'],['pending','processing'])) {
                $db->prepare("UPDATE transactions SET status='success', note=?, updated_at=NOW() WHERE id=?")->execute([$note ?: 'Admin approved', $id]);
                require_once '../includes/commission.php';
                applyCommission($db, $t['user_id'], 'topup', $t['amount'], $t['reference']);
                $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
                   ->execute([$t['user_id'],'✅ Recharge Successful!',$t['phone_number'].' — '.CURRENCY.number_format($t['amount'],2).' completed. Ref: '.$t['reference']]);
                notifyUser($t['user_id'], 'রিচার্জ সফল! 📱', ['📱 নম্বর'=>$t['phone_number'], '📡 Operator'=>$t['op_name']??'', '💰 পরিমাণ'=>CURRENCY.number_format($t['amount'],2), '🔖 Ref'=>$t['reference']]);
                $msg = ['ok'=>true,'text'=>'✅ Approved!'];
                header('Location: recharges.php?ok=1'); exit;

            } elseif ($action === 'processing' && $t['status']==='pending') {
                $db->prepare("UPDATE transactions SET status='processing', note=?, updated_at=NOW() WHERE id=?")->execute([$note ?: 'Processing', $id]);
                $msg = ['ok'=>true,'text'=>'🔄 Processing!'];
                header('Location: recharges.php?ok=1'); exit;

            } elseif ($action === 'failed' && in_array($t['status'],['pending','processing'])) {
                $db->beginTransaction();
                try {
                    $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$t['amount'],$t['user_id']]);
                    $newBal = $t['balance'] + $t['amount'];
                    $db->prepare("UPDATE transactions SET status='refunded', note=?, balance_after=?, updated_at=NOW() WHERE id=?")->execute([$note ?: 'Rejected & refunded', $newBal, $id]);
                    $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")
                       ->execute([$t['user_id'],'refund',$t['amount'],$t['amount'],$t['balance'],$newBal,'RF-'.$t['reference'],'success','Refund: '.$t['reference']]);
                    $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'warning')")
                       ->execute([$t['user_id'],'❌ Recharge Rejected — Refunded',CURRENCY.number_format($t['amount'],2).' refunded to your balance.']);
                    $db->commit();
                    $msg = ['ok'=>true,'text'=>'❌ Rejected & '.CURRENCY.number_format($t['amount'],2).' refunded!'];
                    header('Location: recharges.php?ok=1'); exit;
                } catch(Exception $e) { $db->rollBack(); $msg=['ok'=>false,'text'=>$e->getMessage()]; }
            }
        }
    }
}

// Add api_response column
try { $db->exec("ALTER TABLE transactions ADD COLUMN api_response TEXT"); } catch(Exception $e) {}

// Settings
$recharge_mode = getSetting('api_mode') ?: 'manual';
$operators = $db->query("SELECT * FROM operators WHERE status='active' AND code NOT IN ('DING') ORDER BY name")->fetchAll();
$opModes = []; $opApis = [];
foreach ($operators as $op) {
    $opApis[$op['id']] = getSetting('op_api_'.$op['id']) ?: 'manual';
    $opModes[$op['id']] = getSetting('op_mode_'.$op['id']) ?: $recharge_mode;
}

// Custom APIs from API Manager
$customApiList = [];
try {
    $customApiList = $db->query("SELECT id, slug, name FROM custom_apis WHERE is_active=1 ORDER BY name")->fetchAll();
} catch(Exception $e) {}

// Filters
$status = $_GET['status'] ?? 'pending';
$search = sanitize($_GET['search'] ?? '');
$opFilter = intval($_GET['op'] ?? 0);

$where = "WHERE t.type='topup'";
$params = [];
if ($status !== 'all') { $where .= " AND t.status=?"; $params[] = $status; }
if ($search) {
    $where .= " AND (u.name LIKE ? OR t.phone_number LIKE ? OR t.reference LIKE ?)";
    $s = "%$search%"; $params = array_merge($params,[$s,$s,$s]);
}
if ($opFilter) { $where .= " AND t.operator_id=?"; $params[] = $opFilter; }

$txns = $db->prepare("SELECT t.*, u.name as uname, u.username, u.balance, o.name as op_name, o.code as op_code
    FROM transactions t JOIN users u ON t.user_id=u.id LEFT JOIN operators o ON t.operator_id=o.id
    $where ORDER BY t.created_at DESC LIMIT 100");
$txns->execute($params);
$requests = $txns->fetchAll();

$counts = [];
foreach (['pending','processing','success','refunded','failed','all'] as $s) {
    $w = $s === 'all' ? "WHERE type='topup'" : "WHERE type='topup' AND status='$s'";
    $counts[$s] = $db->query("SELECT COUNT(*) FROM transactions $w")->fetchColumn();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Recharge Requests - 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>
.stats-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(100px,1fr));gap:10px;margin-bottom:16px}
.stat-box{background:white;border-radius:10px;padding:12px;text-align:center;box-shadow:0 2px 6px rgba(0,0,0,0.05);border-top:3px solid #e8ecf4}
.stat-box.yellow{border-color:#d69e2e}.stat-box.blue{border-color:#3182ce}.stat-box.green{border-color:#38a169}.stat-box.red{border-color:#e53e3e}.stat-box.purple{border-color:#805ad5}
.stat-num{font-size:20px;font-weight:800;color:var(--dark)}.stat-lbl{font-size:10px;color:#888;margin-top:1px;font-weight:600}
.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}
.filter-bar{display:flex;gap:8px;padding:12px 18px;border-bottom:1px solid #f5f5f5;flex-wrap:wrap;align-items:center}
.fbtn{padding:6px 13px;border-radius:20px;border:2px solid #e8ecf4;background:white;font-size:12px;font-weight:700;cursor:pointer;color:#666;text-decoration:none;white-space:nowrap}
.fbtn.active{background:var(--primary);color:white;border-color:var(--primary)}
.search-in{flex:1;padding:8px 12px;border:2px solid #e8ecf4;border-radius:9px;font-size:13px;outline:none;min-width:120px}
.search-in:focus{border-color:var(--primary)}
/* Request cards */
.req-card{border:2px solid #f0f0f0;border-radius:12px;margin:10px 16px;overflow:hidden}
.req-card.pending{border-color:#fbd38d}.req-card.processing{border-color:#90cdf4}.req-card.success{border-color:#9ae6b4}.req-card.refunded{border-color:#d6bcfa}.req-card.failed{border-color:#feb2b2}
.req-head{padding:12px 14px;display:flex;align-items:center;gap:10px;cursor:pointer;background:#fafafa;user-select:none}
.req-head:hover{background:#f0f0f0}
.req-ic{width:40px;height:40px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
.req-ic.pending{background:#fffaf0;color:#d69e2e}.req-ic.processing{background:#ebf8ff;color:#3182ce}.req-ic.success{background:#f0fff4;color:#38a169}.req-ic.refunded{background:#faf5ff;color:#805ad5}.req-ic.failed{background:#fff5f5;color:#e53e3e}
.req-info{flex:1;min-width:0}
.req-title{font-size:13px;font-weight:700;color:#222}
.req-sub{font-size:11px;color:#aaa;margin-top:1px}
.req-right{text-align:right;flex-shrink:0}
.req-amt{font-size:16px;font-weight:800;color:var(--primary)}
.req-badge{font-size:11px;font-weight:700;padding:2px 8px;border-radius:20px;margin-top:2px;display:inline-block}
.b-pending{background:#fffaf0;color:#d69e2e}.b-processing{background:#ebf8ff;color:#3182ce}.b-success{background:#f0fff4;color:#38a169}.b-refunded{background:#faf5ff;color:#805ad5}.b-failed{background:#fff5f5;color:#e53e3e}
.req-detail{display:none;padding:14px;border-top:1px solid #f5f5f5;background:white}
.req-detail.show{display:block}
.dg{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:12px}
.dg-item{background:#f8fafc;border-radius:9px;padding:9px 11px}
.dg-lbl{font-size:10px;color:#aaa;font-weight:700;text-transform:uppercase;margin-bottom:2px}
.dg-val{font-size:13px;font-weight:700;color:#333}
.api-box{background:#1a1a2e;color:#00ff88;font-family:monospace;font-size:11px;padding:10px;border-radius:8px;white-space:pre-wrap;word-break:break-all;max-height:120px;overflow-y:auto;margin-bottom:10px}
.note-box{background:#f8fafc;border-radius:8px;padding:10px;font-size:12px;color:#555;margin-bottom:10px;font-family:monospace}
.act-row{display:flex;gap:8px;flex-wrap:wrap}
.btn{padding:8px 14px;border:none;border-radius:9px;font-size:12px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:5px}
.btn-ok{background:#38a169;color:white}.btn-proc{background:#3182ce;color:white}.btn-fail{background:#e53e3e;color:white}.btn-api{background:#805ad5;color:white}
.note-in{width:100%;padding:8px 12px;border:2px solid #e8ecf4;border-radius:9px;font-size:13px;outline:none;margin-bottom:8px}
.note-in:focus{border-color:var(--primary)}
/* Mode settings */
.op-mode-row{display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-bottom:1px solid #f5f5f5;gap:8px}
.op-mode-row:last-child{border:none}
/* Settings Modal */
.set-modal-bg{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.45);z-index:9999;align-items:flex-end;justify-content:center}
.set-modal-bg.show{display:flex;animation:smFade 0.2s ease}
@keyframes smFade{from{opacity:0}to{opacity:1}}
.set-modal{background:white;border-radius:24px 24px 0 0;width:100%;max-width:520px;max-height:90vh;overflow-y:auto;animation:smSlide 0.3s cubic-bezier(0.34,1.1,0.64,1)}
@keyframes smSlide{from{transform:translateY(100%)}to{transform:translateY(0)}}
.set-modal-h{padding:18px 20px 14px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #f5f5f5;position:sticky;top:0;background:white;z-index:1}
.set-modal-h h3{font-size:16px;font-weight:800;color:var(--dark);display:flex;align-items:center;gap:8px}
.set-close{width:32px;height:32px;background:#f5f5f5;border:none;border-radius:50%;font-size:15px;cursor:pointer;color:#666;display:flex;align-items:center;justify-content:center}
.set-body{padding:16px 20px 30px}
.mode-global{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:18px}
.mode-opt{display:flex;align-items:center;gap:10px;padding:12px;border-radius:12px;border:2px solid #e8ecf4;cursor:pointer;transition:0.2s}
.mode-opt.auto-sel{border-color:#38a169;background:#f0fff4}
.mode-opt.manual-sel{border-color:#e53e3e;background:#fff5f5}
.mode-opt-title{font-size:13px;font-weight:700}
.mode-opt-sub{font-size:11px;color:#888}
</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">📱 Recharge Requests</span>
    </div>
    <div class="topbar-right" style="font-size:12px;gap:8px;display:flex;align-items:center">
        <span style="background:<?= $recharge_mode==='auto'?'#f0fff4':'#fffaf0' ?>;color:<?= $recharge_mode==='auto'?'#276749':'#d69e2e' ?>;padding:5px 12px;border-radius:20px;font-weight:700">
            <?= $recharge_mode==='auto'?'⚡ Auto':'🖐 Manual' ?>
        </span>
        <button onclick="openSettings()" style="width:36px;height:36px;background:#f0f4ff;border:none;border-radius:10px;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:16px;color:var(--primary)">
            <i class="fas fa-cog"></i>
        </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"><div class="stat-num"><?= $counts['all'] ?></div><div class="stat-lbl">Total</div></div>
    <div class="stat-box yellow"><div class="stat-num"><?= $counts['pending'] ?></div><div class="stat-lbl">⏳ Pending</div></div>
    <div class="stat-box blue"><div class="stat-num"><?= $counts['processing'] ?></div><div class="stat-lbl">🔄 Processing</div></div>
    <div class="stat-box green"><div class="stat-num"><?= $counts['success'] ?></div><div class="stat-lbl">✅ Success</div></div>
    <div class="stat-box red"><div class="stat-num"><?= $counts['failed'] ?></div><div class="stat-lbl">❌ Failed</div></div>
    <div class="stat-box purple"><div class="stat-num"><?= $counts['refunded'] ?></div><div class="stat-lbl">↩️ Refunded</div></div>
</div>



<!-- Request List -->
<div class="card">
    <div class="card-h"><i class="fas fa-mobile-alt" style="color:var(--primary)"></i> Recharge Requests</div>

    <!-- Filters -->
    <form method="GET" class="filter-bar">
        <?php
        $tabs = ['pending'=>'⏳','processing'=>'🔄','success'=>'✅','refunded'=>'↩️','failed'=>'❌','all'=>'📋 All'];
        foreach ($tabs as $s => $label): ?>
        <a href="?status=<?= $s ?>" class="fbtn <?= $status===$s?'active':'' ?>"><?= $label ?> <?= $s!=='all'?'('.$counts[$s].')':'' ?></a>
        <?php endforeach; ?>
        <input type="hidden" name="status" value="<?= $status ?>">
        <input type="text" name="search" class="search-in" placeholder="Search name/phone/ref..." value="<?= htmlspecialchars($search) ?>">
        <select name="op" style="padding:8px 10px;border:2px solid #e8ecf4;border-radius:9px;font-size:12px;outline:none">
            <option value="">All Operators</option>
            <?php foreach($operators as $op): ?>
            <option value="<?= $op['id'] ?>" <?= $opFilter==$op['id']?'selected':'' ?>><?= htmlspecialchars($op['name']) ?></option>
            <?php endforeach; ?>
        </select>
        <button type="submit" style="padding:8px 12px;background:var(--primary);color:white;border:none;border-radius:9px;font-size:12px;cursor:pointer"><i class="fas fa-search"></i></button>
    </form>

    <?php if(empty($requests)): ?>
    <div style="text-align:center;padding:40px;color:#aaa"><i class="fas fa-inbox" style="font-size:28px;display:block;margin-bottom:8px"></i>No requests found</div>
    <?php else: ?>
    <?php foreach($requests as $r):
        $apiResp = $r['api_response'] ?? null;
        $canAct  = in_array($r['status'],['pending','processing']);
        $thisOpMode = $opModes[$r['operator_id']??0] ?? $recharge_mode;
    ?>
    <div class="req-card <?= $r['status'] ?>">
        <div class="req-head" onclick="toggleReq(<?= $r['id'] ?>)">
            <div class="req-ic <?= $r['status'] ?>">
                <?= $r['status']==='success'?'✅':($r['status']==='pending'?'⏳':($r['status']==='processing'?'🔄':($r['status']==='refunded'?'↩️':'❌'))) ?>
            </div>
            <div class="req-info">
                <div class="req-title">
                    <?= htmlspecialchars($r['op_name']??'Unknown') ?> — <?= $r['phone_number'] ?>
                    <?php if($thisOpMode==='auto'): ?>
                    <span style="background:#f0fff4;color:#276749;font-size:10px;padding:2px 6px;border-radius:8px;margin-left:4px">⚡API</span>
                    <?php else: ?>
                    <span style="background:#fffaf0;color:#d69e2e;font-size:10px;padding:2px 6px;border-radius:8px;margin-left:4px">🖐Manual</span>
                    <?php endif; ?>
                </div>
                <div class="req-sub">👤 <?= htmlspecialchars($r['uname']) ?> · 🔖 <?= $r['reference'] ?> · <?= date('d M, h:i A',strtotime($r['created_at'])) ?></div>
            </div>
            <div class="req-right">
                <div class="req-amt"><?= CURRENCY ?><?= number_format($r['amount'],2) ?></div>
                <span class="req-badge b-<?= $r['status'] ?>"><?= ucfirst($r['status']) ?></span>
            </div>
            <i class="fas fa-chevron-down" id="ch<?= $r['id'] ?>" style="color:#ddd;font-size:11px;margin-left:6px;transition:0.2s"></i>
        </div>

        <div class="req-detail" id="det<?= $r['id'] ?>">
            <div class="dg">
                <div class="dg-item"><div class="dg-lbl">👤 User</div><div class="dg-val"><?= htmlspecialchars($r['uname']) ?></div></div>
                <div class="dg-item"><div class="dg-lbl">📱 Phone</div><div class="dg-val" style="font-family:monospace;font-weight:700"><?= $r['phone_number'] ?></div></div>
                <div class="dg-item"><div class="dg-lbl">📡 Operator</div><div class="dg-val"><?= htmlspecialchars($r['op_name']??'—') ?></div></div>
                <div class="dg-item"><div class="dg-lbl">💰 Amount</div><div class="dg-val" style="color:var(--primary);font-weight:800"><?= CURRENCY ?><?= number_format($r['amount'],2) ?></div></div>
                <div class="dg-item"><div class="dg-lbl">💳 Bal Before</div><div class="dg-val"><?= CURRENCY ?><?= number_format($r['balance_before'],2) ?></div></div>
                <div class="dg-item"><div class="dg-lbl">📅 Date</div><div class="dg-val"><?= date('d M Y, h:i A',strtotime($r['created_at'])) ?></div></div>
                <div class="dg-item" style="grid-column:1/-1"><div class="dg-lbl">🔖 Reference</div><div class="dg-val" style="font-family:monospace"><?= $r['reference'] ?></div></div>
            </div>

            <?php
            // Parse API info
            $apiData   = $apiResp ? json_decode($apiResp, true) : null;
            $ecareRef  = $apiData['ecare_ref'] ?? null;
            $rcStatus  = $apiData['RECHARGE_STATUS'] ?? $apiData['rc_status'] ?? $apiData['status'] ?? null;
            $trxId     = $apiData['TRXID'] ?? $apiData['trxid'] ?? $apiData['RECHARGE_TRXID'] ?? $apiData['transaction_id'] ?? $apiData['txn_id'] ?? null;
            $noteStr   = $r['note'] ?? '';
            if(strpos($noteStr,'ECARE')!==false)             $apiSource = 'ECARE';
            elseif(strpos($noteStr,'ST ')!==false)           $apiSource = 'ST';
            elseif(preg_match('/✅\s*(\w+)\s*Success/i', $noteStr, $sm)) $apiSource = $sm[1];
            elseif(preg_match('/❌\s*(\w+)[:\s]/i', $noteStr, $sm))      $apiSource = $sm[1];
            else $apiSource = 'Manual';
            ?>

            <!-- API Info bar -->
            <div style="background:#f8fafc;border-radius:10px;padding:10px 14px;margin-bottom:12px;display:flex;flex-wrap:wrap;gap:10px;font-size:12px">
                <span><b>⚙️ API:</b> <span style="font-weight:700;color:<?= $apiSource==='ECARE'?'#e67e22':($apiSource==='ST'?'#38a169':'#888') ?>"><?= $apiSource ?></span></span>
                <?php if($rcStatus): ?><span><b>📊 RC:</b> <span style="color:<?= $rcStatus==='SUCCESS'?'#38a169':($rcStatus==='RECEIVED'?'#d69e2e':'#e53e3e') ?>;font-weight:700"><?= $rcStatus ?></span></span><?php endif; ?>
                <?php if($trxId): ?><span><b>🔑 TrxID:</b> <span style="font-family:monospace"><?= htmlspecialchars($trxId) ?></span></span><?php endif; ?>
                <?php if($ecareRef): ?><span><b>📋 ECARE Ref:</b> <span style="font-family:monospace;font-size:11px"><?= htmlspecialchars($ecareRef) ?></span></span><?php endif; ?>
            </div>

            <!-- Note -->
            <?php if($r['note']): ?>
            <div style="font-size:11px;font-weight:700;color:#888;margin-bottom:4px;text-transform:uppercase">📋 Status Note</div>
            <div style="background:#f8fafc;border-radius:8px;padding:9px 12px;font-size:12px;color:#555;margin-bottom:10px;font-family:monospace;line-height:1.5">
                <?= htmlspecialchars(preg_replace('/^[^\w]/', '', $r['note'])) ?>
            </div>
            <?php endif; ?>

            <!-- API Response -->
            <?php if($apiResp): ?>
            <div style="font-size:11px;font-weight:700;color:#888;margin-bottom:4px;text-transform:uppercase">📡 API Response</div>
            <div class="api-box"><?= htmlspecialchars($apiData ? json_encode($apiData, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE) : $apiResp) ?></div>
            <?php endif; ?>

            <?php if($canAct): ?>
            <form method="POST" id="f<?= $r['id'] ?>">
                <input type="hidden" name="txn_id" value="<?= $r['id'] ?>">
                <input type="hidden" name="action" id="a<?= $r['id'] ?>">
                <input type="hidden" name="use_api" id="ua<?= $r['id'] ?>" value="<?= $thisOpMode==='auto'?'ecare':'ecare' ?>">
                <input type="text" name="note" class="note-in" placeholder="Note (optional)...">
                <div class="act-row">
                    <!-- API select + retry -->
                    <div style="display:flex;gap:6px;align-items:center">
                        <select onchange="document.getElementById('ua<?= $r['id'] ?>').value=this.value" style="font-size:12px;padding:7px 10px;border:2px solid #e8ecf4;border-radius:8px;outline:none;font-weight:700;background:white">
                            <?php $curApi = getSetting('op_api_'.($r['operator_id']??0)) ?: 'ecare'; ?>
                            <option value="ecare"        <?= $curApi==='ecare'?'selected':'' ?>>⚡ ECARE</option>
                            <option value="successtopup" <?= $curApi==='successtopup'?'selected':'' ?>>🔄 ST</option>
                            <?php
                            // Custom APIs from DB
                            try {
                                $customApis = $db->query("SELECT slug, name FROM custom_apis WHERE is_active=1 ORDER BY name")->fetchAll();
                                foreach($customApis as $ca):
                            ?>
                            <option value="<?= htmlspecialchars($ca['slug']) ?>" <?= $curApi===$ca['slug']?'selected':'' ?>>
                                🔌 <?= htmlspecialchars($ca['name']) ?>
                            </option>
                            <?php endforeach; } catch(Exception $e){} ?>
                        </select>
                        <button type="button" class="btn btn-api" onclick="doAct(<?= $r['id'] ?>,'retry_api')">
                            <i class="fas fa-sync"></i> Retry
                        </button>
                    </div>
                    <?php if($r['status']==='pending'): ?>
                    <button type="button" class="btn btn-proc" onclick="doAct(<?= $r['id'] ?>,'processing')">
                        <i class="fas fa-clock"></i> Processing
                    </button>
                    <?php endif; ?>
                    <button type="button" class="btn btn-ok" onclick="doAct(<?= $r['id'] ?>,'success')">
                        <i class="fas fa-check"></i> ✅ Approve
                    </button>
                    <button type="button" class="btn btn-fail" onclick="doAct(<?= $r['id'] ?>,'failed')">
                        <i class="fas fa-times"></i> ❌ Refund
                    </button>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

</div>
</div>

<script>
function toggleReq(id) {
    const det = document.getElementById('det'+id);
    const ch  = document.getElementById('ch'+id);
    const show = det.classList.toggle('show');
    ch.style.transform = show ? 'rotate(180deg)' : '';
}
function doAct(id, action) {
    const labels = {success:'✅ Approve this recharge?', processing:'🔄 Mark as Processing?', failed:'❌ Reject & Refund to user?', retry_api:'⚡ Send to API now?'};
    if (!confirm(labels[action] || 'Confirm?')) return;
    document.getElementById('a'+id).value = action;
    document.getElementById('f'+id).submit();
}
function openSettings() { document.getElementById('settingsModal').classList.add('show'); }
function closeSettings() { document.getElementById('settingsModal').classList.remove('show'); }

function setGlobalMode(mode) {
    document.querySelectorAll('[name^="op_mode_"]').forEach(r => {
        if (r.value === mode) r.checked = true;
    });
}
// Auto-expand pending
document.querySelectorAll('.req-card.pending').forEach(c => {
    const id = c.querySelector('.req-head')?.getAttribute('onclick')?.match(/\d+/)?.[0];
    if(id) { document.getElementById('det'+id)?.classList.add('show'); const ch = document.getElementById('ch'+id); if(ch) ch.style.transform = 'rotate(180deg)'; }
});
</script>
<!-- Settings Modal -->
<div class="set-modal-bg" id="settingsModal" onclick="if(event.target===this)closeSettings()">
<div class="set-modal">
    <div class="set-modal-h">
        <h3><i class="fas fa-cog" style="color:#805ad5"></i> Recharge Mode Settings</h3>
        <button class="set-close" onclick="closeSettings()">✕</button>
    </div>
    <div class="set-body">
        <form method="POST">
            <input type="hidden" name="action" value="save_mode">

            <!-- Global Mode -->
            <div style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase;letter-spacing:0.8px;margin-bottom:10px">Global Mode</div>
            <div class="mode-global">
                <label class="mode-opt <?= $recharge_mode==='auto'?'auto-sel':'' ?>">
                    <input type="radio" name="recharge_mode" value="auto" <?= $recharge_mode==='auto'?'checked':'' ?> onchange="setGlobalMode('auto')" style="width:16px;height:16px;flex-shrink:0">
                    <div>
                        <div class="mode-opt-title">⚡ Auto Mode</div>
                        <div class="mode-opt-sub">API দিয়ে সরাসরি</div>
                    </div>
                </label>
                <label class="mode-opt <?= $recharge_mode==='manual'?'manual-sel':'' ?>">
                    <input type="radio" name="recharge_mode" value="manual" <?= $recharge_mode==='manual'?'checked':'' ?> onchange="setGlobalMode('manual')" style="width:16px;height:16px;flex-shrink:0">
                    <div>
                        <div class="mode-opt-title">🖐 Manual Mode</div>
                        <div class="mode-opt-sub">Admin approve করবে</div>
                    </div>
                </label>
            </div>

            <!-- Operator-wise API -->
            <div style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase;letter-spacing:0.8px;margin-bottom:10px">Operator-wise API Selection</div>
            <div style="font-size:11px;color:#aaa;margin-bottom:10px">প্রতিটা operator এর জন্য কোন API দিয়ে recharge যাবে select করুন। API fail হলে auto pending → admin approve করবে।</div>
            <?php
            $opColors = ['GP'=>'#009B3A','BL'=>'#FF6B00','RB'=>'#E4001D','AL'=>'#F7941D','TT'=>'#1C3F7A'];
            foreach($operators as $op):
                $oa = $opApis[$op['id']] ?? 'manual';
                $oc = $opColors[$op['code']] ?? '#1a3c8f';
            ?>
            <div class="op-mode-row">
                <div style="display:flex;align-items:center;gap:8px">
                    <div style="width:10px;height:10px;border-radius:50%;background:<?= $oc ?>;flex-shrink:0"></div>
                    <span style="font-size:13px;font-weight:700"><?= htmlspecialchars($op['name']) ?></span>
                    <span style="font-size:10px;color:#aaa">(<?= $op['code'] ?>)</span>
                </div>
                <div style="display:flex;gap:5px;flex-wrap:wrap">
                    <label style="display:flex;align-items:center;gap:4px;padding:5px 10px;border-radius:8px;border:2px solid <?= $oa==='successtopup'?'#38a169':'#e8ecf4' ?>;cursor:pointer;font-size:11px;font-weight:700;background:<?= $oa==='successtopup'?'#f0fff4':'white' ?>">
                        <input type="radio" name="op_api_<?= $op['id'] ?>" value="successtopup" <?= $oa==='successtopup'?'checked':'' ?> style="width:12px;height:12px"> 🔄 ST
                    </label>
                    <label style="display:flex;align-items:center;gap:4px;padding:5px 10px;border-radius:8px;border:2px solid <?= $oa==='ecare'?'#d69e2e':'#e8ecf4' ?>;cursor:pointer;font-size:11px;font-weight:700;background:<?= $oa==='ecare'?'#fffaf0':'white' ?>">
                        <input type="radio" name="op_api_<?= $op['id'] ?>" value="ecare" <?= $oa==='ecare'?'checked':'' ?> style="width:12px;height:12px"> ⚡ ECARE
                    </label>
                    <?php foreach($customApiList as $ca): ?>
                    <label style="display:flex;align-items:center;gap:4px;padding:5px 10px;border-radius:8px;border:2px solid <?= $oa===$ca['slug']?'#553c9a':'#e8ecf4' ?>;cursor:pointer;font-size:11px;font-weight:700;background:<?= $oa===$ca['slug']?'#faf5ff':'white' ?>">
                        <input type="radio" name="op_api_<?= $op['id'] ?>" value="<?= htmlspecialchars($ca['slug']) ?>" <?= $oa===$ca['slug']?'checked':'' ?> style="width:12px;height:12px"> 🔌 <?= htmlspecialchars($ca['name']) ?>
                    </label>
                    <?php endforeach; ?>
                    <label style="display:flex;align-items:center;gap:4px;padding:5px 10px;border-radius:8px;border:2px solid <?= $oa==='manual'?'#e53e3e':'#e8ecf4' ?>;cursor:pointer;font-size:11px;font-weight:700;background:<?= $oa==='manual'?'#fff5f5':'white' ?>">
                        <input type="radio" name="op_api_<?= $op['id'] ?>" value="manual" <?= $oa==='manual'?'checked':'' ?> style="width:12px;height:12px"> 🖐 Manual
                    </label>
                </div>
            </div>
            <?php endforeach; ?>

            <!-- Legend -->
            <div style="background:#f8fafc;border-radius:9px;padding:10px 12px;margin-top:10px;font-size:11px;color:#666;line-height:1.9">
                🔄 <b>SuccessTopUp</b> — GP ✅ BL ✅ Robi ✅ Airtel ✅ TT ✅ Skitto ✅<br>
                ⚡ <b>ECARE</b> — GP ✅ BL ✅ Robi ✅ Airtel ✅ TT ✅<br>
                <?php foreach($customApiList as $ca): ?>
                🔌 <b><?= htmlspecialchars($ca['name']) ?></b> — Custom API<br>
                <?php endforeach; ?>
                🖐 <b>Manual</b> — Admin manually process করবে<br>
                ⚠️ API fail হলে → auto pending → admin approve করবে
            </div>

            <button type="submit" style="width:100%;padding:13px;background:var(--primary);color:white;border:none;border-radius:12px;font-size:14px;font-weight:700;cursor:pointer;margin-top:14px;display:flex;align-items:center;justify-content:center;gap:8px">
                <i class="fas fa-save"></i> Save Settings
            </button>
        </form>
    </div>
</div>
</div>

</body>
</html>
