var VORI = 11.664;
var ANA = VORI / 16;
var ROTI = VORI / 96;
var POINT = 0.01;

var PURITY_MAP = {
  '24K': 96,
  '22K': 88,
  '21K': 84,
  '18K': 72,
  'bangla': 88,
  'custom': 0
};

var today = new Date().toISOString().split('T')[0];

function tk(n){
  return '\u09F3' + Number(parseFloat(n || 0).toFixed(0)).toLocaleString('en-IN');
}

function g2v(g){
  g = parseFloat(g || 0);

  var v = Math.floor(g / VORI);
  var rem = g - (v * VORI);

  var a = Math.floor(rem / ANA);
  rem -= a * ANA;

  var r = Math.floor(rem / ROTI);
  rem -= r * ROTI;

  var p = Math.round(rem / POINT);

  return v + 'v ' + a + 'a ' + r + 'r ' + p + 'p';
}

function getEl(id){
  return document.getElementById(id);
}

function getNum(id){
  return parseFloat(getEl(id).value || 0);
}

function setText(id, val){
  getEl(id).textContent = val;
}

function getSystemPurityFromType(type){
  return parseFloat(PURITY_MAP[type] || 0);
}

function syncPurityFields(){
  var type = getEl('mKarat').value;
  var systemInput = getEl('mSystemPurity');
  var deductionInput = getEl('mDeduction');

  if(type === 'custom'){
    systemInput.readOnly = false;
    if(parseFloat(systemInput.value || 0) <= 0){
      systemInput.value = '';
    }
  } else {
    systemInput.readOnly = true;
    systemInput.value = getSystemPurityFromType(type).toFixed(2);
  }

  if(deductionInput.value === ''){
    deductionInput.value = '0';
  }

  calculate();
}

function convertWeight(){
  var v = getNum('wVori');
  var a = getNum('wAna');
  var r = getNum('wRoti');
  var p = getNum('wPoint');

  var g = (v * VORI) + (a * ANA) + (r * ROTI) + (p * POINT);

  setText('wGram', g.toFixed(3));
  setText('wVoriShow', v);
  setText('wAnaShow', a);
  setText('wRotiShow', r);
  setText('wPointShow', p);

  calculate();
}

function calculate(){
  var grossGram = parseFloat(getEl('wGram').textContent || 0);
  var rate24kVori = getNum('mRate');

  var systemPurity = getNum('mSystemPurity');
  var deduction = getNum('mDeduction');

  if(deduction < 0){
    deduction = 0;
    getEl('mDeduction').value = '0';
  }

  var actualPurity = systemPurity - deduction;
  if(actualPurity < 0){
    actualPurity = 0;
  }

  getEl('mActualPurity').value = actualPurity.toFixed(2);

  var ratePerPoint = rate24kVori / 96;
  var ratePerGram = rate24kVori / VORI;
  var perVoriPrice = ratePerPoint * actualPurity;
  var purityRatio = actualPurity / 96;
  var pureWeight = grossGram * purityRatio;
  var totalAmount = pureWeight * ratePerGram;

  setText('cSystemPurity', systemPurity.toFixed(2));
  setText('cDeduction', deduction.toFixed(2));
  setText('cActualPurity', actualPurity.toFixed(2));
  setText('cGross', grossGram.toFixed(3) + ' g (' + g2v(grossGram) + ')');
  setText('cPure', pureWeight.toFixed(3) + ' g (' + g2v(pureWeight) + ')');
  setText('cRatePoint', tk(ratePerPoint));
  setText('cRateG', tk(ratePerGram) + '/g');
  setText('cPerVori', tk(perVoriPrice));
  setText('cTotal', tk(totalAmount));
}

function toggleCash(){
  var p = getEl('mPayment').value;
  getEl('cashAccDiv').style.display = (p == '1') ? 'block' : 'none';
}

function resetModalFields(){
  getEl('mDate').value = today;
  getEl('mParty').value = '';
  getEl('mKarat').value = '22K';
  getEl('mLocation').value = '1';
  getEl('mSystemPurity').value = '88.00';
  getEl('mDeduction').value = '0';
  getEl('mActualPurity').value = '88.00';
  getEl('mRate').value = '';
  getEl('mPayment').value = '1';
  getEl('mNote').value = '';

  getEl('wVori').value = '';
  getEl('wAna').value = '';
  getEl('wRoti').value = '';
  getEl('wPoint').value = '';

  setText('wGram', '0.000');
  setText('wVoriShow', '0');
  setText('wAnaShow', '0');
  setText('wRotiShow', '0');
  setText('wPointShow', '0');

  getEl('mOk').style.display = 'none';
  getEl('mEr').style.display = 'none';
  getEl('mBtn').textContent = 'Save Purchase';
  getEl('mBtn').disabled = false;
}

