<div class="d-flex flex-wrap gap-2 mb-3">
  <a class="btn btn-sm btn-light" href="<?= url('/kartu-piutang') ?>"><i class="bi bi-arrow-left me-1"></i>Kembali</a>
  <?php if (can('kartu_piutang','export')): ?>
    <a class="btn btn-sm btn-outline-primary" href="<?= url('/kartu-piutang/'.(int)$cust['id'].'/ekspor',['format'=>'xlsx']) ?>"><i class="bi bi-file-earmark-excel me-1"></i>Excel</a>
    <a class="btn btn-sm btn-outline-danger" href="<?= url('/kartu-piutang/'.(int)$cust['id'].'/ekspor',['format'=>'pdf']) ?>"><i class="bi bi-file-earmark-pdf me-1"></i>PDF</a>
  <?php endif; ?>
  <?php if (can('master','edit')): ?>
    <a class="btn btn-sm btn-outline-secondary ms-auto" href="<?= url('/master/customer/'.(int)$cust['id'].'/ubah') ?>"><i class="bi bi-pencil me-1"></i>Ubah Data Customer</a>
  <?php endif; ?>
</div>

<div class="kpi-grid mb-3">
  <div class="kpi kpi-primary"><span class="kpi-label">Jumlah Invoice</span><span class="kpi-value"><?= nf($summary['jumlah_invoice']) ?></span></div>
  <div class="kpi kpi-info"><span class="kpi-label">Total Tagihan</span><span class="kpi-value sm"><?= e(rp($summary['total_bersih'])) ?></span></div>
  <div class="kpi kpi-success"><span class="kpi-label">Dibayar</span><span class="kpi-value sm"><?= e(rp($summary['total_bayar'])) ?></span></div>
  <div class="kpi kpi-warning"><span class="kpi-label">Saldo Piutang</span><span class="kpi-value sm"><?= e(rp($summary['total_saldo'])) ?></span></div>
  <div class="kpi kpi-danger"><span class="kpi-label">Terlambat</span><span class="kpi-value sm"><?= e(rp($summary['total_terlambat'])) ?></span></div>
  <div class="kpi kpi-secondary"><span class="kpi-label">Rata Hari Penagihan</span><span class="kpi-value"><?= $summary['rata_hari_penagihan']===null?'-':nf($summary['rata_hari_penagihan'],1) ?></span>
    <span class="kpi-sub">hari</span></div>
</div>

