<?php
// vars: $payment, $party, $isEdit, $id
$p = $payment ?? [];
$partyName = (string)($party['name'] ?? '');
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h3 class="mb-0"><?= $isEdit ? 'تعديل سند سداد طرف' : 'سند سداد طرف جديد' ?></h3>
  <a class="btn btn-outline-secondary" href="<?= e($supplier_payments_url ?? url('/purchases/supplier-payments')) ?>">رجوع</a>
</div>

<form method="post" class="card card-body">
  <?= csrf_field() ?>
  <input type="hidden" id="save_action" name="save_action" value="draft">
  <!-- allocations payload flag (so backend saves allocations arrays) -->
  <input type="hidden" name="alloc_payload" value="1">

  <div class="row g-3">
    <div class="col-md-6">
      <label class="form-label">الطرف</label>
      <input type="hidden" name="party_id" id="party_id" value="<?= e((string)($p['party_id'] ?? '')) ?>">
      <input type="text" class="form-control" id="party_query" value="<?= e($partyName) ?>" placeholder="ابحث عن الطرف..." autocomplete="off" required>
      <div class="list-group position-absolute w-100" id="party_box" style="z-index:1050; display:none"></div>
      <div class="form-text">ابدأ بالكتابة لاختيار الطرف.</div>
    </div>

    <div class="col-md-3">
      <label class="form-label">تاريخ السداد</label>
      <input type="date" name="pay_date" class="form-control" value="<?= e((string)($p['pay_date'] ?? date('Y-m-d'))) ?>" required>
    </div>

    <div class="col-md-3">
      <label class="form-label">المبلغ</label>
      <input type="number" step="0.01" min="0" name="amount" class="form-control" value="<?= e((string)($p['amount'] ?? '0')) ?>" required>
    </div>

    <div class="col-md-3">
      <label class="form-label">طريقة السداد</label>
      <select name="method" class="form-select">
        <?php $m = strtoupper((string)($p['method'] ?? 'CASH')); ?>
        <option value="CASH" <?= $m==='CASH'?'selected':'' ?>>نقدي</option>
        <option value="TRANSFER" <?= $m==='TRANSFER'?'selected':'' ?>>تحويل</option>
        <option value="CHEQUE" <?= $m==='CHEQUE'?'selected':'' ?>>شيك</option>
      </select>
    </div>

    <div class="col-md-3">
      <label class="form-label">رقم مرجعي</label>
      <input name="ref_no" class="form-control" value="<?= e((string)($p['ref_no'] ?? '')) ?>" placeholder="اختياري">
    </div>

    <div class="col-md-6">
      <label class="form-label">ملاحظات</label>
      <input name="notes" class="form-control" value="<?= e((string)($p['notes'] ?? '')) ?>" placeholder="اختياري">
    </div>
  </div>

  
  <hr class="my-4">

  <div class="card border-0 bg-light">
    <div class="card-body">
      <div class="d-flex justify-content-between align-items-center mb-2">
        <div class="fw-bold">توزيع السداد على فواتير الشراء <span class="text-muted fw-normal">(اختياري)</span></div>
        <div class="d-flex align-items-center gap-2">
          <button type="button" class="btn btn-sm btn-outline-primary" id="btn_auto_alloc">
            <i class="fa-solid fa-wand-magic-sparkles me-1"></i>توزيع تلقائي
          </button>
          <button type="button" class="btn btn-sm btn-outline-secondary" id="btn_clear_alloc">
            <i class="fa-solid fa-eraser me-1"></i>مسح التوزيع
          </button>
          <small class="text-muted">سيظهر بعد اختيار الطرف.</small>
        </div>
      </div>

      <div class="table-responsive">
        <table class="table table-sm table-bordered align-middle mb-2">
          <thead class="table-secondary">
            <tr>
              <th style="width:18%">رقم الفاتورة</th>
              <th style="width:18%">تاريخ</th>
              <th class="text-end" style="width:16%">إجمالي</th>
              <th class="text-end" style="width:16%">المتاح للسداد</th>
              <th class="text-end" style="width:22%">مبلغ التوزيع</th>
            </tr>
          </thead>
          <tbody id="alloc_tbody">
            <tr><td colspan="5" class="text-center text-muted">اختر الطرف لعرض فواتيره.</td></tr>
          </tbody>
        </table>
      </div>

      <div class="row g-2">
        <div class="col-md-6 text-muted">
          <small>إذا تركت التوزيع فارغًا سيكون السداد <b>دفعة مقدّمة</b>. إذا كان مبلغ السداد أكبر من إجمالي التوزيع، المتبقي يُعتبر <b>دفعة مقدّمة</b>.</small>
        </div>
        <div class="col-md-6">
          <div class="d-flex justify-content-end gap-3">
            <div>إجمالي التوزيع: <b id="alloc_total">0.00</b></div>
            <div>المتبقي (دفعة مقدّمة): <b id="alloc_remain">0.00</b></div>
          </div>
        </div>
      </div>
    </div>
  </div>

