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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id     = intval($_POST['id']);
    $action = $_POST['action'] ?? '';
    $note   = trim($_POST['note'] ?? '');

    $stmt = $db->prepare("SELECT dr.*, u.name as uname, u.phone as uphone, u.balance as ubal,
        dp.name as pkg_name, dp.cashback_amount, dp.api_package_id, dp.operator_id as op_id,
        o.name as op_name, o.code as op_code
        FROM drive_requests dr
        JOIN users u ON dr.user_id=u.id
        LEFT JOIN drive_packages dp ON dr.package_id=dp.id
        LEFT JOIN operators o ON dp.operator_id=o.id
        WHERE dr.id=?");
    $stmt->execute([$id]);
    $req = $stmt->fetch();

    if ($req) {
        if ($action === 'success') {
            $db->prepare("UPDATE drive_requests SET status='success', note=? WHERE id=?")->execute([$note ?: 'Approved by admin', $id]);
            $db->prepare("UPDATE transactions SET status='success' WHERE reference=?")->execute([$req['reference']]);
            // Commission
            try { require_once '../includes/commission.php'; $cbBase = floatval($req['cashback_amount']??0); applyCommission($db, $req['user_id'], 'drive', $req['amount'], $req['reference'], $cbBase); } catch(Exception $e) {}
            // Cashback
            try {
                $cb = floatval($req['cashback_amount'] ?? 0);
                if ($cb > 0) {
                    $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$cb, $req['user_id']]);
                    $cbBal = floatval($db->query("SELECT balance FROM users WHERE id={$req['user_id']}")->fetchColumn());
                    $cbRef = 'CB'.strtoupper(substr(uniqid(),7));
                    $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")
                       ->execute([$req['user_id'],'commission',$cb,$cb,$cbBal-$cb,$cbBal,$cbRef,'success','Drive cashback: '.$req['pkg_name']]);
                    $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
                       ->execute([$req['user_id'],'💰 Cashback!','৳'.number_format($cb,2).' cashback from Drive: '.$req['pkg_name']]);
                }
            } catch(Exception $e) {}
            $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
               ->execute([$req['user_id'],'⚡ Drive Successful!', $req['pkg_name'].' for '.$req['phone_number'].' completed.']);
                notifyUser($req['user_id'], 'Drive সফল! ⚡', ['📦 Package'=>$req['pkg_name']??'', '📱 নম্বর'=>$req['phone_number'], '💰 পরিমাণ'=>CURRENCY.number_format($req['amount'],2), '🔖 Ref'=>$req['reference']]);
            $msg = ['ok'=>true,'text'=>'✅ Drive approved!'];
            header('Location: drive_requests.php?ok=1'); exit;

        } elseif ($action === 'failed') {
            $db->beginTransaction();
            try {
                $db->prepare("UPDATE drive_requests SET status='failed', note=? WHERE id=?")->execute([$note ?: 'Failed', $id]);
                $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$req['amount'], $req['user_id']]);
                $newBal = $req['ubal'] + $req['amount'];
                $db->prepare("UPDATE transactions SET status='failed', note=?, balance_after=? WHERE reference=?")->execute([$note, $newBal, $req['reference']]);
                $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")
                   ->execute([$req['user_id'],'refund',$req['amount'],$req['amount'],$req['ubal'],$newBal,'RF-'.$req['reference'],'success','Drive refund']);
                $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'error')")
                   ->execute([$req['user_id'],'❌ Drive Failed','৳'.number_format($req['amount'],2).' refunded to your balance.']);
                $db->commit();
                $msg = ['ok'=>true,'text'=>'Failed & refunded!'];
                header('Location: drive_requests.php?ok=1'); exit;
            } catch(Exception $e) { $db->rollBack(); $msg = ['ok'=>false,'text'=>$e->getMessage()]; }

        } elseif ($action === 'retry_api') {
            require_once '../includes/successtopup.php';
            require_once '../includes/ecare.php';

            $apiPkgId   = $req['api_package_id'] ?? null;
            $opCode     = $req['op_code'] ?? '';
            $driveApi   = getSetting('drive_auto_sync_api') ?: 'ecare';

            // Extract op code from ECARE api_package_id (format: ECARE_GP_xxxx)
            if (empty($opCode) && $apiPkgId && strpos($apiPkgId,'ECARE_')===0) {
                $parts  = explode('_', $apiPkgId);
                $opCode = $parts[1] ?? '';
            }

            // Extract from note: | OP:GP |
            if (empty($opCode) && $req['note']) {
                if (preg_match('/\| OP:([A-Z]+)/', $req['note'], $m)) $opCode = trim($m[1]);
            }

            // Final fallback — manual operator selection from form
            if (empty($opCode)) {
                $opCode = strtoupper(sanitize($_POST['manual_op'] ?? ''));
            }

            // Determine API: ECARE if api_package_id has ECARE_ prefix OR drive source is ecare
            $isEcare   = ($apiPkgId && strpos($apiPkgId,'ECARE_')===0) || in_array($driveApi,['ecare']);
            $useEcare  = $isEcare || $_POST['use_api'] === 'ecare';

            if ($useEcare) {
                if (empty($opCode)) {
                    $msg = ['ok'=>false,'text'=>'❌ Cannot detect operator code. Please set operator in package settings.'];
                } else {
                    $ecareRef = $req['reference'].'R'.substr(time(),-4);
                    $apiResp  = ecareRecharge($req['phone_number'], $req['amount'], $opCode, 'prepaid', $ecareRef);
                    $apiJson  = json_encode($apiResp['raw'] ?? $apiResp, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);

                    $db->prepare("UPDATE drive_requests SET api_response=? WHERE id=?")->execute([$apiJson, $id]);

                    if ($apiResp['result'] || ($apiResp['rc_status']??'') === 'RECEIVED') {
                        $db->prepare("UPDATE drive_requests SET status='success', note=? WHERE id=?")->execute(['✅ ECARE '.($apiResp['rc_status']??'SUCCESS').' TrxID: '.($apiResp['trxid']??''), $id]);
                        $db->prepare("UPDATE transactions SET status='success' WHERE reference=?")->execute([$req['reference']]);
                        try { require_once '../includes/commission.php'; $cbBase = floatval($req['cashback_amount']??0); applyCommission($db, $req['user_id'], 'drive', $req['amount'], $req['reference'], $cbBase); } catch(Exception $e) {}
                        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")->execute([$req['user_id'],'⚡ Drive Success!', ($req['pkg_name']??'Drive').' completed. Ref: '.$req['reference']]);
                        notifyUser($req['user_id'], 'Drive সফল! ⚡', ['📱 Number'=>$req['phone_number'], '💰 Amount'=>CURRENCY.number_format($req['amount'],2), '🔖 Ref'=>$req['reference']]);
                        $msg = ['ok'=>true,'text'=>'✅ ECARE '.($apiResp['rc_status']??'Success').'! TrxID: '.($apiResp['trxid']??'—')];
                        header('Location: drive_requests.php?ok=1'); exit;
                    } else {
                        $db->prepare("UPDATE drive_requests SET note=? WHERE id=?")->execute(['❌ ECARE: '.($apiResp['rc_status']??'').': '.($apiResp['message']??'Failed'), $id]);
                        $msg = ['ok'=>false,'text'=>'❌ ECARE '.($apiResp['rc_status']??'Failed').': '.($apiResp['message']??'Unknown error')];
                    }
                }

            } else {
                // SuccessTopUp
                if (!$apiPkgId) {
                    $msg = ['ok'=>false,'text'=>'❌ No package ID for SuccessTopUp'];
                } else {
                    $apiResp = successTopupDrive($req['phone_number'], $apiPkgId, $opCode, $req['reference']);
                    $apiJson = json_encode($apiResp, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
                    $db->prepare("UPDATE drive_requests SET api_response=? WHERE id=?")->execute([$apiJson, $id]);

                    if (isset($apiResp['result']) && $apiResp['result'] === true) {
                        $db->prepare("UPDATE drive_requests SET status='success', note='✅ ST Success' WHERE id=?")->execute([$id]);
                        $db->prepare("UPDATE transactions SET status='success' WHERE reference=?")->execute([$req['reference']]);
                        try { require_once '../includes/commission.php'; $cbBase = floatval($req['cashback_amount']??0); applyCommission($db, $req['user_id'], 'drive', $req['amount'], $req['reference'], $cbBase); } catch(Exception $e) {}
                        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")->execute([$req['user_id'],'⚡ Drive Success!', ($req['pkg_name']??'Drive').' completed.']);
                        $msg = ['ok'=>true,'text'=>'✅ ST Success!'];
                        header('Location: drive_requests.php?ok=1'); exit;
                    } else {
                        $db->prepare("UPDATE drive_requests SET note=? WHERE id=?")->execute(['❌ ST: '.($apiResp['message']??'Failed'), $id]);
                        $msg = ['ok'=>false,'text'=>'❌ ST Failed: '.($apiResp['message']??'Unknown')];
                    }
                }
            }
        }
    }
}

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

