
const limoOptions = <?= json_encode(array_map(function($r){
  $due = max(0, (float)$r['total_amount'] - (float)$r['collected_amount']);
  return [
    'id' => (int)$r['id'],
    'label' => trim('سريال ' . ($r['serial_no'] ?? '-') . ' / أمر ' . ($r['display_no'] ?? '-') . ' / ' . ($r['customer_name'] ?? '-')),
    'reference' => trim('ليموزين - سريال ' . ($r['serial_no'] ?? '-') . ' - أمر ' . ($r['display_no'] ?? '-')),
    'amount' => $due > 0 ? $due : (float)$r['total_amount'],
  ];
}, $limoOptions), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
const rentOptions = <?= json_encode(array_map(function($r){
  $due = max(0, (float)$r['total_amount'] - (float)$r['collected_amount']);
  return [
    'id' => (int)$r['id'],
    'label' => trim('سريال ' . ($r['order_serial_no'] ?? '-') . ' / عقد ' . ($r['contract_serial'] ?? '-') . ' / ' . ($r['customer_name'] ?? '-')),
    'reference' => trim('تأجير - سريال ' . ($r['order_serial_no'] ?? '-') . ' - عقد ' . ($r['contract_serial'] ?? '-')),
    'amount' => $due > 0 ? $due : (float)$r['total_amount'],
  ];
}, $rentOptions), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;

const sourceType = document.getElementById('f_source_type');
const sourceId = document.getElementById('f_source_id');
const amountInput = document.getElementById('f_amount');
const refView = document.getElementById('f_reference_view');
const sourceWrap = document.querySelector('.source-wrap');
const paymentMethod = document.getElementById('f_payment_method');
const dueDateInput = document.getElementById('f_due_date');
const bankOnlyEls = Array.from(document.querySelectorAll('.bank-only'));
const modalEl = document.getElementById('mReceipt');
const modal = bootstrap.Modal.getOrCreateInstance(modalEl);

function pickerRefresh(el){
  if (!el) return;
  if (window.jQuery && jQuery.fn && jQuery.fn.selectpicker && el.classList.contains('selectpicker')) {
    jQuery(el).selectpicker('refresh');
  }
}
function pickerSetValue(el, value){
  if (!el) return;
  el.value = value == null ? '' : String(value);
  if (window.jQuery && jQuery.fn && jQuery.fn.selectpicker && el.classList.contains('selectpicker')) {
    jQuery(el).selectpicker('val', el.value);
    jQuery(el).selectpicker('refresh');
  }
}
function currentSourceData(){
  const map = sourceType.value === 'LIMO' ? limoOptions : (sourceType.value === 'RENT' ? rentOptions : []);
  const id = parseInt(sourceId.value || '0', 10);
  return map.find(x => parseInt(x.id, 10) === id) || null;
}
function rebuildSourceOptions(selectedValue=''){
  const map = sourceType.value === 'LIMO' ? limoOptions : (sourceType.value === 'RENT' ? rentOptions : []);
  sourceId.innerHTML = '<option value="">اختر</option>' + map.map(item => `<option value="${item.id}">${item.label}</option>`).join('');
  if (selectedValue) sourceId.value = String(selectedValue);
  pickerRefresh(sourceId);
}
function syncSourceState(){
  const advance = sourceType.value === 'ADVANCE';
  sourceWrap.style.display = advance ? 'none' : '';
  if (advance) {
    sourceId.value = '';
    refView.value = 'مقدم تحت الحساب';
  } else {
    rebuildSourceOptions(sourceId.value);
    const data = currentSourceData();
    if (data) {
      if (!amountInput.value || parseFloat(amountInput.value) <= 0) amountInput.value = data.amount || '';
      refView.value = data.reference || '';
    } else {
      refView.value = '';
    }
  }
}
function syncPaymentMethod(){
  const isBank = paymentMethod.value === 'BANK';
  bankOnlyEls.forEach(el => el.classList.toggle('d-none', !isBank));
  if (isBank) {
    if (!dueDateInput.value) dueDateInput.value = document.getElementById('f_receipt_date').value || '<?= date('Y-m-d') ?>';
  } else {
    document.getElementById('f_bank_name').value = '';
    document.getElementById('f_bank_account_no').value = '';
    dueDateInput.value = '';
  }
}
function resetReceiptForm(){
  document.getElementById('receiptForm').reset();
  document.getElementById('f_action').value = 'create';
  document.getElementById('f_id').value = '';
  document.getElementById('f_receipt_no').value = '<?= h(fleet_receipt_next_code($pdo, $cid)) ?>';
  document.getElementById('f_receipt_date').value = '<?= date('Y-m-d') ?>';
  pickerSetValue(sourceType, 'LIMO');
  pickerSetValue(document.getElementById('f_cash_account_id'), '<?= (int)$acc['cash_id'] ?>');
  pickerSetValue(paymentMethod, 'CASH');
  rebuildSourceOptions('');
  amountInput.value = '';
  document.getElementById('f_memo').value = '';
  syncSourceState();
  syncPaymentMethod();
}

sourceType.addEventListener('change', function(){ amountInput.value = ''; syncSourceState(); });
sourceId.addEventListener('change', function(){ const data = currentSourceData(); if (data) { amountInput.value = data.amount || ''; refView.value = data.reference || ''; } });
paymentMethod.addEventListener('change', syncPaymentMethod);
document.getElementById('f_receipt_date').addEventListener('change', function(){ if (paymentMethod.value === 'BANK' && !dueDateInput.value) dueDateInput.value = this.value; });

Array.from(document.querySelectorAll('.btnEdit')).forEach(btn => btn.addEventListener('click', function(){
  document.getElementById('f_action').value = 'update';
  document.getElementById('f_id').value = this.dataset.id;
  document.getElementById('f_receipt_no').value = this.dataset.receiptno || '';
  pickerSetValue(sourceType, this.dataset.sourcetype || 'ADVANCE');
  rebuildSourceOptions(this.dataset.sourceid || '');
  sourceId.value = this.dataset.sourceid || '';
  document.getElementById('f_receipt_date').value = this.dataset.date || '<?= date('Y-m-d') ?>';
  pickerSetValue(document.getElementById('f_cash_account_id'), this.dataset.cash || '<?= (int)$acc['cash_id'] ?>');
  amountInput.value = this.dataset.amount || '';
  pickerSetValue(paymentMethod, this.dataset.method || 'CASH');
  document.getElementById('f_bank_name').value = this.dataset.bankname || '';
  document.getElementById('f_bank_account_no').value = this.dataset.bankaccount || '';
  dueDateInput.value = this.dataset.duedate || '';
  document.getElementById('f_memo').value = this.dataset.memo || '';
  syncSourceState();
  syncPaymentMethod();
  modal.show();
}));

modalEl.addEventListener('show.bs.modal', function(e){
  if (!(e.relatedTarget && e.relatedTarget.classList.contains('btnEdit'))) resetReceiptForm();
});

document.getElementById('btnOpenReceipt').addEventListener('click', function(){
  resetReceiptForm();
  modal.show();
});

document.getElementById('receiptForm').addEventListener('submit', function(){
  const submitBtn = document.getElementById('btnSubmitReceipt');
  if (submitBtn) {
    submitBtn.disabled = true;
    submitBtn.innerText = 'جاري الحفظ...';
  }
});

resetReceiptForm();
