/* newpur.js — New Purchase Module */

var VORI = 11.664;
var KARAT_RATIO = {'24K':1,'22K':0.9167,'21K':0.875,'18K':0.75,'other':0.7};
var currentPurId = 0;
var currentRemaining = 0;

function G(id){ return document.getElementById(id); }
function fmt(n){ return Number(parseFloat(n)||0).toLocaleString('en-IN',{minimumFractionDigits:2,maximumFractionDigits:2}); }

/* ── Date helpers ── */
function today(){
  var d = new Date();
  var m = String(d.getMonth()+1).padStart(2,'0');
  var day = String(d.getDate()).padStart(2,'0');
  return d.getFullYear()+'-'+m+'-'+day;
}

/* ── Init ── */
document.addEventListener('DOMContentLoaded', function(){
  G('fromDate').value = today();
  G('toDate').value   = today();
  G('mDate').value    = today();

  loadSummary();
  loadList();
  loadParties();
  loadCashAccounts();

  /* Weight inputs */
  ['wVori','wAna','wRoti','wPoint'].forEach(function(id){
    G(id).addEventListener('input', calcWeight);
  });

  /* Rate / Karat / Pieces */
  G('mRate').addEventListener('input', calcAmount);
  G('mKarat').addEventListener('change', calcAmount);
  G('mPieces').addEventListener('input', calcAmount);

  /* Payment method toggle */
  G('mPayment').addEventListener('change', function(){
    G('cashAccDiv').style.display = this.value==='1' ? '' : 'none';
  });

  /* Buttons — onclick already set in HTML */
  G('searchBtn').addEventListener('click', function(){ loadSummary(); loadList(); });
});

/* ── Weight Calculation ── */
function calcWeight(){
  var v = parseFloat(G('wVori').value)||0;
  var a = parseFloat(G('wAna').value)||0;
  var r = parseFloat(G('wRoti').value)||0;
  var p = parseFloat(G('wPoint').value)||0;
  var gram = v*VORI + a*(VORI/16) + r*(VORI/96) + p*(VORI/960);

  G('wGram').textContent      = gram.toFixed(3);
  G('wVoriShow').textContent  = v;
  G('wAnaShow').textContent   = a;
  G('wRotiShow').textContent  = r;
  G('wPointShow').textContent = p;
  calcAmount();
}

function calcAmount(){
  var karat  = G('mKarat').value || '22K';
  var ratio  = KARAT_RATIO[karat] || 0.9167;
  var gram   = parseFloat(G('wGram').textContent)||0;
  var rate   = parseFloat(G('mRate').value)||0;
  var pieces = parseInt(G('mPieces').value)||1;
  var pure   = gram * ratio;
  var rateG  = rate / VORI;
  var total  = gram * rateG;
  var wpp    = pieces > 0 ? gram/pieces : 0;

  G('cRatio').textContent  = (ratio*100).toFixed(2)+'%';
  G('cGross').textContent  = gram.toFixed(3)+' গ্রাম';
  G('cPure').textContent   = pure.toFixed(3)+' গ্রাম';
  G('cRateG').textContent  = '৳'+rateG.toFixed(2)+'/গ্রাম';
  G('cWpp').textContent    = wpp.toFixed(3)+' গ্রাম/পিস';
  G('cTotal').textContent  = '৳'+Math.round(total).toLocaleString('en-IN');
}

/* ── Load Parties ── */
function loadParties(){
  fetch('../api/parties/get_parties.php?limit=200',{credentials:'same-origin'})
  .then(function(r){return r.json();})
  .then(function(res){
    var sel = G('mParty');
    sel.innerHTML = '<option value="">— সাপ্লায়ার বাছাই করুন —</option>';
    var list = (res.data&&(Array.isArray(res.data)?res.data:(res.data.parties||[]))) || [];
    list.forEach(function(p){
      var o = document.createElement('option');
      o.value = p.id;
      o.textContent = p.name+(p.phone?' — '+p.phone:'');
      sel.appendChild(o);
    });
  }).catch(function(){});
}

/* ── Load Cash Accounts ── */
function loadCashAccounts(){
  fetch('../api/cash/get_accounts.php',{credentials:'same-origin'})
  .then(function(r){return r.json();})
  .then(function(res){
    var sel = G('mCashAcc');
    sel.innerHTML = '';
    var list = (res.data&&(Array.isArray(res.data)?res.data:(res.data.accounts||[]))) || [];
    list.forEach(function(a){
      var o = document.createElement('option');
      o.value = a.id;
      o.textContent = a.account_name+' (৳'+Number(a.current_balance).toLocaleString('en-IN')+')';
      sel.appendChild(o);
    });
  }).catch(function(){});
}