<div class="row g-3 mb-3">
  <div class="col-lg-4">
    <div class="card h-100"><div class="card-header"><i class="bi bi-person-vcard me-1"></i>Data Customer</div>
      <div class="card-body"><dl class="dl-grid">
        <dt>Kode</dt><dd class="font-monospace"><?= e($cust['code']) ?></dd>
        <dt>Nama</dt><dd class="fw-bold"><?= e($cust['name']) ?></dd>
        <dt>NPWP</dt><dd><?= e($cust['npwp'] ?: '-') ?></dd>
        <dt>NITKU</dt><dd><?= e($cust['nitku'] ?: '-') ?></dd>
        <dt>Narahubung</dt><dd><?= e($cust['contact_person'] ?: '-') ?></dd>
        <dt>Telepon</dt><dd><?= e($cust['phone'] ?: '-') ?></dd>
        <dt>Email</dt><dd class="small"><?= e($cust['email'] ?: '-') ?></dd>
        <dt>Termin</dt><dd><?= $cust['payment_term_days'] ? nf($cust['payment_term_days']).' hari' : 'Ikuti pengaturan' ?></dd>
        <dt>Limit Kredit</dt><dd><?= rph($cust['credit_limit']) ?></dd>
        <dt>Pemakaian Limit</dt><dd><?php
            $lim = (float)$cust['credit_limit'];
            echo $lim > 0 ? pct((float)$summary['total_saldo']/$lim*100) : '<span class="text-body-tertiary">tanpa limit</span>'; ?></dd>
        <dt>Status</dt><dd><?= badge(['AKTIF'=>'Aktif','TIDAK_AKTIF'=>'Tidak Aktif','BLOKIR'=>'Blokir'][$cust['status']] ?? $cust['status'],
              $cust['status']==='AKTIF'?'success':($cust['status']==='BLOKIR'?'danger':'secondary')) ?></dd>
        <dt>Skor Risiko</dt><dd><?= nf($risk['skor'],1) ?> —
          <?= badge(['RENDAH'=>'Rendah','SEDANG'=>'Sedang','TINGGI'=>'Tinggi','SANGAT_TINGGI'=>'Sangat Tinggi'][$risk['kategori']],
              ['RENDAH'=>'success','SEDANG'=>'info','TINGGI'=>'warning','SANGAT_TINGGI'=>'danger'][$risk['kategori']]) ?></dd>
      </dl>
      <?php if ($cust['billing_address']): ?><hr><div class="small"><strong>Alamat Penagihan:</strong><br><?= nlbr($cust['billing_address']) ?></div><?php endif; ?>
      <?php if ($cust['notes']): ?><hr><div class="small"><strong>Catatan:</strong><br><?= nlbr($cust['notes']) ?></div><?php endif; ?>
      </div></div>
  </div>
  <div class="col-lg-4">
    <div class="card h-100"><div class="card-header"><i class="bi bi-hourglass-split me-1"></i>Komposisi Aging</div>
      <div class="card-body"><div class="chart-box sm"><canvas id="chKartuAging"></canvas></div>
        <table class="table table-sm mt-2 mb-0">
          <?php foreach ($aging['buckets'] as $i => $b): ?>
            <tr><td><span class="badge bg-<?= e($b['color']) ?>">&nbsp;</span> <?= e($b['label']) ?></td>
              <td class="num"><?= rph($aging['total']['b'.$i]) ?></td></tr>
          <?php endforeach; ?>
        </table>
      </div></div>
  </div>
  <div class="col-lg-4">
    <div class="card h-100"><div class="card-header"><i class="bi bi-telephone me-1"></i>Aktivitas Penagihan Terakhir</div>
      <div class="card-body">
        <?php if (!$followups): ?><p class="text-body-secondary small mb-0">Belum ada aktivitas penagihan.</p><?php endif; ?>
        <div class="timeline">
          <?php foreach (array_slice($followups,0,8) as $fu): ?>
            <div class="timeline-item">
              <div class="timeline-time"><?= tgl($fu['followup_date']) ?><?= $fu['invoice_no'] ? ' · ' . e($fu['invoice_no']) : '' ?></div>
              <?php if ($fu['status_name']): ?><div><?= badge($fu['status_name'], $fu['status_color'] ?: 'secondary') ?></div><?php endif; ?>
              <div class="small"><?= e(truncate($fu['result'] ?: '-',110)) ?></div>
            </div>
          <?php endforeach; ?>
        </div>
      </div></div>
  </div>
</div>