<div class="d-flex justify-content-end gap-2 mt-4">
    <button type="submit" class="btn btn-success px-4" onclick="document.getElementById('save_action').value='draft'">
      <i class="fa-solid fa-floppy-disk me-1"></i>حفظ كمسودة
    </button>
    <button type="submit" class="btn btn-primary px-4" onclick="document.getElementById('save_action').value='post'">
      <i class="fa-solid fa-circle-check me-1"></i>حفظ وترحيل
    </button>
  </div>
</form>

<script>
(function(){
  const supQ = document.getElementById('party_query');
  const supId = document.getElementById('party_id');
  const supBox = document.getElementById('party_box');
  let st=null;

  function hideSup(){ supBox.style.display='none'; supBox.innerHTML=''; }
  function showSup(){ supBox.style.display='block'; }

  supQ.addEventListener('input', () => {
    clearTimeout(st);
    const val = supQ.value.trim();
    supId.value = '';
    if (val.length < 1) { hideSup(); return; }
    st = setTimeout(async () => {
      try {
        const res = await fetch(<?= json_encode(url('/ajax/parties/search?type=supplier')) ?> + '&q=' + encodeURIComponent(val));
        const items = await res.json();
        if (!items || !items.length) { hideSup(); return; }
        supBox.innerHTML = items.map(it => `
          <button type="button" class="list-group-item list-group-item-action" data-id="${it.id}">
            <div class="fw-bold">${it.name}</div>
            <div class="small text-muted">${it.code || ''}</div>
          </button>`).join('');
        showSup();
      } catch(e){ hideSup(); }
    }, 200);
  });

  supBox.addEventListener('click', (e) => {
    const btn = e.target.closest('button[data-id]');
    if(!btn) return;
    supId.value = btn.getAttribute('data-id');
    supQ.value = btn.querySelector('.fw-bold').textContent.trim();
    hideSup();
    document.dispatchEvent(new Event('party:selected'));
  });

  document.addEventListener('click', (e) => {
    if (!supBox.contains(e.target) && e.target !== supQ) hideSup();
  });
})();
</script>