$status_filter = $_GET['status'] ?? '';
$search_filter = trim($_GET['search'] ?? '');
$where = "WHERE 1=1";
$params = [];
if ($status_filter) { $where .= " AND dr.status=?"; $params[] = $status_filter; }
if ($search_filter) {
    $where .= " AND (u.name LIKE ? OR u.phone LIKE ? OR dr.phone_number LIKE ? OR dr.reference LIKE ? OR dp.name LIKE ?)";
    $s = "%$search_filter%";
    $params = array_merge($params, [$s,$s,$s,$s,$s]);
}

$reqs = $db->prepare("SELECT dr.*, u.name as uname, u.phone as uphone, u.balance as ubal,
    dp.name as pkg_name, dp.cashback_amount, dp.api_package_id, dp.operator_id as op_id,
    o.name as op_name, o.code as op_code
    FROM drive_requests dr
    JOIN users u ON dr.user_id=u.id
    LEFT JOIN drive_packages dp ON dr.package_id=dp.id
    LEFT JOIN operators o ON dp.operator_id=o.id
    $where ORDER BY dr.created_at DESC LIMIT 100");
$reqs->execute($params);
$requests = $reqs->fetchAll();

$stats = [
    'total'   => $db->query("SELECT COUNT(*) FROM drive_requests")->fetchColumn(),
    'pending' => $db->query("SELECT COUNT(*) FROM drive_requests WHERE status='pending'")->fetchColumn(),
    'success' => $db->query("SELECT COUNT(*) FROM drive_requests WHERE status='success'")->fetchColumn(),
    'failed'  => $db->query("SELECT COUNT(*) FROM drive_requests WHERE status='failed'")->fetchColumn(),
    'revenue' => $db->query("SELECT COALESCE(SUM(amount),0) FROM drive_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>Drive 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(120px,1fr));gap:12px;margin-bottom:18px}
.stat-box{background:white;border-radius:12px;padding:14px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.05);border-top:3px solid var(--primary)}
.stat-box.green{border-color:#38a169}.stat-box.yellow{border-color:#d69e2e}.stat-box.red{border-color:#e53e3e}
.stat-num{font-size:22px;font-weight:800;color:var(--dark)}
.stat-lbl{font-size:11px;color:#888;margin-top:2px;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:14px 18px;border-bottom:1px solid #f5f5f5;font-size:14px;font-weight:700;display:flex;align-items:center;gap:8px}
.alert{padding:11px 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:7px 14px;border-radius:20px;border:2px solid #e8ecf4;background:white;font-size:12px;font-weight:700;cursor:pointer;color:#666;text-decoration:none}
.fbtn.active,.fbtn:hover{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:150px}
.search-in:focus{border-color:var(--primary)}

/* Request cards */
.req-card{border:2px solid #f0f0f0;border-radius:12px;margin:12px 18px;overflow:hidden;transition:0.2s}
.req-card.pending{border-color:#fbd38d}
.req-card.success{border-color:#9ae6b4}
.req-card.failed{border-color:#feb2b2}
.req-head{padding:13px 16px;display:flex;align-items:center;gap:12px;cursor:pointer;background:#fafafa}
.req-head:hover{background:#f5f5f5}
.req-icon{width:42px;height:42px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0}
.req-icon.pending{background:#fffaf0;color:#d69e2e}
.req-icon.success{background:#f0fff4;color:#38a169}
.req-icon.failed{background:#fff5f5;color:#e53e3e}
.req-info{flex:1;min-width:0}
.req-title{font-size:14px;font-weight:700;color:#222}
.req-sub{font-size:11px;color:#aaa;margin-top:2px}
.req-right{text-align:right;flex-shrink:0}
.req-amt{font-size:16px;font-weight:800;color:var(--primary)}
.req-status{font-size:11px;font-weight:700;padding:3px 9px;border-radius:20px;margin-top:3px;display:inline-block}
.s-pending{background:#fffaf0;color:#d69e2e}
.s-success{background:#f0fff4;color:#38a169}
.s-failed{background:#fff5f5;color:#e53e3e}

/* Detail panel */
.req-detail{display:none;padding:16px;border-top:1px solid #f0f0f0;background:white}
.req-detail.show{display:block}
.detail-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:14px}
.dg-item{background:#f8fafc;border-radius:10px;padding:10px 12px}
.dg-lbl{font-size:10px;color:#aaa;font-weight:700;text-transform:uppercase;margin-bottom:3px}
.dg-val{font-size:13px;font-weight:700;color:#333}
.api-resp{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:100px;overflow-y:auto;margin-bottom:12px}
.action-row{display:flex;gap:8px;flex-wrap:wrap}
.btn{padding:9px 16px;border:none;border-radius:9px;font-size:13px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:6px}
.btn-ok{background:#38a169;color:white}
.btn-fail{background:#e53e3e;color:white}
.btn-api{background:#805ad5;color:white}
.btn-gray{background:#f5f5f5;color:#555}
.note-in{width:100%;padding:9px 12px;border:2px solid #e8ecf4;border-radius:9px;font-size:13px;outline:none;margin-bottom:10px}
.note-in:focus{border-color:var(--primary)}
</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">⚡ Drive Requests</span>
    </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"><?= $stats['total'] ?></div><div class="stat-lbl">Total</div></div>
    <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 red"><div class="stat-num"><?= $stats['failed'] ?></div><div class="stat-lbl">❌ Failed</div></div>
    <div class="stat-box green"><div class="stat-num"><?= CURRENCY ?><?= number_format($stats['revenue'],0) ?></div><div class="stat-lbl">Revenue</div></div>
</div>

<!-- Requests -->
<div class="card">
    <div class="card-h"><i class="fas fa-bolt" style="color:#f5a623"></i> Drive Requests</div>

    <!-- Filters -->
    <form method="GET" class="filter-bar">
        <a href="drive_requests.php" class="fbtn <?= !$status_filter?'active':'' ?>">All (<?= $stats['total'] ?>)</a>
        <a href="?status=pending"  class="fbtn <?= $status_filter==='pending' ?'active':'' ?>">⏳ Pending (<?= $stats['pending'] ?>)</a>
        <a href="?status=success"  class="fbtn <?= $status_filter==='success' ?'active':'' ?>">✅ Success</a>
        <a href="?status=failed"   class="fbtn <?= $status_filter==='failed'  ?'active':'' ?>">❌ Failed</a>
        <input type="text" name="search" class="search-in" placeholder="Search user/phone/ref..." value="<?= htmlspecialchars($search_filter) ?>">
        <button type="submit" style="padding:8px 14px;background:var(--primary);color:white;border:none;border-radius:9px;font-size:12px;font-weight:700;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:30px;display:block;margin-bottom:10px"></i>No requests found</div>
    <?php else: ?>
    <?php foreach($requests as $r): 
        $isApiPkg = !empty($r['api_package_id']);
        $apiResp  = $r['api_response'] ?? null;

        // Extract pkg name and op code from note for ECARE real-time requests
        $pkgName = $r['pkg_name'] ?? '';
        $opName  = $r['op_name']  ?? '';
        $opCode  = $r['op_code']  ?? '';
        if (empty($pkgName) && $r['note']) {
            if (preg_match('/PKG:([^|]+)/', $r['note'], $m)) $pkgName = trim($m[1]);
            if (preg_match('/OP_NAME:([^|]+)/', $r['note'], $m)) $opName = trim($m[1]);
            if (preg_match('/\| OP:([^|]+)/', $r['note'], $m)) $opCode = trim($m[1]);
        }
        // Clean note for display (remove PKG/OP parts)
        $displayNote = preg_replace('/\s*\|\s*(PKG|OP|OP_NAME):[^|]+/', '', $r['note'] ?? '');
    ?>
    <div class="req-card <?= $r['status'] ?>" id="reqCard<?= $r['id'] ?>">
        <!-- Header — click to expand -->
        <div class="req-head" onclick="toggleReq(<?= $r['id'] ?>)">
            <div class="req-icon <?= $r['status'] ?>">
                <?= $r['status']==='success'?'✅':($r['status']==='failed'?'❌':'⏳') ?>
            </div>
            <div class="req-info">
                <div class="req-title">
                    <?= htmlspecialchars($pkgName ?: '—') ?>
                    <?php if($opName): ?><span style="background:#f0f4ff;color:var(--primary);font-size:10px;padding:2px 7px;border-radius:10px;margin-left:5px"><?= htmlspecialchars($opName) ?></span><?php endif; ?>
                </div>
                <div class="req-sub">
                    👤 <?= htmlspecialchars($r['uname']) ?> · 📱 <?= $r['phone_number'] ?> · <?= 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-status s-<?= $r['status'] ?>"><?= ucfirst($r['status']) ?></span>
            </div>
            <i class="fas fa-chevron-down" style="color:#ddd;font-size:12px;margin-left:8px" id="chevron<?= $r['id'] ?>"></i>
        </div>

        <!-- Detail Panel -->
        <div class="req-detail" id="detail<?= $r['id'] ?>">
            <div class="detail-grid">
                <div class="dg-item"><div class="dg-lbl">Package</div><div class="dg-val"><?= htmlspecialchars($pkgName ?: '—') ?></div></div>
                <div class="dg-item"><div class="dg-lbl">Operator</div><div class="dg-val"><?= htmlspecialchars($opName ?: '—') ?></div></div>
                <div class="dg-item"><div class="dg-lbl">Phone</div><div class="dg-val" style="font-family:monospace"><?= $r['phone_number'] ?></div></div>
                <div class="dg-item"><div class="dg-lbl">Amount</div><div class="dg-val" style="color:var(--primary)"><?= CURRENCY ?><?= number_format($r['amount'],2) ?></div></div>
                <div class="dg-item"><div class="dg-lbl">Reference</div><div class="dg-val" style="font-family:monospace;font-size:11px"><?= $r['reference'] ?></div></div>
                <div class="dg-item"><div class="dg-lbl">Cashback</div><div class="dg-val" style="color:#38a169"><?= floatval($r['cashback_amount']??0)>0 ? CURRENCY.number_format($r['cashback_amount'],2) : '—' ?></div></div>
                <div class="dg-item"><div class="dg-lbl">User Balance</div><div class="dg-val"><?= CURRENCY ?><?= number_format($r['ubal'],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>
                <?php if($r['note']): ?>
                <div class="dg-item" style="grid-column:1/-1"><div class="dg-lbl">Note</div><div class="dg-val"><?= htmlspecialchars($displayNote) ?></div></div>
                <?php endif; ?>
            </div>

            <?php if($apiResp): ?>
            <div style="font-size:11px;font-weight:700;color:#555;margin-bottom:6px">📡 API Response:</div>
            <div class="api-resp"><?= htmlspecialchars(json_encode(json_decode($apiResp),JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)) ?></div>
            <?php elseif($r['note']): ?>
            <div style="font-size:11px;font-weight:700;color:#555;margin-bottom:6px">📋 Status Note:</div>
            <div style="background:#f8fafc;border-radius:8px;padding:10px;font-size:12px;color:#555;margin-bottom:12px;font-family:monospace">
                <?= $r['note'] === 'Awaiting admin approval' 
                    ? '🖐 Manual Mode — Waiting for admin to process'
                    : htmlspecialchars($r['note']) ?>
            </div>
            <?php endif; ?>

            <?php if($r['status'] === 'pending'): ?>
            <form method="POST" id="form<?= $r['id'] ?>">
                <input type="hidden" name="id" value="<?= $r['id'] ?>">
                <input type="hidden" name="action" id="act<?= $r['id'] ?>">
                <input type="text" name="note" class="note-in" placeholder="Add note (optional)...">
                <div class="action-row" style="flex-direction:column;gap:8px">
                    <?php $driveApiMode = getSetting('drive_auto_sync_api') ?: 'ecare'; ?>
                    <!-- API + Operator select -->
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:6px">
                        <select name="use_api" id="useApi<?= $r['id'] ?>" style="font-size:12px;padding:8px 10px;border:2px solid #e8ecf4;border-radius:8px;outline:none;font-weight:700;background:white">
                            <option value="ecare"        <?= $driveApiMode==='ecare'?'selected':'' ?>>⚡ ECARE</option>
                            <option value="successtopup" <?= $driveApiMode==='successtopup'?'selected':'' ?>>🔄 SuccessTopUp</option>
                        </select>
                        <select name="manual_op" id="manualOp<?= $r['id'] ?>" style="font-size:12px;padding:8px 10px;border:2px solid #e8ecf4;border-radius:8px;outline:none;font-weight:700;background:white">
                            <?php
                            $selOp = $opCode ?: '';
                            $ops2  = [['GP','Grameenphone'],['BL','Banglalink'],['RB','Robi'],['AR','Airtel'],['TT','Teletalk']];
                            foreach($ops2 as $o2):
                            ?>
                            <option value="<?= $o2[0] ?>" <?= $selOp===$o2[0]?'selected':'' ?>><?= $o2[1] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div style="display:flex;gap:6px">
                        <button type="button" class="btn btn-api" style="flex:1;justify-content:center" onclick="doRetry(<?= $r['id'] ?>)">
                            <i class="fas fa-sync"></i> Retry API
                        </button>
                        <button type="button" class="btn btn-ok" style="flex:1;justify-content:center" onclick="doAction(<?= $r['id'] ?>,'success')">
                            <i class="fas fa-check"></i> ✅ Success
                        </button>
                        <button type="button" class="btn btn-fail" style="flex:1;justify-content:center" onclick="doAction(<?= $r['id'] ?>,'failed')">
                            <i class="fas fa-times"></i> ❌ Refund
                        </button>
                    </div>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

</div>
</div>

<script>
function toggleReq(id) {
    const det  = document.getElementById('detail'+id);
    const chev = document.getElementById('chevron'+id);
    const show = det.classList.toggle('show');
    chev.style.transform = show ? 'rotate(180deg)' : '';
}

function doRetry(id) {
    if (!confirm('Send to API?')) return;
    const useApi   = document.getElementById('useApi'+id)?.value || 'ecare';
    const manualOp = document.getElementById('manualOp'+id)?.value || '';
    document.getElementById('act'+id).value = 'retry_api';

    let inp = document.getElementById('useApiHidden'+id);
    if (!inp) { inp = document.createElement('input'); inp.type='hidden'; inp.name='use_api'; inp.id='useApiHidden'+id; document.getElementById('form'+id).appendChild(inp); }
    inp.value = useApi;

    let inp2 = document.getElementById('manualOpHidden'+id);
    if (!inp2) { inp2 = document.createElement('input'); inp2.type='hidden'; inp2.name='manual_op'; inp2.id='manualOpHidden'+id; document.getElementById('form'+id).appendChild(inp2); }
    inp2.value = manualOp;

    document.getElementById('form'+id).submit();
}

function doAction(id, action) {
    const labels = {success:'Mark as Successful?', failed:'Fail & Refund to user?', retry_api:'Send to API?'};
    if (!confirm(labels[action] || 'Confirm?')) return;
    document.getElementById('act'+id).value = action;
    document.getElementById('form'+id).submit();
}

// Auto-expand pending
document.querySelectorAll('.req-card.pending').forEach(c => {
    const id = c.id.replace('reqCard','');
    document.getElementById('detail'+id)?.classList.add('show');
    const chev = document.getElementById('chevron'+id);
    if(chev) chev.style.transform = 'rotate(180deg)';
});
</script>
</body>
</html>