<div class="card mb-3">
  <div class="card-header"><i class="bi bi-receipt me-1"></i>Daftar Invoice (<?= count($invoices) ?>)</div>
  <div class="table-wrap" style="max-height:520px"><table class="table table-sm table-hover table-sticky mb-0">
    <thead><tr><th>Invoice</th><th class="ctr">Tgl Invoice</th><th class="ctr">Jatuh Tempo</th><th>Outlet</th><th>Jenis Pekerjaan</th>
      <th class="num">Nominal</th><th class="num">Tagihan</th><th class="num">Dibayar</th><th class="num">Saldo</th>
      <th class="ctr">Tgl Bayar</th><th class="ctr">Umur</th><th class="ctr">Status</th></tr></thead>
    <tbody>
    <?php $tB=0;$tN=0;$tP=0;$tS=0;
    foreach ($invoices as $iv): $tB+=(float)$iv['gross_amount'];$tN+=(float)$iv['net_amount'];$tP+=(float)$iv['paid_amount'];$tS+=(float)$iv['outstanding_amount']; ?>
      <tr>
        <td><a class="text-decoration-none" href="<?= url('/invoice/'.(int)$iv['id']) ?>"><?= e($iv['invoice_no']) ?></a></td>
        <td class="ctr"><?= tgl($iv['invoice_date']) ?></td>
        <td class="ctr"><?= tgl($iv['due_date']) ?></td>
        <td class="small"><?= e(truncate($iv['outlet_name'] ?: '-',20)) ?></td>
        <td class="small"><?= e(truncate($iv['job_type_name'] ?: '-',22)) ?></td>
        <td class="num"><?= rph($iv['gross_amount']) ?></td>
        <td class="num"><?= rph($iv['net_amount']) ?></td>
        <td class="num"><?= rph($iv['paid_amount']) ?></td>
        <td class="num cell-strong"><?= rph($iv['outstanding_amount']) ?></td>
        <td class="ctr small"><?= tgl($iv['last_payment_date']) ?></td>
        <td class="ctr"><?= $iv['aging_days']===null?'-':badge(nf($iv['aging_days']).' hr', agingColor((int)$iv['aging_days'])) ?></td>
        <td class="ctr"><?= statusBadge($iv['payment_status_code']) ?></td>
      </tr>
    <?php endforeach; ?>
    <?php if (!$invoices): ?><tr><td colspan="12" class="text-center text-body-secondary py-3">Belum ada invoice.</td></tr><?php endif; ?>
    </tbody>
    <?php if ($invoices): ?><tfoot><tr><td colspan="5">TOTAL</td>
      <td class="num"><?= rph($tB) ?></td><td class="num"><?= rph($tN) ?></td>
      <td class="num"><?= rph($tP) ?></td><td class="num"><?= rph($tS) ?></td><td colspan="3"></td></tr></tfoot><?php endif; ?>
  </table></div>
</div>

<div class="card">
  <div class="card-header"><i class="bi bi-wallet2 me-1"></i>Riwayat Pembayaran (<?= count($payments) ?>)</div>
  <div class="table-wrap" style="max-height:380px"><table class="table table-sm table-hover table-sticky mb-0">
    <thead><tr><th>No. Pembayaran</th><th class="ctr">Tanggal</th><th>Invoice</th><th>Metode</th><th>Bank</th><th>Referensi</th><th>Jenis</th><th class="num">Nilai</th></tr></thead>
    <tbody>
    <?php foreach ($payments as $pm): ?>
      <tr><td><a href="<?= url('/pembayaran') ?>?cari=<?= urlencode($pm['payment_no']) ?>"><?= e($pm['payment_no']) ?></a></td>
        <td class="ctr"><?= tgl($pm['payment_date']) ?></td><td class="small"><?= e($pm['invoice_no']) ?></td>
        <td class="small"><?= e($pm['method']) ?></td><td class="small"><?= e($pm['bank_name'] ?: '-') ?></td>
        <td class="small"><?= e($pm['reference_no'] ?: '-') ?></td><td class="small"><?= e($pm['payment_type']) ?></td>
        <td class="num"><?= rph($pm['amount']) ?></td></tr>
    <?php endforeach; ?>
    <?php if (!$payments): ?><tr><td colspan="8" class="text-center text-body-secondary py-3">Belum ada pembayaran.</td></tr><?php endif; ?>
    </tbody></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)$aging['total']['b'.$i]],
      array_keys($aging['buckets']), $aging['buckets']), JSON_UNESCAPED_UNICODE) ?>;
  const c = {success:'#198754',info:'#0dcaf0',warning:'#ffc107',danger:'#dc3545',primary:'#0d6efd',secondary:'#6c757d',dark:'#343a40'};
  SP.makeChart('chKartuAging', { 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:{display:false}, tooltip:{callbacks:{label:x=>x.label+': '+SP.rp(x.parsed)}} } } });
})();
</script>
<?php viewStop(); ?>
