<?php
require_once 'includes/config.php';
requireLogin();
require_once 'includes/service_check.php';
checkServiceEnabled('topup');
$user = getCurrentUser();
$db   = getDB();
$operators = $db->query("SELECT * FROM operators WHERE status='active' ORDER BY id")->fetchAll();

// User's preferred secondary currency
$_uc = null;
try {
    $s = $db->prepare("SELECT c.* FROM users u JOIN currencies c ON u.preferred_currency=c.code WHERE u.id=? AND c.is_active=1 AND c.code<>'BDT'");
    $s->execute([$user['id']]);
    $_uc = $s->fetch() ?: null;
} catch(Exception $e) { $_uc = null; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Mobile Recharge</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        *{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}
        :root{
            --primary:<?= getSetting('color_primary') ?: '#1a3c8f' ?>;
            --secondary:<?= getSetting('color_secondary') ?: '#f5a623' ?>;
            --dark:<?= getSetting('color_dark') ?: '#0d1f4e' ?>;
        }
        body{font-family:'Segoe UI',sans-serif;background:#f0f4f8;min-height:100vh;padding-bottom:160px}

        .hdr{background:var(--primary);padding:0 18px;position:sticky;top:0;z-index:50}
        .hdr-in{display:flex;align-items:center;gap:12px;height:58px;max-width:480px;margin:0 auto}
        .back-btn{width:38px;height:38px;background:rgba(255,255,255,0.15);border:none;color:white;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:17px;cursor:pointer;flex-shrink:0}
        .hdr-op-wrap{flex:1;display:flex;align-items:center;gap:10px}
        .hdr-op-logo{width:34px;height:34px;border-radius:8px;overflow:hidden;background:white;display:none;align-items:center;justify-content:center;flex-shrink:0}
        .hdr-op-logo img{width:100%;height:100%;object-fit:contain;padding:3px}
        .hdr-op-logo.show{display:flex}
        .hdr-op-ic{width:34px;height:34px;border-radius:8px;display:none;align-items:center;justify-content:center;font-size:12px;font-weight:800;color:white;flex-shrink:0}
        .hdr-op-ic.show{display:flex}
        .hdr-title{color:white;font-size:18px;font-weight:700}

        .content{max-width:480px;margin:0 auto;padding:16px 18px}
        .card{background:white;border-radius:16px;padding:18px;margin-bottom:14px;box-shadow:0 1px 8px rgba(0,0,0,0.06)}
        .lbl{font-size:13px;color:#888;font-weight:600;margin-bottom:10px;display:block;letter-spacing:0.3px}

        /* Phone + Operator trigger */
        .phone-row{display:flex;align-items:center;gap:10px}
        .op-trigger{width:52px;height:52px;border-radius:12px;background:#f0f4ff;border:2px solid #e8ecf4;display:flex;align-items:center;justify-content:center;cursor:pointer;flex-shrink:0;overflow:hidden;transition:0.2s;position:relative}
        .op-trigger:active{transform:scale(0.95)}
        .op-trigger img{width:100%;height:100%;object-fit:contain;padding:4px}
        .op-trigger i{color:#aaa;font-size:20px}
        .op-trigger span{color:white;font-size:12px;font-weight:800}
        .op-trigger .caret{position:absolute;bottom:2px;right:2px;font-size:8px;color:rgba(255,255,255,0.8)}
        .phone-in{flex:1;padding:14px 14px;border:2px solid #e8ecf4;border-radius:12px;font-size:16px;outline:none;background:white;color:#333;transition:0.2s}
        .phone-in:focus{border-color:var(--primary)}
        .phone-hint{font-size:12px;color:#aaa;margin-top:7px}

        /* Operator Dropdown */
        .op-dropdown{display:none;position:absolute;top:calc(100% + 8px);left:0;right:0;background:white;border-radius:16px;box-shadow:0 8px 30px rgba(0,0,0,0.15);z-index:200;padding:14px;border:1px solid #eee}
        .op-dropdown.show{display:block}
        .op-drop-title{font-size:12px;color:#888;font-weight:600;margin-bottom:10px}
        .op-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:8px}
        .op-card{background:#f8fafc;border:2px solid #f0f0f0;border-radius:12px;padding:10px 5px;text-align:center;cursor:pointer;transition:0.2s}
        .op-card:active{transform:scale(0.95)}
        .op-card.sel{border-color:var(--primary);background:#eef2ff}
        .op-ic{width:40px;height:40px;border-radius:10px;margin:0 auto 5px;overflow:hidden;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:800;color:white}
        .op-ic img{width:100%;height:100%;object-fit:contain;padding:3px;background:white}
        .ic-gp{background:linear-gradient(135deg,#00a651,#007a3e)}
        .ic-robi{background:linear-gradient(135deg,#e31837,#a0001a)}
        .ic-bl{background:linear-gradient(135deg,#ff6600,#cc5200)}
        .ic-tt{background:linear-gradient(135deg,#1a3c8f,#0d2260)}
        .ic-bt{background:linear-gradient(135deg,#8b5cf6,#6d28d9)}
        .ic-def{background:linear-gradient(135deg,#1a3c8f,#2856c8)}
        .op-nm{font-size:10px;color:#666;font-weight:600;line-height:1.2}
        .op-card.sel .op-nm{color:var(--primary);font-weight:700}

        /* Dropdown overlay */
        .drop-overlay{display:none;position:fixed;inset:0;z-index:199}
        .drop-overlay.show{display:block}

        /* Phone wrap relative */
        .phone-wrap-rel{position:relative}

        /* Type */
        .type-row{display:grid;grid-template-columns:1fr 1fr;gap:10px}
        .type-btn{padding:13px;border-radius:12px;border:2px solid #e8ecf4;background:#f8fafc;font-size:14px;font-weight:700;cursor:pointer;color:#aaa;transition:0.2s}
        .type-btn.sel{background:var(--primary);border-color:var(--primary);color:white}

        /* Amount */
        .amt-row{position:relative}
        .amt-pfx{position:absolute;left:14px;top:50%;transform:translateY(-50%);font-size:20px;color:#bbb;font-weight:600;pointer-events:none}
        .amt-in{width:100%;padding:14px 14px 14px 32px;border:2px solid #e8ecf4;border-radius:12px;font-size:26px;font-weight:800;outline:none;background:white;color:var(--primary);transition:0.2s}
        .amt-in:focus{border-color:var(--primary)}
        .bal-hint{font-size:12px;color:#888;margin-top:6px}
        .quick{display:flex;gap:7px;margin-top:10px;flex-wrap:wrap}
        .qbtn{padding:8px 14px;border:2px solid #e8ecf4;border-radius:10px;background:white;font-size:13px;font-weight:600;cursor:pointer;color:#555;transition:0.2s}
        .qbtn.sel,.qbtn:active{border-color:var(--primary);background:#eef2ff;color:var(--primary)}

        .err{background:#fff5f5;color:#e53e3e;padding:10px 14px;border-radius:10px;font-size:13px;margin-bottom:12px;border-left:3px solid #e53e3e;display:none}

        /* Tap Hold — Fixed, always visible */
        .thold-wrap{position:fixed;bottom:70px;left:0;right:0;z-index:100;padding:10px 18px}
        .thold-inner{max-width:480px;margin:0 auto}
        .thold-btn{width:100%;border:none;border-radius:18px;padding:18px;display:flex;align-items:center;justify-content:center;gap:14px;cursor:pointer;position:relative;overflow:hidden;background:var(--primary);user-select:none;-webkit-user-select:none;touch-action:none;box-shadow:0 4px 20px rgba(26,60,143,0.35)}
        .thold-btn.off{background:#c8d0db;box-shadow:none;cursor:not-allowed}
        .tprog{position:absolute;left:0;top:0;bottom:0;background:rgba(255,255,255,0.2);width:0%;border-radius:18px;pointer-events:none}
        .thold-ic{width:44px;height:44px;background:white;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;box-shadow:0 2px 8px rgba(0,0,0,0.1)}
        .thold-ic i{color:var(--primary);font-size:19px}
        .thold-txt{color:white;font-size:15px;font-weight:700}

        .spin-wrap{display:none;position:fixed;inset:0;background:rgba(255,255,255,0.9);z-index:400;align-items:center;justify-content:center;flex-direction:column;gap:12px}
        .spin-wrap.on{display:flex}
        .spin{width:46px;height:46px;border:4px solid #e8ecf4;border-top-color:var(--primary);border-radius:50%;animation:sp 0.8s linear infinite}
        .spin-txt{color:var(--primary);font-size:14px;font-weight:600}
        @keyframes sp{to{transform:rotate(360deg)}}

        .pop-ov{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.4);z-index:500;align-items:flex-end;justify-content:center}
        .pop-ov.on{display:flex}
        .pop-box{background:white;border-radius:24px 24px 0 0;padding:24px 20px 34px;width:100%;max-width:480px;animation:su 0.3s ease;position:relative}
        @keyframes su{from{transform:translateY(100%)}to{transform:translateY(0)}}
        .pop-x{position:absolute;top:14px;right:16px;background:none;border:none;font-size:20px;color:#bbb;cursor:pointer}
        .suc-icon{width:62px;height:62px;background:#22c55e;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 12px;box-shadow:0 4px 18px rgba(34,197,94,0.3)}
        .suc-icon i{color:white;font-size:26px}
        .pop-ttl{text-align:center;font-size:18px;font-weight:800;color:#222;margin-bottom:16px}
        .pop-ttl span{color:#22c55e}
        .ph-row{background:#f8fafc;border-radius:12px;padding:12px 16px;display:flex;justify-content:space-between;align-items:center;margin-bottom:14px}
        .ph-num{font-size:20px;font-weight:800;color:#222}
        .copy-btn{background:#eef2ff;color:var(--primary);border:none;padding:6px 13px;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer}
        .drow{display:flex;justify-content:space-between;padding:9px 0;border-bottom:1px solid #f5f5f5;font-size:13px}
        .drow:last-child{border:none}
        .drow .dl{color:#888}
        .drow .dv{font-weight:700;color:#333}
        .bal-box{background:#f8fafc;border-radius:12px;padding:13px 16px;margin:12px 0 16px}
        .bal-box .nb .dv{font-size:20px;font-weight:800;color:#22c55e}
        .home-btn{width:100%;padding:15px;background:var(--primary);color:white;border:none;border-radius:14px;font-size:15px;font-weight:700;cursor:pointer}
        .pend-icon{width:62px;height:62px;background:#f6ad55;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 12px}
        .pend-icon i{color:white;font-size:26px}
        .pend-ref{background:#fffaf0;border-radius:10px;padding:10px 14px;font-size:13px;color:#92400e;margin:10px 0 16px;text-align:center}
    </style>
</head>
<body>

<div class="hdr">
    <div class="hdr-in">
        <button class="back-btn" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
        <div class="hdr-op-wrap">
            <div class="hdr-op-logo" id="hdrLogo"></div>
            <div class="hdr-op-ic" id="hdrIc"></div>
            <div class="hdr-title" id="hdrTitle">Mobile Recharge</div>
        </div>
    </div>
</div>

<div class="content">
    <div class="err" id="errMsg"></div>

    <!-- Phone + Operator trigger -->
    <div class="card">
        <label class="lbl">PHONE NUMBER</label>
        <div class="phone-wrap-rel">
            <div class="phone-row">
                <!-- Operator trigger button -->
                <div class="op-trigger" id="opTrigger" onclick="toggleDropdown()">
                    <i class="fas fa-mobile-alt" id="trigIco"></i>
                    <i class="fas fa-caret-down caret"></i>
                </div>
                <input type="tel" id="phoneIn" class="phone-in" placeholder="Enter phone number (11 digits)" maxlength="11" oninput="onPhone(this.value)">
            </div>
            <div class="phone-hint" id="phoneHint">Tap <i class="fas fa-mobile-alt" style="font-size:10px"></i> to select operator</div>

            <!-- Operator Dropdown -->
            <div class="op-dropdown" id="opDropdown">
                <div class="op-drop-title">SELECT OPERATOR</div>
                <div class="op-grid">
                    <?php foreach ($operators as $op):
                        $code = strtolower($op['code']);
                        if (in_array($code,['gp','sk'])) $cc='ic-gp';
                        elseif (in_array($code,['rb','robi','at'])) $cc='ic-robi';
                        elseif ($code==='bl') $cc='ic-bl';
                        elseif ($code==='tt') $cc='ic-tt';
                        elseif ($code==='bt') $cc='ic-bt';
                        else $cc='ic-def';
                        $initials = strtoupper(substr($op['name'],0,2));
                    ?>
                    <div class="op-card" data-id="<?= $op['id'] ?>" data-name="<?= htmlspecialchars($op['name']) ?>" data-cc="<?= $cc ?>" onclick="selOp(this)">
                        <div class="op-ic <?= $cc ?>">
                            <?php if ($op['logo']): ?>
                            <img src="<?= $op['logo'] ?>" onerror="this.parentElement.textContent='<?= $initials ?>'">
                            <?php else: ?>
                            <?= $initials ?>
                            <?php endif; ?>
                        </div>
                        <div class="op-nm"><?= $op['name'] ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Type -->
    <div class="card">
        <label class="lbl">SELECT TYPE</label>
        <div class="type-row">
            <button class="type-btn sel" id="btnPre" onclick="selType('prepaid')">Prepaid</button>
            <button class="type-btn" id="btnPost" onclick="selType('postpaid')">Postpaid</button>
        </div>
    </div>

    <!-- Amount -->
    <div class="card">
        <label class="lbl">AMOUNT</label>
        <div class="amt-row">
            <span class="amt-pfx">৳</span>
            <input type="number" id="amtIn" class="amt-in" placeholder="0.00" min="1" oninput="onAmt()">
        </div>
        <?php
// $_uc already fetched at top of file
?>
<div id="amtDualBox" style="display:none;font-size:13px;color:#b7791f;font-weight:600;margin-top:6px;padding:6px 14px;background:#fffaf0;border-radius:8px"></div>
<div class="bal-hint">
    Available Balance: ৳<?= number_format($user['balance'],2) ?>
    <?php if($_uc): ?>
    <span style="color:#aaa;font-size:11px"> ≈ <?= htmlspecialchars($_uc['symbol']) ?><?= number_format($user['balance']*floatval($_uc['rate']),2) ?> <?= $_uc['code'] ?></span>
    <?php endif; ?>
</div>
        <div class="quick">
            <button class="qbtn" onclick="setAmt(20,this)">৳20</button>
            <button class="qbtn" onclick="setAmt(30,this)">৳30</button>
            <button class="qbtn" onclick="setAmt(50,this)">৳50</button>
            <button class="qbtn" onclick="setAmt(80,this)">৳80</button>
            <button class="qbtn" onclick="setAmt(100,this)">৳100</button>
            <button class="qbtn" onclick="setAmt(500,this)">৳500</button>
        </div>
    </div>
</div>

<!-- Dropdown overlay -->
<div class="drop-overlay" id="dropOverlay" onclick="closeDropdown()"></div>

<!-- Tap Hold — Fixed above bottom nav -->
<div class="thold-wrap">
    <div class="thold-inner">
        <div class="thold-btn off" id="thBtn"
             ontouchstart="startH(event)" ontouchend="endH()" ontouchcancel="endH()"
             onmousedown="startH(event)" onmouseup="endH()" onmouseleave="endH()">
            <div class="tprog" id="thProg"></div>
            <div class="thold-ic"><i class="fas fa-mobile-alt"></i></div>
            <span class="thold-txt">Tap and hold to Recharge</span>
        </div>
    </div>
</div>

<div class="spin-wrap" id="spinner"><div class="spin"></div><div class="spin-txt">Processing...</div></div>

<!-- Success Popup -->
<div class="pop-ov" id="sucPop">
    <div class="pop-box">
        <button class="pop-x" onclick="document.getElementById('sucPop').classList.remove('on')"><i class="fas fa-times"></i></button>
        <div class="suc-icon"><i class="fas fa-check"></i></div>
        <div class="pop-ttl">Recharge <span>Successful!</span></div>
        <div class="ph-row">
            <span class="ph-num" id="pPhone">-</span>
            <button class="copy-btn" onclick="cpPhone()">Copy</button>
        </div>
        <div class="drow"><span class="dl">Time</span><span class="dv" id="pTime">-</span></div>
        <div class="drow"><span class="dl">Txn ID</span><span class="dv" id="pTxn">-</span></div>
        <div class="drow"><span class="dl">Operator</span><span class="dv" id="pOp">-</span></div>
        <div class="bal-box">
            <div class="drow"><span class="dl">Previous Balance</span><span class="dv" id="pOld">-</span></div>
            <div class="drow"><span class="dl">Recharged</span><span class="dv" style="color:#38a169" id="pAmt">-</span></div>
            <div class="drow nb"><span class="dl">New Balance</span><span class="dv" id="pNew">-</span></div>
        </div>
        <button class="home-btn" onclick="location.href='dashboard.php'"><i class="fas fa-home"></i> Back to Home</button>
    </div>
</div>

<!-- Pending Popup -->
<div class="pop-ov" id="pendPop">
    <div class="pop-box">
        <button class="pop-x" onclick="document.getElementById('pendPop').classList.remove('on')"><i class="fas fa-times"></i></button>
        <div class="pend-icon"><i class="fas fa-clock"></i></div>
        <div class="pop-ttl">Request Submitted!</div>
        <p style="text-align:center;font-size:13px;color:#666">Admin approval এর পর recharge সম্পন্ন হবে।</p>
        <div class="pend-ref">Ref: <strong id="pRef">-</strong></div>
        <button class="home-btn" onclick="location.href='dashboard.php'"><i class="fas fa-home"></i> Back to Home</button>
    </div>
</div>

<!-- Recharge Sent Popup (for API recharges) -->
<div class="pop-ov" id="sentPop">
    <div class="pop-box" style="text-align:center">
        <div style="font-size:52px;margin-bottom:10px">📤</div>
        <div class="pop-ttl" style="color:#1a3c8f">Recharge Sent!</div>
        <p style="font-size:13px;color:#666;margin-bottom:14px">রিচার্জ request পাঠানো হয়েছে।<br>সম্পন্ন হলে notification পাবেন।</p>
        <div style="background:#f0f4ff;border-radius:10px;padding:10px 14px;margin-bottom:16px;font-family:monospace;font-size:13px;color:var(--primary);font-weight:700" id="sentRef">-</div>
        <button class="home-btn" onclick="goHomeAfterSent()"><i class="fas fa-home"></i> Back to Home</button>
    </div>
</div>

<script>
const USER_CUR_RATE = <?php echo $_uc ? floatval($_uc['rate']) : 0; ?>;
const USER_CUR_SYM  = "<?php echo $_uc ? htmlspecialchars($_uc['symbol']) : ''; ?>";
const USER_CUR_CODE = "<?php echo $_uc ? $_uc['code'] : ''; ?>";
function showDual(bdt) {
    if (!USER_CUR_RATE) return '';
    return ' <span style="color:#aaa;font-size:12px">≈ '+USER_CUR_SYM+(bdt*USER_CUR_RATE).toFixed(2)+' '+USER_CUR_CODE+'</span>';
}
const pfxMap = <?php
    $m=[];
    foreach($operators as $op)
        foreach(json_decode($op['prefix']??'[]',true)??[] as $p)
            $m[$p]=['id'=>(int)$op['id'],'name'=>$op['name'],'logo'=>$op['logo']??''];
    echo json_encode($m);
?>;

const opColors = {'ic-gp':'#00a651','ic-robi':'#e31837','ic-bl':'#ff6600','ic-tt':'#1a3c8f','ic-bt':'#8b5cf6','ic-def':'#1a3c8f'};
let curOpId=null, curOpName='', selType_='prepaid';
let hInt=null, hProg=0;
const HOLD=2000;

function toggleDropdown(){
    const dd=document.getElementById('opDropdown');
    const ov=document.getElementById('dropOverlay');
    const show=!dd.classList.contains('show');
    dd.classList.toggle('show',show);
    ov.classList.toggle('show',show);
}
function closeDropdown(){
    document.getElementById('opDropdown').classList.remove('show');
    document.getElementById('dropOverlay').classList.remove('show');
}

function selOp(el){
    document.querySelectorAll('.op-card').forEach(c=>c.classList.remove('sel'));
    el.classList.add('sel');
    curOpId   = parseInt(el.dataset.id);
    curOpName = el.dataset.name;
    const cc  = el.dataset.cc;
    const img = el.querySelector('img');

    // Update trigger button
    const trig = document.getElementById('opTrigger');
    if(img){
        trig.innerHTML=`<img src="${img.src}" style="width:100%;height:100%;object-fit:contain;padding:5px"><i class="fas fa-caret-down caret"></i>`;
        trig.style.background='white';
        trig.style.border='2px solid #e8ecf4';
    } else {
        const color = opColors[cc]||'#1a3c8f';
        trig.style.background=color;
        trig.style.border='none';
        trig.innerHTML=`<span style="color:white;font-size:11px;font-weight:800">${curOpName.substring(0,2).toUpperCase()}</span><i class="fas fa-caret-down caret"></i>`;
    }

    // Update header
    updateHeader(el);
    document.getElementById('phoneHint').textContent='✅ '+curOpName+' selected';
    closeDropdown();
    chkReady();
}

function updateHeader(el){
    const img=el.querySelector('img');
    const hdrLogo=document.getElementById('hdrLogo');
    const hdrIc=document.getElementById('hdrIc');
    if(img){
        hdrLogo.innerHTML=`<img src="${img.src}">`;
        hdrLogo.classList.add('show'); hdrIc.classList.remove('show');
    } else {
        const cc=el.dataset.cc;
        hdrIc.style.background=opColors[cc]||'#1a3c8f';
        hdrIc.textContent=curOpName.substring(0,2).toUpperCase();
        hdrIc.classList.add('show'); hdrLogo.classList.remove('show');
    }
    document.getElementById('hdrTitle').textContent=curOpName;
}

function onPhone(v){
    if(v.length>=3){
        const info=pfxMap[v.substring(0,3)];
        if(info){
            curOpId=info.id; curOpName=info.name;
            document.querySelectorAll('.op-card').forEach(c=>{
                const active=parseInt(c.dataset.id)===curOpId;
                c.classList.toggle('sel',active);
                if(active){selOp(c);}
            });
        } else { resetOp(); }
    } else { resetOp(); }
    chkReady();
}

function resetOp(){
    if(curOpId) return; // Don't reset if manually selected
    document.querySelectorAll('.op-card').forEach(c=>c.classList.remove('sel'));
    const trig=document.getElementById('opTrigger');
    trig.innerHTML='<i class="fas fa-mobile-alt" id="trigIco"></i><i class="fas fa-caret-down caret"></i>';
    trig.style.background='#f0f4ff'; trig.style.border='2px solid #e8ecf4';
    document.getElementById('hdrLogo').classList.remove('show');
    document.getElementById('hdrIc').classList.remove('show');
    document.getElementById('hdrTitle').textContent='Mobile Recharge';
    document.getElementById('phoneHint').innerHTML='Tap <i class="fas fa-mobile-alt" style="font-size:10px"></i> to select operator';
}

function selType(t){
    selType_=t;
    document.getElementById('btnPre').classList.toggle('sel',t==='prepaid');
    document.getElementById('btnPost').classList.toggle('sel',t==='postpaid');
}

function setAmt(v,btn){
    document.getElementById('amtIn').value=v;
    document.querySelectorAll('.qbtn').forEach(b=>b.classList.remove('sel'));
    btn.classList.add('sel');
    chkReady();
    showAmtDual(v);
}
function onAmt(){
    document.querySelectorAll('.qbtn').forEach(b=>b.classList.remove('sel'));
    chkReady();
    const v = parseFloat(document.getElementById('amtIn').value)||0;
    showAmtDual(v);
}
function showAmtDual(v){
    const box = document.getElementById('amtDualBox');
    if(!box) return;
    if(USER_CUR_RATE && USER_CUR_CODE && v > 0){
        box.innerHTML = '≈ ' + USER_CUR_SYM + (v * USER_CUR_RATE).toFixed(2) + ' ' + USER_CUR_CODE;
        box.style.display = 'block';
    } else {
        box.style.display = 'none';
    }
}

function chkReady(){
    const ph=document.getElementById('phoneIn').value;
    const am=parseFloat(document.getElementById('amtIn').value)||0;
    document.getElementById('thBtn').classList.toggle('off',!(ph.length===11&&am>=1&&curOpId));
}

function startH(e){
    e.preventDefault();
    if(document.getElementById('thBtn').classList.contains('off')) return;
    document.getElementById('errMsg').style.display='none';
    hProg=0;
    const pr=document.getElementById('thProg');
    pr.style.transition='none'; pr.style.width='0%';
    hInt=setInterval(()=>{
        hProg+=(50/HOLD)*100;
        pr.style.width=Math.min(hProg,100)+'%';
        if(hProg>=100){clearInterval(hInt);doRecharge();}
    },50);
}
function endH(){
    if(hInt){clearInterval(hInt);hInt=null;}
    const pr=document.getElementById('thProg');
    pr.style.transition='width 0.3s ease'; pr.style.width='0%';
}

function doRecharge(){
    const phone=document.getElementById('phoneIn').value;
    const amount=parseFloat(document.getElementById('amtIn').value);
    document.getElementById('spinner').classList.add('on');
    fetch('api/recharge.php',{
        method:'POST',headers:{'Content-Type':'application/json'},
        body:JSON.stringify({phone,amount,operator_id:curOpId,type:selType_})
    }).then(r=>r.json()).then(d=>{
        document.getElementById('spinner').classList.remove('on');
        if(d.success){
            if(d.status==='success') {
                showSuccess(d,phone,amount);
            } else if(d.need_polling && d.txn_id && d.reference) {
                // API sent — show popup then go home, poll in background
                showSentPopup(d.reference, d.txn_id);
            } else {
                showPending(d);
            }
        } else {
            const em=document.getElementById('errMsg');
            em.textContent=d.message; em.style.display='block'; window.scrollTo(0,0);
        }
    }).catch(()=>{
        document.getElementById('spinner').classList.remove('on');
        document.getElementById('errMsg').textContent='❌ Connection error!';
        document.getElementById('errMsg').style.display='block';
    });
}

function showSentPopup(ref, txnId) {
    document.getElementById('sentRef').textContent = 'Ref: ' + ref;
    document.getElementById('sentPop').classList.add('on');
    // Start background polling silently
    bgPoll(ref, txnId, 1);
}

function goHomeAfterSent() {
    document.getElementById('sentPop').classList.remove('on');
    location.href = 'dashboard.php';
}

function bgPoll(ref, txnId, attempt) {
    if (attempt > 20) return;
    setTimeout(() => {
        fetch('api/ecare_status_check.php?ref='+encodeURIComponent(ref)+'&txn_id='+txnId)
        .then(r=>r.json())
        .then(d=>{
            if (!d.done) {
                bgPoll(ref, txnId, attempt + 1);
            }
            // If done, dashboard/history will show updated status
        }).catch(() => {
            bgPoll(ref, txnId, attempt + 1);
        });
    }, 30000);
}

function showSuccess(d,phone,amount){
    const now=new Date();
    document.getElementById('pPhone').textContent=phone;
    document.getElementById('pTime').textContent=now.toLocaleTimeString('en',{hour:'2-digit',minute:'2-digit',hour12:true})+' · '+now.toLocaleDateString('en-GB',{day:'2-digit',month:'short',year:'numeric'});
    document.getElementById('pTxn').textContent=d.reference||'-';
    document.getElementById('pOp').textContent=curOpName;
    document.getElementById('pOld').textContent='৳'+parseFloat(d.old_balance||0).toFixed(2);
    document.getElementById('pAmt').textContent='+৳'+amount.toFixed(2);
    document.getElementById('pNew').textContent='৳'+parseFloat(d.new_balance||0).toFixed(2);
    document.getElementById('sucPop').classList.add('on');
}
function showPending(d){
    document.getElementById('pRef').textContent=d.reference||'-';
    document.getElementById('pendPop').classList.add('on');
}
function cpPhone(){
    navigator.clipboard?.writeText(document.getElementById('pPhone').textContent).then(()=>{
        const b=event.target; b.textContent='Copied!'; b.style.background='#38a169'; b.style.color='white';
        setTimeout(()=>{b.textContent='Copy';b.style.background='';b.style.color='';},2000);
    });
}
</script>
<?php include 'includes/bottom_nav.php'; ?>
<script>document.addEventListener("DOMContentLoaded",function(){ if(window.pageReady) window.pageReady(); });</script>
</body>
</html>
