<?php $qs = array_filter(array_merge($filters, ['dari'=>$from,'sampai'=>$to,'metode'=>$method,'dimensi'=>$dimensi]), fn($v)=>$v!==''&&$v!==null&&!is_array($v)); ?>
<form class="filter-bar" method="get" action="<?= url('/acp') ?>">
  <div class="row g-2 align-items-end">
    <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="acp_preset">Periode</label>
      <select class="form-select form-select-sm" id="acp_preset" name="preset" data-auto-submit>
        <?php foreach (['custom'=>'Rentang Bebas','bulan_ini'=>'Bulan Ini','bulan_lalu'=>'Bulan Lalu','kuartal_ini'=>'Kuartal Ini',
                        'kuartal_lalu'=>'Kuartal Lalu','ytd'=>'Tahun Berjalan (YTD)','tahun_ini'=>'Tahun Ini','tahun_lalu'=>'Tahun Lalu'] as $k=>$v): ?>
          <option value="<?= $k ?>" <?= $preset===$k?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?>
      </select></div>
    <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="acp_d1">Dari</label>
      <input type="date" class="form-control form-control-sm" id="acp_d1" name="dari" value="<?= attr($from) ?>"></div>
    <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="acp_d2">Sampai</label>
      <input type="date" class="form-control form-control-sm" id="acp_d2" name="sampai" value="<?= attr($to) ?>"></div>
    <div class="col-12 col-md-6 col-lg-3"><label class="form-label" for="acp_metode">Metode Perhitungan</label>
      <select class="form-select form-select-sm" id="acp_metode" name="metode" data-auto-submit>
        <?php foreach ($metodeOptions as $k=>$v): ?><option value="<?= $k ?>" <?= $method===$k?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?>
      </select></div>
    <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="acp_dim">Rincian per</label>
      <select class="form-select form-select-sm" id="acp_dim" name="dimensi" data-auto-submit>
        <?php foreach ($dimensiOptions as $k=>$v): ?><option value="<?= $k ?>" <?= $dimensi===$k?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?>
      </select></div>
    <?php foreach ([['area_id','Area','area'],['business_unit_id','Unit Bisnis','business_unit'],['salesperson_id','Sales','salesperson']] as [$fk,$lbl,$ok]): ?>
      <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="acp_<?= $fk ?>"><?= e($lbl) ?></label>
        <select class="form-select form-select-sm" id="acp_<?= $fk ?>" name="<?= $fk ?>"><option value="">Semua</option>
          <?php foreach ($opsi[$ok] as $o): ?><option value="<?= (int)$o['id'] ?>" <?= (($filters[$fk] ?? '')==$o['id'])?'selected':'' ?>><?= e($o['name']) ?></option><?php endforeach; ?>
        </select></div>
    <?php endforeach; ?>
    <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('acp','edit')): ?><a class="btn btn-outline-secondary btn-sm" href="<?= url('/acp/target') ?>"><i class="bi bi-bullseye me-1"></i>Target</a><?php endif; ?>
      <?php if (can('acp','export')): ?>
      <div class="dropdown"><button class="btn btn-outline-primary btn-sm dropdown-toggle" data-bs-toggle="dropdown"><i class="bi bi-download me-1"></i>Ekspor</button>
        <ul class="dropdown-menu dropdown-menu-end">
          <?php foreach (['xlsx'=>'Excel','csv'=>'CSV','pdf'=>'PDF'] as $fm=>$lb): ?>
            <li><a class="dropdown-item" href="<?= url('/acp/ekspor', array_merge($qs,['format'=>$fm])) ?>"><?= e($lb) ?></a></li><?php endforeach; ?>
          <li><a class="dropdown-item" target="_blank" href="<?= url('/acp/ekspor', array_merge($qs,['format'=>'print'])) ?>">Cetak</a></li>
        </ul></div>
      <?php endif; ?>
    </div>
  </div>
</form>

