<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>CETAK LAPORAN TRANSAKSI</title>
    <link href="<?= base_url('assets/vendor/font-awesome/css/font-awesome.min.css'); ?>" rel="stylesheet" type="text/css">
    <style>
      :root{
        --ink:#0f172a; --ink-600:#475569; --muted:#64748b;
        --line:#d1d5db; --head:#0f172a; --head-light:#f1f5f9;
        --chip-bg:#eef2ff; --chip-ink:#312e81; --chip-line:#e0e7ff;
      }
      @page { margin: 8mm; }
      *{
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
      }
      body{
        margin:0; font-family:'Helvetica Neue','Helvetica',Arial,sans-serif;
        color:var(--ink); font-size:10px; line-height:1.35;
      }
      footer {
        position: fixed; 
        bottom: 0cm; 
        left: 0cm; 
        right: 0cm;
        height: 0.5cm;
        padding:5px;
        background-color: <?=$info['warna_lunas'];?>;
        color: white;
        text-align: center;
      }
      .invoice-box{ width:100%; margin:0 auto; padding:10px 10px 18mm 10px; }
      .alamat,.sosmed{ color:var(--ink-600); }

      /* ====== HEADER SEKSI ====== */
      .section-header{
        margin-top:12px;
        padding:6px 10px;
        font-weight:700;
        letter-spacing:.2px;
        border:1px solid #111;
        background:#0f172a !important;
        color:#fff;
        border-radius:6px;
      }
      @media print{
        .section-header{
          background:#e5e7eb !important;
          color:#111 !important;
          border-color:#111 !important;
        }
      }

      /* ====== Tabel ====== */
      .table{
        width:100%;
        background:#fff;
        border-collapse:collapse;
        table-layout:fixed;
        margin-top:6px;
        border:1px solid #111;
      }
      .table th,.table td{
        padding:.10rem .15rem;
        border:1px solid #111;
        vertical-align:middle;
        font-variant-numeric:tabular-nums;
      }
      .table thead th{
        background:#0f172a !important;
        color:#fff !important;
        border-color:var(--head) !important;
        font-weight:700;
      }
      @media print{
        .table thead th{
          background:#e5e7eb !important;
          color:#111 !important;
          border-color:#111 !important;
        }
      }

      .text-left{ text-align:left; } .text-right{ text-align:right; } .text-center{ text-align:center; }
      .muted{ color:var(--muted); }
      .nowrap{ white-space:nowrap!important; }
      .cell-id,.cell-date,.cell-kasir,.cell-money{ white-space:nowrap!important; }
      .cell-right{ text-align:right; }
      .cell-left{ text-align:left; }
      .avoid-break{ break-inside:avoid !important; page-break-inside:avoid !important; }

      /* Lebar kolom */
      .th-no{ width:4%; } .th-id{ width:14%; } .th-nama{ width:18%; }
      .th-tgl{ width:14%; } .th-kasir{ width:12%; } .th-jenis{ width:20%; }
      .th-ket{ width:17%; } .th-num{ width:10%; }

      /* Ringkasan */
      tfoot .summary-title{ background:#f1f5f9 !important; font-weight:700; }
      tfoot .summary-sub{ background:#f8fafc !important; }
      tfoot .summary-warn{ background:#fff7ed !important; font-weight:600; }
      tfoot .summary-ok{ background:#ecfdf5 !important; font-weight:700; }

      /* Print rules */
      @media print{
        thead{ display:table-header-group; }
        tfoot{ display:table-footer-group; }
        .table tr,.table th,.table td{ break-inside:avoid !important; page-break-inside:avoid !important; }
        .table{ page-break-after:avoid; }
        a[href]:after{ content:"" !important; }
      }

      /* KOP */
      .head{ width:100%; border-collapse:collapse; }
      .head td{ border:none !important; padding:2px 4px; }
      .head .badge{ background:<?=$info['warna_lunas'];?> !important; color:#fff !important; padding:3px 6px; border-radius:4px; white-space:nowrap; }
      .kop-title{ font-weight:700; }
    </style>
  </head>
  <body>
    <?php
      /* Util tanggal kompak */
      if (!function_exists('indo_compact_date')) {
        function indo_compact_date($ts){
          if (empty($ts) || $ts==='0000-00-00' || $ts==='0000-00-00 00:00:00' || $ts==='-') return '-';
          $mon = ['Jan'=>'Jan','Feb'=>'Feb','Mar'=>'Mar','Apr'=>'Apr','May'=>'Mei','Jun'=>'Jun','Jul'=>'Jul','Aug'=>'Agu','Sep'=>'Sep','Oct'=>'Okt','Nov'=>'Nov','Dec'=>'Des'];
          $t = is_numeric($ts) ? (int)$ts : strtotime($ts); if(!$t) return '-';
          return (int)date('d',$t).' '.($mon[date('M',$t)] ?? date('M',$t)).' '.date('Y',$t);
        }
      }
      if (!function_exists('is_tunai')) {
        function is_tunai($row, $akunName = '') {
          if (isset($row['id_sub_bayar']) && (int)$row['id_sub_bayar'] === 1) return true;
          $hay = strtolower(trim( ($row['nama_bayar'] ?? '').' '.($row['jenis_bayar'] ?? '').' '.($akunName ?? '') ));
          return (strpos($hay,'tunai') !== false);
        }
      }

      /* ✅ Formatter universal untuk NO_ORDER */
      if (!function_exists('fmt_no_order_lap')) {
        /**
         * Urutan prioritas:
         * 1) no_transaksi  (kas keluar / pembelian)
         * 2) id_transaksi  (penjualan tunai/transfer)
         * 3) fallback via id_invoice/noid -> get_id_transaksi()
         */
        function fmt_no_order_lap(array $v)
        {
          if (!empty($v['no_transaksi'])) {
            return (string)$v['no_transaksi'];
          }
          if (!empty($v['id_transaksi'])) {
            $ord = trim((string)$v['id_transaksi']);
            if (is_numeric($ord)) return format_transaction_number($ord);
            return $ord;
          }
          if (!empty($v['noid']) && function_exists('get_id_transaksi')) {
            $g = get_id_transaksi($v['noid']);
            if (is_array($g) && !empty($g['nomor_order'])) {
              $ord = $g['nomor_order'];
              return is_numeric($ord) ? format_transaction_number($ord) : (string)$ord;
            }
          }
          return '-';
        }
      }

      /* alamat toko */
      $alamat = cleanString(base64_decode($info['deskripsi']));

      /* agregasi */
      $total_masuk_tunai=0; $total_masuk_transfer=0; $total_keluar=0; $total_beli=0;
      $total_keluar_tunai=0; $total_beli_tunai=0;
      $penjualan_tunai=[]; $penjualan_transfer=[];

      if (!empty($result['masuk'])) {
        foreach ($result['masuk'] as $val) {
          $bayar = $this->model_app->cara_bayar(['bid.id_invoice' => ($val['noid'] ?? null)]);
          $akunNama = '';
          if (!empty($val['id_sub_bayar'])) $akunNama = (string)(getAkun($val['id_sub_bayar']) ?? '');
          elseif (!empty($bayar->nama_bayar)) $akunNama = (string)$bayar->nama_bayar;

          $isTunai = is_tunai($val + ['nama_bayar' => $bayar->nama_bayar ?? ''], $akunNama);
          $jml = (float)($val['jml_bayar'] ?? 0);

          if ($isTunai) { $total_masuk_tunai += $jml; $penjualan_tunai[] = ['val'=>$val,'bayar'=>$bayar,'akunNama'=>$akunNama]; }
          else { $total_masuk_transfer += $jml; $penjualan_transfer[] = ['val'=>$val,'bayar'=>$bayar,'akunNama'=>$akunNama]; }
        }
      }
      if (!empty($result['keluar'])) {
        foreach ($result['keluar'] as $val) {
          $j=(float)($val['jml_bayar'] ?? 0); $total_keluar += $j;
          $akunNama = isset($val['id_bayar']) ? (string)(getAkun($val['id_bayar']) ?? '') : '';
          if (is_tunai($val,$akunNama)) $total_keluar_tunai += $j;
        }
      }
      if (!empty($result['beli'])) {
        foreach ($result['beli'] as $val) {
          $j=(float)($val['jml_bayar'] ?? 0); $total_beli += $j;
          $akunNama = isset($val['id_bayar']) ? (string)(getAkun($val['id_bayar']) ?? '') : '';
          if (is_tunai($val,$akunNama)) $total_beli_tunai += $j;
        }
      }
      $total_masuk = $total_masuk_tunai + $total_masuk_transfer;
      $sum_keluar  = $total_keluar + $total_beli;
      $total_pendapatan = $total_masuk - $sum_keluar;
      $saldo_tunai = $total_masuk_tunai - ($total_keluar_tunai + $total_beli_tunai);
    ?>

    <footer><?=$info['title'];?> © <?=date('Y');?></footer>

    <div class="invoice-box">
      <!-- ====== KOP ====== -->
      <table width="100%" cellpadding="0" cellspacing="0" style="border:none">
        <tr>
          <td colspan="4" rowspan="5" style="width:350px;border:none">
            <img src="<?=$logo;?>" style="display:block; width:auto; height:auto; max-width:350px; max-height:80px; margin:0 auto;">
          </td>
          <td colspan="2" style="font-weight:bold;border:none">LAPORAN PENDAPATAN & PENGELUARAN</td>
        </tr>
        <tr><td colspan="2" style="border:none">TGL. CETAK : <?= tgl_indo(date('Y-m-d')); ?></td></tr>
        <tr><td colspan="2" style="border:none"></td></tr>
        <tr>
          <td style="background:<?=$info['warna_lunas'];?>;color:#fff;width:20%;border:none;padding:4px 6px">PENGGUNA</td>
          <td style="border-bottom:1px dotted #000;"><?=$user;?></td>
        </tr>
        <tr>
          <td style="background:<?=$info['warna_lunas'];?>;color:#fff;width:20%;border:none;padding:4px 6px"><?=$periode_name;?></td>
          <td style="border-bottom:1px dotted #000;"><?=($periode);?></td>
        </tr>
        <tr><td colspan="2" style="border:none"></td></tr>
        <tr>
          <td colspan="4" style="border:none">
            <span class="alamat"><?=($alamat);?></span><br>
            Phone:<span class="sosmed"><?=$info['phone'];?></span>&nbsp;Email:<span class="sosmed"><?=$info['email'];?></span>&nbsp;FB:<span class="sosmed"><?=$info['fb'];?></span>&nbsp;IG:<span class="sosmed"><?=$info['ig'];?></span>
          </td>
          <td colspan="2" style="border:none"></td>
        </tr>
      </table>

      <!-- =========================
           TABEL-TABEL PER SEKSI
      ========================== -->

      <!-- PENJUALAN — TUNAI -->
      <?php if (!empty($penjualan_tunai)) : ?>
        <div class="section-header">Pendapatan — Tunai</div>
        <table class="table" cellpadding="0" cellspacing="0">
          <thead>
            <tr>
              <th class="cell-left th-no">NO</th>
              <th class="cell-left th-id nowrap">NO_ORDER</th>
              <th class="cell-left th-nama">PEMESAN</th>
              <th class="cell-left th-tgl">TGL_ORDER</th>
              <th class="cell-left th-tgl">TGL_BAYAR</th>
              <th class="cell-left th-kasir">KASIR</th>
              <th class="cell-left th-jenis">JENIS BAYAR</th>
              <th class="cell-right th-num">MASUK</th>
              <th class="cell-right th-num">KELUAR</th>
            </tr>
          </thead>
          <tbody>
            <?php $no=1; foreach ($penjualan_tunai as $row):
              $val=$row['val']; $bayar=$row['bayar'];
              $nama = '-'; if (!empty($val['id_konsumen'])) { $ck=cekKonsumen($val['id_konsumen']); $nama=$ck['nama'] ?? '-'; }
              $tgl_order = !empty($val['tgl_trx']) ? indo_compact_date($val['tgl_trx']) : (!empty($bayar->tgl_trx)?indo_compact_date($bayar->tgl_trx):'-');
              $tgl_bayar = !empty($val['tgl_bayar']) ? indo_compact_date($val['tgl_bayar']) : (!empty($bayar->tgl_bayar)?indo_compact_date($bayar->tgl_bayar):'-');
              $nama_bayar = $bayar->nama_bayar ?? 'Tunai';
              $akun = !empty($val['id_sub_bayar']) ? (getAkun($val['id_sub_bayar']) ?? 'Tunai') : 'Tunai';
            ?>
            <tr>
              <td class="text-left"><?=$no;?></td>
              <!-- ✅ NO_ORDER BENAR -->
              <td class="text-left cell-id nowrap"><?= htmlspecialchars(fmt_no_order_lap($val), ENT_QUOTES); ?></td>
              <td class="text-left"><?=htmlspecialchars($nama,ENT_QUOTES);?></td>
              <td class="text-left cell-date nowrap"><?=$tgl_order;?></td>
              <td class="text-left cell-date nowrap"><?=$tgl_bayar;?></td>
              <td class="text-left cell-kasir nowrap"><?=htmlspecialchars($val['fo'] ?? '-',ENT_QUOTES);?></td>
              <td class="text-left"><span class="muted"><?=htmlspecialchars($nama_bayar,ENT_QUOTES);?></span> (<?=htmlspecialchars($akun,ENT_QUOTES);?>)</td>
              <td class="text-right cell-money"><?=rp($val['jml_bayar'] ?? 0);?></td>
              <td class="text-right cell-money"></td>
            </tr>
            <?php $no++; endforeach; ?>
          </tbody>
          <tfoot>
            <tr class="summary-sub">
              <th colspan="7" class="text-left">Total Pendapatan Tunai</th>
              <th colspan="2" class="text-right"><?=rp($total_masuk_tunai);?></th>
            </tr>
          </tfoot>
        </table>
      <?php endif; ?>

      <!-- PENJUALAN — TRANSFER -->
      <?php if (!empty($penjualan_transfer)) : ?>
        <div class="section-header">Pendapatan — Transfer</div>
        <table class="table" cellpadding="0" cellspacing="0">
          <thead>
            <tr>
              <th class="text-left th-no">NO</th>
              <th class="text-left th-id nowrap">NO_ORDER</th>
              <th class="text-left th-nama">PEMESAN</th>
              <th class="text-left th-tgl">TGL_ORDER</th>
              <th class="text-left th-tgl">TGL_BAYAR</th>
              <th class="text-left th-kasir">KASIR</th>
              <th class="text-left th-jenis">JENIS BAYAR</th>
              <th class="text-right th-num">MASUK</th>
              <th class="text-right th-num">KELUAR</th>
            </tr>
          </thead>
          <tbody>
            <?php $no=1; foreach ($penjualan_transfer as $row):
              $val=$row['val']; $bayar=$row['bayar'];
              $nama='-'; if (!empty($val['id_konsumen'])) { $ck=cekKonsumen($val['id_konsumen']); $nama=$ck['nama'] ?? '-'; }
              $tgl_order = !empty($val['tgl_trx']) ? indo_compact_date($val['tgl_trx']) : (!empty($bayar->tgl_trx)?indo_compact_date($bayar->tgl_trx):'-');
              $tgl_bayar = !empty($val['tgl_bayar']) ? indo_compact_date($val['tgl_bayar']) : (!empty($bayar->tgl_bayar)?indo_compact_date($bayar->tgl_bayar):'-');
              $nama_bayar = !empty($bayar->nama_bayar) ? $bayar->nama_bayar : 'Transfer';
              $getAkun   = !empty($val['id_sub_bayar']) ? (getAkun($val['id_sub_bayar']) ?? 'Transfer') : 'Transfer';
              $lampiranUrl = !empty($val['lampiran']) ? base_url('uploads/lampiran/').$val['lampiran'] : '';
              $link = $lampiranUrl
                ? '<a class="lightbox" href="'.$lampiranUrl.'" title="'.htmlspecialchars($getAkun,ENT_QUOTES).': '.rprp($val['jml_bayar'] ?? 0).'">'.htmlspecialchars($getAkun,ENT_QUOTES).'</a>'
                : htmlspecialchars($getAkun,ENT_QUOTES);
            ?>
            <tr>
              <td class="text-left"><?=$no;?></td>
              <!-- ✅ NO_ORDER BENAR -->
              <td class="text-left cell-id nowrap"><?= htmlspecialchars(fmt_no_order_lap($val), ENT_QUOTES); ?></td>
              <td class="text-left"><?=htmlspecialchars($nama,ENT_QUOTES);?></td>
              <td class="text-left cell-date nowrap"><?=$tgl_order;?></td>
              <td class="text-left cell-date nowrap"><?=$tgl_bayar;?></td>
              <td class="text-left cell-kasir nowrap"><?=htmlspecialchars($val['fo'] ?? '-',ENT_QUOTES);?></td>
              <td class="text-left"><span class="muted"><?=htmlspecialchars($nama_bayar,ENT_QUOTES);?></span> (<?=$link;?>)</td>
              <td class="text-right cell-money"><?=rp($val['jml_bayar'] ?? 0);?></td>
              <td class="text-right cell-money"></td>
            </tr>
            <?php $no++; endforeach; ?>
          </tbody>
          <tfoot>
            <tr class="summary-sub">
              <th colspan="7" class="text-left">Total Pendapatan Transfer</th>
              <th colspan="2" class="text-right"><?=rp($total_masuk_transfer);?></th>
            </tr>
            <tr class="summary-sub">
              <th colspan="7" class="text-left"><b>Total Pendapatan (Tunai + Transfer)</b></th>
              <th colspan="2" class="text-right"><b><?=rp($total_masuk);?></b></th>
            </tr>
          </tfoot>
        </table>
      <?php endif; ?>

      <!-- PENGELUARAN -->
      <?php if (!empty($result['keluar'])) : ?>
        <div class="section-header">Pengeluaran</div>
        <table class="table" cellpadding="0" cellspacing="0">
          <thead>
            <tr>
              <th class="text-left th-no">NO</th>
              <th class="text-left th-id nowrap">NO_ORDER</th>
              <th class="text-left th-tgl">TGL_BAYAR</th>
              <th class="text-left th-kasir">KASIR</th>
              <th colspan="2" class="text-left th-jenis">JENIS BAYAR</th>
              <th class="text-left th-jenis">KETERANGAN</th>
              <th class="text-right th-num">MASUK</th>
              <th class="text-right th-num">KELUAR</th>
            </tr>
          </thead>
          <tbody>
            <?php $no=1; foreach ($result['keluar'] as $val):
              $id_bayar = $val['id_bayar'] ?? 0;
              $ket='-'; foreach (['keterangan','ket','keterangan_kas','uraian','catatan','deskripsi'] as $k){ if (isset($val[$k]) && $val[$k] !== '') { $ket=$val[$k]; break; } }
            ?>
            <tr>
              <td class="text-left"><?=$no;?></td>
              <!-- ✅ NO_ORDER BENAR -->
              <td class="text-left cell-id nowrap"><?= htmlspecialchars(fmt_no_order_lap($val), ENT_QUOTES); ?></td>
              <td class="text-left cell-date nowrap"><?= !empty($val['tgl_bayar']) ? indo_compact_date($val['tgl_bayar']) : '-'; ?></td>
              <td class="text-left cell-kasir nowrap"><?=htmlspecialchars($val['fo'] ?? '-',ENT_QUOTES);?></td>
              <td colspan="2" class="text-left"><?=getAkun($id_bayar);?></td>
              <td class="text-left"><?=htmlspecialchars($ket,ENT_QUOTES);?></td>
              <td class="text-right cell-money"></td>
              <td class="text-right cell-money"><?=rp($val['jml_bayar'] ?? 0);?></td>
            </tr>
            <?php $no++; endforeach; ?>
          </tbody>
          <tfoot>
            <tr class="summary-sub">
              <th colspan="8" class="text-left">Total Pengeluaran</th>
              <th class="text-right"><?=rp($total_keluar);?></th>
            </tr>
          </tfoot>
        </table>
      <?php endif; ?>

      <!-- PEMBELIAN -->
      <?php if (!empty($result['beli'])) : ?>
        <div class="section-header">Pembelian</div>
        <table class="table" cellpadding="0" cellspacing="0">
          <thead>
            <tr>
              <th class="text-left th-no">NO</th>
              <th class="text-left th-id nowrap">NO_ORDER</th>
              <th class="text-left th-tgl">TGL_BAYAR</th>
              <th class="text-left th-kasir">KASIR</th>
              <th colspan="2" class="text-left th-jenis">JENIS BAYAR</th>
              <th class="text-left th-jenis">KETERANGAN</th>
              <th class="text-right th-num">MASUK</th>
              <th class="text-right th-num">KELUAR</th>
            </tr>
          </thead>
          <tbody>
            <?php $no=1; foreach ($result['beli'] as $val):
              $id_bayar = $val['id_bayar'] ?? 0;
              $ket='-'; foreach (['keterangan','ket','catatan','deskripsi'] as $k){ if (isset($val[$k]) && $val[$k] !== '') { $ket=$val[$k]; break; } }
            ?>
            <tr>
              <td class="text-left"><?=$no;?></td>
              <!-- ✅ NO_ORDER BENAR -->
              <td class="text-left cell-id nowrap"><?= htmlspecialchars(fmt_no_order_lap($val), ENT_QUOTES); ?></td>
              <td class="text-left cell-date nowrap"><?= !empty($val['tgl_bayar']) ? indo_compact_date($val['tgl_bayar']) : '-'; ?></td>
              <td class="text-left cell-kasir nowrap"><?=htmlspecialchars($val['fo'] ?? '-',ENT_QUOTES);?></td>
              <td colspan="2" class="text-left"><?=htmlspecialchars(getAkun($id_bayar) ?: '-', ENT_QUOTES);?></td>
              <td class="text-left"><?=htmlspecialchars($ket,ENT_QUOTES);?></td>
              <td class="text-right cell-money"></td>
              <td class="text-right cell-money"><?=rp($val['jml_bayar'] ?? 0);?></td>
            </tr>
            <?php $no++; endforeach; ?>
          </tbody>
          <tfoot>
            <tr class="summary-sub">
              <th colspan="8" class="text-left">Total Pembelian</th>
              <th class="text-right"><?=rp($total_beli);?></th>
            </tr>
          </tfoot>
        </table>
      <?php endif; ?>

      <!-- RINGKASAN -->
      <div class="section-header">Ringkasan</div>
      <table class="table" cellpadding="0" cellspacing="0">
        <tfoot>
          <tr class="summary-title"><th colspan="9" class="text-left">Ringkasan</th></tr>
          <tr class="summary-sub"><th colspan="7" class="text-left">Total Pendapatan Tunai</th><th colspan="2" class="text-right"><?=rp($total_masuk_tunai);?></th></tr>
          <tr class="summary-sub"><th colspan="7" class="text-left">Total Pendapatan Transfer</th><th colspan="2" class="text-right"><?=rp($total_masuk_transfer);?></th></tr>
          <tr class="summary-sub"><th colspan="7" class="text-left"><b>Total Pendapatan (Tunai + Transfer)</b></th><th colspan="2" class="text-right"><b><?=rp($total_masuk);?></b></th></tr>
          <tr class="summary-sub"><th colspan="7" class="text-left">Total Pengeluaran (Kas Keluar)</th><th colspan="2" class="text-right"><?=rp($total_keluar);?></th></tr>
          <tr class="summary-sub"><th colspan="7" class="text-left">Total Pembelian</th><th colspan="2" class="text-right"><?=rp($total_beli);?></th></tr>
          <tr class="summary-warn"><th colspan="7" class="text-left">Total Uang Keluar (Pengeluaran + Pembelian)</th><th colspan="2" class="text-right"><?=rp($sum_keluar);?></th></tr>
          <tr class="summary-ok"><th colspan="7" class="text-left"><b>Saldo / Total Keseluruhan (Masuk - Total Keluar)</b></th><th colspan="2" class="text-right"><b><?=rp($total_pendapatan);?></b></th></tr>
          <tr class="summary-ok"><th colspan="7" class="text-left"><b>Total Saldo Tunai</b> <span class="muted">(Tunai Masuk − Pengeluaran Tunai − Pembelian Tunai)</span></th><th colspan="2" class="text-right"><b><?=rp($saldo_tunai);?></b></th></tr>
        </tfoot>
      </table>
    </div>

    <script>
      // Lightbox aman (kalau GLightbox tidak ada, tidak error)
      var lightboxDescription = (typeof GLightbox === 'function') ? GLightbox({ selector: '.lightbox', loop: true }) : null;
    </script>
  </body>
</html>