function loadParties(){
  return fetch('../api/parties/get_parties.php?limit=200', {
    method:'GET',
    credentials:'same-origin',
    cache:'no-store'
  })
  .then(function(r){ return r.json(); })
  .then(function(d){
    var s = getEl('mParty');
    s.innerHTML = '<option value="">-- Select Party --</option>';

    if(!d.success || !d.data || !d.data.parties){
      return;
    }

    d.data.parties.forEach(function(p){
      var o = document.createElement('option');
      o.value = p.id;
      o.textContent = p.name + (p.phone ? ' - ' + p.phone : '');
      s.appendChild(o);
    });
  })
  .catch(function(){});
}

function loadCashAccounts(){
  return fetch('../api/cash/get_accounts.php', {
    method:'GET',
    credentials:'same-origin',
    cache:'no-store'
  })
  .then(function(r){ return r.json(); })
  .then(function(d){
    var s = getEl('mCashAcc');
    s.innerHTML = '';

    if(!d.success || !d.data || !d.data.accounts){
      return;
    }

    d.data.accounts.forEach(function(a){
      var o = document.createElement('option');
      o.value = a.id;
      o.textContent = a.account_name + ' (' + tk(a.current_balance) + ')';
      s.appendChild(o);
    });
  })
  .catch(function(){});
}

function loadTodayRate(){
  return fetch('../api/gold/get_rate.php', {
    method:'GET',
    credentials:'same-origin',
    cache:'no-store'
  })
  .then(function(r){ return r.json(); })
  .then(function(d){
    if(!d.success || !d.data){
      return;
    }

    getEl('mRate').value = (parseFloat(d.data.rate_24k || 0) * VORI).toFixed(0);
    calculate();
  })
  .catch(function(){});
}

function openModal(){
  resetModalFields();
  getEl('purModal').style.display = 'block';
  toggleCash();

  Promise.allSettled([
    loadParties(),
    loadCashAccounts(),
    loadTodayRate()
  ]).then(function(){
    syncPurityFields();
    convertWeight();
    calculate();
  });
}

function closeModal(){
  getEl('purModal').style.display = 'none';
}

function getKaratClass(karat){
  var k = String(karat || '').toLowerCase();

  if(k === '24k') return 'k-24';
  if(k === '22k') return 'k-22';
  if(k === '21k') return 'k-21';
  if(k === '18k') return 'k-18';
  if(k === 'bangla' || k === 'sanatan') return 'k-bangla';
  if(k === 'custom') return 'k-custom';

  return 'k-custom';
}

