<?php
use App\Core\Dates;
$qs = array_filter($filters, fn($v) => $v !== '' && $v !== null && !is_array($v));
?>

<?= \App\Core\View::partial('partials/filter_piutang', [
      'filters' => $filters, 'opsi' => $opsi, 'action' => url('/piutang'),
      'tampilkan' => ['cari','area','bu','sales','co','jobcat','revcat','status','tanggal','jatuh_tempo','nilai','outstanding'],
    ]) ?>

<div class="kpi-grid mb-3">
  <div class="kpi kpi-primary"><span class="kpi-label">Jumlah Invoice</span><span class="kpi-value"><?= nf($tot['jumlah']) ?></span><span class="kpi-sub"><?= nf($tot['jumlah_customer']) ?> customer</span></div>
  <div class="kpi kpi-secondary"><span class="kpi-label">Nominal Bruto</span><span class="kpi-value sm"><?= e(rp($tot['bruto'])) ?></span><span class="kpi-sub">Sebelum potongan</span></div>
  <div class="kpi kpi-info"><span class="kpi-label">Total Tagihan</span><span class="kpi-value sm"><?= e(rp($tot['bersih'])) ?></span><span class="kpi-sub">Potongan <?= e(rp($tot['potongan'])) ?></span></div>
  <div class="kpi kpi-success"><span class="kpi-label">Pembayaran</span><span class="kpi-value sm"><?= e(rp($tot['dibayar'])) ?></span><span class="kpi-sub">Diterima</span></div>
  <div class="kpi kpi-warning"><span class="kpi-label">Saldo Piutang</span><span class="kpi-value sm"><?= e(rp($tot['saldo'])) ?></span><span class="kpi-sub">Sesuai filter aktif</span></div>
  <div class="kpi kpi-dark"><span class="kpi-label">PPh 23 Dipotong</span><span class="kpi-value sm"><?= e(rp($tot['pph23'])) ?></span><span class="kpi-sub">Total periode terpilih</span></div>
</div>

