<?php
$qs = array_filter(array_merge($filters, [
  'tanggal_lapor' => $asOf, 'grup' => $groupBy, 'konfigurasi' => $configId,
]), fn($v) => $v !== '' && $v !== null && !is_array($v));
$total = $rep['total'];
$bs = $rep['buckets'];
$grandTotal = (float)$total['total_nilai'];
?>

<form class="filter-bar" method="get" action="<?= url('/aging') ?>">
  <div class="row g-2 align-items-end">
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="a_asof">Tanggal Pelaporan</label>
      <input type="date" class="form-control form-control-sm" id="a_asof" name="tanggal_lapor" value="<?= attr($asOf) ?>">
    </div>
    <div class="col-6 col-md-3 col-lg-3">
      <label class="form-label" for="a_konf">Konfigurasi Aging</label>
      <select class="form-select form-select-sm" id="a_konf" name="konfigurasi" data-auto-submit>
        <?php foreach ($configs as $c): ?>
          <option value="<?= (int)$c['id'] ?>" <?= (int)$configId === (int)$c['id'] ? 'selected' : '' ?>><?= e($c['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="a_grup">Kelompokkan per</label>
      <select class="form-select form-select-sm" id="a_grup" name="grup" data-auto-submit>
        <?php foreach ($groupOptions as $k => $v): ?>
          <option value="<?= attr($k) ?>" <?= $groupBy === $k ? 'selected' : '' ?>><?= e($v) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="a_area">Area</label>
      <select class="form-select form-select-sm" id="a_area" name="area_id">
        <option value="">Semua Area</option>
        <?php foreach ($opsi['area'] as $o): ?>
          <option value="<?= (int)$o['id'] ?>" <?= (($filters['area_id'] ?? '') == $o['id']) ? 'selected' : '' ?>><?= e($o['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="a_bu">Unit Bisnis</label>
      <select class="form-select form-select-sm" id="a_bu" name="business_unit_id">
        <option value="">Semua Unit</option>
        <?php foreach ($opsi['business_unit'] as $o): ?>
          <option value="<?= (int)$o['id'] ?>" <?= (($filters['business_unit_id'] ?? '') == $o['id']) ? 'selected' : '' ?>><?= e($o['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="a_sales">Sales</label>
      <select class="form-select form-select-sm" id="a_sales" name="salesperson_id">
        <option value="">Semua Sales</option>
        <?php foreach ($opsi['salesperson'] as $o): ?>
          <option value="<?= (int)$o['id'] ?>" <?= (($filters['salesperson_id'] ?? '') == $o['id']) ? 'selected' : '' ?>><?= e($o['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-12 col-lg-auto d-flex gap-2 ms-lg-auto">
      <button class="btn btn-primary btn-sm" type="submit"><i class="bi bi-funnel me-1"></i>Terapkan</button>
      <a class="btn btn-light btn-sm" href="<?= url('/aging') ?>"><i class="bi bi-arrow-counterclockwise"></i></a>
      <?php if (can('aging', 'export')): ?>
      <div class="dropdown">
        <button class="btn btn-outline-primary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown"><i class="bi bi-download me-1"></i>Ekspor</button>
        <ul class="dropdown-menu dropdown-menu-end">
          <li><a class="dropdown-item" href="<?= url('/aging/ekspor', array_merge($qs, ['format' => 'xlsx'])) ?>"><i class="bi bi-file-earmark-excel me-2"></i>Excel</a></li>
          <li><a class="dropdown-item" href="<?= url('/aging/ekspor', array_merge($qs, ['format' => 'csv'])) ?>"><i class="bi bi-filetype-csv me-2"></i>CSV</a></li>
          <li><a class="dropdown-item" href="<?= url('/aging/ekspor', array_merge($qs, ['format' => 'pdf'])) ?>"><i class="bi bi-file-earmark-pdf me-2"></i>PDF</a></li>
          <li><a class="dropdown-item" target="_blank" href="<?= url('/aging/ekspor', array_merge($qs, ['format' => 'print'])) ?>"><i class="bi bi-printer me-2"></i>Cetak</a></li>
        </ul>
      </div>
      <?php endif; ?>
    </div>
  </div>
</form>

<div class="row g-3 mb-3">
  <div class="col-lg-5">
    <div class="card h-100">
      <div class="card-header"><i class="bi bi-pie-chart me-1"></i>Komposisi Bucket</div>
      <div class="card-body"><div class="chart-box"><canvas id="chAgingKomposisi"></canvas></div></div>
    </div>
  </div>
  <div class="col-lg-7">
    <div class="kpi-grid h-100">
      <?php foreach ($bs as $i => $b):
        $nilai = (float)$total['b' . $i];
        $pctVal = $grandTotal > 0 ? $nilai / $grandTotal * 100 : 0; ?>
        <a class="kpi kpi-<?= e($b['color']) ?>" href="<?= url('/aging/detail', array_merge($qs, ['bucket' => $i])) ?>">
          <span class="kpi-label"><?= e($b['label']) ?></span>
          <span class="kpi-value sm"><?= e(rp($nilai)) ?></span>
          <span class="kpi-sub"><?= nf($total['c' . $i]) ?> invoice · <?= pct($pctVal) ?></span>
        </a>
      <?php endforeach; ?>
      <div class="kpi kpi-dark">
        <span class="kpi-label">Total Piutang</span>
        <span class="kpi-value sm"><?= e(rp($grandTotal)) ?></span>
        <span class="kpi-sub"><?= nf($total['jumlah_invoice']) ?> invoice</span>
      </div>
    </div>
  </div>
</div>

<div class="card">
  <div class="card-header">
    <i class="bi bi-table me-1"></i>Aging per <?= e($groupOptions[$groupBy]) ?>
    <span class="text-body-secondary fw-normal ms-1">(<?= nf(count($rep['rows'])) ?> baris)</span>
  </div>
  <div class="table-wrap">
    <table class="table table-hover table-sticky mb-0">
      <thead>
        <tr>
          <th><?= e($groupOptions[$groupBy]) ?></th>
          <th class="num">Invoice</th>
          <?php foreach ($bs as $b): ?>
            <th class="num"><span class="badge bg-<?= e($b['color']) ?>">&nbsp;</span> <?= e($b['label']) ?></th>
          <?php endforeach; ?>
          <th class="num">Total Saldo</th>
          <th class="num">%</th>
          <th class="ctr">Rata Umur</th>
          <th style="min-width:110px">Distribusi</th>
        </tr>
      </thead>
      <tbody>
      <?php if (!$rep['rows']): ?>
        <tr><td colspan="<?= count($bs) + 6 ?>"><div class="empty-state"><i class="bi bi-inbox"></i>Tidak ada piutang outstanding pada filter ini.</div></td></tr>
      <?php endif; ?>
      <?php foreach ($rep['rows'] as $row):
        $rowTotal = (float)$row['total_nilai']; ?>
        <tr>
          <td class="cell-strong">
            <?php if ($groupBy === 'customer' && !empty($row['grup_id'])): ?>
              <a class="text-decoration-none" href="<?= url('/kartu-piutang/' . (int)$row['grup_id']) ?>"><?= e(truncate($row['grup_label'], 40)) ?></a>
            <?php else: ?><?= e(truncate($row['grup_label'], 40)) ?><?php endif; ?>
          </td>
          <td class="num"><?= nf($row['jumlah_invoice']) ?></td>
          <?php foreach ($bs as $i => $b): ?>
            <td class="num"><?= (float)$row['b' . $i] != 0 ? rph($row['b' . $i]) : '<span class="text-body-tertiary">-</span>' ?></td>
          <?php endforeach; ?>
          <td class="num cell-strong"><?= rph($rowTotal) ?></td>
          <td class="num"><?= $grandTotal > 0 ? pct($rowTotal / $grandTotal * 100) : '-' ?></td>
          <td class="ctr"><?= $row['rata_hari'] === null ? '-' : nf($row['rata_hari'], 0) . ' hr' ?></td>
          <td>
            <div class="aging-bar" title="Distribusi bucket">
              <?php foreach ($bs as $i => $b):
                $w = $rowTotal > 0 ? (float)$row['b' . $i] / $rowTotal * 100 : 0;
                if ($w <= 0) continue; ?>
                <span class="bg-<?= e($b['color']) ?>" style="width:<?= number_format($w, 2, '.', '') ?>%"></span>
              <?php endforeach; ?>
            </div>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
      <?php if ($rep['rows']): ?>
      <tfoot>
        <tr>
          <td>TOTAL</td>
          <td class="num"><?= nf($total['jumlah_invoice']) ?></td>
          <?php foreach ($bs as $i => $b): ?><td class="num"><?= rph($total['b' . $i]) ?></td><?php endforeach; ?>
          <td class="num"><?= rph($grandTotal) ?></td>
          <td class="num">100,0%</td>
          <td colspan="2"></td>
        </tr>
      </tfoot>
      <?php endif; ?>
    </table>
  </div>
</div>

<?php viewStart('scripts'); ?>
<script>
(function () {
  const B = <?= json_encode(array_map(fn($i, $b) => [
      'label' => $b['label'], 'color' => $b['color'], 'nilai' => (float)$total['b' . $i], 'idx' => $i,
    ], array_keys($bs), $bs), JSON_UNESCAPED_UNICODE) ?>;
  const DRILL = <?= json_encode(url('/aging/detail', $qs)) ?>;
  const c = { success:'#198754', info:'#0dcaf0', warning:'#ffc107', danger:'#dc3545', primary:'#0d6efd', secondary:'#6c757d', dark:'#343a40' };
  SP.makeChart('chAgingKomposisi', {
    type: 'doughnut',
    data: { labels: B.map(b => b.label),
            datasets: [{ data: B.map(b => b.nilai), backgroundColor: B.map(b => c[b.color] || '#6c757d'), borderWidth: 2, borderColor: '#fff' }] },
    options: {
      cutout: '55%',
      plugins: { legend: { position: 'bottom' }, tooltip: { callbacks: { label: x => x.label + ': ' + SP.rp(x.parsed) } } },
      onClick: (e, els) => { if (els.length) window.location = DRILL + (DRILL.includes('?') ? '&' : '?') + 'bucket=' + B[els[0].index].idx; }
    }
  });
})();
</script>
<?php viewStop(); ?>