<script>
(function(){
  const supplierIdEl = document.getElementById('party_id');
  const amountEl = document.querySelector('input[name="amount"]');
  const tbody = document.getElementById('alloc_tbody');
  const allocTotalEl = document.getElementById('alloc_total');
  const allocRemainEl = document.getElementById('alloc_remain');
  const btnAuto = document.getElementById('btn_auto_alloc');
  const btnClear = document.getElementById('btn_clear_alloc');

  const paymentId = <?= (int)$id ?>;

  function money(n){
    try { return (Number(n)||0).toFixed(2); } catch(e){ return '0.00'; }
  }

  function recalcTotals(){
    let total = 0;
    document.querySelectorAll('.alloc-input').forEach(inp=>{
      const v = Number(inp.value)||0;
      total += v;
    });
    allocTotalEl.textContent = money(total);
    const pay = Number(amountEl?.value)||0;
    allocRemainEl.textContent = money(Math.max(0, pay - total));
  }

  function clearAllocations(){
    document.querySelectorAll('.alloc-input').forEach(inp=>{ inp.value = '0.00'; });
    recalcTotals();
  }

  // Auto allocate payment amount across invoices by order shown (newest first currently).
  // We allocate up to "available" for each invoice until the payment amount is consumed.
  function autoAllocate(){
    const pay = Number(amountEl?.value)||0;
    if (pay <= 0) { clearAllocations(); return; }
    let remaining = pay;
    document.querySelectorAll('#alloc_tbody tr').forEach(tr=>{
      const inp = tr.querySelector('.alloc-input');
      if (!inp) return;
      const max = Number(inp.getAttribute('max')) || 0;
      const v = Math.min(max, Math.max(0, remaining));
      inp.value = v.toFixed(2);
      remaining -= v;
    });
    recalcTotals();
  }

  // wire buttons
  if (btnAuto) btnAuto.addEventListener('click', autoAllocate);
  if (btnClear) btnClear.addEventListener('click', clearAllocations);

  function renderRows(items){
    tbody.innerHTML = '';
    if (!items || items.length === 0){
      tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">لا توجد فواتير متاحة للتوزيع.</td></tr>';
      recalcTotals();
      return;
    }
    items.forEach(it=>{
      const tr = document.createElement('tr');
      tr.innerHTML = `
        <td><span class="badge bg-secondary">${it.inv_no}</span><input type="hidden" name="alloc_invoice_id[]" value="${it.id}"></td>
        <td>${it.inv_date || ''}</td>
        <td class="text-end">${money(it.total)}</td>
        <td class="text-end">${money(it.available)}</td>
        <td class="text-end">
          <input type="number" step="0.01" min="0" max="${money(it.available)}" class="form-control form-control-sm text-end alloc-input" name="alloc_amount[]" value="${money(it.cur_alloc || 0)}">
        </td>
      `;
      tbody.appendChild(tr);
    });

    // NOTE: do NOT force toFixed() on every keypress.
    // Doing so prevents typing numbers like 200 (it becomes 2.00 after the first key).
    // Instead, clamp during input and format on blur.
    tbody.querySelectorAll('.alloc-input').forEach(inp=>{
      inp.addEventListener('input', ()=>{
        const max = Number(inp.getAttribute('max')) || 0;
        let v = Number(inp.value);
        if (Number.isNaN(v)) { recalcTotals(); return; }
        if (v < 0) v = 0;
        if (max > 0 && v > max) {
          inp.value = String(max);
        }
        recalcTotals();
      });
      inp.addEventListener('blur', ()=>{
        let v = Number(inp.value);
        if (Number.isNaN(v) || v < 0) v = 0;
        inp.value = v.toFixed(2);
        recalcTotals();
      });
    });

    recalcTotals();
  }

  if (btnClear) btnClear.addEventListener('click', clearAlloc);
  if (btnAuto) btnAuto.addEventListener('click', autoAllocate);

  async function loadInvoices(){
    const sid = Number(supplierIdEl?.value)||0;
    if (!sid){
      tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">اختر الطرف لعرض فواتيره.</td></tr>';
      recalcTotals();
      return;
    }
    tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">جاري التحميل...</td></tr>';
    const url = `<?= e(url('/ajax/purchases/supplier-open-invoices')) ?>?party_id=${sid}&payment_id=${paymentId}`;
    try{
      const res = await fetch(url, {credentials:'same-origin'});
      const data = await res.json();
      if (!data.ok){
        tbody.innerHTML = '<tr><td colspan="5" class="text-center text-danger">تعذر تحميل الفواتير (شغّل migrate_v1_30).</td></tr>';
        recalcTotals();
        return;
      }
      renderRows(data.items || []);
    }catch(e){
      tbody.innerHTML = '<tr><td colspan="5" class="text-center text-danger">خطأ في الاتصال.</td></tr>';
      recalcTotals();
    }
  }

  // recalc when payment amount changes
  if (amountEl){
    amountEl.addEventListener('input', recalcTotals);
    amountEl.addEventListener('change', recalcTotals);
  }

  // initial load for edit
  loadInvoices();

  // also reload when supplier changes (supplier autocomplete sets hidden supplier_id)
  const observer = new MutationObserver(()=>loadInvoices());
  if (supplierIdEl){
    observer.observe(supplierIdEl, {attributes:true, attributeFilter:['value']});
    supplierIdEl.addEventListener('change', loadInvoices);
  }

  // hook into supplier autocomplete selection (it sets value programmatically)
  document.addEventListener('party:selected', loadInvoices);
})();
</script>
