<div class="d-flex gap-2 mb-3">
  <a class="btn btn-sm btn-light" href="<?= url('/pengaturan') ?>"><i class="bi bi-arrow-left me-1"></i>Pengaturan</a>
  <button class="btn btn-sm btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#formKonfig">
    <i class="bi bi-plus-lg me-1"></i>Konfigurasi Baru</button>
</div>

<div class="collapse mb-3" id="formKonfig">
  <div class="card"><div class="card-header"><i class="bi bi-plus-square me-1"></i>Tambah / Ubah Konfigurasi Aging</div>
    <form method="post" action="<?= url('/pengaturan/aging/simpan') ?>" class="card-body" id="formAging">
      <?= csrf() ?>
      <input type="hidden" name="id" id="agingId" value="">
      <div class="row g-3 mb-3">
        <div class="col-md-3"><label class="form-label required" for="ag_code">Kode</label>
          <input type="text" class="form-control" id="ag_code" name="code" required maxlength="40" placeholder="mis. OVERDUE_KETAT"></div>
        <div class="col-md-4"><label class="form-label required" for="ag_name">Nama Konfigurasi</label>
          <input type="text" class="form-control" id="ag_name" name="name" required maxlength="150"></div>
        <div class="col-md-2"><label class="form-label" for="ag_basis">Basis Nilai</label>
          <select class="form-select" id="ag_basis" name="basis">
            <option value="outstanding">Saldo Piutang</option><option value="net">Nilai Bersih</option><option value="gross">Nominal Bruto</option></select></div>
        <div class="col-md-3"><label class="form-label" for="ag_ref">Tanggal Referensi</label>
          <select class="form-select" id="ag_ref" name="reference">
            <option value="due_date">Jatuh Tempo</option><option value="invoice_date">Tanggal Invoice</option><option value="sent_date">Tanggal Kirim</option></select></div>
        <div class="col-md-3"><div class="form-check mt-4">
          <input class="form-check-input" type="checkbox" id="ag_paid" name="include_paid" value="1">
          <label class="form-check-label small" for="ag_paid">Sertakan invoice lunas</label></div></div>
        <div class="col-md-3"><div class="form-check mt-4">
          <input class="form-check-input" type="checkbox" id="ag_def" name="set_default" value="1">
          <label class="form-check-label small" for="ag_def">Jadikan konfigurasi default</label></div></div>
      </div>
      <label class="form-label">Bucket Aging</label>
      <div id="bucketWrap"></div>
      <button class="btn btn-sm btn-outline-secondary" type="button" id="tambahBucket"><i class="bi bi-plus-lg me-1"></i>Tambah Bucket</button>
      <div class="form-text mt-2">Kosongkan kolom "Sampai" pada bucket terakhir untuk rentang tak terbatas.
        Nilai negatif berarti belum jatuh tempo (mis. −99999 sampai −1).</div>
      <hr>
      <button class="btn btn-primary" type="submit"><i class="bi bi-save me-1"></i>Simpan Konfigurasi</button>
    </form>
  </div>
</div>

