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 el(id) {
  return document.getElementById(id);
}

function setText(id, txt) {
  var x = el(id);
  if (x) x.textContent = txt;
}

function getNum(id) {
  var x = el(id);
  return parseFloat((x && x.value) || 0);
}

function tk(n) {
  n = parseFloat(n || 0);
  return '৳' + n.toLocaleString('en-IN', { maximumFractionDigits: 2, minimumFractionDigits: 2 });
}

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);

  if (p >= Math.round(ROTI / POINT)) {
    p = 0;
    r += 1;
  }
  if (r >= 6) {
    r = 0;
    a += 1;
  }
  if (a >= 16) {
    a = 0;
    v += 1;
  }

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

function esc(s) {
  return String(s == null ? '' : s)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

function openModal() {
  if (el('pledgeModal')) el('pledgeModal').style.display = 'block';
  resetModalFields();
  loadParties();
  loadCashAccountsForNew();
  loadTodayRate();
  syncPurityFields();
  convertWeight();
  calculate();
}

function closeModal() {
  if (el('pledgeModal')) el('pledgeModal').style.display = 'none';
}

function resetModalFields() {
  if (el('mDate')) el('mDate').value = today;
  if (el('mParty')) el('mParty').value = '';
  if (el('mKarat')) el('mKarat').value = '22K';
  if (el('mLocation')) el('mLocation').value = '2';
  if (el('mSystemPurity')) el('mSystemPurity').value = '88.00';
  if (el('mDeduction')) el('mDeduction').value = '0';
  if (el('mActualPurity')) el('mActualPurity').value = '88.00';
  if (el('mRate')) el('mRate').value = '';
  if (el('mInterestRate')) el('mInterestRate').value = '3';
  if (el('mLoanAmount')) el('mLoanAmount').value = '';
  if (el('mNote')) el('mNote').value = '';
  if (el('mCashAcc')) el('mCashAcc').value = '';

  ['wVori', 'wAna', 'wRoti', 'wPoint'].forEach(function(id) {
    if (el(id)) el(id).value = '';
  });

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

  setText('cSystemPurity', '0');
  setText('cDeduction', '0');
  setText('cActualPurity', '0');
  setText('cGross', '0');
  setText('cPure', '0');
  setText('cGoldValue', '0');
  setText('cLoanSuggestion', '0');
  setText('cLoanFinal', '0');

  if (el('mEr')) el('mEr').style.display = 'none';
  if (el('mOk')) el('mOk').style.display = 'none';
  if (el('mBtn')) {
    el('mBtn').disabled = false;
    el('mBtn').textContent = 'Save Pledge';
  }
}

function loadParties() {
  return fetch('/api/parties/get_parties.php?limit=300', {
    method: 'GET',
    credentials: 'same-origin',
    cache: 'no-store'
  })
  .then(function(r) { return r.json(); })
  .then(function(res) {
    var select = el('mParty');
    if (!select) return;

    select.innerHTML = '<option value="">-- Select Party --</option>';

    var parties = [];
    if (res && res.success && res.data) {
      parties = res.data.parties || res.data || [];
    }

    parties.forEach(function(p) {
      var opt = document.createElement('option');
      opt.value = p.id;
      opt.textContent = (p.name || '') + (p.phone ? ' - ' + p.phone : '');
      select.appendChild(opt);
    });
  })
  .catch(function() {
    console.log('Party load failed');
  });
}

function loadCashAccountsForNew() {
  return fetch('/api/cash/get_accounts.php?_=' + Date.now(), {
    method: 'GET',
    credentials: 'same-origin',
    cache: 'no-store'
  })
  .then(function(r) { return r.json(); })
  .then(function(res) {
    var select = el('mCashAcc');
    if (!select) return;

    select.innerHTML = '<option value="">-- Select Cash Account --</option>';

    var accounts = [];
    if (res && res.success && res.data) {
      accounts = res.data.accounts || [];
    }

    accounts.forEach(function(a) {
      var opt = document.createElement('option');
      opt.value = a.id;
      opt.textContent = a.account_name || a.name || ('Account #' + a.id);
      select.appendChild(opt);
    });
  })
  .catch(function() {
    console.log('Cash account load failed');
  });
}

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

    var rate = 0;
    if (res.data.rate_24k) {
      rate = parseFloat(res.data.rate_24k) * VORI;
    } else if (res.data.buy_24k_per_vori) {
      rate = parseFloat(res.data.buy_24k_per_vori);
    } else if (res.data.price_24k) {
      rate = parseFloat(res.data.price_24k);
    }

    if (el('mRate') && rate > 0) {
      el('mRate').value = Math.round(rate);
      calculate();
    }
  })
  .catch(function() {
    console.log('Rate load failed');
  });
}

