<?php $isEdit = !empty($pay); ?>
<form method="post" action="<?= $isEdit ? url('/pembayaran/'.(int)$pay['id'].'/ubah') : url('/pembayaran/tambah') ?>" data-loading>
<?= csrf() ?>
<div class="row g-3">
  <div class="col-lg-5">
    <div class="card mb-3"><div class="card-header"><i class="bi bi-wallet2 me-1"></i>Informasi Pembayaran</div>
      <div class="card-body row g-3">
        <div class="col-6"><label class="form-label" for="payment_no">Nomor Pembayaran</label>
          <input type="text" class="form-control" id="payment_no" value="<?= attr($isEdit ? $pay['payment_no'] : ($nomorSaran ?? '')) ?>" readonly>
          <div class="form-text">Dibuat otomatis oleh sistem.</div></div>
        <div class="col-6"><label class="form-label required" for="payment_date">Tanggal Pembayaran</label>
          <input type="date" class="form-control" id="payment_date" name="payment_date" required
                 value="<?= attr($isEdit ? $pay['payment_date'] : App\Core\Dates::today()) ?>"></div>
        <div class="col-12"><label class="form-label" for="customer_id">Customer</label>
          <select class="form-select" id="customer_id" name="customer_id">
            <option value="">— Pilih customer (untuk saran alokasi) —</option>
            <?php $curCust = $isEdit ? (int)$pay['customer_id'] : (int)($prefill['customer_id'] ?? 0);
            foreach ($customers as $c): ?>
              <option value="<?= (int)$c['id'] ?>" <?= $curCust === (int)$c['id'] ? 'selected':'' ?>><?= e($c['name']) ?> (<?= e($c['code']) ?>)</option>
            <?php endforeach; ?></select></div>
        <div class="col-6"><label class="form-label" for="method">Metode Pembayaran</label>
          <select class="form-select" id="method" name="method">
            <?php foreach ($methods as $k=>$v): ?><option value="<?= $k ?>" <?= ($isEdit && $pay['method']===$k)?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select></div>
        <div class="col-6"><label class="form-label" for="bank_id">Bank Penerima</label>
          <select class="form-select" id="bank_id" name="bank_id"><option value="">—</option>
            <?php foreach ($banks as $b): ?><option value="<?= (int)$b['id'] ?>" <?= ($isEdit && (int)$pay['bank_id']===(int)$b['id'])?'selected':'' ?>><?= e($b['name']) ?></option><?php endforeach; ?></select></div>
        <div class="col-6"><label class="form-label" for="payment_type">Jenis Pembayaran</label>
          <select class="form-select" id="payment_type" name="payment_type">
            <?php foreach ($types as $k=>$v): ?><option value="<?= $k ?>" <?= ($isEdit && $pay['payment_type']===$k)?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select></div>
        <div class="col-6"><label class="form-label" for="reference_no">Nomor Referensi</label>
          <input type="text" class="form-control" id="reference_no" name="reference_no" maxlength="80" value="<?= attr($isEdit ? $pay['reference_no'] : '') ?>"></div>
        <div class="col-12"><label class="form-label" for="amount">Nilai Pembayaran Diterima</label>
          <div class="input-group"><span class="input-group-text">Rp</span>
            <input type="text" class="form-control text-end" id="amount" name="amount" data-uang value="<?= attr($isEdit ? nf($pay['amount'],0) : '') ?>">
            <button class="btn btn-outline-secondary" type="button" id="btnSaran" title="Alokasikan otomatis ke invoice tertua"><i class="bi bi-magic"></i></button></div>
          <div class="form-text">Klik ikon untuk mengalokasikan otomatis ke invoice tertua (FIFO).</div></div>
        <div class="col-12"><label class="form-label" for="notes">Catatan</label>
          <textarea class="form-control" id="notes" name="notes" rows="2" maxlength="2000"><?= e($isEdit ? $pay['notes'] : '') ?></textarea></div>
      </div>
    </div>
    <div class="card"><div class="card-body">
      <div class="d-flex justify-content-between mb-1"><span class="text-body-secondary">Total Alokasi</span><strong id="totalAlokasi">Rp 0</strong></div>
      <div class="d-flex justify-content-between mb-3"><span class="text-body-secondary">Selisih vs Nilai Pembayaran</span><strong id="selisih">Rp 0</strong></div>
      <div class="d-flex gap-2">
        <button class="btn btn-primary flex-fill" type="submit"><i class="bi bi-check-lg me-1"></i>Simpan Pembayaran</button>
        <a class="btn btn-light" href="<?= $isEdit ? url('/pembayaran/'.(int)$pay['id']) : url('/pembayaran') ?>">Batal</a>
      </div>
    </div></div>
  </div>

  <div class="col-lg-7">
    <div class="card">
      <div class="card-header"><i class="bi bi-list-check me-1"></i>Alokasi ke Invoice</div>
      <div class="card-body">
        <div class="mb-3"><label class="form-label" for="cariInvoice">Cari &amp; Tambah Invoice</label>
          <input type="text" class="form-control" id="cariInvoice" placeholder="Ketik nomor invoice, faktur pajak, atau nama customer…" autocomplete="off">
          <div class="form-text">Minimal 2 karakter. Hanya invoice aktif yang ditampilkan.</div></div>
        <div class="table-wrap"><table class="table table-sm mb-0" id="tabelAlokasi">
          <thead><tr><th>Invoice</th><th>Customer</th><th class="ctr">Jatuh Tempo</th><th class="num">Saldo</th><th class="num" style="width:150px">Alokasi</th><th style="width:40px"></th></tr></thead>
          <tbody></tbody>
        </table></div>
        <p class="small text-body-secondary mt-2 mb-0">Satu pembayaran dapat dialokasikan ke beberapa invoice sekaligus
          (misalnya satu transfer melunasi 5 invoice). Saldo tiap invoice dihitung ulang otomatis setelah disimpan.</p>
      </div>
    </div>
  </div>