<div class="alert alert-<?= $indikator['color'] ?> d-flex flex-wrap align-items-center gap-3">
  <i class="bi bi-<?= e($indikator['icon']) ?> fs-3"></i>
  <div>
    <div class="fs-4 fw-bold"><?= $hasil['acp_hari']===null ? 'Tidak dapat dihitung' : nf($hasil['acp_hari'],1) . ' hari' ?></div>
    <div class="small"><strong><?= e($hasil['metode_label']) ?></strong></div>
    <div class="small">Target <?= $target ? nf($target['target_days'],0) . ' hari (toleransi ' . nf($target['tolerance_days'],0) . ' hari)' : 'belum ditetapkan' ?>
      — <strong><?= e($indikator['label']) ?></strong></div>
    <?php if (!empty($hasil['catatan'])): ?><div class="small mt-1"><i class="bi bi-info-circle me-1"></i><?= e($hasil['catatan']) ?></div><?php endif; ?>
  </div>
</div>

<div class="row g-3 mb-3">
  <div class="col-lg-6"><div class="card h-100">
    <div class="card-header"><i class="bi bi-calculator me-1"></i>Rincian Metode Aktif</div>
    <div class="table-wrap"><table class="table table-sm mb-0"><tbody>
      <?php if ($hasil['metode'] === 'finansial'): ?>
        <tr><td>Saldo AR Awal (<?= tgl(App\Core\Dates::addDays($from,-1)) ?>)</td><td class="num"><?= rph($hasil['ar_awal']) ?></td></tr>
        <tr><td>Saldo AR Akhir (<?= tgl($to) ?>)</td><td class="num"><?= rph($hasil['ar_akhir']) ?></td></tr>
        <tr class="table-light"><td class="fw-semibold">AR Rata-rata</td><td class="num fw-semibold"><?= rph($hasil['ar_rata_rata']) ?></td></tr>
        <tr><td>Penjualan Kredit Bersih</td><td class="num"><?= rph($hasil['penjualan_kredit_bersih']) ?></td></tr>
        <tr><td>Jumlah Hari Periode</td><td class="num"><?= nf($hasil['jumlah_hari']) ?> hari</td></tr>
        <tr><td>Jumlah Invoice Diterbitkan</td><td class="num"><?= nf($hasil['jumlah_invoice']) ?></td></tr>
        <tr><td>Penerimaan Kas Periode</td><td class="num"><?= rph($hasil['penerimaan_kas']) ?></td></tr>
        <tr><td>Perputaran Piutang</td><td class="num"><?= $hasil['perputaran_piutang']===null?'-':nf($hasil['perputaran_piutang'],2).'×' ?></td></tr>
        <tr class="table-warning"><td class="fw-bold">ACP</td><td class="num fw-bold"><?= $hasil['acp_hari']===null?'-':nf($hasil['acp_hari'],2).' hari' ?></td></tr>
      <?php else: ?>
        <tr><td>Invoice Lunas pada Periode</td><td class="num"><?= nf($hasil['jumlah_invoice']) ?></td></tr>
        <tr><td>Nilai Tertagih</td><td class="num"><?= rph($hasil['nilai_tertagih']) ?></td></tr>
        <tr class="table-light"><td class="fw-semibold">Rata-rata Hari Penagihan</td><td class="num fw-semibold"><?= $hasil['rata_sederhana']===null?'-':nf($hasil['rata_sederhana'],2).' hari' ?></td></tr>
        <tr><td>Rata-rata Tertimbang Nilai</td><td class="num"><?= $hasil['rata_tertimbang']===null?'-':nf($hasil['rata_tertimbang'],2).' hari' ?></td></tr>
        <tr><td>Median Hari Penagihan</td><td class="num"><?= $hasil['median']===null?'-':nf($hasil['median'],1).' hari' ?></td></tr>
        <tr><td>Tercepat / Terlama</td><td class="num"><?= $hasil['minimum']===null?'-':nf($hasil['minimum']).' / '.nf($hasil['maksimum']).' hari' ?></td></tr>
        <tr><td>Dibayar Tepat Waktu</td><td class="num"><?= nf($hasil['jumlah_tepat_waktu']) ?> (<?= $hasil['persen_tepat_waktu']===null?'-':pct($hasil['persen_tepat_waktu']) ?>)</td></tr>
        <tr><td>Dibayar Terlambat</td><td class="num"><?= nf($hasil['jumlah_terlambat']) ?> (<?= $hasil['persen_terlambat']===null?'-':pct($hasil['persen_terlambat']) ?>)</td></tr>
        <tr><td>Rata-rata Keterlambatan</td><td class="num"><?= $hasil['rata_keterlambatan']===null?'-':nf($hasil['rata_keterlambatan'],1).' hari' ?></td></tr>
      <?php endif; ?>
    </tbody></table></div>
  </div></div>

  <div class="col-lg-6"><div class="card h-100">
    <div class="card-header"><i class="bi bi-arrow-left-right me-1"></i>Metode Pembanding
      <span class="badge bg-secondary-subtle text-secondary-emphasis ms-1"><?= e($pembanding['metode']==='finansial'?'Standar Finansial':'Operasional') ?></span></div>
    <div class="card-body">
      <div class="d-flex align-items-baseline gap-2 mb-2">
        <span class="fs-3 fw-bold"><?= $pembanding['acp_hari']===null?'-':nf($pembanding['acp_hari'],1) ?></span>
        <span class="text-body-secondary">hari</span></div>
      <p class="small text-body-secondary mb-3"><?= e($pembanding['metode_label']) ?></p>
      <?php $sel = ($hasil['acp_hari'] !== null && $pembanding['acp_hari'] !== null) ? $hasil['acp_hari'] - $pembanding['acp_hari'] : null; ?>
      <div class="small">Selisih terhadap metode aktif: <strong><?= $sel===null?'-':nf($sel,2).' hari' ?></strong></div>
      <hr>
      <h6 class="small text-uppercase text-body-secondary">Perbandingan Periode</h6>
      <div class="table-wrap"><table class="table table-sm mb-0">
        <thead><tr><th>Perbandingan</th><th class="num">Sekarang</th><th class="num">Sebelumnya</th><th class="num">Selisih</th></tr></thead>
        <tbody><?php foreach ($comparisons as $c): ?>
          <tr><td class="small"><?= e($c['sekarang_label']) ?> vs <?= e($c['sebelum_label']) ?></td>
            <td class="num"><?= $c['sekarang']['acp_hari']===null?'-':nf($c['sekarang']['acp_hari'],1) ?></td>
            <td class="num"><?= $c['sebelum']['acp_hari']===null?'-':nf($c['sebelum']['acp_hari'],1) ?></td>
            <td class="num <?= $c['arah']==='membaik'?'text-success':($c['arah']==='memburuk'?'text-danger':'') ?>">
              <?= $c['selisih']===null?'-':(($c['selisih']>0?'+':'').nf($c['selisih'],1)) ?>
              <?php if ($c['arah']==='membaik'): ?><i class="bi bi-arrow-down-short"></i><?php elseif ($c['arah']==='memburuk'): ?><i class="bi bi-arrow-up-short"></i><?php endif; ?>
            </td></tr>
        <?php endforeach; ?></tbody>
      </table></div>
    </div>
  </div></div>