function syncPurityFields() {
  var karat = el('mKarat') ? el('mKarat').value : '22K';
  var system = el('mSystemPurity');
  if (!system) return;

  if (karat === 'custom') {
    system.readOnly = false;
  } else {
    system.readOnly = true;
    system.value = (PURITY_MAP[karat] || 0).toFixed(2);
  }

  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((el('wGram') && el('wGram').textContent) || 0);
  var rate24kVori = getNum('mRate');
  var systemPurity = getNum('mSystemPurity');
  var deduction = getNum('mDeduction');

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

  if (el('mActualPurity')) {
    el('mActualPurity').value = actualPurity.toFixed(2);
  }

  var pureWeight = grossGram * (actualPurity / 96);
  var ratePerGram = rate24kVori / VORI;
  var goldValue = pureWeight * ratePerGram;
  var loanSuggestion = goldValue * 0.70;
  var finalLoan = getNum('mLoanAmount');

  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('cGoldValue', tk(goldValue));
  setText('cLoanSuggestion', tk(loanSuggestion));
  setText('cLoanFinal', tk(finalLoan));
}

function savePledge() {
  var er = el('mEr');
  var ok = el('mOk');

  if (er) er.style.display = 'none';
  if (ok) ok.style.display = 'none';

  var partyId = el('mParty') ? el('mParty').value : '';
  var pledgeDate = el('mDate') ? el('mDate').value : today;
  var karat = el('mKarat') ? el('mKarat').value : '22K';
  var locationId = el('mLocation') ? el('mLocation').value : '2';
  var systemPurity = getNum('mSystemPurity');
  var deduction = getNum('mDeduction');
  var actualPurity = getNum('mActualPurity');
  var grossWeight = parseFloat((el('wGram') && el('wGram').textContent) || 0);
  var pureWeight = grossWeight * (actualPurity / 96);
  var goldValue = pureWeight * (getNum('mRate') / VORI);
  var loanAmount = getNum('mLoanAmount');
  var interestRate = getNum('mInterestRate');
  var cashAccountId = el('mCashAcc') ? el('mCashAcc').value : '';
  var note = el('mNote') ? el('mNote').value : '';

  if (!partyId) {
    if (er) {
      er.style.display = 'block';
      er.textContent = 'Party select করুন';
    }
    return;
  }

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

  if (loanAmount <= 0) {
    if (er) {
      er.style.display = 'block';
      er.textContent = 'Loan amount দিন';
    }
    return;
  }

  if (!cashAccountId) {
    if (er) {
      er.style.display = 'block';
      er.textContent = 'Cash account select করুন';
    }
    return;
  }

  if (el('mBtn')) {
    el('mBtn').disabled = true;
    el('mBtn').textContent = 'Saving...';
  }

  fetch('/api/pawn/pledge_add.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    credentials: 'same-origin',
    body: JSON.stringify({
      party_id: parseInt(partyId, 10),
      pledge_date: pledgeDate,
      karat: karat,
      location_id: parseInt(locationId, 10),
      system_purity: systemPurity,
      deduction: deduction,
      actual_purity: actualPurity,
      gross_weight: grossWeight,
      pure_weight: parseFloat(pureWeight.toFixed(3)),
      gold_value: parseFloat(goldValue.toFixed(2)),
      loan_amount: parseFloat(loanAmount.toFixed(2)),
      interest_rate: parseFloat(interestRate.toFixed(2)),
      cash_account_id: parseInt(cashAccountId, 10),
      note: note
    })
  })
  .then(function(r) { return r.json(); })
  .then(function(res) {
    if (el('mBtn')) {
      el('mBtn').disabled = false;
      el('mBtn').textContent = 'Save Pledge';
    }

    if (res && res.success) {
      if (ok) {
        ok.style.display = 'block';
        ok.textContent = res.message || 'Saved';
      }
      setTimeout(function() {
        closeModal();
        lpledge();
      }, 700);
    } else {
      if (er) {
        er.style.display = 'block';
        er.textContent = (res && res.message) || 'Save failed';
      }
    }
  })
  .catch(function() {
    if (el('mBtn')) {
      el('mBtn').disabled = false;
      el('mBtn').textContent = 'Save Pledge';
    }
    if (er) {
      er.style.display = 'block';
      er.textContent = 'Server error';
    }
  });
}

