<?php
use App\Core\Dates;
use App\Services\AcpService;

$ind = acpIndicator($kpi['acp'], $kpi['acp_target'], $kpi['acp_toleransi']);
$qs  = array_filter(array_merge($filters, ['tanggal_lapor' => $asOf]), fn($v) => $v !== '' && $v !== null);
$drill = fn(string $jenis) => url('/dashboard/drill', array_merge($qs, ['jenis' => $jenis]));
?>

<!-- ============================== FILTER ============================== -->
<form class="filter-bar" method="get" action="<?= url('/dashboard') ?>" id="formFilter">
  <div class="row g-2 align-items-end">
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="tanggal_lapor">Tanggal Pelaporan</label>
      <input type="date" class="form-control form-control-sm" id="tanggal_lapor" name="tanggal_lapor" value="<?= attr($asOf) ?>">
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="f_area">Area</label>
      <select class="form-select form-select-sm" id="f_area" name="area_id" data-auto-submit>
        <option value="">Semua Area</option>
        <?php foreach ($opsi['area'] as $o): ?>
          <option value="<?= (int)$o['id'] ?>" <?= (($filters['area_id'] ?? '') == $o['id']) ? 'selected' : '' ?>><?= e($o['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="f_bu">Unit Bisnis</label>
      <select class="form-select form-select-sm" id="f_bu" name="business_unit_id" data-auto-submit>
        <option value="">Semua Unit</option>
        <?php foreach ($opsi['business_unit'] as $o): ?>
          <option value="<?= (int)$o['id'] ?>" <?= (($filters['business_unit_id'] ?? '') == $o['id']) ? 'selected' : '' ?>><?= e($o['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="f_sales">Sales</label>
      <select class="form-select form-select-sm" id="f_sales" name="salesperson_id" data-auto-submit>
        <option value="">Semua Sales</option>
        <?php foreach ($opsi['salesperson'] as $o): ?>
          <option value="<?= (int)$o['id'] ?>" <?= (($filters['salesperson_id'] ?? '') == $o['id']) ? 'selected' : '' ?>><?= e($o['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="f_job">Kategori Pekerjaan</label>
      <select class="form-select form-select-sm" id="f_job" name="job_category_id" data-auto-submit>
        <option value="">Semua Kategori</option>
        <?php foreach ($opsi['job_category'] as $o): ?>
          <option value="<?= (int)$o['id'] ?>" <?= (($filters['job_category_id'] ?? '') == $o['id']) ? 'selected' : '' ?>><?= e($o['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="f_rev">PMSC / By Case</label>
      <select class="form-select form-select-sm" id="f_rev" name="revenue_category_id" data-auto-submit>
        <option value="">Semua</option>
        <?php foreach ($opsi['revenue_category'] as $o): ?>
          <option value="<?= (int)$o['id'] ?>" <?= (($filters['revenue_category_id'] ?? '') == $o['id']) ? 'selected' : '' ?>><?= e($o['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="f_co">Petugas Penagihan</label>
      <select class="form-select form-select-sm" id="f_co" name="collection_officer_id" data-auto-submit>
        <option value="">Semua Petugas</option>
        <?php foreach ($opsi['collection_officer'] as $o): ?>
          <option value="<?= (int)$o['id'] ?>" <?= (($filters['collection_officer_id'] ?? '') == $o['id']) ? 'selected' : '' ?>><?= e($o['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="f_status">Status Pembayaran</label>
      <select class="form-select form-select-sm" id="f_status" name="payment_status_code" data-auto-submit>
        <option value="">Semua Status</option>
        <?php foreach ($opsi['payment_status'] as $o): ?>
          <option value="<?= attr($o['id']) ?>" <?= (($filters['payment_status_code'] ?? '') === $o['id']) ? 'selected' : '' ?>><?= e($o['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="f_dari">Invoice Dari</label>
      <input type="date" class="form-control form-control-sm" id="f_dari" name="invoice_date_from" value="<?= attr($filters['invoice_date_from'] ?? '') ?>">
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="f_sampai">Invoice Sampai</label>
      <input type="date" class="form-control form-control-sm" id="f_sampai" name="invoice_date_to" value="<?= attr($filters['invoice_date_to'] ?? '') ?>">
    </div>
    <div class="col-6 col-md-3 col-lg-2">
      <label class="form-label" for="f_aging">Konfigurasi Aging</label>
      <select class="form-select form-select-sm" id="f_aging" name="aging_config" data-auto-submit>
        <?php foreach ($agingConfigs as $c): ?>
          <option value="<?= (int)$c['id'] ?>" <?= ((int)($agingId ?? 0) === (int)$c['id'] || ($agingId === null && (int)$c['is_default'] === 1)) ? 'selected' : '' ?>><?= e($c['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-12 col-lg-2 d-flex gap-2">
      <button class="btn btn-primary btn-sm flex-fill" type="submit"><i class="bi bi-funnel me-1"></i>Terapkan</button>
      <a class="btn btn-light btn-sm" href="<?= url('/dashboard') ?>" title="Atur ulang filter"><i class="bi bi-arrow-counterclockwise"></i></a>
      <?php if (can('dashboard', 'export')): ?>
        <div class="dropdown">
          <button class="btn btn-light btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown"><i class="bi bi-download"></i></button>
          <ul class="dropdown-menu dropdown-menu-end">
            <li><a class="dropdown-item" href="<?= url('/dashboard/ekspor', array_merge($qs, ['format' => 'xlsx'])) ?>"><i class="bi bi-file-earmark-excel me-2"></i>Excel</a></li>
            <li><a class="dropdown-item" href="<?= url('/dashboard/ekspor', array_merge($qs, ['format' => 'pdf'])) ?>"><i class="bi bi-file-earmark-pdf me-2"></i>PDF</a></li>
            <li><a class="dropdown-item" href="<?= url('/dashboard/ekspor', array_merge($qs, ['format' => 'csv'])) ?>"><i class="bi bi-filetype-csv me-2"></i>CSV</a></li>
          </ul>
        </div>
      <?php endif; ?>
    </div>
  </div>
</form>

<!-- ============================== KPI ============================== -->
<div class="kpi-grid mb-3">
  <?php
  $cards = [
    ['Total Nominal Invoice', rp($kpi['total_bruto']), nf($kpi['jumlah_invoice']) . ' invoice', 'primary', 'receipt', 'semua'],
    ['Total Tagihan Bersih',  rp($kpi['total_bersih']), 'Setelah potongan ' . rp($kpi['total_potongan']), 'primary', 'file-earmark-text', 'semua'],
    ['Pembayaran Diterima',   rp($kpi['total_pembayaran']), nf($kpi['jumlah_lunas']) . ' invoice lunas', 'success', 'wallet2', 'lunas'],
    ['Total Piutang (AR)',    rp($kpi['total_saldo']), 'Per ' . tgl($asOf), 'warning', 'cash-stack', 'outstanding'],
    ['Piutang Terlambat',     rp($kpi['saldo_terlambat']), nf($kpi['jumlah_terlambat']) . ' invoice', 'danger', 'exclamation-octagon', 'terlambat'],
    ['Jatuh Tempo Hari Ini',  rp($kpi['saldo_jatuh_tempo']), 'Perlu ditagih hari ini', 'warning', 'calendar-event', 'jatuh_tempo'],
    ['Belum Jatuh Tempo',     rp($kpi['saldo_belum_jt']), 'Piutang lancar', 'info', 'calendar-check', 'belum_jatuh_tempo'],
    ['Pembayaran Sebagian',   rp($kpi['saldo_sebagian']), nf($kpi['jumlah_sebagian']) . ' invoice', 'primary', 'pie-chart', 'sebagian'],
    ['Invoice Dibatalkan',    nf($kpi['jumlah_dibatalkan']), 'Dikeluarkan dari AR', 'dark', 'x-octagon', 'dibatalkan'],
    ['Invoice Direvisi (RF)', nf($kpi['jumlah_direvisi']), 'Anti dobel hitung aktif', 'secondary', 'arrow-repeat', 'direvisi'],
    ['Customer Aktif',        nf($kpi['jumlah_customer']), 'Memiliki invoice', 'info', 'people', ''],
    ['Rata-rata Umur Piutang', $kpi['rata_umur_piutang'] === null ? '-' : nf($kpi['rata_umur_piutang'], 1) . ' hari', 'Terhadap jatuh tempo', 'secondary', 'hourglass-split', 'outstanding'],
  ];
  foreach ($cards as [$label, $val, $sub, $color, $icon, $jenis]):
    $tag = $jenis ? 'a' : 'div';
    $href = $jenis ? ' href="' . attr($drill($jenis)) . '"' : '';
  ?>
    <<?= $tag ?><?= $href ?> class="kpi kpi-<?= $color ?>">
      <i class="bi bi-<?= $icon ?> kpi-icon"></i>
      <span class="kpi-label"><?= e($label) ?></span>
      <span class="kpi-value <?= mb_strlen($val) > 15 ? 'sm' : '' ?>"><?= e($val) ?></span>
      <span class="kpi-sub"><?= e($sub) ?></span>
    </<?= $tag ?>>
  <?php endforeach; ?>

  <div class="kpi kpi-<?= $ind['color'] ?>">
    <i class="bi bi-<?= e($ind['icon']) ?> kpi-icon"></i>
    <span class="kpi-label">Average Collection Period</span>
    <span class="kpi-value"><?= $kpi['acp'] === null ? '-' : nf($kpi['acp'], 1) . ' hari' ?></span>
    <span class="kpi-sub">
      Target <?= $kpi['acp_target'] === null ? '-' : nf($kpi['acp_target'], 0) . ' hari' ?> ·
      <span class="text-<?= $ind['color'] ?> fw-semibold"><?= e($ind['label']) ?></span>
    </span>
  </div>
  <div class="kpi kpi-success">
    <i class="bi bi-graph-up-arrow kpi-icon"></i>
    <span class="kpi-label">Collection Rate</span>
    <span class="kpi-value"><?= $kpi['collection_rate'] === null ? '-' : pct($kpi['collection_rate']) ?></span>
    <span class="kpi-sub">Pembayaran / total tagihan</span>
  </div>
  <div class="kpi kpi-danger">
    <i class="bi bi-graph-down-arrow kpi-icon"></i>
    <span class="kpi-label">Overdue Rate</span>
    <span class="kpi-value"><?= $kpi['overdue_rate'] === null ? '-' : pct($kpi['overdue_rate']) ?></span>
    <span class="kpi-sub">Terlambat / total piutang</span>
  </div>
  <div class="kpi kpi-primary">
    <i class="bi bi-calendar3 kpi-icon"></i>
    <span class="kpi-label">Bulan Berjalan</span>
    <span class="kpi-value sm"><?= e(rp($kpi['revenue_bulan'])) ?></span>
    <span class="kpi-sub">Penerimaan <?= e(rp($kpi['penerimaan_bulan'])) ?></span>
  </div>
</div>

<!-- ============================== WORKLIST ============================== -->
<?php if (can('penagihan', 'view')): ?>
<div class="card mb-3">
  <div class="card-header">
    <i class="bi bi-telephone-outbound me-1"></i>Worklist Penagihan
    <div class="card-actions"><a class="btn btn-sm btn-outline-primary" href="<?= url('/penagihan') ?>">Buka Worklist</a></div>
  </div>
  <div class="card-body pt-2 pb-3">
    <div class="row g-2">
      <?php foreach ($worklist as $cat => $w): ?>
        <div class="col-6 col-md-4 col-xl">
          <a class="d-block text-decoration-none p-2 rounded border border-<?= e($w['color']) ?>-subtle bg-<?= e($w['color']) ?>-subtle h-100"
             href="<?= url('/penagihan', array_merge($qs, ['kategori' => $cat])) ?>">
            <div class="d-flex align-items-center gap-2 mb-1">
              <i class="bi bi-<?= e($w['icon']) ?> text-<?= e($w['color']) ?>"></i>
              <small class="text-<?= e($w['color']) ?>-emphasis fw-semibold" style="font-size:11px"><?= e($w['label']) ?></small>
            </div>
            <div class="fw-bold" style="font-size:15px"><?= nf($w['jumlah']) ?> <span class="fw-normal text-body-secondary" style="font-size:11px">invoice</span></div>
            <div class="text-body-secondary" style="font-size:11.5px"><?= e(rp($w['nilai'])) ?></div>
          </a>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
</div>
<?php endif; ?>

<!-- ============================== CHART BARIS 1 ============================== -->
<div class="row g-3 mb-3">
  <div class="col-lg-5">
    <div class="card h-100">
      <div class="card-header">
        <i class="bi bi-pie-chart me-1"></i>Komposisi Aging Piutang
        <span class="badge bg-secondary-subtle text-secondary-emphasis ms-1"><?= e($aging['config']['name']) ?></span>
      </div>
      <div class="card-body">
        <div class="chart-box"><canvas id="chAging" aria-label="Komposisi aging piutang"></canvas></div>
        <div class="table-wrap mt-2">
          <table class="table table-sm mb-0">
            <thead><tr><th>Bucket</th><th class="num">Invoice</th><th class="num">Nilai</th><th class="num">%</th></tr></thead>
            <tbody>
            <?php foreach ($aging['buckets'] as $b):
              $pctVal = $aging['total'] > 0 ? $b['nilai'] / $aging['total'] * 100 : 0; ?>
              <tr>
                <td><span class="badge bg-<?= e($b['color']) ?>">&nbsp;</span> <?= e($b['label']) ?></td>
                <td class="num"><?= nf($b['jumlah']) ?></td>
                <td class="num"><?= rph($b['nilai']) ?></td>
                <td class="num"><?= pct($pctVal) ?></td>
              </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot><tr><td>TOTAL</td>
              <td class="num"><?= nf(array_sum(array_column($aging['buckets'], 'jumlah'))) ?></td>
              <td class="num"><?= rph($aging['total']) ?></td><td class="num">100,0%</td></tr></tfoot>
          </table>
        </div>
      </div>
    </div>
  </div>

  <div class="col-lg-7">
    <div class="card h-100">
      <div class="card-header"><i class="bi bi-graph-up me-1"></i>Tren Invoice, Penerimaan &amp; Saldo Piutang (12 Bulan)</div>
      <div class="card-body"><div class="chart-box lg"><canvas id="chTren" aria-label="Tren bulanan"></canvas></div></div>
    </div>
  </div>
</div>

<!-- ============================== CHART BARIS 2 ============================== -->
<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-speedometer2 me-1"></i>Tren ACP vs Target
        <span class="badge bg-info-subtle text-info-emphasis ms-1"><?= e($kpi['acp_metode']) ?></span>
      </div>
      <div class="card-body"><div class="chart-box"><canvas id="chAcp" aria-label="Tren ACP"></canvas></div></div>
    </div>
  </div>
  <div class="col-lg-6">
    <div class="card h-100">
      <div class="card-header"><i class="bi bi-cash-coin me-1"></i>Perkiraan Penerimaan Kas (8 Minggu)</div>
      <div class="card-body"><div class="chart-box"><canvas id="chForecast" aria-label="Perkiraan penerimaan kas"></canvas></div></div>
    </div>
  </div>
</div>

<!-- ============================== CHART BARIS 3 ============================== -->
<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-geo-alt me-1"></i>Piutang per Area</div>
      <div class="card-body"><div class="chart-box sm"><canvas id="chArea"></canvas></div></div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="card h-100">
      <div class="card-header"><i class="bi bi-person-badge me-1"></i>Piutang per Sales</div>
      <div class="card-body"><div class="chart-box sm"><canvas id="chSales"></canvas></div></div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="card h-100">
      <div class="card-header"><i class="bi bi-tools me-1"></i>Piutang per Kategori Pekerjaan</div>
      <div class="card-body"><div class="chart-box sm"><canvas id="chJob"></canvas></div></div>
    </div>
  </div>
</div>

<!-- ============================== TOP CUSTOMER ============================== -->
<div class="row g-3">
  <div class="col-lg-6">
    <div class="card h-100">
      <div class="card-header"><i class="bi bi-trophy me-1"></i>10 Customer dengan Piutang Terbesar</div>
      <div class="table-wrap">
        <table class="table table-sm table-hover mb-0">
          <thead><tr><th>#</th><th>Customer</th><th class="num">Invoice</th><th class="num">Saldo</th><th class="num">Terlambat</th></tr></thead>
          <tbody>
          <?php if (!$topCust): ?>
            <tr><td colspan="5" class="text-center text-muted py-3">Tidak ada data.</td></tr>
          <?php endif; ?>
          <?php foreach ($topCust as $i => $c): ?>
            <tr>
              <td><?= $i + 1 ?></td>
              <td><a class="text-decoration-none" href="<?= url('/kartu-piutang/' . (int)$c['id']) ?>"><?= e(truncate($c['label'], 34)) ?></a></td>
              <td class="num"><?= nf($c['jumlah']) ?></td>
              <td class="num cell-strong"><?= rph($c['saldo']) ?></td>
              <td class="num"><?= (float)$c['terlambat'] > 0 ? '<span class="text-danger">' . e(rp($c['terlambat'])) . '</span>' : '-' ?></td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  <div class="col-lg-6">
    <div class="card h-100">
      <div class="card-header"><i class="bi bi-exclamation-triangle me-1 text-danger"></i>10 Customer dengan Tunggakan Terbesar</div>
      <div class="table-wrap">
        <table class="table table-sm table-hover mb-0">
          <thead><tr><th>#</th><th>Customer</th><th class="num">Invoice</th><th class="num">Nilai Terlambat</th></tr></thead>
          <tbody>
          <?php if (!$topOverdue): ?>
            <tr><td colspan="4" class="text-center text-muted py-3">Tidak ada tunggakan. </td></tr>
          <?php endif; ?>
          <?php foreach ($topOverdue as $i => $c): ?>
            <tr>
              <td><?= $i + 1 ?></td>
              <td><a class="text-decoration-none" href="<?= url('/kartu-piutang/' . (int)$c['id']) ?>"><?= e(truncate($c['label'], 34)) ?></a></td>
              <td class="num"><?= nf($c['jumlah']) ?></td>
              <td class="num text-danger fw-semibold"><?= e(rp($c['terlambat'])) ?></td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<?php viewStart('scripts'); ?>
<script>
(function () {
  const AG = <?= json_encode($aging['buckets'], JSON_UNESCAPED_UNICODE) ?>;
  const TREN = <?= json_encode($monthly, JSON_UNESCAPED_UNICODE) ?>;
  const ARTREN = <?= json_encode($arTrend, JSON_UNESCAPED_UNICODE) ?>;
  const ACP = <?= json_encode($acpTrend, JSON_UNESCAPED_UNICODE) ?>;
  const FC = <?= json_encode($forecast, JSON_UNESCAPED_UNICODE) ?>;
  const AREA = <?= json_encode($byArea, JSON_UNESCAPED_UNICODE) ?>;
  const SALES = <?= json_encode($bySales, JSON_UNESCAPED_UNICODE) ?>;
  const JOB = <?= json_encode($byJob, JSON_UNESCAPED_UNICODE) ?>;
  const DRILL = <?= json_encode(url('/dashboard/drill', array_merge($qs, ['jenis' => 'aging']))) ?>;

  const bsColor = { success: '#198754', info: '#0dcaf0', warning: '#ffc107', danger: '#dc3545',
                    primary: '#0d6efd', secondary: '#6c757d', dark: '#343a40' };

  // 1. Komposisi aging (donat) + drill-down
  SP.makeChart('chAging', {
    type: 'doughnut',
    data: {
      labels: AG.map(b => b.label),
      datasets: [{ data: AG.map(b => b.nilai), backgroundColor: AG.map(b => bsColor[b.color] || '#6c757d'), borderWidth: 2, borderColor: '#fff' }]
    },
    options: {
      cutout: '58%',
      plugins: {
        legend: { position: 'bottom' },
        tooltip: { callbacks: { label: c => c.label + ': ' + SP.rp(c.parsed) } }
      },
      onClick: (e, els) => { if (els.length) window.location = DRILL + '&bucket=' + els[0].index; }
    }
  });

  // 2. Tren invoice / penerimaan / saldo AR
  SP.makeChart('chTren', {
    data: {
      labels: TREN.map(t => t.label),
      datasets: [
        { type: 'bar', label: 'Nilai Invoice', data: TREN.map(t => t.invoice_nilai), backgroundColor: 'rgba(31,56,100,.82)', borderRadius: 4, order: 3 },
        { type: 'bar', label: 'Penerimaan', data: TREN.map(t => t.penerimaan), backgroundColor: 'rgba(0,184,148,.85)', borderRadius: 4, order: 2 },
        { type: 'line', label: 'Saldo Piutang (akhir bulan)', data: ARTREN.map(a => a.saldo),
          borderColor: '#e74c3c', backgroundColor: 'rgba(231,76,60,.12)', tension: .32, fill: true,
          pointRadius: 3, borderWidth: 2, yAxisID: 'y', order: 1 }
      ]
    },
    options: {
      interaction: { mode: 'index', intersect: false },
      plugins: { legend: { position: 'bottom' }, tooltip: SP.moneyTooltip },
      scales: { y: SP.moneyAxis, x: { grid: { display: false } } }
    }
  });

  // 3. ACP vs target
  SP.makeChart('chAcp', {
    data: {
      labels: ACP.map(a => a.label),
      datasets: [
        { type: 'line', label: 'ACP Aktual (hari)', data: ACP.map(a => a.acp), borderColor: '#1f3864',
          backgroundColor: 'rgba(31,56,100,.10)', tension: .3, fill: true, pointRadius: 4, borderWidth: 2.5 },
        { type: 'line', label: 'Target (hari)', data: ACP.map(a => a.target), borderColor: '#00b894',
          borderDash: [6, 4], pointRadius: 0, borderWidth: 2, fill: false }
      ]
    },
    options: {
      plugins: {
        legend: { position: 'bottom' },
        tooltip: { callbacks: { label: c => c.dataset.label + ': ' + (c.parsed.y === null ? '-' : SP.nf(c.parsed.y, 1) + ' hari') } }
      },
      scales: { y: { beginAtZero: true, ticks: { callback: v => v + ' hr' }, grid: { color: 'rgba(0,0,0,.05)' } }, x: { grid: { display: false } } }
    }
  });

  // 4. Perkiraan penerimaan kas
  const fcLabels = ['Sudah Lewat'].concat(FC.minggu.map(m => m.label)).concat([FC.jauh.label]);
  const fcNilai  = [FC.lewat.nilai].concat(FC.minggu.map(m => m.nilai)).concat([FC.jauh.nilai]);
  const fcBobot  = [FC.lewat.tertimbang].concat(FC.minggu.map(m => m.tertimbang)).concat([FC.jauh.tertimbang]);
  SP.makeChart('chForecast', {
    type: 'bar',
    data: {
      labels: fcLabels,
      datasets: [
        { label: 'Nilai Jatuh Tempo', data: fcNilai, backgroundColor: 'rgba(31,56,100,.32)', borderRadius: 4 },
        { label: 'Perkiraan Tertimbang', data: fcBobot, backgroundColor: 'rgba(0,184,148,.9)', borderRadius: 4 }
      ]
    },
    options: {
      plugins: { legend: { position: 'bottom' }, tooltip: SP.moneyTooltip },
      scales: { y: SP.moneyAxis, x: { grid: { display: false }, ticks: { maxRotation: 45, minRotation: 0 } } }
    }
  });

  // 5-7. Distribusi per dimensi
  function dimChart(id, rows, horizontal) {
    SP.makeChart(id, {
      type: 'bar',
      data: {
        labels: rows.map(r => (r.label || '-').substring(0, 22)),
        datasets: [{ label: 'Saldo Piutang', data: rows.map(r => r.saldo),
                     backgroundColor: rows.map((r, i) => SP.palette[i % SP.palette.length]), borderRadius: 4 }]
      },
      options: {
        indexAxis: horizontal ? 'y' : 'x',
        plugins: { legend: { display: false }, tooltip: { callbacks: { label: c => SP.rp(c.parsed[horizontal ? 'x' : 'y']) } } },
        scales: horizontal
          ? { x: SP.moneyAxis, y: { grid: { display: false } } }
          : { y: SP.moneyAxis, x: { grid: { display: false } } }
      }
    });
  }
  dimChart('chArea', AREA, false);
  dimChart('chSales', SALES, true);
  dimChart('chJob', JOB, true);
})();
</script>
<?php viewStop(); ?>
