<div class="kpi-grid mb-3">
  <div class="kpi kpi-primary"><span class="kpi-label">Total Revisi (RF)</span><span class="kpi-value"><?= nf($stat['total']) ?></span></div>
  <div class="kpi kpi-success"><span class="kpi-label">Disetujui &amp; Diterapkan</span><span class="kpi-value"><?= nf($stat['disetujui']) ?></span></div>
  <div class="kpi kpi-warning"><span class="kpi-label">Menunggu Persetujuan</span><span class="kpi-value"><?= nf($stat['menunggu']) ?></span></div>
  <div class="kpi kpi-danger"><span class="kpi-label">Belum Cocok Invoice</span><span class="kpi-value"><?= nf($stat['belum_cocok']) ?></span></div>
  <div class="kpi kpi-info"><span class="kpi-label">Nilai Invoice Lama</span><span class="kpi-value sm"><?= e(rp($stat['nilai_lama'])) ?></span></div>
  <div class="kpi kpi-dark"><span class="kpi-label">Revenue Dobel Dicegah</span><span class="kpi-value sm"><?= e(rp($stat['revenue_dicegah'])) ?></span>
    <span class="kpi-sub">DPP invoice yang dikeluarkan</span></div>
</div>

<?php if ($gaps): ?>
<div class="alert alert-warning"><i class="bi bi-exclamation-triangle-fill me-1"></i>
  <strong>Celah penomoran RF terdeteksi:</strong> <?= e(implode(', ', array_slice($gaps,0,20))) ?><?= count($gaps)>20 ? ' …' : '' ?>.
  Pastikan tidak ada dokumen revisi yang belum dicatat di sistem.</div>
<?php endif; ?>

<form class="filter-bar" method="get" action="<?= url('/revisi') ?>">
  <div class="row g-2 align-items-end">
    <div class="col-12 col-md-4 col-lg-3"><label class="form-label" for="rv_cari">Pencarian</label>
      <input type="search" class="form-control form-control-sm" id="rv_cari" name="cari" value="<?= attr($filters['cari'] ?? '') ?>" placeholder="No. RF, invoice lama/baru, alasan…"></div>
    <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="rv_st">Status</label>
      <select class="form-select form-select-sm" id="rv_st" name="status"><option value="">Semua</option>
        <?php foreach (['pending'=>'Menunggu','approved'=>'Disetujui','rejected'=>'Ditolak','menunggu_pencocokan'=>'Menunggu Pencocokan','draft'=>'Draf'] as $k=>$v): ?>
          <option value="<?= $k ?>" <?= (($filters['status'] ?? '')===$k)?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select></div>
    <div class="col-6 col-md-3 col-lg-3"><label class="form-label" for="rv_tp">Jenis Revisi</label>
      <select class="form-select form-select-sm" id="rv_tp" name="revision_type_id"><option value="">Semua</option>
        <?php foreach ($types as $t): ?><option value="<?= (int)$t['id'] ?>" <?= (($filters['revision_type_id'] ?? '')==$t['id'])?'selected':'' ?>><?= e($t['name']) ?></option><?php endforeach; ?></select></div>
    <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="rv_ac">Tindakan</label>
      <select class="form-select form-select-sm" id="rv_ac" name="action"><option value="">Semua</option>
        <?php foreach ($actions as $k=>$v): ?><option value="<?= $k ?>" <?= (($filters['action'] ?? '')===$k)?'selected':'' ?>><?= e($v) ?></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>
      <?php if (can('revisi','edit')): ?>
      <form method="post" action="<?= url('/revisi/cocokkan-ulang') ?>"><?= csrf() ?>
        <button class="btn btn-outline-secondary btn-sm"><i class="bi bi-link-45deg me-1"></i>Cocokkan Ulang</button></form><?php endif; ?>
      <?php if (can('revisi','create')): ?><a class="btn btn-primary btn-sm" href="<?= url('/revisi/tambah') ?>"><i class="bi bi-plus-lg me-1"></i>Tambah RF</a><?php endif; ?>
      <?php if (can('revisi','export')): ?><a class="btn btn-outline-primary btn-sm" href="<?= url('/revisi/ekspor',['format'=>'xlsx']) ?>"><i class="bi bi-download"></i></a><?php endif; ?>
    </div>
  </div>
</form>

