/* pledge_view.js — locker move fixed version */

function fmt(n){
  return Number(Math.round(n) || 0).toLocaleString('en-IN');
}

function fmtD(n){
  return Number(parseFloat(n) || 0).toLocaleString('en-IN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
}

/* ══ LOCKER MODAL ══ */
function openLock(){
  var m = document.getElementById('modalLock');
  if(!m) return;

  m.style.display = 'block';
  m.classList.add('show');

  doCalc();

  fetch('/api/cash/get_accounts.php', {credentials:'same-origin'})
  .then(function(r){ return r.json(); })
  .then(function(res){
    var sel = document.getElementById('lAcc');
    if(!sel) return;

    sel.innerHTML = '<option value="">— select করুন —</option>';

    var list = [];
    if(res && res.data){
      list = Array.isArray(res.data) ? res.data : (res.data.accounts || []);
    }

    list.forEach(function(a){
      var o = document.createElement('option');
      o.value = a.id;

      var name = a.account_name_bn || a.account_name || ('Account #' + a.id);
      var bal  = Number(a.current_balance || 0).toLocaleString('en-IN');

      o.textContent = name + ' (৳' + bal + ')';
      sel.appendChild(o);
    });
  })
  .catch(function(e){
    console.warn(e);
  });
}

function closeLock(){
  var m = document.getElementById('modalLock');
  if(m){
    m.style.display = 'none';
    m.classList.remove('show');
  }
}

function doCalc(){
  var amt  = parseFloat((document.getElementById('lAmt')  || {}).value) || 0;
  var cr   = parseFloat((document.getElementById('lCR')   || {}).value) || 0;
  var lr   = parseFloat((document.getElementById('lLR')   || {}).value) || 0;
  var LOAN = parseFloat((document.getElementById('lLoan') || {}).value) || 0;

  var diffRate = Math.max(0, cr - lr);
  var net      = amt - LOAN;

  /*
    ব্যবসার ভাষা:
    এটা “লাভ” না বলে “ভাড়ার পার্থক্য”
  */
  var rentDiffAmount = LOAN * (diffRate / 100);

  var lpr = document.getElementById('lPR');
  var fI  = document.getElementById('fI');
  var fO  = document.getElementById('fO');
  var fN  = document.getElementById('fN');
  var pA  = document.getElementById('pA');
  var pS  = document.getElementById('pS');
  var pC  = document.getElementById('pC');

  if(lpr) lpr.value = diffRate.toFixed(2);

  if(fI) fI.textContent = fmt(amt);
  if(fO) fO.textContent = fmt(LOAN);

  if(fN){
    if(net >= 0){
      fN.style.color = '#22c55e';
      fN.textContent = '+ ' + fmt(net) + ' ৳';
    } else {
      fN.style.color = '#f87171';
      fN.textContent = '- ' + fmt(Math.abs(net)) + ' ৳';
    }
  }

  if(pA) pA.textContent = '৳' + fmt(Math.round(rentDiffAmount));

  if(pS){
    pS.textContent = '৳' + fmt(LOAN) + ' × ' + diffRate.toFixed(2) + '% = প্রতি মাসে';
  }

  if(pC){
    pC.textContent = 'গ্রাহক দেয় ' + cr + '% — লকারকে ' + lr + '% = ' + diffRate.toFixed(2) + '% ভাড়ার পার্থক্য';
  }
}

function doAlert(msg, t){
  var b = document.getElementById('mAl');
  if(!b) return;

  b.textContent = msg;
  b.className = 'mal ' + t;
  b.style.display = 'block';

  if(t === 'ok'){
    setTimeout(function(){
      b.style.display = 'none';
    }, 3000);
  }
}

function doSave(){
  var btn = document.getElementById('btnSave');

  var date     = (document.getElementById('lDate') || {}).value || '';
  var acc      = parseInt((document.getElementById('lAcc') || {}).value) || 0;
  var amt      = parseFloat((document.getElementById('lAmt') || {}).value) || 0;
  var cr       = parseFloat((document.getElementById('lCR') || {}).value) || 0;
  var lr       = parseFloat((document.getElementById('lLR') || {}).value) || 0;
  var note     = ((document.getElementById('lNote') || {}).value || '').trim();
  var lockerId = parseInt((document.getElementById('lLockerId') || {}).value) || 0;
  var PID      = parseInt((document.getElementById('hdnPid') || {}).value) || 0;

  if(!PID)      return doAlert('❌ বন্ধক ID পাওয়া যায়নি', 'err');
  if(!lockerId) return doAlert('❌ লকার select করুন', 'err');
  if(!date)     return doAlert('❌ তারিখ দিন', 'err');
  if(!acc)      return doAlert('❌ Cash account select করুন', 'err');
  if(amt <= 0)  return doAlert('❌ লকার থেকে আসা টাকা দিন', 'err');

  if(btn){
    btn.disabled = true;
    btn.textContent = '⏳ সেভ হচ্ছে...';
  }

  /*
    Important:
    API compatibility এর জন্য locker_amount এবং locker_value দুইটাই পাঠানো হচ্ছে।
    পুরনো API যেটা নেবে, সেটাই value পাবে।
  */
  var payload = {
    pledge_id: PID,
    locker_id: lockerId,
    move_date: date,
    cash_account_id: acc,

    locker_amount: amt,
    locker_value: amt,

    customer_rate: cr,
    locker_rate: lr,
    note: note
  };

  fetch('/api/pawn/pledge_locker_move.php', {
    method: 'POST',
    headers: {'Content-Type':'application/json'},
    credentials: 'same-origin',
    body: JSON.stringify(payload)
  })
  .then(function(r){
    return r.text();
  })
  .then(function(txt){
    var res;

    try {
      res = JSON.parse(txt);
    } catch(e) {
      doAlert('❌ API error: JSON response পাওয়া যায়নি', 'err');
      if(btn){
        btn.disabled = false;
        btn.textContent = '✅ লকারে পাঠান নিশ্চিত করুন';
      }
      return;
    }

    if(res && res.success){
      doAlert('✅ লকারে পাঠানো হয়েছে!', 'ok');
      setTimeout(function(){
        window.location.reload();
      }, 1500);
    } else {
      doAlert('❌ ' + (res.message || 'Error'), 'err');
      if(btn){
        btn.disabled = false;
        btn.textContent = '✅ লকারে পাঠান নিশ্চিত করুন';
      }
    }
  })
  .catch(function(){
    doAlert('❌ Network error', 'err');
    if(btn){
      btn.disabled = false;
      btn.textContent = '✅ লকারে পাঠান নিশ্চিত করুন';
    }
  });
}

/* ══ CLOSE / RETURN — নতুন page-এ redirect ══ */
function openClose(){
  var PID = parseInt((document.getElementById('hdnPid') || {}).value) || 0;

  if(!PID){
    var params = new URLSearchParams(window.location.search);
    PID = parseInt(params.get('pledge_id')) || 0;
  }

  if(PID > 0){
    window.location.href = '/pledge_close.php?pledge_id=' + PID;
  } else {
    alert('বন্ধক ID পাওয়া যায়নি।');
  }
}

function closeClose(){
  var m = document.getElementById('modalClose');
  if(m){
    m.style.display = 'none';
    m.classList.remove('show');
  }
}

function calcClose(){
  var prin  = parseFloat((document.getElementById('cPrin') || {}).value) || 0;
  var intr  = parseFloat((document.getElementById('cIntr') || {}).value) || 0;
  var total = prin + intr;

  var tEl = document.getElementById('cTotal');
  if(tEl) tEl.textContent = '৳' + fmtD(total);
}

function closeAlert(msg, t){
  var b = document.getElementById('cAl');
  if(!b) return;

  b.textContent = msg;
  b.className = 'mal ' + t;
  b.style.display = 'block';

  if(t === 'ok'){
    setTimeout(function(){
      b.style.display = 'none';
    }, 3000);
  }
}

function doClose(){
  openClose();
}

/* ══ EVENT DELEGATION ══ */
document.addEventListener('click', function(e){
  var t = e.target;
  if(!t) return;

  if(t.classList.contains('btn-lk')){
    openLock();
  }

  if(t.classList.contains('btn-cls')){
    openClose();
  }

  if(t.id === 'btnSave'){
    doSave();
  }

  if(t.id === 'btnClose'){
    doClose();
  }

  if(t.classList.contains('mcl')){
    closeLock();
    closeClose();
  }

  if(t.classList.contains('bcc')){
    closeLock();
    closeClose();
  }
});

document.addEventListener('input', function(e){
  var id = e.target && e.target.id;

  if(id === 'lAmt' || id === 'lCR' || id === 'lLR'){
    doCalc();
  }

  if(id === 'cPrin' || id === 'cIntr'){
    calcClose();
  }
});