function lpledge() {
  var list = el('pledgeList');
  if (!list) return;

  var from = el('fromDate') && el('fromDate').value ? el('fromDate').value : today;
  var to = el('toDate') && el('toDate').value ? el('toDate').value : today;

  if (el('fromDate') && !el('fromDate').value) el('fromDate').value = today;
  if (el('toDate') && !el('toDate').value) el('toDate').value = today;

  list.innerHTML = '<div class="empty">Loading...</div>';

  fetch('/api/pawn/pledge_list.php?from_date=' + encodeURIComponent(from) + '&to_date=' + encodeURIComponent(to) + '&limit=100', {
    method: 'GET',
    credentials: 'same-origin',
    cache: 'no-store'
  })
  .then(function(r) { return r.json(); })
  .then(function(res) {
    if (!res || !res.success || !res.data) {
      list.innerHTML = '<div class="empty">Error!</div>';
      return;
    }

    var data = res.data;
    var pledges = data.pledges || [];
    var summary = data.summary || {};

    setText('sumEntries', summary.total_entries || 0);
    setText('sumLoan', tk(summary.total_loan_amount || 0));
    setText('sumGross', g2v(summary.total_gross || 0));
    setText('sumPure', g2v(summary.total_pure || 0));

    if (!pledges.length) {
      list.innerHTML = '<div class="empty">No pledge found</div>';
      return;
    }

    var html = '';

    pledges.forEach(function(p) {
      var outstanding = parseFloat(p.outstanding_principal || 0);
      var status = String(p.status || 'OPEN').toUpperCase();
      var holding = String(p.holding_status || 'SHOWROOM').toUpperCase();
      var isClosed = (status === 'CLOSED' || outstanding <= 0);
      var canPay = !isClosed;

      html += '<div class="pl-card">';
      html +=   '<div class="pl-top">';
      html +=     '<div>';
      html +=       '<div class="pl-party">' + esc(p.party_name || '') + '</div>';
      html +=       '<div class="pl-date">' + esc(p.pledge_date || '') + ' | #' + esc(p.id || '') + '</div>';
      html +=     '</div>';
      html +=     '<span class="pl-code">' + esc(p.pledge_code || '') + '</span>';
      html +=   '</div>';

      html +=   '<div class="pl-details">';
      html +=     '<div class="pl-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="pl-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="pl-detail"><div class="lbl">Purity</div><div class="val">' + parseFloat(p.actual_purity || 0).toFixed(2) + '</div><div class="val2">SP ' + parseFloat(p.system_purity || 0).toFixed(2) + ' | D ' + parseFloat(p.deduction || 0).toFixed(2) + '</div></div>';
      html +=   '</div>';

      html +=   '<div class="pl-bottom">';
      html +=     '<div>';
      html +=       '<div class="pl-amount">' + tk(p.loan_amount || 0) + '</div>';
      html +=       '<div style="font-size:12px;color:rgba(255,255,255,.6);margin-top:4px;">Outstanding: ' + tk(outstanding) + '</div>';
      html +=       '<div style="font-size:12px;color:' + (isClosed ? '#7ee787' : '#f5d060') + ';margin-top:4px;font-weight:700;">Status: ' + esc(status) + '</div>';
      html +=       '<div style="font-size:12px;color:' + (holding === 'LOCKER' ? '#42a5f5' : '#f5d060') + ';margin-top:4px;font-weight:700;">Holding: ' + esc(holding) + '</div>';
      html +=     '</div>';
      html +=     '<div class="pl-meta">';
      html +=       '<div class="loc">' + esc(p.location_name || '') + '</div>';
      html +=       '<div class="rate">' + parseFloat(p.interest_rate || 0).toFixed(2) + '% / month</div>';
      html +=     '</div>';
      html +=   '</div>';

      html +=   '<div class="pl-actions">';
      html +=     '<button class="view-btn" type="button" onclick="viewPledge(' + parseInt(p.id || 0, 10) + ')">View</button>';
      if (canPay) {
        html += '<button class="pay-btn" type="button" onclick="goPayment(' + parseInt(p.id || 0, 10) + ')">Payment</button>';
      }
      html +=   '</div>';
      html += '</div>';
    });

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

function viewPledge(id) {
  window.location.href = '/pledge_view.php?pledge_id=' + encodeURIComponent(id) + '&v=' + Date.now();
}

function goPayment(id) {
  window.location.href = '/pledge_payment.php?pledge_id=' + encodeURIComponent(id) + '&v=' + Date.now();
}

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

  if (el('addBtn')) el('addBtn').addEventListener('click', openModal);
  if (el('cancelBtn')) el('cancelBtn').addEventListener('click', closeModal);
  if (el('searchBtn')) el('searchBtn').addEventListener('click', lpledge);
  if (el('mBtn')) el('mBtn').addEventListener('click', savePledge);

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

  ['mSystemPurity', 'mDeduction', 'mRate', 'mLoanAmount', 'mInterestRate'].forEach(function(id) {
    if (el(id)) {
      el(id).addEventListener('input', calculate);
      el(id).addEventListener('change', calculate);
    }
  });

  if (el('mKarat')) el('mKarat').addEventListener('change', syncPurityFields);

  lpledge();
});