</div>
</form>

<?php viewStart('scripts'); ?>
<script>
(function(){
  const tbody = document.querySelector('#tabelAlokasi tbody');
  const parse = v => parseFloat(String(v||'').replace(/\./g,'').replace(',','.')) || 0;

  function baris(row, nilai) {
    const tr = document.createElement('tr');
    tr.innerHTML =
      '<td><input type="hidden" name="alokasi_invoice_id[]" value="' + row.id + '">' +
        '<a href="' + SP.url('/invoice/' + row.id) + '" target="_blank">' + row.invoice_no + '</a></td>' +
      '<td class="small">' + (row.customer_name || '-') + '</td>' +
      '<td class="ctr small">' + (row.due_date_fmt || '-') + '</td>' +
      '<td class="num">' + SP.rp(row.outstanding_amount) + '</td>' +
      '<td><input type="text" class="form-control form-control-sm text-end nilai-alokasi" name="alokasi_nilai[]" data-uang value="' +
        (nilai !== undefined && nilai !== null ? Number(nilai).toLocaleString('id-ID') : Number(row.outstanding_amount).toLocaleString('id-ID')) + '"></td>' +
      '<td><button type="button" class="btn btn-sm btn-outline-danger px-1 hapus-baris">&times;</button></td>';
    tbody.appendChild(tr);
    hitung();
  }

  function hitung() {
    let t = 0;
    document.querySelectorAll('.nilai-alokasi').forEach(i => t += parse(i.value));
    document.getElementById('totalAlokasi').textContent = SP.rp(t);
    const amt = parse(document.getElementById('amount').value) || t;
    const d = amt - t;
    const el = document.getElementById('selisih');
    el.textContent = SP.rp(d);
    el.className = Math.abs(d) < 1 ? 'text-success' : 'text-danger';
  }

  tbody.addEventListener('click', e => { if (e.target.closest('.hapus-baris')) { e.target.closest('tr').remove(); hitung(); } });
  document.addEventListener('input', e => { if (e.target.matches('.nilai-alokasi, #amount')) hitung(); });

  SP.invoiceSearch(document.getElementById('cariInvoice'), row => {
    if (document.querySelector('input[name="alokasi_invoice_id[]"][value="' + row.id + '"]')) { SP.toast('Invoice sudah ada di daftar alokasi.','warning'); return; }
    baris(row);
  }, true);

  document.getElementById('btnSaran').addEventListener('click', function(){
    const cust = document.getElementById('customer_id').value;
    const amt = parse(document.getElementById('amount').value);
    if (!cust) { SP.toast('Pilih customer terlebih dahulu.','warning'); return; }
    if (amt <= 0) { SP.toast('Isi nilai pembayaran terlebih dahulu.','warning'); return; }
    SP.get(SP.url('/pembayaran/saran-alokasi'), { customer_id: cust, amount: amt }).then(res => {
      if (!res.sukses) { SP.toast(res.pesan,'warning'); return; }
      tbody.innerHTML = '';
      (res.alokasi || []).forEach(a => baris({
        id: a.invoice_id, invoice_no: a.invoice_no, customer_name: '',
        due_date_fmt: a.due_date, outstanding_amount: a.outstanding
      }, a.amount));
      if (res.sisa > 0.5) SP.toast('Sisa yang belum teralokasi: ' + SP.rp(res.sisa), 'info');
      else SP.toast('Alokasi otomatis selesai.','success');
    });
  });

  // Prefill
  <?php if (!empty($prefill)): ?>
  baris({ id: <?= (int)$prefill['id'] ?>, invoice_no: <?= json_encode($prefill['invoice_no']) ?>,
          customer_name: <?= json_encode($prefill['customer_name'] ?? '') ?>,
          due_date_fmt: <?= json_encode(tgl($prefill['due_date'])) ?>,
          outstanding_amount: <?= (float)$prefill['outstanding_amount'] ?> });
  document.getElementById('amount').value = Number(<?= (float)$prefill['outstanding_amount'] ?>).toLocaleString('id-ID');
  <?php endif; ?>
  <?php foreach ($allocations as $a): ?>
  baris({ id: <?= (int)$a['invoice_id'] ?>, invoice_no: <?= json_encode($a['invoice_no']) ?>,
          customer_name: <?= json_encode($a['customer_name'] ?? '') ?>,
          due_date_fmt: <?= json_encode(tgl($a['due_date'])) ?>,
          outstanding_amount: <?= (float)$a['outstanding_amount'] ?> }, <?= (float)$a['amount'] ?>);
  <?php endforeach; ?>
  hitung();
})();
</script>
<?php viewStop(); ?>
