<?php $qs = array_filter(array_merge($filters,['tanggal_lapor'=>$asOf,'minggu'=>$weeks]), fn($v)=>$v!==''&&$v!==null&&!is_array($v));
$totalNilai = $fc['lewat']['nilai'] + array_sum(array_column($fc['minggu'],'nilai')) + $fc['jauh']['nilai'];
$totalBobot = $fc['lewat']['tertimbang'] + array_sum(array_column($fc['minggu'],'tertimbang')) + $fc['jauh']['tertimbang'];
?>
<form class="filter-bar" method="get" action="<?= url('/forecast') ?>">
  <div class="row g-2 align-items-end">
    <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="fc_asof">Tanggal Pelaporan</label>
      <input type="date" class="form-control form-control-sm" id="fc_asof" name="tanggal_lapor" value="<?= attr($asOf) ?>"></div>
    <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="fc_w">Jumlah Minggu</label>
      <input type="number" class="form-control form-control-sm" id="fc_w" name="minggu" min="4" max="26" value="<?= (int)$weeks ?>"></div>
    <?php foreach ([['area_id','Area','area'],['business_unit_id','Unit Bisnis','business_unit'],['collection_officer_id','Petugas Penagihan','collection_officer']] as [$fk,$lbl,$ok]): ?>
      <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="fc_<?= $fk ?>"><?= e($lbl) ?></label>
        <select class="form-select form-select-sm" id="fc_<?= $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('forecast','export')): ?>
        <a class="btn btn-outline-primary btn-sm" href="<?= url('/forecast/ekspor', array_merge($qs,['format'=>'xlsx'])) ?>"><i class="bi bi-file-earmark-excel me-1"></i>Excel</a>
        <a class="btn btn-outline-danger btn-sm" href="<?= url('/forecast/ekspor', array_merge($qs,['format'=>'pdf'])) ?>"><i class="bi bi-file-earmark-pdf me-1"></i>PDF</a>
      <?php endif; ?>
    </div>
  </div>
</form>

<div class="kpi-grid mb-3">
  <div class="kpi kpi-primary"><span class="kpi-label">Total Piutang Outstanding</span><span class="kpi-value sm"><?= e(rp($totalNilai)) ?></span></div>
  <div class="kpi kpi-success"><span class="kpi-label">Perkiraan Tertimbang</span><span class="kpi-value sm"><?= e(rp($totalBobot)) ?></span>
    <span class="kpi-sub">Berdasarkan bobot keyakinan</span></div>
  <div class="kpi kpi-danger"><span class="kpi-label">Sudah Lewat Jatuh Tempo</span><span class="kpi-value sm"><?= e(rp($fc['lewat']['nilai'])) ?></span>
    <span class="kpi-sub"><?= nf($fc['lewat']['jumlah']) ?> invoice</span></div>
  <div class="kpi kpi-info"><span class="kpi-label"><?= (int)$weeks ?> Minggu ke Depan</span>
    <span class="kpi-value sm"><?= e(rp(array_sum(array_column($fc['minggu'],'nilai')))) ?></span>
    <span class="kpi-sub"><?= nf(array_sum(array_column($fc['minggu'],'jumlah'))) ?> invoice</span></div>
</div>

<div class="card mb-3">
  <div class="card-header"><i class="bi bi-bar-chart-line me-1"></i>Proyeksi Penerimaan Kas per Minggu</div>
  <div class="card-body"><div class="chart-box lg"><canvas id="chFc"></canvas></div>
    <p class="small text-body-secondary mt-2 mb-0">Bobot keyakinan: janji bayar <?= (int)setting('penagihan.bobot_janji_bayar',90) ?>%,
      jatuh tempo mendatang <?= (int)setting('penagihan.bobot_jatuh_tempo',80) ?>%, estimasi historis <?= (int)setting('penagihan.bobot_perkiraan',50) ?>%.
      Bobot dapat diubah di Pengaturan → Penagihan.</p></div>
</div>