<div class="card">
  <div class="card-header">
    <i class="bi bi-cash-stack me-1"></i>Daftar Piutang
    <span class="text-body-secondary fw-normal ms-1">(<?= nf($p['total']) ?> baris)</span>
    <div class="card-actions">
      <div class="dropdown">
        <button class="btn btn-sm btn-light dropdown-toggle" type="button" data-bs-toggle="dropdown">
          <i class="bi bi-layout-three-columns me-1"></i>Kolom
        </button>
        <div class="dropdown-menu p-2" style="min-width:210px">
          <?php foreach ([
            'faktur' => 'No. Faktur Pajak', 'so' => 'No. SO', 'kirim' => 'Tgl Kirim',
            'outlet' => 'Outlet', 'area' => 'Area', 'unit' => 'Unit Bisnis', 'sales' => 'Sales',
            'kategori' => 'Kategori Pekerjaan', 'bruto' => 'Nominal Bruto', 'potongan' => 'Potongan',
          ] as $k => $lbl): ?>
            <div class="form-check">
              <input class="form-check-input" type="checkbox" id="col_<?= $k ?>" data-col-toggle="<?= $k ?>"
                     <?= in_array($k, ['faktur','outlet','area','sales','bruto'], true) ? 'checked' : '' ?>>
              <label class="form-check-label small" for="col_<?= $k ?>"><?= e($lbl) ?></label>
            </div>
          <?php endforeach; ?>
        </div>
      </div>
      <?php if (can('piutang', 'export')): ?>
        <div class="dropdown">
          <button class="btn btn-sm btn-outline-primary 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('/piutang/ekspor', array_merge($qs, ['format' => 'xlsx', 'urut' => $sort, 'arah' => $dir])) ?>"><i class="bi bi-file-earmark-excel me-2"></i>Excel (.xlsx)</a></li>
            <li><a class="dropdown-item" href="<?= url('/piutang/ekspor', array_merge($qs, ['format' => 'csv', 'urut' => $sort, 'arah' => $dir])) ?>"><i class="bi bi-filetype-csv me-2"></i>CSV</a></li>
            <li><a class="dropdown-item" href="<?= url('/piutang/ekspor', array_merge($qs, ['format' => 'pdf', 'urut' => $sort, 'arah' => $dir])) ?>"><i class="bi bi-file-earmark-pdf me-2"></i>PDF</a></li>
            <li><a class="dropdown-item" target="_blank" href="<?= url('/piutang/ekspor', array_merge($qs, ['format' => 'print', 'urut' => $sort, 'arah' => $dir])) ?>"><i class="bi bi-printer me-2"></i>Cetak</a></li>
          </ul>
        </div>
      <?php endif; ?>
    </div>
  </div>

  <div class="table-wrap">
    <table class="table table-hover table-sticky mb-0">
      <thead>
        <tr>
          <th><?= sortLink('invoice_no', 'No. Invoice', $sort, $dir) ?></th>
          <th data-col="faktur">No. Faktur Pajak</th>
          <th data-col="so">No. SO</th>
          <th class="ctr"><?= sortLink('invoice_date', 'Tgl Invoice', $sort, $dir) ?></th>
          <th class="ctr" data-col="kirim"><?= sortLink('sent_date', 'Tgl Kirim', $sort, $dir) ?></th>
          <th class="ctr"><?= sortLink('due_date', 'Jatuh Tempo', $sort, $dir) ?></th>
          <th><?= sortLink('customer', 'Customer', $sort, $dir) ?></th>
          <th data-col="outlet">Outlet</th>
          <th data-col="area"><?= sortLink('area', 'Area', $sort, $dir) ?></th>
          <th data-col="unit">Unit Bisnis</th>
          <th data-col="sales"><?= sortLink('salesperson', 'Sales', $sort, $dir) ?></th>
          <th data-col="kategori">Kategori</th>
          <th class="num" data-col="bruto"><?= sortLink('gross_amount', 'Nominal', $sort, $dir) ?></th>
          <th class="num" data-col="potongan">Potongan</th>
          <th class="num"><?= sortLink('net_amount', 'Total Tagihan', $sort, $dir) ?></th>
          <th class="num"><?= sortLink('paid_amount', 'Dibayar', $sort, $dir) ?></th>
          <th class="num"><?= sortLink('outstanding_amount', 'Saldo', $sort, $dir) ?></th>
          <th class="ctr"><?= sortLink('aging_days', 'Umur', $sort, $dir) ?></th>
          <th class="ctr">Status</th>
          <th class="ctr">Aksi</th>
        </tr>
      </thead>
      <tbody>
      <?php if (!$p['data']): ?>
        <tr><td colspan="20">
          <div class="empty-state"><i class="bi bi-inbox"></i>
            Tidak ada piutang yang sesuai dengan filter.<br>
            <a href="<?= url('/piutang') ?>" class="btn btn-sm btn-light mt-2">Atur ulang filter</a>
          </div>
        </td></tr>
      <?php endif; ?>
      <?php foreach ($p['data'] as $r):
        $umur = $r['aging_days'];
        $warna = agingColor($umur === null ? null : (int)$umur); ?>
        <tr>
          <td class="nowrap">
            <a class="text-decoration-none fw-semibold" href="<?= url('/invoice/' . (int)$r['id']) ?>"><?= e($r['invoice_no']) ?></a>
            <?php if (!empty($r['dq_flags']) && $r['dq_flags'] !== '[]'): ?>
              <i class="bi bi-exclamation-triangle-fill text-warning small" data-bs-toggle="tooltip"
                 title="<?= attr(implode(', ', array_map(fn($f) => \App\Services\DataQualityService::FLAG_LABELS[$f] ?? $f, arr($r['dq_flags'])))) ?>"></i>
            <?php endif; ?>
          </td>
          <td data-col="faktur" class="nowrap small font-monospace"><?= e($r['tax_invoice_no'] ?: '-') ?></td>
          <td data-col="so" class="nowrap small"><?= e($r['so_no'] ?: '-') ?></td>
          <td class="ctr"><?= tgl($r['invoice_date']) ?></td>
          <td class="ctr" data-col="kirim"><?= tgl($r['sent_date']) ?></td>
          <td class="ctr"><?= tgl($r['due_date']) ?></td>
          <td><a class="text-decoration-none" href="<?= url('/kartu-piutang/' . (int)$r['customer_id']) ?>"><?= e(truncate($r['customer_name'], 30)) ?></a></td>
          <td data-col="outlet"><?= e(truncate($r['outlet_name'] ?: '-', 26)) ?></td>
          <td data-col="area"><?= e($r['area_name'] ?: '-') ?></td>
          <td data-col="unit"><?= e($r['business_unit_name'] ?: '-') ?></td>
          <td data-col="sales"><?= e($r['salesperson_name'] ?: '-') ?></td>
          <td data-col="kategori"><?= e(truncate($r['job_category_name'] ?: '-', 20)) ?></td>
          <td class="num" data-col="bruto"><?= rph($r['gross_amount']) ?></td>
          <td class="num" data-col="potongan"><?= rph($r['total_deduction']) ?></td>
          <td class="num"><?= rph($r['net_amount']) ?></td>
          <td class="num"><?= rph($r['paid_amount']) ?></td>
          <td class="num cell-strong"><?= rph($r['outstanding_amount']) ?></td>
          <td class="ctr">
            <?php if ($umur === null): ?><span class="text-body-tertiary">-</span>
            <?php else: ?><span class="badge bg-<?= $warna ?>-subtle text-<?= $warna ?>-emphasis"><?= nf($umur) ?> hr</span><?php endif; ?>
          </td>
          <td class="ctr"><?= statusBadge($r['payment_status_code']) ?></td>
          <td class="ctr nowrap">
            <a class="btn btn-sm btn-light py-0 px-1" href="<?= url('/invoice/' . (int)$r['id']) ?>" title="Lihat detail"><i class="bi bi-eye"></i></a>
            <?php if (can('pembayaran', 'create') && (float)$r['outstanding_amount'] > 0): ?>
              <a class="btn btn-sm btn-light py-0 px-1" href="<?= url('/pembayaran/tambah', ['invoice_id' => (int)$r['id']]) ?>" title="Catat pembayaran"><i class="bi bi-wallet2"></i></a>
            <?php endif; ?>
            <?php if (can('penagihan', 'create') && (float)$r['outstanding_amount'] > 0): ?>
              <a class="btn btn-sm btn-light py-0 px-1" href="<?= url('/penagihan/tambah', ['invoice_id' => (int)$r['id']]) ?>" title="Catat follow-up"><i class="bi bi-telephone"></i></a>
            <?php endif; ?>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
      <?php if ($p['data']): ?>
      <tfoot>
        <tr>
          <td colspan="12">TOTAL SELURUH HASIL FILTER (<?= nf($tot['jumlah']) ?> invoice)</td>
          <td class="num" data-col="bruto"><?= rph($tot['bruto']) ?></td>
          <td class="num" data-col="potongan"><?= rph($tot['potongan']) ?></td>
          <td class="num"><?= rph($tot['bersih']) ?></td>
          <td class="num"><?= rph($tot['dibayar']) ?></td>
          <td class="num"><?= rph($tot['saldo']) ?></td>
          <td colspan="3"></td>
        </tr>
      </tfoot>
      <?php endif; ?>
    </table>
  </div>
  <?= \App\Core\View::partial('partials/pagination', ['p' => $p]) ?>
</div>