/* ── Load Summary ── */
function loadSummary(){
  var from = G('fromDate').value;
  var to   = G('toDate').value;
  fetch('../api/new_purchase/get_new_purchases.php?from_date='+from+'&to_date='+to,{credentials:'same-origin'})
  .then(function(r){return r.json();})
  .then(function(res){
    var list = (res.data&&res.data.purchases) || [];
    var entries=0, amount=0, gross=0, pieces=0;
    list.forEach(function(p){
      entries++;
      amount += parseFloat(p.total_amount||0);
      gross  += parseFloat(p.gross_weight||0);
      pieces += parseInt(p.total_pieces||0);
    });
    G('sumEntries').textContent = entries;
    G('sumAmount').textContent  = '৳'+Math.round(amount).toLocaleString('en-IN');
    G('sumGross').textContent   = gross.toFixed(3)+'g';
    G('sumPieces').textContent  = pieces;
  }).catch(function(){});
}

/* ── Load List ── */
function lpur(){
  loadSummary();
  loadList();
}

function loadList(){
  var from = G('fromDate').value;
  var to   = G('toDate').value;
  G('purList').innerHTML = '<div class="empty">লোড হচ্ছে...</div>';
  fetch('../api/new_purchase/get_new_purchases.php?from_date='+from+'&to_date='+to,{credentials:'same-origin'})
  .then(function(r){return r.text();})
  .then(function(txt){
    var res;
    try{res=JSON.parse(txt);}catch(e){G('purList').innerHTML='<div class="empty">রেসপন্স পার্স সমস্যা</div>';return;}
    if(!res||!res.success||!res.data){G('purList').innerHTML='<div class="empty">লোড হয়নি</div>';return;}
    var list = res.data.purchases||[];
    if(!list.length){G('purList').innerHTML='<div class="empty">কোনো রেকর্ড নেই</div>';return;}
    var html='';
    list.forEach(function(p){
      var kc = 'k-'+((p.karat||'other').toLowerCase().replace('k',''));
      if(['k-24','k-22','k-21','k-18'].indexOf(kc)===-1) kc='k-other';
      var remaining = parseInt(p.total_pieces||0) - parseInt(p.barcode_count||0);
      html += '<div class="pur-card">';
      html += '<div class="pur-top">';
      html += '<div><div class="pur-name">'+(p.item_name||'—')+'</div>';
      html += '<div class="pur-supplier">'+(p.supplier_name||'সাপ্লায়ার নেই')+'</div>';
      html += '<div class="pur-date">📅 '+(p.purchase_date||'')+'</div></div>';
      html += '<span class="pur-karat '+kc+'">'+(p.karat||'')+'</span>';
      html += '</div>';
      html += '<div class="pur-details">';
      html += '<div class="pur-detail"><div class="dl">গ্রস ওজন</div><div class="dv">'+parseFloat(p.gross_weight||0).toFixed(3)+'</div><div class="ds">গ্রাম</div></div>';
      html += '<div class="pur-detail"><div class="dl">পিস</div><div class="dv">'+(p.total_pieces||0)+'</div><div class="ds">পিস</div></div>';
      html += '<div class="pur-detail"><div class="dl">বারকোড</div><div class="dv">'+(p.barcode_count||0)+'</div><div class="ds">তৈরি</div></div>';
      html += '</div>';
      html += '<div class="pur-bottom">';
      html += '<div><div class="pur-amount">৳'+Math.round(p.total_amount||0).toLocaleString('en-IN')+'</div>';
      html += '<div class="pur-loc">📍 '+(p.location_name||'')+'</div></div>';
      html += '<div class="pur-actions">';
      if(remaining>0){
        html += '<button class="bc-btn" onclick="openBcModal('+p.id+','+remaining+','+parseFloat(p.gross_weight||0).toFixed(3)+')">🏷️ বারকোড</button>';
        html += '<div class="bc-done">'+remaining+' পিস বাকি</div>';
      } else {
        html += '<div class="bc-done">✅ সব বারকোড হয়েছে</div>';
      }
      html += '</div></div></div>';
    });
    G('purList').innerHTML = html;
  })
  .catch(function(e){G('purList').innerHTML='<div class="empty">এরর: '+e.message+'</div>';});
}

/* ── Modal ── */
function openModal(){
  G('purModal').classList.add('show');
  G('mDate').value = today();
  G('mOk').style.display = 'none';
  G('mEr').style.display = 'none';
  G('mBtn').disabled = false;
  G('mBtn').textContent = '💾 ক্রয় সেভ করুন';
  loadParties();
  loadCashAccounts();
}

function closeModal(){
  G('purModal').classList.remove('show');
  G('wVori').value = '';
  G('wAna').value  = '';
  G('wRoti').value = '';
  G('wPoint').value= '';
  G('mRate').value = '';
  G('mNote').value = '';
  G('mPieces').value = '1';
  G('mItemName').value = '';
  G('wGram').textContent      = '০.০০০';
  G('wVoriShow').textContent  = '০';
  G('wAnaShow').textContent   = '০';
  G('wRotiShow').textContent  = '০';
  G('wPointShow').textContent = '০';
  calcAmount();
}

