(()=>{'use strict';
const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)];
let key=sessionStorage.getItem('lz_admin_key')||'',data=null,pendingAction=null,depositMethods=[];
function money(v){return Number(v||0).toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2})}
function esc(v){return String(v??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]))}
function toast(t,e=false){const x=$('#toast');x.textContent=t;x.classList.toggle('error',e);x.classList.add('show');clearTimeout(toast.t);toast.t=setTimeout(()=>x.classList.remove('show'),2200)}
async function api(url,opt={}){
 const headers={...(opt.headers||{}),'X-Zoo-Admin-Key':key};
 if(opt.body)headers['Content-Type']='application/json';
 const r=await fetch(url,{cache:'no-store',...opt,headers});
 const j=await r.json().catch(()=>({ok:false,error:'Invalid server response'}));
 if(!r.ok||!j.ok)throw new Error(j.error||'Request failed');return j;
}
function status(s){const v=esc(s||'');return `<span class="status ${v}">${v}</span>`}
function depositButtons(d){
 if(d.status!=='pending')return '';
 return `<button class="good" data-kind="deposit" data-id="${d.id}" data-action="confirm">CONFIRM</button>
 <button class="bad" data-kind="deposit" data-id="${d.id}" data-action="reject">REJECT</button>`;
}
function withdrawalButtons(w){
 const s=w.status;
 if(s==='requested')return `<button class="warn" data-kind="withdrawal" data-id="${w.id}" data-action="review">REVIEW</button><button class="good" data-kind="withdrawal" data-id="${w.id}" data-action="approve">APPROVE</button><button class="bad" data-kind="withdrawal" data-id="${w.id}" data-action="reject">REJECT</button>`;
 if(s==='review')return `<button class="good" data-kind="withdrawal" data-id="${w.id}" data-action="approve">APPROVE</button><button class="bad" data-kind="withdrawal" data-id="${w.id}" data-action="reject">REJECT</button>`;
 if(s==='approved')return `<button class="warn" data-kind="withdrawal" data-id="${w.id}" data-action="processing">PROCESSING</button><button class="bad" data-kind="withdrawal" data-id="${w.id}" data-action="reject">REJECT</button>`;
 if(s==='processing')return `<button class="good" data-kind="withdrawal" data-id="${w.id}" data-action="paid">MARK PAID</button>`;
 return '';
}
function bindActions(){
 $$('[data-kind][data-action]').forEach(b=>b.onclick=()=>openAction(b.dataset.kind,Number(b.dataset.id),b.dataset.action));
}

async function loadMethods(){
 try{
   const j=await api('/api/admin_deposit_methods.php?ts='+Date.now());
   depositMethods=j.methods||[];
   renderMethods();
 }catch(e){toast(e.message,true)}
}
function renderMethods(){
 const box=$('#methodEditor');if(!box)return;
 if(!depositMethods.length){box.innerHTML='<div class="empty">JazzCash / Easypaisa method rows are missing. Run the deposit SQL patch.</div>';return}
 box.innerHTML=depositMethods.map(m=>`<article class="method-config" data-method="${esc(m.code)}">
   <div class="method-title"><div><b>${esc(m.name)}</b><small>${esc(m.currency)} • ${m.enabled==1?'ENABLED':'DISABLED'}</small></div>
     <label class="switch"><input type="checkbox" data-f="enabled" ${m.enabled==1?'checked':''}><span></span></label>
   </div>
   <div class="method-fields">
     <label>Destination label<input data-f="destination_label" value="${esc(m.destination_label||'')}" placeholder="JazzCash Number"></label>
     <label>Account / destination<input data-f="destination_value" value="${esc(m.destination_value||'')}" placeholder="03xxxxxxxxx"></label>
     <label>Minimum PKR<input data-f="min_amount" type="number" value="${esc(m.min_amount||100)}"></label>
     <label>Maximum PKR<input data-f="max_amount" type="number" value="${esc(m.max_amount||1000000)}"></label>
   </div>
   <label class="wide-label">Player instructions<textarea data-f="instructions" rows="3">${esc(m.instructions||'')}</textarea></label>
   <button class="save-method" data-save-method="${esc(m.code)}">SAVE ${esc(m.name).toUpperCase()}</button>
 </article>`).join('');
 $$('[data-save-method]').forEach(b=>b.onclick=()=>saveMethod(b.dataset.saveMethod));
}
async function saveMethod(code){
 const card=document.querySelector(`[data-method="${CSS.escape(code)}"]`);if(!card)return;
 const get=f=>card.querySelector(`[data-f="${f}"]`);
 const payload={
   code,
   enabled:get('enabled').checked,
   destination_label:get('destination_label').value.trim(),
   destination_value:get('destination_value').value.trim(),
   min_amount:Number(get('min_amount').value||0),
   max_amount:Number(get('max_amount').value||0),
   instructions:get('instructions').value.trim()
 };
 try{
   const j=await api('/api/admin_deposit_methods.php',{method:'POST',body:JSON.stringify(payload)});
   depositMethods=j.methods||[];renderMethods();toast(`${code} settings saved.`);
 }catch(e){toast(e.message,true)}
}