<div class="card">
  <div class="card-header"><i class="bi bi-arrow-repeat me-1"></i>Register Revisi Invoice <span class="text-body-secondary fw-normal">(<?= nf($p['total']) ?>)</span></div>
  <div class="table-wrap"><table class="table table-hover table-sticky mb-0">
    <thead><tr><th>No. RF</th><th class="ctr">Tgl RF</th><th>Invoice Lama</th><th>Invoice Baru</th><th>Customer</th>
      <th>Jenis Revisi</th><th class="ctr">Tindakan</th><th class="num">Nominal Lama</th><th class="num">Nominal Baru</th>
      <th class="ctr">Status</th><th>Alasan</th><th class="ctr">Aksi</th></tr></thead>
    <tbody>
    <?php if (!$p['data']): ?><tr><td colspan="12"><div class="empty-state"><i class="bi bi-arrow-repeat"></i>Belum ada data revisi invoice.</div></td></tr><?php endif; ?>
    <?php foreach ($p['data'] as $r): ?>
      <tr>
        <td><a class="text-decoration-none fw-semibold" href="<?= url('/revisi/'.(int)$r['id']) ?>"><?= e($r['rf_no']) ?></a></td>
        <td class="ctr"><?= tgl($r['rf_date']) ?><?php if (!$r['rf_date'] && $r['rf_date_raw']): ?><div class="small text-danger" title="Format tanggal tidak dapat dibaca"><?= e($r['rf_date_raw']) ?></div><?php endif; ?></td>
        <td class="nowrap"><?= $r['old_invoice_id'] ? '<a href="'.attr(url('/invoice/'.(int)$r['old_invoice_id'])).'">'.e($r['old_invoice_no']).'</a>' : e($r['old_invoice_no'] ?: '-') ?>
          <?php if (!$r['old_invoice_id'] && $r['old_invoice_no']): ?><i class="bi bi-exclamation-circle text-warning" data-bs-toggle="tooltip" title="Invoice lama belum ada di database"></i><?php endif; ?></td>
        <td class="nowrap"><?= $r['new_invoice_id'] ? '<a href="'.attr(url('/invoice/'.(int)$r['new_invoice_id'])).'">'.e($r['new_invoice_no']).'</a>' : e($r['new_invoice_no'] ?: '—') ?></td>
        <td><?= e(truncate($r['customer_name'] ?: '-',22)) ?></td>
        <td class="small"><?= e($r['jenis_revisi'] ?: '-') ?></td>
        <td class="ctr"><?= badge($actions[$r['old_invoice_action']] ?? $r['old_invoice_action'],
              ['replaced'=>'secondary','cancelled'=>'dark','revised'=>'info','written_off'=>'danger'][$r['old_invoice_action']] ?? 'secondary') ?></td>
        <td class="num"><?= rph($r['original_amount']) ?></td>
        <td class="num"><?= rph($r['revised_amount']) ?></td>
        <td class="ctr"><?= badge(['pending'=>'Menunggu','approved'=>'Disetujui','rejected'=>'Ditolak','menunggu_pencocokan'=>'Belum Cocok','draft'=>'Draf'][$r['status']] ?? $r['status'],
              ['pending'=>'warning','approved'=>'success','rejected'=>'danger','menunggu_pencocokan'=>'secondary','draft'=>'light'][$r['status']] ?? 'secondary') ?></td>
        <td class="small"><?= e(truncate($r['reason'] ?: '-',44)) ?></td>
        <td class="ctr nowrap">
          <a class="btn btn-sm btn-light py-0 px-1" href="<?= url('/revisi/'.(int)$r['id']) ?>"><i class="bi bi-eye"></i></a>
          <?php if (can('revisi','approve') && $r['status'] !== 'approved'): ?>
            <form method="post" action="<?= url('/revisi/'.(int)$r['id'].'/setujui') ?>" class="d-inline"><?= csrf() ?>
              <button class="btn btn-sm btn-light py-0 px-1 text-success" title="Setujui &amp; terapkan"
                data-konfirmasi="Setujui revisi <?= attr($r['rf_no']) ?>? Invoice lama akan dikeluarkan dari piutang aktif dan pendapatan tidak dihitung dua kali."
                data-konfirmasi-warna="success"><i class="bi bi-check-lg"></i></button></form><?php endif; ?>
        </td>
      </tr>
    <?php endforeach; ?>
    </tbody></table></div>
  <?= \App\Core\View::partial('partials/pagination', ['p' => $p]) ?>
</div>