/* ── Save Purchase ── */
function savePurchase(){
  var btn   = G('mBtn');
  var gram  = parseFloat(G('wGram').textContent)||0;
  var karat = G('mKarat').value;
  var ratio = KARAT_RATIO[karat]||0.9167;
  var rate  = parseFloat(G('mRate').value)||0;
  var total = gram * (rate/VORI);

  var data = {
    purchase_date:     G('mDate').value,
    item_name:         G('mItemName').value.trim(),
    party_id:          parseInt(G('mParty').value)||0,
    karat:             karat,
    total_pieces:      parseInt(G('mPieces').value)||1,
    location_id:       parseInt(G('mLocation').value)||1,
    gross_weight:      gram,
    pure_weight:       parseFloat((gram*ratio).toFixed(3)),
    rate_per_vori:     rate,
    total_amount:      parseFloat(total.toFixed(2)),
    payment_method_id: parseInt(G('mPayment').value)||1,
    cash_account_id:   parseInt(G('mCashAcc').value)||0,
    note:              G('mNote').value.trim()
  };

  if(!data.purchase_date)   return showMErr('তারিখ দিন');
  if(!data.item_name)       return showMErr('আইটেমের নাম দিন');
  if(data.gross_weight<=0)  return showMErr('ওজন দিন');
  if(data.rate_per_vori<=0) return showMErr('রেট দিন');

  btn.disabled=true; btn.textContent='সেভ হচ্ছে...';

  fetch('../api/new_purchase/add_new_purchase.php',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    credentials:'same-origin',
    body:JSON.stringify(data)
  })
  .then(function(r){return r.json();})
  .then(function(res){
    if(res&&res.success){
      G('mOk').style.display='block';
      G('mOk').textContent='✅ সেভ হয়েছে!';
      loadSummary(); loadList();
      setTimeout(closeModal, 1500);
    } else {
      showMErr('❌ '+(res.message||'সমস্যা হয়েছে'));
    }
    btn.disabled=false; btn.textContent='💾 ক্রয় সেভ করুন';
  })
  .catch(function(){
    showMErr('নেটওয়ার্ক এরর');
    btn.disabled=false; btn.textContent='💾 ক্রয় সেভ করুন';
  });
}

function showMErr(msg){
  G('mEr').style.display='block';
  G('mEr').textContent=msg;
}

/* ── Barcode Modal ── */
function openBcModal(id, remaining, totalGram){
  currentPurId     = id;
  currentRemaining = remaining;
  G('bcModal').classList.add('show');
  G('bcTitle').textContent     = '🏷️ বারকোড তৈরি করুন — #'+id;
  G('bcRemaining').textContent = 'বাকি: '+remaining+' পিস';
  G('bcPieces').value  = remaining;
  G('bcWpp').value     = remaining>0 ? (totalGram/remaining).toFixed(3) : '';
  G('bcOk').style.display = 'none';
  G('bcEr').style.display = 'none';
  G('bcResult').innerHTML = '';
  G('bcBtn').disabled = false;
  G('bcBtn').textContent = '✅ বারকোড তৈরি করুন';
}

function closeBcModal(){
  G('bcModal').classList.remove('show');
}

/* ── Generate Barcode ── */
function generateBarcode(){
  var btn      = G('bcBtn');
  var pieces   = parseInt(G('bcPieces').value)||0;
  var wpp      = parseFloat(G('bcWpp').value)||0;
  var saleRate = parseFloat(G('bcSaleRate').value)||0;

  G('bcEr').style.display='none';

  if(pieces<=0)               return (G('bcEr').style.display='block', G('bcEr').textContent='পিস সংখ্যা দিন');
  if(pieces>currentRemaining) return (G('bcEr').style.display='block', G('bcEr').textContent='সর্বোচ্চ '+currentRemaining+' পিস');
  if(wpp<=0)                  return (G('bcEr').style.display='block', G('bcEr').textContent='প্রতি পিসের ওজন দিন');

  btn.disabled=true; btn.textContent='তৈরি হচ্ছে...';

  fetch('../api/new_purchase/generate_barcode.php',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    credentials:'same-origin',
    body:JSON.stringify({
      purchase_id:        currentPurId,
      pieces:             pieces,
      weight_per_piece:   wpp,
      sale_rate_per_vori: saleRate
    })
  })
  .then(function(r){return r.json();})
  .then(function(res){
    if(res&&res.success){
      G('bcOk').style.display='block';
      G('bcOk').textContent='✅ '+pieces+' টি বারকোড তৈরি হয়েছে!';
      var barcodes = (res.data&&res.data.barcodes)||[];
      var html='';
      barcodes.forEach(function(b){
        html+='<div class="bc-item">';
        html+='<div class="bc-code">'+(b.barcode_number||b.barcode||'')+'</div>';
        html+='<div class="bc-info">'+parseFloat(b.weight_per_piece||wpp).toFixed(3)+'g | ৳'+(b.sale_rate||saleRate).toLocaleString('en-IN')+'</div>';
        html+='</div>';
      });
      G('bcResult').innerHTML=html;
      loadList();
    } else {
      G('bcEr').style.display='block';
      G('bcEr').textContent='❌ '+(res.message||'সমস্যা হয়েছে');
    }
    btn.disabled=false; btn.textContent='✅ বারকোড তৈরি করুন';
  })
  .catch(function(){
    G('bcEr').style.display='block';
    G('bcEr').textContent='নেটওয়ার্ক এরর';
    btn.disabled=false; btn.textContent='✅ বারকোড তৈরি করুন';
  });
}