function render(){
 const s=data.summary||{};
 $('#pendingDeposits').textContent=s.pending_deposits_count||0;$('#pendingDepositAmount').textContent=money(s.pending_deposits_amount);
 $('#pendingWithdrawals').textContent=s.pending_withdrawals_count||0;$('#pendingWithdrawalAmount').textContent=money(s.pending_withdrawals_amount);
 $('#confirmedToday').textContent=s.confirmed_deposits_today_count||0;$('#confirmedTodayAmount').textContent=money(s.confirmed_deposits_today_amount);
 $('#paidToday').textContent=s.paid_withdrawals_today_count||0;$('#paidTodayAmount').textContent=money(s.paid_withdrawals_today_amount);

 const deps=data.pending_deposits||[];$('#depCount').textContent=deps.length;
 $('#depositList').innerHTML=deps.length?deps.map(d=>`<article class="item">
   <div class="main"><b>Deposit #${d.id} ${status(d.status)}</b><small>Player: ${esc(d.public_id||d.user_id)} • ${esc(d.method)} • ${esc(d.created_at||'')}</small><small>LuckZoo Ref: ${esc(d.reference)}${d.payer_reference?' • Payer Ref: '+esc(d.payer_reference):' • Payment reference not submitted yet'}</small></div>
   <div class="money">PKR ${money(d.amount)}<small>${d.submitted_at?'Submitted '+esc(d.submitted_at):'Created, awaiting payer reference'}</small></div>
   <div class="actions">${depositButtons(d)}</div>
 </article>`).join(''):'<div class="empty">No pending deposits.</div>';

 const wds=data.pending_withdrawals||[];$('#wdCount').textContent=wds.length;
 $('#withdrawalList').innerHTML=wds.length?wds.map(w=>`<article class="item">
   <div class="main"><b>Withdrawal #${w.id} ${status(w.status)}</b><small>Player: ${esc(w.public_id||w.user_id)} • ${esc(w.phone||'')} • ${esc(w.method)}</small><small>Destination: ${esc(w.destination)}${w.admin_note?' • Note: '+esc(w.admin_note):''}</small></div>
   <div class="money">PKR ${money(w.amount)}<small>${esc(w.created_at||'')}</small></div>
   <div class="actions">${withdrawalButtons(w)}</div>
 </article>`).join(''):'<div class="empty">No pending withdrawals.</div>';

 const dh=data.recent_deposits||[];
 $('#depositHistory').innerHTML=dh.length?dh.map(d=>`<div class="history-row"><div><b>#${d.id} • ${esc(d.public_id||d.user_id)} ${status(d.status)}</b><small>${esc(d.method)} • ${esc(d.reference||'')} • ${esc(d.updated_at||d.created_at||'')}</small></div><strong>PKR ${money(d.status==='confirmed'?d.total_credit:d.amount)}</strong></div>`).join(''):'<div class="empty">No deposits.</div>';
 const wh=data.recent_withdrawals||[];
 $('#withdrawalHistory').innerHTML=wh.length?wh.map(w=>`<div class="history-row"><div><b>#${w.id} • ${esc(w.public_id||w.user_id)} ${status(w.status)}</b><small>${esc(w.method)} • ${esc(w.provider_txn_id||'')} • ${esc(w.processed_at||w.reviewed_at||w.created_at||'')}</small></div><strong>PKR ${money(w.amount)}</strong></div>`).join(''):'<div class="empty">No withdrawals.</div>';
 bindActions();
}
async function load(){
 try{
  const j=await api('/api/admin_cashier.php?ts='+Date.now());
  data=j;$('#loginCard').classList.add('hide');$('#app').classList.remove('hide');$('#loginError').textContent='';render();await loadMethods();
 }catch(e){
  if($('#app').classList.contains('hide'))$('#loginError').textContent=e.message;
  else toast(e.message,true);
 }
}
function openAction(kind,id,action){
 pendingAction={kind,id,action};
 const isDep=kind==='deposit';
 $('#modalTitle').textContent=`${action.toUpperCase()} ${isDep?'DEPOSIT':'WITHDRAWAL'} #${id}`;
 let text='';
 if(isDep&&action==='confirm')text='Confirm only after you have independently verified that the payment was actually received. Confirmation immediately credits the player wallet.';
 else if(isDep&&action==='reject')text='Reject this pending deposit. No player funds will be credited.';
 else if(action==='reject')text='Rejecting a withdrawal refunds the reserved withdrawal amount back to the player wallet.';
 else if(action==='paid')text='Mark as paid only after the payout has actually been sent. A payment reference is required.';
 else text=`Move this withdrawal to ${action}.`;
 $('#modalText').textContent=text;
 const needsRef=(isDep&&action==='confirm')||(!isDep&&action==='paid');
 $('#referenceLabel').textContent=isDep?'Provider / payment reference':'TXID / payment reference';
 $('#referenceLabel').classList.toggle('hide',!needsRef);$('#actionRef').classList.toggle('hide',!needsRef);
 $('#actionRef').value='';$('#actionNote').value='';
 $('#modal').classList.remove('hide');
}
async function executeAction(){
 if(!pendingAction)return;
 const {kind,id,action}=pendingAction,ref=$('#actionRef').value.trim(),note=$('#actionNote').value.trim();
 if(((kind==='deposit'&&action==='confirm')||(kind==='withdrawal'&&action==='paid'))&&!ref)return toast('Payment reference is required.',true);
 $('#confirmAction').disabled=true;
 try{
   if(kind==='deposit'){
     await api('/api/admin_deposit_action.php',{method:'POST',body:JSON.stringify({deposit_id:id,action,provider_reference:ref,note})});
   }else{
     await api('/api/admin_withdrawal_action.php',{method:'POST',body:JSON.stringify({withdrawal_id:id,action,note,txid:ref})});
   }
   $('#modal').classList.add('hide');toast('Action completed.');await load();
 }catch(e){toast(e.message,true)}
 finally{$('#confirmAction').disabled=false}
}
$('#unlock').onclick=()=>{key=$('#adminKey').value.trim();if(!key)return;sessionStorage.setItem('lz_admin_key',key);load()};
$('#adminKey').addEventListener('keydown',e=>{if(e.key==='Enter')$('#unlock').click()});
$('#refresh').onclick=()=>{if(key)load()};
$('#lock').onclick=()=>{sessionStorage.removeItem('lz_admin_key');key='';$('#app').classList.add('hide');$('#loginCard').classList.remove('hide');$('#adminKey').value=''};
$$('.tabs [data-tab]').forEach(b=>b.onclick=()=>{
 $$('.tabs [data-tab]').forEach(x=>x.classList.toggle('active',x===b));
 ['deposits','withdrawals','history','methods'].forEach(t=>$('#'+t+'Pane').classList.toggle('hide',t!==b.dataset.tab));
});
$('#cancelAction').onclick=()=>$('#modal').classList.add('hide');$('#confirmAction').onclick=executeAction;
if(key)load();
})();