<?php
// Format meter: 4.5 -> 4,5 | 4.00 -> 4
if (!function_exists('pj_fmt_meter')) {
  function pj_fmt_meter($val)
  {
    if ($val === null || $val === '') return '0';
    $n = (float)$val;

    // anggap integer jika beda sangat kecil (hindari masalah float)
    $isInt = abs($n - round($n)) < 0.000000001;

    if ($isInt) return number_format($n, 0, ',', '.');

    // max 2 desimal, buang nol belakang -> 4,50 jadi 4,5
    return rtrim(rtrim(number_format($n, 2, ',', '.'), '0'), ',');
  }
}
?>

<h5 class="mb-2 text-gray-800">Periode : <?=$dari.' - '.$sampai;?></h5>
<div class="table-responsive">
  <table class="table align-items-center table-flush">
    <thead class="thead-light">
      <tr>
        <th>Produk & Jasa</th>
        <th class="text-right w-5">Jumlah</th>
        <th class="text-right w-15">Total Meter</th>
        <th class="text-right w-15">Omset</th>
      </tr>
    </thead>
    <tbody>
      <?php
        $total = 0;
        $jumlah = 0;
        $total_ukuran = 0;
        $grandtotal = 0;

        if(!empty($result)){
          foreach ($result as $row){
            $jumlah += (float)$row->jumlah;
            $total = (float)$row->total;
            $total_ukuran += (float)$row->total_ukuran;
            $grandtotal += (float)$row->total;
      ?>
        <tr>
          <td><?=$row->title;?></td>
          <td class="text-right"><?=$row->jumlah;?></td>

          <!-- FIX: jangan pakai rp() untuk meter -->
          <td class="text-right" data-value="<?= (float)$row->total_ukuran; ?>">
            <?= pj_fmt_meter($row->total_ukuran); ?>
          </td>

          <td align="right"><?=rp($total);?></td>
        </tr>
      <?php }} ?>
    </tbody>
    <tfoot class="thead-light">
      <tr>
        <th>Total Omset</th>
        <th class="text-right"><?=$jumlah;?></th>

        <!-- FIX: total meter footer -->
        <th class="text-right" data-value="<?= (float)$total_ukuran; ?>">
          <?= pj_fmt_meter($total_ukuran); ?>
        </th>

        <th class="text-right">
          <input type="hidden" id="total_pj" value="<?=($grandtotal);?>">
          <?=rp($grandtotal);?>
        </th>
      </tr>
    </tfoot>
  </table>
</div>
