<?php $qs = $_GET; unset($qs['format']); ?>
<div class="d-flex flex-wrap gap-2 mb-3">
  <a class="btn btn-sm btn-light" href="<?= url('/laporan') ?>"><i class="bi bi-arrow-left me-1"></i>Daftar Laporan</a>
  <?php if (can('laporan','export')): ?>
    <?php foreach (['xlsx'=>['Excel','file-earmark-excel'],'csv'=>['CSV','filetype-csv'],'pdf'=>['PDF','file-earmark-pdf']] as $fm=>$lb): ?>
      <a class="btn btn-sm btn-outline-primary" href="<?= url('/laporan/'.$kode.'/ekspor', array_merge($qs,['format'=>$fm])) ?>"><i class="bi bi-<?= $lb[1] ?> me-1"></i><?= $lb[0] ?></a>
    <?php endforeach; ?>
    <a class="btn btn-sm btn-outline-dark" target="_blank" href="<?= url('/laporan/'.$kode.'/ekspor', array_merge($qs,['format'=>'print'])) ?>"><i class="bi bi-printer me-1"></i>Cetak</a>
  <?php endif; ?>
  <?php if (can('report_builder','view')): ?>
    <a class="btn btn-sm btn-outline-secondary ms-auto" href="<?= url('/pembuat-laporan/baru',['sumber'=>$def['data_source']]) ?>"><i class="bi bi-sliders me-1"></i>Buka di Pembuat Laporan</a>
  <?php endif; ?>
</div>

<form class="filter-bar" method="get" action="<?= url('/laporan/'.$kode) ?>">
  <div class="row g-2 align-items-end">
    <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="lp_d1">Dari Tanggal</label>
      <input type="date" class="form-control form-control-sm" id="lp_d1" name="dari" value="<?= attr(App\Core\Request::get('dari','')) ?>"></div>
    <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="lp_d2">Sampai Tanggal</label>
      <input type="date" class="form-control form-control-sm" id="lp_d2" name="sampai" value="<?= attr(App\Core\Request::get('sampai','')) ?>"></div>
    <?php foreach ([['area_id','Area','area'],['business_unit_id','Unit Bisnis','business_unit'],
                    ['salesperson_id','Sales','salesperson'],['job_category_id','Kategori Pekerjaan','job_category'],
                    ['revenue_category_id','PMSC / By Case','revenue_category']] as [$fk,$lbl,$ok]): ?>
      <div class="col-6 col-md-3 col-lg-2"><label class="form-label" for="lp_<?= $fk ?>"><?= e($lbl) ?></label>
        <select class="form-select form-select-sm" id="lp_<?= $fk ?>" name="<?= $fk ?>">
          <option value="">Semua</option>
          <?php foreach ($opsi[$ok] as $o): ?>
            <option value="<?= (int)$o['id'] ?>" <?= (string)App\Core\Request::get($fk,'') === (string)$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>
      <a class="btn btn-light btn-sm" href="<?= url('/laporan/'.$kode) ?>">Reset</a>
    </div>
  </div>
</form>

<?php if (($def['chart_type'] ?? 'none') !== 'none' && $res['rows']): ?>
<div class="card mb-3">
  <div class="card-header"><i class="bi bi-bar-chart me-1"></i>Grafik</div>
  <div class="card-body"><div class="chart-box lg"><canvas id="lapChart"></canvas></div></div>
</div>
<?php endif; ?>