<div class="row g-3">
  <div class="col-lg-7">
    <div class="card h-100"><div class="card-header"><i class="bi bi-calendar-week me-1"></i>Rincian per Minggu</div>
      <div class="table-wrap"><table class="table table-sm table-hover mb-0">
        <thead><tr><th>Periode</th><th class="ctr">Rentang</th><th class="num">Invoice</th><th class="num">Nilai Jatuh Tempo</th><th class="num">Perkiraan Tertimbang</th></tr></thead>
        <tbody>
          <tr class="table-danger"><td class="fw-semibold">Sudah Lewat Jatuh Tempo</td><td class="ctr">—</td>
            <td class="num"><?= nf($fc['lewat']['jumlah']) ?></td><td class="num"><?= rph($fc['lewat']['nilai']) ?></td><td class="num"><?= rph($fc['lewat']['tertimbang']) ?></td></tr>
          <?php foreach ($fc['minggu'] as $m): ?>
            <tr><td><?= e($m['label']) ?></td><td class="ctr small"><?= tgl($m['mulai']) ?> – <?= tgl($m['selesai']) ?></td>
              <td class="num"><?= nf($m['jumlah']) ?></td><td class="num"><?= rph($m['nilai']) ?></td><td class="num"><?= rph($m['tertimbang']) ?></td></tr>
          <?php endforeach; ?>
          <tr class="table-secondary"><td><?= e($fc['jauh']['label']) ?></td><td class="ctr">—</td>
            <td class="num"><?= nf($fc['jauh']['jumlah']) ?></td><td class="num"><?= rph($fc['jauh']['nilai']) ?></td><td class="num"><?= rph($fc['jauh']['tertimbang']) ?></td></tr>
        </tbody>
        <tfoot><tr><td colspan="2">TOTAL</td>
          <td class="num"><?= nf($fc['lewat']['jumlah'] + array_sum(array_column($fc['minggu'],'jumlah')) + $fc['jauh']['jumlah']) ?></td>
          <td class="num"><?= rph($totalNilai) ?></td><td class="num"><?= rph($totalBobot) ?></td></tr></tfoot>
      </table></div>
    </div>
  </div>
  <div class="col-lg-5">
    <div class="card h-100"><div class="card-header"><i class="bi bi-calendar3 me-1"></i>Jatuh Tempo per Bulan</div>
      <div class="table-wrap" style="max-height:420px"><table class="table table-sm table-sticky mb-0">
        <thead><tr><th>Bulan Jatuh Tempo</th><th class="num">Invoice</th><th class="num">Nilai</th></tr></thead>
        <tbody><?php foreach ($byMonth as $m):
          $ym = $m['periode']; $parts = explode('-', (string)$ym); ?>
          <tr><td><?= e(count($parts)===2 ? App\Core\Dates::monthName((int)$parts[1]).' '.$parts[0] : $ym) ?></td>
            <td class="num"><?= nf($m['jumlah']) ?></td><td class="num"><?= rph($m['nilai']) ?></td></tr>
        <?php endforeach; ?>
        <?php if (!$byMonth): ?><tr><td colspan="3" class="text-center text-body-secondary py-3">Tidak ada data.</td></tr><?php endif; ?>
        </tbody></table></div>
    </div>
  </div>
</div>

<?php viewStart('scripts'); ?>
<script>
(function(){
  const FC = <?= json_encode($fc, JSON_UNESCAPED_UNICODE) ?>;
  const labels = ['Sudah Lewat'].concat(FC.minggu.map(m=>m.label)).concat([FC.jauh.label]);
  const nilai  = [FC.lewat.nilai].concat(FC.minggu.map(m=>m.nilai)).concat([FC.jauh.nilai]);
  const bobot  = [FC.lewat.tertimbang].concat(FC.minggu.map(m=>m.tertimbang)).concat([FC.jauh.tertimbang]);
  let kum = 0; const kumulatif = bobot.map(v => (kum += v));
  SP.makeChart('chFc', {
    data:{ labels: labels, datasets:[
      { type:'bar', label:'Nilai Jatuh Tempo', data:nilai, backgroundColor:'rgba(31,56,100,.30)', borderRadius:4, order:3 },
      { type:'bar', label:'Perkiraan Tertimbang', data:bobot, backgroundColor:'rgba(0,184,148,.9)', borderRadius:4, order:2 },
      { type:'line', label:'Kumulatif Tertimbang', data:kumulatif, borderColor:'#e74c3c', tension:.3, pointRadius:3, borderWidth:2, fill:false, order:1 }
    ]},
    options:{ interaction:{mode:'index',intersect:false},
      plugins:{ legend:{position:'bottom'}, tooltip:SP.moneyTooltip },
      scales:{ y:SP.moneyAxis, x:{grid:{display:false}, ticks:{maxRotation:45}} } }
  });
})();
</script>
<?php viewStop(); ?>