</div>

<div class="card mb-3">
  <div class="card-header"><i class="bi bi-graph-up me-1"></i>Tren ACP Bulanan vs Target — Tahun <?= e(substr($to,0,4)) ?></div>
  <div class="card-body"><div class="chart-box lg"><canvas id="chAcpTren"></canvas></div></div>
</div>

<div class="card">
  <div class="card-header"><i class="bi bi-list-ol me-1"></i>Kinerja Penagihan per <?= e($dimensiOptions[$dimensi]) ?>
    <span class="text-body-secondary fw-normal">(<?= nf(count($byDim)) ?> baris)</span></div>
  <div class="table-wrap"><table class="table table-hover table-sticky mb-0">
    <thead><tr>
      <th><?= e($dimensiOptions[$dimensi]) ?></th><th class="num">Invoice Lunas</th><th class="num">Nilai Tertagih</th>
      <th class="num">Rata Hari</th><th class="num">Tertimbang</th><th class="num">Min</th><th class="num">Maks</th>
      <th class="num">% Tepat Waktu</th><th class="num">Rata Telat</th><th class="num">Target</th><th class="ctr">Status</th>
    </tr></thead>
    <tbody>
    <?php if (!$byDim): ?><tr><td colspan="11"><div class="empty-state"><i class="bi bi-inbox"></i>Tidak ada invoice lunas pada periode ini.</div></td></tr><?php endif; ?>
    <?php foreach ($byDim as $r): ?>
      <tr>
        <td class="cell-strong"><?= e(truncate($r['grup_label'],38)) ?></td>
        <td class="num"><?= nf($r['jumlah_invoice']) ?></td>
        <td class="num"><?= rph($r['nilai_tertagih']) ?></td>
        <td class="num cell-strong"><?= $r['rata_hari']===null?'-':nf($r['rata_hari'],1) ?></td>
        <td class="num"><?= $r['rata_tertimbang']===null?'-':nf($r['rata_tertimbang'],1) ?></td>
        <td class="num"><?= nf($r['min_hari']) ?></td>
        <td class="num"><?= nf($r['maks_hari']) ?></td>
        <td class="num"><?= $r['persen_tepat_waktu']===null?'-':pct($r['persen_tepat_waktu']) ?></td>
        <td class="num"><?= $r['rata_telat']===null?'-':nf($r['rata_telat'],1) ?></td>
        <td class="num"><?= $r['target']===null?'-':nf($r['target'],0) ?></td>
        <td class="ctr"><span class="badge bg-<?= e($r['indikator']['color']) ?>-subtle text-<?= e($r['indikator']['color']) ?>-emphasis">
          <i class="bi bi-<?= e($r['indikator']['icon']) ?> me-1"></i><?= e($r['indikator']['label']) ?></span></td>
      </tr>
    <?php endforeach; ?>
    </tbody></table></div>