function lpur(){
  var f = getEl('fromDate').value;
  var t = getEl('toDate').value;

  getEl('purList').innerHTML = '<div class="empty">Loading...</div>';

  fetch('../api/purchases/get_purchases.php?from_date=' + encodeURIComponent(f) + '&to_date=' + encodeURIComponent(t) + '&limit=50', {
    method:'GET',
    credentials:'same-origin',
    cache:'no-store'
  })
  .then(function(r){ return r.json(); })
  .then(function(d){
    if(!d.success){
      getEl('purList').innerHTML = '<div class="empty">' + (d.message || 'Error!') + '</div>';
      return;
    }

    var ps = d.data.purchases || [];
    var sm = d.data.summary || {};

    setText('sumEntries', sm.total_entries || 0);
    setText('sumAmount', tk(sm.total_amount || 0));
    setText('sumGross', g2v(sm.total_gross || 0));
    setText('sumPure', g2v(sm.total_pure || 0));

    if(ps.length === 0){
      getEl('purList').innerHTML = '<div class="empty">No purchase found</div>';
      return;
    }

    var html = '';

    ps.forEach(function(p){
      var kc = getKaratClass(p.karat);
      var rv = parseFloat(p.rate_24k || 0) * VORI;
      var partyName = (p.party_name || 'Unknown').replace(/'/g, '&#39;');

      html += '<div class="pur-card">';
      html += '<div class="pur-top"><div>';
      html += '<div class="pur-party">' + (p.party_name || 'Unknown') + '</div>';
      html += '<div class="pur-date">' + (p.purchase_date || '') + ' | #' + p.id + '</div>';
      html += '</div><span class="pur-karat ' + kc + '">' + (p.karat || '') + '</span></div>';

      html += '<div class="pur-details">';
      html += '<div class="pur-detail"><div class="lbl">Gross</div><div class="val">' + parseFloat(p.gross_weight || 0).toFixed(3) + 'g</div><div class="val2">' + g2v(p.gross_weight || 0) + '</div></div>';
      html += '<div class="pur-detail"><div class="lbl">Pure</div><div class="val">' + parseFloat(p.pure_weight || 0).toFixed(3) + 'g</div><div class="val2">' + g2v(p.pure_weight || 0) + '</div></div>';
      html += '<div class="pur-detail"><div class="lbl">Rate/vori</div><div class="val">' + tk(rv) + '</div></div>';
      html += '</div>';

      html += '<div class="pur-bottom">';
      html += '<div class="pur-amount">' + tk(p.total_amount || 0) + '</div>';
      html += '<div class="pur-meta"><div class="loc">' + (p.location_name || '') + '</div><div class="pay">' + (p.payment_method || 'CASH') + '</div></div>';
      html += '</div>';

      html += '<div style="padding-top:10px;border-top:1px solid rgba(255,255,255,0.06);text-align:right;margin-top:10px;">';
      html += '<button class="del-pur-btn" onclick="deletePurchase(' + p.id + ',\'' + tk(p.total_amount || 0) + '\',\'' + partyName + '\')">Delete</button>';
      html += '</div>';
      html += '</div>';
    });

    getEl('purList').innerHTML = html;
  })
  .catch(function(){
    getEl('purList').innerHTML = '<div class="empty">Error!</div>';
  });
}

function savePurchase(){
  var grossGram = parseFloat(getEl('wGram').textContent || 0);
  var rate24kVori = getNum('mRate');
  var systemPurity = getNum('mSystemPurity');
  var deduction = getNum('mDeduction');
  var actualPurity = parseFloat(getEl('mActualPurity').value || 0);

  var er = getEl('mEr');
  var ok = getEl('mOk');

  er.style.display = 'none';
  ok.style.display = 'none';

  if(grossGram <= 0){
    er.style.display = 'block';
    er.textContent = 'Weight দিন!';
    return;
  }

  if(rate24kVori <= 0){
    er.style.display = 'block';
    er.textContent = 'Rate দিন!';
    return;
  }

  if(systemPurity <= 0){
    er.style.display = 'block';
    er.textContent = 'System purity সঠিক দিন!';
    return;
  }

  if(actualPurity <= 0){
    er.style.display = 'block';
    er.textContent = 'Actual purity সঠিক দিন!';
    return;
  }

  if(actualPurity > systemPurity){
    er.style.display = 'block';
    er.textContent = 'Actual purity, system purity-এর বেশি হতে পারবে না!';
    return;
  }

  var btn = getEl('mBtn');
  var pv = getEl('mParty').value;

  btn.disabled = true;
  btn.textContent = 'Saving...';

  var paymentMethodId = parseInt(getEl('mPayment').value || 0);
  var cashAccountId = getEl('mCashAcc').value ? parseInt(getEl('mCashAcc').value) : null;

  var payload = {
    purchase_date: getEl('mDate').value,
    party_id: pv ? parseInt(pv) : null,
    location_id: parseInt(getEl('mLocation').value || 0),
    karat: getEl('mKarat').value,
    system_purity: systemPurity,
    deduction: deduction,
    actual_purity: actualPurity,
    gross_weight: grossGram,
    rate_24k: rate24kVori / VORI,
    payment_method_id: paymentMethodId,
    cash_account_id: paymentMethodId === 1 ? cashAccountId : null,
    note: getEl('mNote').value
  };

  fetch('../api/purchases/add_purchase.php', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    credentials:'same-origin',
    body:JSON.stringify(payload)
  })
  .then(function(r){ return r.json(); })
  .then(function(d){
    btn.disabled = false;
    btn.textContent = 'Save Purchase';

    if(d.success){
      ok.style.display = 'block';
      ok.textContent = 'Saved! Pure: ' + g2v(d.data.pure_weight || 0) + ' | ' + tk(d.data.total_amount || 0);

      setTimeout(function(){
        closeModal();
        setTimeout(function(){ lpur(); }, 300);
      }, 1500);
    } else {
      er.style.display = 'block';
      er.textContent = d.message || 'Error!';
    }
  })
  .catch(function(){
    btn.disabled = false;
    btn.textContent = 'Save Purchase';
    er.style.display = 'block';
    er.textContent = 'Server error!';
  });
}

document.addEventListener('DOMContentLoaded', function(){
  getEl('fromDate').value = today;
  getEl('toDate').value = today;
  getEl('mDate').value = today;

  getEl('addBtn').onclick = openModal;
  getEl('cancelBtn').onclick = closeModal;
  getEl('mBtn').onclick = savePurchase;
  getEl('searchBtn').onclick = lpur;

  ['wVori','wAna','wRoti','wPoint'].forEach(function(id){
    getEl(id).addEventListener('input', convertWeight);
    getEl(id).addEventListener('change', convertWeight);
  });

  getEl('mKarat').addEventListener('change', syncPurityFields);
  getEl('mSystemPurity').addEventListener('input', calculate);
  getEl('mSystemPurity').addEventListener('change', calculate);
  getEl('mDeduction').addEventListener('input', calculate);
  getEl('mDeduction').addEventListener('change', calculate);
  getEl('mRate').addEventListener('input', calculate);
  getEl('mRate').addEventListener('change', calculate);
  getEl('mPayment').addEventListener('change', toggleCash);

  loadParties();
  loadCashAccounts();
  syncPurityFields();
  lpur();
});