<div class="card">
  <div class="card-header"><i class="bi bi-table me-1"></i><?= e($meta['nama']) ?>
    <span class="text-body-secondary fw-normal ms-1">(<?= nf($res['jumlah_baris']) ?> baris<?= $res['terpotong'] ? ', ditampilkan ' . nf(count($res['rows'])) : '' ?>)</span></div>
  <div class="table-wrap" style="max-height:70vh">
    <table class="table table-sm table-hover table-sticky mb-0">
      <thead><tr>
        <?php foreach ($res['columns'] as $c): ?>
          <th class="<?= in_array($c['type'],['money','int','dec','pct'],true)?'num':'' ?>"><?= e($c['label']) ?></th>
        <?php endforeach; ?>
        <?php foreach ($res['pivot_columns'] as $pc): ?><th class="num"><?= e($pc['label']) ?></th><?php endforeach; ?>
      </tr></thead>
      <tbody>
      <?php if (!$res['rows']): ?>
        <tr><td colspan="<?= count($res['columns']) + count($res['pivot_columns']) ?>"><div class="empty-state"><i class="bi bi-inbox"></i>Tidak ada data yang sesuai filter.</div></td></tr>
      <?php endif; ?>
      <?php foreach ($res['rows'] as $row): ?>
        <tr>
          <?php foreach ($res['columns'] as $c):
            $v = $row[$c['alias']] ?? null;
            $isNum = in_array($c['type'],['money','int','dec','pct'],true);
            $neg = in_array($c['type'],['money','dec'],true) && (float)$v < 0; ?>
            <td class="<?= $isNum?'num':'' ?> <?= $neg?'text-negative':'' ?>">
              <?= e(App\Services\ReportBuilder::formatCell($v, $c['type'], $res['total'][$c['alias']] ?? null, $c['aggregate'])) ?></td>
          <?php endforeach; ?>
          <?php foreach ($res['pivot_columns'] as $pc): ?>
            <td class="num"><?= e(App\Services\ReportBuilder::formatCell($row[$pc['alias']] ?? null, $pc['type'])) ?></td>
          <?php endforeach; ?>
        </tr>
      <?php endforeach; ?>
      </tbody>
      <?php if ($res['rows'] && $res['total']): ?>
      <tfoot><tr>
        <?php foreach ($res['columns'] as $i => $c): ?>
          <td class="<?= in_array($c['type'],['money','int','dec','pct'],true)?'num':'' ?>">
            <?= $i === 0 ? 'TOTAL' : (array_key_exists($c['alias'],$res['total']) ? e(App\Services\ReportBuilder::formatCell($res['total'][$c['alias']], $c['type'])) : '') ?></td>
        <?php endforeach; ?>
        <?php foreach ($res['pivot_columns'] as $pc): ?>
          <td class="num"><?= e(App\Services\ReportBuilder::formatCell($res['total'][$pc['alias']] ?? null, $pc['type'])) ?></td>
        <?php endforeach; ?>
      </tr></tfoot>
      <?php endif; ?>
    </table>
  </div>
</div>

<?php if (($def['chart_type'] ?? 'none') !== 'none' && $res['rows']):
  $labelAlias = $res['group_by'] ? 'g0' : ($res['columns'][0]['alias'] ?? null);
  $valueCols = array_values(array_filter($res['columns'], fn($c) => in_array($c['type'],['money','int','dec','pct'],true)));
  $labels = array_map(fn($r) => (string)($r[$labelAlias] ?? '-'), array_slice($res['rows'],0,40));
  $datasets = array_map(fn($c) => ['label'=>$c['label'],'data'=>array_map(fn($r)=>(float)($r[$c['alias']] ?? 0), array_slice($res['rows'],0,40))], array_slice($valueCols,0,3));
  viewStart('scripts'); ?>
<script>
(function(){
  const T = <?= json_encode($def['chart_type']) ?>;
  const type = T === 'horizontalBar' ? 'bar' : (T === 'area' ? 'line' : (T === 'stackedBar' ? 'bar' : T));
  SP.makeChart('lapChart', {
    type: type,
    data: { labels: <?= json_encode($labels, JSON_UNESCAPED_UNICODE) ?>,
      datasets: <?= json_encode($datasets, JSON_UNESCAPED_UNICODE) ?>.map((d,i)=>({
        label:d.label, data:d.data,
        backgroundColor: ['pie','doughnut'].includes(type) ? d.data.map((_,j)=>SP.palette[j%SP.palette.length]) : SP.palette[i%SP.palette.length],
        borderColor: SP.palette[i%SP.palette.length], fill: T==='area', tension:.3, borderRadius:4 })) },
    options: { indexAxis: T==='horizontalBar'?'y':'x',
      plugins:{ legend:{position:'bottom'}, tooltip:{callbacks:{label:c=>c.dataset.label+': '+SP.rp(c.parsed.y!==undefined&&c.parsed.y!==null?c.parsed.y:c.parsed)}} },
      scales: ['pie','doughnut'].includes(type) ? {} : (T==='horizontalBar' ? {x:SP.moneyAxis} : {y:SP.moneyAxis}) }
  });
})();
</script>
<?php viewStop(); endif; ?>