</div>

<?php viewStart('scripts'); ?>
<script>
(function(){
  const T = <?= json_encode($trend, JSON_UNESCAPED_UNICODE) ?>;
  SP.makeChart('chAcpTren', {
    data: { labels: T.map(t=>t.label), datasets: [
      { type:'line', label:'ACP Aktual (hari)', data:T.map(t=>t.acp), borderColor:'#1f3864',
        backgroundColor:'rgba(31,56,100,.10)', tension:.3, fill:true, pointRadius:4, borderWidth:2.5, yAxisID:'y' },
      { type:'line', label:'Target (hari)', data:T.map(t=>t.target), borderColor:'#00b894',
        borderDash:[6,4], pointRadius:0, borderWidth:2, fill:false, yAxisID:'y' },
      { type:'bar', label:'Nilai Tertagih', data:T.map(t=>t.nilai), backgroundColor:'rgba(46,134,222,.28)',
        borderRadius:4, yAxisID:'y1' }
    ]},
    options: { interaction:{mode:'index',intersect:false},
      plugins:{ legend:{position:'bottom'} },
      scales: {
        y: { position:'left', beginAtZero:true, title:{display:true,text:'Hari'}, ticks:{callback:v=>v+' hr'}, grid:{color:'rgba(0,0,0,.05)'} },
        y1:{ position:'right', beginAtZero:true, title:{display:true,text:'Nilai'}, grid:{drawOnChartArea:false}, ticks:{callback:v=>SP.rpShort(v)} },
        x: { grid:{display:false} } }
    }
  });
})();
</script>
<?php viewStop(); ?>