<?php foreach ($configs as $c): ?>
<div class="card mb-3">
  <div class="card-header">
    <i class="bi bi-hourglass-split me-1"></i><?= e($c['name']) ?>
    <?php if ((int)$c['is_default'] === 1): ?><span class="badge bg-success ms-1">Default</span><?php endif; ?>
    <span class="text-body-secondary fw-normal ms-2 small">
      Basis: <?= e(['outstanding'=>'Saldo Piutang','net'=>'Nilai Bersih','gross'=>'Nominal Bruto'][$c['basis']]) ?> ·
      Referensi: <?= e(['due_date'=>'Jatuh Tempo','invoice_date'=>'Tanggal Invoice','sent_date'=>'Tanggal Kirim'][$c['reference']]) ?> ·
      <?= (int)$c['include_paid'] === 1 ? 'Termasuk invoice lunas' : 'Hanya invoice bersaldo' ?></span>
    <div class="card-actions">
      <a class="btn btn-sm btn-outline-primary" href="<?= url('/aging',['konfigurasi'=>(int)$c['id']]) ?>">Lihat Laporan</a>
      <button class="btn btn-sm btn-light" type="button" onclick='muatKonfig(<?= json_attr($c) ?>)'><i class="bi bi-pencil"></i></button>
      <?php if ((int)$c['is_default'] !== 1 && can('pengaturan','edit')): ?>
        <form method="post" action="<?= url('/pengaturan/aging/hapus') ?>" class="d-inline"><?= csrf() ?>
          <input type="hidden" name="id" value="<?= (int)$c['id'] ?>">
          <button class="btn btn-sm btn-light text-danger" data-konfirmasi="Hapus konfigurasi aging ini?"><i class="bi bi-trash"></i></button></form>
      <?php endif; ?>
    </div>
  </div>
  <div class="table-wrap"><table class="table table-sm mb-0">
    <thead><tr><th class="ctr">#</th><th>Label Bucket</th><th class="num">Dari (hari)</th><th class="num">Sampai (hari)</th><th class="ctr">Warna</th></tr></thead>
    <tbody><?php foreach ($c['buckets'] as $i => $b): ?>
      <tr><td class="ctr"><?= $i+1 ?></td><td><?= e($b['label']) ?></td>
        <td class="num"><?= (int)$b['from_days'] <= -99999 ? '−∞' : nf($b['from_days'],0) ?></td>
        <td class="num"><?= $b['to_days'] === null ? '∞' : nf($b['to_days'],0) ?></td>
        <td class="ctr"><span class="badge bg-<?= e($b['color']) ?>">&nbsp;&nbsp;&nbsp;</span></td></tr>
    <?php endforeach; ?></tbody>
  </table></div>
</div>
<?php endforeach; ?>

<?php viewStart('scripts'); ?>
<script>
const WARNA = ['primary','success','info','warning','danger','secondary','dark'];
function barisBucket(b) {
  b = b || {};
  const w = document.getElementById('bucketWrap');
  const div = document.createElement('div');
  div.className = 'row g-1 mb-2 baris-bucket';
  div.innerHTML =
    '<div class="col-md-5"><input type="text" class="form-control form-control-sm" name="bucket_label[]" placeholder="Label bucket" value="' + (b.label || '') + '"></div>' +
    '<div class="col-md-2"><input type="number" class="form-control form-control-sm" name="bucket_from[]" placeholder="Dari" value="' + (b.from_days !== undefined ? b.from_days : '') + '"></div>' +
    '<div class="col-md-2"><input type="number" class="form-control form-control-sm" name="bucket_to[]" placeholder="Sampai (kosong = ∞)" value="' + (b.to_days !== null && b.to_days !== undefined ? b.to_days : '') + '"></div>' +
    '<div class="col-md-2"><select class="form-select form-select-sm" name="bucket_color[]">' +
      WARNA.map(c => '<option value="' + c + '"' + ((b.color || 'secondary') === c ? ' selected' : '') + '>' + c + '</option>').join('') + '</select></div>' +
    '<div class="col-md-1"><button type="button" class="btn btn-sm btn-outline-danger w-100 hapus-bucket">&times;</button></div>';
  w.appendChild(div);
}
document.getElementById('tambahBucket').addEventListener('click', () => barisBucket());
document.getElementById('bucketWrap').addEventListener('click', e => {
  if (e.target.closest('.hapus-bucket')) e.target.closest('.baris-bucket').remove();
});
function muatKonfig(c) {
  document.getElementById('agingId').value = c.id;
  document.getElementById('ag_code').value = c.code;
  document.getElementById('ag_name').value = c.name;
  document.getElementById('ag_basis').value = c.basis;
  document.getElementById('ag_ref').value = c.reference;
  document.getElementById('ag_paid').checked = parseInt(c.include_paid, 10) === 1;
  document.getElementById('ag_def').checked = parseInt(c.is_default, 10) === 1;
  document.getElementById('bucketWrap').innerHTML = '';
  (c.buckets || []).forEach(b => barisBucket(b));
  new bootstrap.Collapse(document.getElementById('formKonfig'), { show: true });
  document.getElementById('formKonfig').scrollIntoView({ behavior: 'smooth' });
}
barisBucket({ label: '0-45 hari', from_days: -99999, to_days: 45, color: 'success' });
barisBucket({ label: '46-90 hari', from_days: 46, to_days: 90, color: 'info' });
barisBucket({ label: '91-120 hari', from_days: 91, to_days: 120, color: 'warning' });
barisBucket({ label: '> 120 hari', from_days: 121, to_days: null, color: 'danger' });
</script>
<?php viewStop(); ?>
