<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<title>Withdraw - CV111</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800;900&display=swap">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
  *{box-sizing:border-box; margin:0; padding:0;}
  :root{
    --bg:#0A0714; --bg2:#120D24;
    --card:#181129; --card-hi:#1F1836;
    --border:rgba(255,255,255,.07); --border-hi:rgba(155,93,229,.35);
    --gold:#F5C542; --gold-dark:#C9971E;
    --purple:#9B5DE5; --purple-deep:#6C3FC5;
    --grad-main:linear-gradient(135deg,#6C3FC5 0%,#9B5DE5 50%,#B57EF0 100%);
    --grad-gold:linear-gradient(135deg,#F5C542,#E0A926);
    --text:#FFFFFF; --muted:#9691B0; --muted-dim:#5C5870;
    --green:#22D67A; --red:#FF5C7A;
  }
  body{
    min-height:100vh; font-family:'Poppins',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
    color:var(--text);
    background:radial-gradient(circle at 20% 0%, rgba(155,93,229,.12), transparent 45%),
               radial-gradient(circle at 90% 90%, rgba(245,197,66,.06), transparent 40%),
               var(--bg);
    padding-bottom:40px; -webkit-tap-highlight-color:transparent;
  }
  ::selection{background:var(--purple); color:#fff;}

  /* Header */
  .top{display:flex;align-items:center;gap:14px;padding:20px 18px 16px;}
  .top a{width:38px;height:38px;border-radius:12px;background:var(--card);border:1px solid var(--border);display:flex;align-items:center;justify-content:center;color:var(--text);text-decoration:none;font-size:16px;}
  .top h1{font-size:19px;font-weight:800;flex:1;text-align:center;padding-right:38px;letter-spacing:.2px;}

  .wrap{max-width:480px;margin:0 auto;padding:0 18px;}

  /* Balance Hero */
  .balance-hero{
    border-radius:24px; padding:26px 22px; margin-bottom:22px; position:relative; overflow:hidden;
    background:linear-gradient(160deg, #1D1533 0%, #120D24 100%);
    border:1px solid var(--border-hi);
    box-shadow:0 20px 50px -12px rgba(108,63,197,.35), inset 0 1px 0 rgba(255,255,255,.06);
  }
  .balance-hero::before{
    content:''; position:absolute; width:180px; height:180px; border-radius:50%;
    background:radial-gradient(circle, rgba(155,93,229,.25), transparent 70%);
    top:-70px; right:-50px;
  }
  .balance-hero .lab{font-size:11.5px; color:var(--muted); font-weight:700; letter-spacing:1.5px; text-transform:uppercase; position:relative; z-index:1;}
  .balance-hero .amt{font-size:38px; font-weight:900; margin-top:8px; position:relative; z-index:1; letter-spacing:-.5px;
    background:linear-gradient(135deg,#fff,#D8CCFA); -webkit-background-clip:text; background-clip:text; color:transparent;}
  .balance-hero .amt span{font-size:22px; opacity:.7; margin-right:4px;}
  .balance-hero .sub-row{display:flex; align-items:center; justify-content:space-between; margin-top:16px; position:relative; z-index:1;}
  .min-chip{background:rgba(245,197,66,.1); border:1px solid rgba(245,197,66,.3); color:var(--gold); font-size:11.5px; font-weight:700; padding:6px 12px; border-radius:20px;}

  /* Amount Input */
  .amount-section{margin-bottom:22px;}
  .amount-box{
    background:var(--card); border:1.5px solid var(--border); border-radius:18px; padding:18px;
    transition:border-color .2s; position:relative;
  }
  .amount-box.focused{border-color:var(--purple); box-shadow:0 0 0 4px rgba(155,93,229,.12);}
  .amount-box .lab{font-size:11px; color:var(--muted); font-weight:700; letter-spacing:.5px; text-transform:uppercase; margin-bottom:8px;}
  .amount-row{display:flex; align-items:center; gap:10px;}
  .amount-row .cur{font-size:24px; font-weight:800; color:var(--gold);}
  .amount-row input{flex:1; background:none; border:none; outline:none; color:var(--text); font-size:26px; font-weight:800; font-family:'Poppins';}
  .amount-row input::placeholder{color:var(--muted-dim); font-weight:600;}
  .all-chip{background:var(--grad-gold); color:#1a1400; font-weight:800; font-size:12px; padding:8px 14px; border-radius:12px; cursor:pointer; border:none;}
  .quick-amts{display:flex; gap:8px; margin-top:14px;}
  .quick-amt{flex:1; background:var(--bg2); border:1px solid var(--border); border-radius:10px; padding:9px 0; text-align:center; font-size:12.5px; font-weight:700; color:var(--muted); cursor:pointer; transition:.15s;}
  .quick-amt.active{border-color:var(--purple); color:var(--purple); background:rgba(155,93,229,.1);}

  /* Section Title */
  .section-title{font-size:14px; font-weight:800; margin:0 0 12px; color:#E8E3F8; letter-spacing:.2px;}

  /* Methods */
  .methods{display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-bottom:18px;}
  .method{
    position:relative; display:flex; align-items:center; gap:12px; background:var(--card);
    border:1.5px solid var(--border); border-radius:16px; padding:14px; cursor:pointer; transition:.18s;
  }
  .method .ic{width:40px; height:40px; border-radius:12px; display:flex; align-items:center; justify-content:center; font-weight:900; font-size:13px; color:#fff; flex-shrink:0; box-shadow:0 4px 12px rgba(0,0,0,.25);}
  .method.bkash .ic{background:linear-gradient(135deg,#E2136E,#B00D57);}
  .method.nagad .ic{background:linear-gradient(135deg,#EC1D24,#B8151B);}
  .method .name{font-weight:700; font-size:14px;}
  .method .tag{font-size:10.5px; color:var(--green); font-weight:600; margin-top:2px; display:flex; align-items:center; gap:4px;}
  .method .tag::before{content:''; width:5px; height:5px; border-radius:50%; background:var(--green);}
  .method.active{border-color:var(--purple); background:linear-gradient(135deg, rgba(155,93,229,.15), rgba(155,93,229,.03)); box-shadow:0 8px 24px -8px rgba(155,93,229,.5);}
  .method .check{position:absolute; top:-6px; right:-6px; width:22px; height:22px; border-radius:50%; background:var(--grad-main); color:#fff; display:none; align-items:center; justify-content:center; font-size:11px; font-weight:900; box-shadow:0 2px 8px rgba(155,93,229,.5); border:2px solid var(--bg);}
  .method.active .check{display:flex;}

  /* Saved Wallet */
  .saved-wallet{display:flex; align-items:center; gap:14px; background:var(--card); border:1.5px solid var(--border); border-radius:16px; padding:16px; margin-bottom:14px;}
  .saved-wallet .badge{width:46px; height:46px; border-radius:14px; display:flex; align-items:center; justify-content:center; font-weight:900; font-size:14px; color:#fff; flex-shrink:0;}
  .saved-wallet .info{flex:1;}
  .saved-wallet .num{font-weight:800; font-size:15.5px; letter-spacing:.3px;}
  .saved-wallet .type{color:var(--muted); font-size:11.5px; margin-top:2px; font-weight:600;}
  .saved-wallet .change-link{color:var(--purple); font-size:12px; font-weight:700; cursor:pointer; background:rgba(155,93,229,.1); padding:7px 12px; border-radius:10px;}

  .field-box{background:var(--card); border:1.5px solid var(--border); border-radius:16px; padding:16px; margin-bottom:14px; transition:.2s;}
  .field-box:focus-within{border-color:var(--purple); box-shadow:0 0 0 4px rgba(155,93,229,.12);}
  .field-box label{display:block; font-size:10.5px; color:var(--muted); text-transform:uppercase; letter-spacing:.6px; font-weight:700; margin-bottom:7px;}
  .field-box input{width:100%; background:none; border:none; outline:none; color:var(--text); font-size:15.5px; font-weight:600; font-family:'Poppins';}

  .btn-save{margin-top:12px; width:100%; padding:12px; border-radius:12px; border:none; background:var(--grad-main); color:#fff; font-weight:800; font-size:13.5px; cursor:pointer; box-shadow:0 8px 20px -6px rgba(155,93,229,.5);}

  .note{font-size:12.5px; color:var(--muted); line-height:1.8; margin:18px 4px; text-align:center;}
  .note .hrs{color:var(--gold); font-weight:700;}

  .btn-submit{
    width:100%; padding:18px; border-radius:18px; border:none; font-weight:800; font-size:16px; cursor:pointer;
    background:var(--grad-main); color:#fff; box-shadow:0 16px 36px -10px rgba(108,63,197,.6);
    margin-top:8px; letter-spacing:.3px; transition:transform .12s;
  }
  .btn-submit:active{transform:scale(.98);}
  .btn-submit:disabled{opacity:.5; box-shadow:none;}

  .msg{padding:14px 16px; border-radius:14px; font-size:13px; font-weight:600; margin-bottom:16px; display:flex; align-items:center; gap:10px;}
  .msg-ok{background:rgba(34,214,122,.1); border:1px solid rgba(34,214,122,.3); color:var(--green);}
  .msg-err{background:rgba(255,92,122,.1); border:1px solid rgba(255,92,122,.3); color:var(--red);}
  .hidden{display:none !important;}
  .center{text-align:center; color:var(--muted); padding:60px 0; font-size:14px;}

  /* Success Overlay */
  #withdrawSuccessOverlay{position:fixed; inset:0; z-index:999; background:radial-gradient(circle at 50% 30%,rgba(34,214,122,.1),transparent 55%), var(--bg); display:flex; flex-direction:column; align-items:center; justify-content:center; text-align:center; padding:30px;}
  .ws-check-wrap{width:130px; height:130px; margin-bottom:30px; position:relative;}
  .ws-check-svg{width:100%; height:100%;}
  .ws-glow{position:absolute; inset:0; border-radius:50%; background:radial-gradient(circle, rgba(34,214,122,.3), transparent 70%); animation:ws-pulse 2s ease-in-out infinite;}
  @keyframes ws-pulse{0%,100%{opacity:.5; transform:scale(1);} 50%{opacity:1; transform:scale(1.1);}}
  .ws-check-circle{fill:none; stroke:var(--green); stroke-width:4; stroke-linecap:round; stroke-dasharray:226; stroke-dashoffset:226; animation:ws-circle-draw .6s ease-out forwards;}
  .ws-check-mark{fill:none; stroke:var(--green); stroke-width:5; stroke-linecap:round; stroke-linejoin:round; stroke-dasharray:40; stroke-dashoffset:40; animation:ws-mark-draw .4s ease-out .5s forwards;}
  @keyframes ws-circle-draw{to{stroke-dashoffset:0;}}
  @keyframes ws-mark-draw{to{stroke-dashoffset:0;}}
  .ws-title{font-size:26px; font-weight:900; color:#fff; margin-bottom:14px; opacity:0; animation:ws-fade-up .5s ease-out .7s forwards;}
  .ws-amt{font-size:32px; font-weight:900; background:var(--grad-gold); -webkit-background-clip:text; background-clip:text; color:transparent; margin-bottom:14px; opacity:0; animation:ws-fade-up .5s ease-out .8s forwards;}
  .ws-sub{font-size:14px; color:var(--muted); line-height:1.8; max-width:300px; opacity:0; animation:ws-fade-up .5s ease-out .9s forwards;}
  @keyframes ws-fade-up{from{opacity:0; transform:translateY(10px);} to{opacity:1; transform:translateY(0);}}
</style>
</head>
<body>
<?php $pt = __DIR__ . '/page_transition.php'; if (file_exists($pt)) { include $pt; } ?>
  <div class="top"><a href="/newhome.php">←</a><h1>Withdraw</h1></div>
  <div class="wrap">
    <div id="msgBox"></div>
    <div id="loadingState" class="center">লোড হচ্ছে...</div>

    <div id="mainContent" class="hidden">
      <!-- Balance Hero -->
      <div class="balance-hero">
        <div class="lab">Available Balance</div>
        <div class="amt"><span>৳</span><span id="cashBalance">0</span></div>
        <div class="sub-row">
          <div class="min-chip"><i class="fa-solid fa-bolt"></i> Instant Processing</div>
          <div class="min-chip">Min ৳150</div>
        </div>
      </div>

      <!-- Amount -->
      <div class="amount-section">
        <div class="section-title">Withdraw Amount</div>
        <div class="amount-box" id="amountBox">
          <div class="lab">Enter Amount</div>
          <div class="amount-row">
            <span class="cur">৳</span>
            <input type="number" id="wdAmount" placeholder="0.00" oninput="onAmountInput()">
            <button class="all-chip" onclick="fillAll()">MAX</button>
          </div>
          <div class="quick-amts" id="quickAmts"></div>
        </div>
      </div>

      <!-- Method -->
      <div class="section-title">Payment Method</div>
      <div class="methods">
        <div class="method bkash active" id="wmtd-bKash" onclick="selectMethod('bKash')"><div class="check">✓</div><div class="ic" style="background:#fff;"><img src="https://cv111.site/pay/images/images.png" alt="bKash" style="width:100%; height:100%; object-fit:contain; padding:6px;"></div><div><div class="name">bKash</div><div class="tag">Instant</div></div></div>
        <div class="method nagad" id="wmtd-Nagad" onclick="selectMethod('Nagad')"><div class="check">✓</div><div class="ic" style="background:#fff;"><img src="https://cv111.site/pay/images/unnamed.png" alt="Nagad" style="width:100%; height:100%; object-fit:contain; padding:6px;"></div><div><div class="name">Nagad</div><div class="tag">Instant</div></div></div>
      </div>

      <div id="savedWalletBox"></div>
      <div id="addWalletBox" class="field-box" style="display:none;">
        <label>Save Your Number</label>
        <input type="tel" id="newAccNumber" placeholder="01XXXXXXXXX">
        <button class="btn-save" onclick="saveWallet()">Save করো</button>
      </div>

      <div class="field-box">
        <label>Login Password</label>
        <input type="password" id="loginPwd" placeholder="••••••••">
      </div>

      <p class="note">Withdraw Request Admin কর্তৃক Verify হওয়ার পর, সাধারণত <span class="hrs">১৫-৩০ মিনিটের</span> মধ্যে টাকা পৌঁছাবে।</p>

      <button class="btn-submit" id="submitBtn" onclick="submitWithdraw()">Withdraw করো</button>

      <!-- ✅ নতুন যোগ — Wagering-Requirement-এর নিয়মাবলী, বাংলায় স্পষ্ট বর্ণনা -->
      <div id="wageringInfoBox" style="margin-top:16px; background:rgba(155,93,229,.08); border:1px solid rgba(155,93,229,.25); border-radius:14px; padding:16px;">
        <div style="display:flex; align-items:center; gap:8px; margin-bottom:10px;">
          <i class="fa-solid fa-circle-info" style="color:#9B5DE5; font-size:14px;"></i>
          <span style="color:#fff; font-weight:800; font-size:13px;">Withdraw করার নিয়ম</span>
        </div>
        <div style="color:#9691B0; font-size:11.5px; line-height:1.7;">
          🔹 সর্বনিম্ন Withdraw-Amount: <b style="color:#F5C542;">৳150</b> (এর কম Amount দিয়ে Withdraw করা যাবে না)
          <br><br>
          🔹 তোমার (শেষ Withdraw-এর পর থেকে) মোট Deposit-এর <b style="color:#F5C542;">সমান পরিমাণ টাকা Win</b> করলেই, Withdraw করতে পারবে।
          <br><br>
          একাধিকবার Deposit করলে, প্রতিটাই যোগ হয়ে Requirement বাড়বে।
          <br><br>
          উদাহরণ: ৳1000 Deposit করলে, কমপক্ষে ৳1000 Win করার পরই Withdraw সম্ভব হবে।
        </div>
        <div id="wageringStatus" style="margin-top:12px; padding-top:12px; border-top:1px solid rgba(255,255,255,.08);">
          <div style="color:#9691B0; font-size:11px;">তোমার বর্তমান অবস্থা লোড হচ্ছে...</div>
        </div>
      </div>
    </div>
  </div>

  <div id="withdrawSuccessOverlay" class="hidden">
    <div class="ws-check-wrap">
      <div class="ws-glow"></div>
      <svg class="ws-check-svg" viewBox="0 0 80 80">
        <circle class="ws-check-circle" cx="40" cy="40" r="36"/>
        <path class="ws-check-mark" d="M24 41 L35 52 L57 28"/>
      </svg>
    </div>
    <div class="ws-title">Withdrawal Successful</div>
    <div class="ws-amt" id="successAmt">৳0</div>
    <div class="ws-sub">তোমার Withdraw Request সফলভাবে জমা হয়েছে।<br>Admin Verify করার পর, শীঘ্রই টাকা পৌঁছে যাবে।</div>
  </div>

<script>
const token = localStorage.getItem('token');
if (!token) window.location.href = '/newlogin.php';

let withdrawMethod = 'bKash';
let savedWallets = {};
let selectedNumber = '';
let currentBalance = 0;

function md5(str) {
    function rotateLeft(n, s) { return (n << s) | (n >>> (32 - s)); }
    function toHex(n) { let s = '', v; for (let i = 0; i < 4; i++) { v = (n >>> (i * 8)) & 255; s += ('0' + v.toString(16)).slice(-2); } return s; }
    function utf8Encode(str) { return unescape(encodeURIComponent(str)); }
    str = utf8Encode(str);
    const msgLen = str.length;
    const numBlocks = (((msgLen + 8) >>> 6) + 1) * 16;
    const M = new Array(numBlocks).fill(0);
    for (let i = 0; i < msgLen; i++) M[i >> 2] |= str.charCodeAt(i) << ((i % 4) * 8);
    M[msgLen >> 2] |= 0x80 << ((msgLen % 4) * 8);
    M[numBlocks - 2] = msgLen * 8;
    let a = 1732584193, b = -271733879, c = -1732584194, d = 271733878;
    const S = [7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21];
    const K = [];
    for (let i = 0; i < 64; i++) K[i] = (Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296)) | 0;
    for (let i = 0; i < numBlocks; i += 16) {
        let A = a, B = b, C = c, D = d;
        for (let j = 0; j < 64; j++) {
            let F, g;
            if (j < 16) { F = (B & C) | (~B & D); g = j; }
            else if (j < 32) { F = (D & B) | (~D & C); g = (5 * j + 1) % 16; }
            else if (j < 48) { F = B ^ C ^ D; g = (3 * j + 5) % 16; }
            else { F = C ^ (B | ~D); g = (7 * j) % 16; }
            F = (F + A + K[j] + (M[i + g] | 0)) | 0;
            A = D; D = C; C = B;
            B = (B + rotateLeft(F, S[j])) | 0;
        }
        a = (a + A) | 0; b = (b + B) | 0; c = (c + C) | 0; d = (d + D) | 0;
    }
    return toHex(a) + toHex(b) + toHex(c) + toHex(d);
}

function showMsg(text, ok){
    document.getElementById('msgBox').innerHTML = `<div class="msg ${ok ? 'msg-ok' : 'msg-err'}"><i class="fa-solid ${ok ? 'fa-circle-check' : 'fa-circle-exclamation'}"></i> ${text}</div>`;
}

async function init(){
    const random = Math.random().toString(36).substring(2, 15);
    const shonustr = `{"language":1,"random":"${random}"}`;
    const signature = md5(shonustr).toUpperCase();
    try {
        const res = await fetch('/deepanshu/api/webapi/GetBalance.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
            body: JSON.stringify({ language: 1, random, signature, timestamp: Date.now() })
        });
        const data = await res.json();
        document.getElementById('loadingState').classList.add('hidden');
        document.getElementById('mainContent').classList.remove('hidden');
        if (data.code === 0 && data.data) {
            currentBalance = Number(data.data.amount);
            document.getElementById('cashBalance').textContent = currentBalance.toLocaleString('en-IN', {maximumFractionDigits: 2});
            renderQuickAmounts();
        }
    } catch (e) {
        document.getElementById('loadingState').textContent = 'Load করা যায়নি।';
    }
}

function renderQuickAmounts() {
    const amounts = [500, 1000, 2000];
    const container = document.getElementById('quickAmts');
    container.innerHTML = amounts.map(a => `<div class="quick-amt" onclick="setQuickAmount(${a}, this)">৳${a}</div>`).join('');
}
function setQuickAmount(amt, el) {
    document.getElementById('wdAmount').value = amt;
    document.querySelectorAll('.quick-amt').forEach(e => e.classList.remove('active'));
    el.classList.add('active');
}
function onAmountInput() {
    document.querySelectorAll('.quick-amt').forEach(e => e.classList.remove('active'));
}

document.getElementById('wdAmount')?.addEventListener('focus', () => document.getElementById('amountBox').classList.add('focused'));
document.getElementById('wdAmount')?.addEventListener('blur', () => document.getElementById('amountBox').classList.remove('focused'));

function fillAll(){
    document.getElementById('wdAmount').value = currentBalance;
    onAmountInput();
}

function selectMethod(type){
    withdrawMethod = type;
    document.getElementById('wmtd-bKash').classList.toggle('active', type === 'bKash');
    document.getElementById('wmtd-Nagad').classList.toggle('active', type === 'Nagad');
    renderWalletBox();
}

async function loadSavedWallets() {
    try {
        const res = await fetch('/withdraw_wallets_api.php?action=list', { headers: { 'Authorization': 'Bearer ' + token } });
        const data = await res.json();
        if (data.code === 0) savedWallets = data.wallets || {};
        renderWalletBox();
    } catch (e) { renderWalletBox(); }
}

function renderWalletBox() {
    const box = document.getElementById('savedWalletBox');
    const addBox = document.getElementById('addWalletBox');
    const num = savedWallets[withdrawMethod];

    if (num) {
        selectedNumber = num;
        addBox.style.display = 'none';
        box.innerHTML = `
            <div class="saved-wallet">
                <div class="badge" style="background:#fff; padding:6px;"><img src="${withdrawMethod === 'bKash' ? 'https://cv111.site/pay/images/images.png' : 'https://cv111.site/pay/images/unnamed.png'}" style="width:100%; height:100%; object-fit:contain;"></div>
                <div class="info"><div class="num">${num}</div><div class="type">${withdrawMethod} Account</div></div>
                <div class="change-link" onclick="showAddForm()">Change</div>
            </div>
        `;
    } else {
        selectedNumber = '';
        box.innerHTML = '';
        addBox.style.display = 'block';
    }
}

function showAddForm() {
    document.getElementById('savedWalletBox').innerHTML = '';
    document.getElementById('addWalletBox').style.display = 'block';
}

async function saveWallet() {
    const num = document.getElementById('newAccNumber').value.trim();
    if (!/^01[0-9]{9}$/.test(num)) { showMsg('সঠিক ১১-সংখ্যার Number দাও।', false); return; }
    try {
        const res = await fetch('/withdraw_wallets_api.php?action=save', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
            body: JSON.stringify({ walletType: withdrawMethod, accountNumber: num })
        });
        const data = await res.json();
        if (data.code === 0) {
            savedWallets[withdrawMethod] = num;
            document.getElementById('newAccNumber').value = '';
            renderWalletBox();
            showMsg('Number Save হয়েছে!', true);
        } else {
            showMsg(data.msg || 'ব্যর্থ হয়েছে।', false);
        }
    } catch (e) { showMsg('একটা সমস্যা হয়েছে।', false); }
}

async function submitWithdraw(){
    const amount = parseFloat(document.getElementById('wdAmount').value);
    const bid = selectedNumber;
    const pwd = document.getElementById('loginPwd').value;
    const btn = document.getElementById('submitBtn');

    if (!amount || amount < 150) { showMsg('সর্বনিম্ন ৳150 Withdraw করা যাবে।', false); return; }
    if (amount > currentBalance) { showMsg('Balance-এর চেয়ে বেশি Withdraw করা যাবে না।', false); return; }
    if (!bid) { showMsg('আগে একটা Number Save করো।', false); return; }
    if (!pwd) { showMsg('Password দাও।', false); return; }

    // ✅ নতুন যোগ — Wagering-Requirement Check (Deposit-এর সমান
    // Bet করা হয়েছে কিনা, তা যাচাই করে, তবেই Withdraw এগোতে দেওয়া)
    btn.disabled = true;
    btn.textContent = 'যাচাই হচ্ছে...';
    try {
        const wagerRes = await fetch('/check_wagering_requirement.php', {
            headers: { 'Authorization': 'Bearer ' + token }
        });
        const wagerData = await wagerRes.json();
        if (!wagerData.eligible) {
            showMsg(wagerData.msg || 'এখনো Withdraw করার শর্ত পূরণ হয়নি।', false);
            btn.disabled = false;
            btn.textContent = 'Withdraw করো';
            return;
        }
    } catch (e) {
        showMsg('Wagering-Check করতে সমস্যা হয়েছে, আবার চেষ্টা করো।', false);
        btn.disabled = false;
        btn.textContent = 'Withdraw করো';
        return;
    }

    btn.textContent = 'পাঠানো হচ্ছে...';

    const random = Math.random().toString(36).substring(2, 15);
    const type = withdrawMethod === 'bKash' ? 1 : 2;
    const shonustr = `{"amount":${amount},"bid":"${bid}","language":1,"pwd":"${pwd}","random":"${random}","type":${type}}`;
    const signature = md5(shonustr).toUpperCase();

    try {
        const res = await fetch('/deepanshu/api/webapi/NewSetWithdrawal.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
            body: JSON.stringify({ amount, bid, language: 1, pwd, random, signature, type, timestamp: Date.now() })
        });
        const data = await res.json();
        if (data.code === 0) {
            document.getElementById('successAmt').textContent = '৳' + amount.toLocaleString('en-IN');
            document.getElementById('withdrawSuccessOverlay').classList.remove('hidden');
            setTimeout(() => { window.location.href = '/newhome.php'; }, 5000);
        } else {
            showMsg(data.msg || 'Withdraw ব্যর্থ হয়েছে।', false);
            btn.disabled = false;
            btn.textContent = 'Withdraw করো';
        }
    } catch (e) {
        showMsg('একটা সমস্যা হয়েছে।', false);
        btn.disabled = false;
        btn.textContent = 'Withdraw করো';
    }
}

// ✅ নতুন যোগ — User-এর বর্তমান Wagering-Progress দেখানো
async function loadWageringStatus() {
    const statusBox = document.getElementById('wageringStatus');
    try {
        const res = await fetch('/check_wagering_requirement.php', {
            headers: { 'Authorization': 'Bearer ' + token }
        });
        const data = await res.json();

        if (data.eligible) {
            statusBox.innerHTML = `
                <div style="display:flex; align-items:center; gap:8px; color:#22D67A; font-size:12px; font-weight:700;">
                    <i class="fa-solid fa-circle-check"></i> শর্ত পূরণ হয়েছে — তুমি এখন Withdraw করতে পারবে
                </div>
            `;
        } else {
            const pct = data.required_win > 0 ? Math.min(100, (data.current_win / data.required_win) * 100) : 0;
            // ✅ নতুন যোগ — Bonus-Requirement হলে, "Win" এর বদলে "Bet" Label
            // (কারণ Bonus-Wagering আসলে মোট Bet-Amount Track করে)
            const actionWord = data.is_bonus_requirement ? 'Bet' : 'Win';
            const badgeText = data.is_bonus_requirement ? '🎁 ১৫০% Bonus-Wagering বাকি আছে' : `আরও ৳${data.remaining_win} Win করতে হবে`;
            statusBox.innerHTML = `
                <div style="color:#F5C542; font-size:12px; font-weight:700; margin-bottom:8px;">
                    <i class="fa-solid fa-circle-exclamation"></i> ${badgeText}
                </div>
                <div style="background:rgba(255,255,255,.08); border-radius:10px; height:6px; overflow:hidden;">
                    <div style="background:linear-gradient(90deg,#9B5DE5,#F5C542); height:100%; width:${pct}%;"></div>
                </div>
                <div style="color:#9691B0; font-size:10px; margin-top:6px;">
                    ৳${data.current_win} / ৳${data.required_win} ${actionWord} করা হয়েছে ${data.is_bonus_requirement ? '' : '(Deposit-এর সমান)'}
                </div>
            `;
        }
    } catch (e) {
        statusBox.innerHTML = '<div style="color:#9691B0; font-size:11px;">Status লোড করা যায়নি।</div>';
    }
}

init();
loadSavedWallets();
loadWageringStatus();
</script>
</body>
</html>
