<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Invoice #<?= html_escape($cetak->id_transaksi); ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <?php
    $thermal_font_size = (isset($font_size) && is_numeric($font_size)) ? (int) $font_size : 13;
    if ($thermal_font_size < 7) {
      $thermal_font_size = 7;
    }
    $thermal_line_height = 1.35;
    $thermal_big_font_size = max($thermal_font_size + 5, (int) round($thermal_font_size * 1.38));
  ?>

  <style>
    <?php if (!empty($is_pdf)): ?>
    @page { margin: 0; }
    <?php endif; ?>

    :root { --paper-width: 302px; }
    * { box-sizing: border-box; }
    body {
      margin: 0; padding: 12px 0; background: #f7f7f7;
      -webkit-print-color-adjust: exact; print-color-adjust: exact;
      font: <?=$thermal_font_size;?>px/<?=$thermal_line_height;?> "Courier New", Courier, monospace; color: #000;
    }
    .paper { width: var(--paper-width); margin: 0 auto; background: #fff; padding: 8px 10px; border: 1px dashed #ddd; position: relative; }
    .center { text-align: center; }
    .mt-6 { margin-top: 6px; }
    .bold { font-weight: 700; }
    .big  { font-size: <?=$thermal_big_font_size;?>px; letter-spacing: 1px; }
    .rule { border-top: 1px solid #000; margin: 6px 0; }
    .rule2{ border-top: 2px solid #000; margin: 6px 0; }
    .muted{ opacity: .9; }
    .logo-wrap,
    .qr-wrap { width: 100%; text-align: center; }
	.qr-label { margin: 8px auto 0; font-weight: bold; text-align: center; }
	.qr   { width: 120px; height: auto; margin: 8px auto 0; display:block; }
    .logo { width: 78%; max-width: 190px; height: auto; margin: 0 auto 6px; display:block; }
    .row  { white-space: pre; font: inherit; }

    .lr { display: table; width: 100%; table-layout: fixed; white-space: nowrap; margin-top: 2px; line-height: 1.2; }
    .lr .l { display: table-cell; width: 66%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: top; }
    .lr .r { display: table-cell; width: 34%; text-align: right; white-space: nowrap; vertical-align: top; font-variant-numeric: tabular-nums; }

    .lr-sum{ display: table; width: 100%; table-layout: fixed; margin: 2px 0; line-height: 1.2; }
    .lr-sum .l{ display: table-cell; width: 42%; white-space: nowrap; vertical-align: middle; line-height: 1.2; padding: 2px 0; }
    .lr-sum .r{ display: table-cell; width: 58%; text-align: right; vertical-align: middle; line-height: 1.2; padding: 2px 0; font-variant-numeric: tabular-nums; }

    .sum-area{ position: relative; padding: 4px 0; margin-bottom: 2px; min-height: 86px; }
    .sum-rows { position: relative; z-index: 2; }
    .sum-area .stamp{
      position: absolute; left: 50%; top: 50%;
      margin-left: -74px;   /* width/2 */
      margin-top: -32px;    /* visual center for 3 summary rows */
      transform: rotate(-14deg);
      width: 148px; height: auto; display: block; pointer-events: none;
    }
    .sum-area .stamp.above{ z-index: 1; opacity: .85; }
    .sum-area .stamp.below{ z-index: 0; opacity: .18; mix-blend-mode: multiply; }

    <?php if (!empty($is_pdf)): ?>
    body { padding: 0; background: #fff; }
    .paper { margin: 0 auto; overflow: visible; }
    .sum-area { position: relative; min-height: 88px; padding: 4px 0 0; overflow: visible; }
    .sum-area .stamp{
      position: absolute;
      left: 50%;
      top: 8px;
      margin: 0;
      transform: translateX(-50%) rotate(-14deg);
      z-index: 1;
      opacity: .72;
      width: 132px;
    }
    .sum-area .stamp.below{ opacity: .15; }
    <?php endif; ?>

    @media print { body { background: #fff; -webkit-filter: grayscale(100%); filter: grayscale(100%); } .paper { border: 0; } }
  </style>
</head>
<body>
<?php
  // helper sederhana
  if (!function_exists('html_escape')) {
    function html_escape($s){ return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
  }
  function line_58($left, $right = '', $width = 32) {
    $left  = trim((string)$left); $right = trim((string)$right);
    $llen  = strlen(preg_replace('/<[^>]+>/', '', $left));
    $rlen  = strlen(preg_replace('/<[^>]+>/', '', $right));
    $sp    = max(1, $width - $llen - $rlen);
    return $left . str_repeat(' ', $sp) . $right;
  }

  // normalisasi nilai
  $jumlah_bayar = isset($jumlah_bayar) ? $jumlah_bayar : 0;
  $kembalian    = isset($kembalian) ? $kembalian : 0;
  $cdetail      = isset($cdetail) ? $cdetail : (isset($bdetail) && is_array($bdetail) ? count($bdetail) : 0);

  // ambil string metode bayar terakhir
  function __resolve_nama_bayar($cara, $bdetail = null) {
    $cands = [];
    if (is_object($cara)) {
      foreach (['nama_bayar','cara_bayar','metode','pembayaran','via'] as $k) {
        if (isset($cara->$k) && trim($cara->$k) !== '') $cands[] = $cara->$k;
      }
    } elseif (is_array($cara)) {
      foreach (['nama_bayar','cara_bayar','metode','pembayaran','via'] as $k) {
        if (!empty($cara[$k])) $cands[] = $cara[$k];
      }
    }
    if (is_array($bdetail) && !empty($bdetail)) {
      $last = end($bdetail);
      if (is_array($last)) {
        foreach (['nama_bayar','cara_bayar','metode','pembayaran','via'] as $k) {
          if (!empty($last[$k])) $cands[] = $last[$k];
        }
      } elseif (is_object($last)) {
        foreach (['nama_bayar','cara_bayar','metode','pembayaran','via'] as $k) {
          if (isset($last->$k) && trim($last->$k) !== '') $cands[] = $last->$k;
        }
      }
    }
    if (empty($cands)) return '-';
    $val = strtoupper(trim($cands[count($cands)-1]));
    $val = str_replace(['  ','- '], [' ','-'], $val);
    return $val;
  }

  // header info
  $title      = isset($info['title']) ? $info['title'] : '';
  $desc       = isset($info['deskripsi']) ? strip_tags(base64_decode($info['deskripsi'])) : '';
  $phone      = isset($info['phone']) ? $info['phone'] : '';
  $logo_path  = isset($logo) ? $logo : (isset($logo_lunas) ? $logo_lunas : '');
	$qris_path  = !empty($kode_qris_pdf) ? $kode_qris_pdf : (isset($kode_qris) ? $kode_qris : '');

  // konsumen
  $k_nama = ($konsumen['tampil']==1) ? $konsumen['perusahaan'] : $konsumen['nama'];
  $panggilan = '';
  if (function_exists('cekKonsumen') && !empty($cetak->id_konsumen)) {
    $ck = cekKonsumen($cetak->id_konsumen);
    $panggilan = isset($ck['panggilan']) ? $ck['panggilan'] : '';
  }

  // subtotal
  $subtotal = 0; $grandtotal = 0;
  foreach ($detail as $v) {
    $disc = $v['jumlah'] * $v['harga'] * $v['diskon'] / 100;
    $tot  = $v['jumlah'] * $v['harga'] - $disc;
    $subtotal += $tot; $grandtotal += $tot;
  }
  $pajak = ($subtotal * (isset($cetak->pajak)?$cetak->pajak:0)) / 100;
  $sisa  = $pajak + $subtotal - $total->total;
  $cek_bayar = $pajak + $subtotal;

  // deteksi jenis bayar
  $raw_method   = __resolve_nama_bayar(isset($cara)?$cara:null, isset($bdetail)?$bdetail:null);
  $has_payment  = ($total->total > 0);
  $jenis_bayar  = 'PIUTANG';
  if ($has_payment) {
    if ($raw_method !== '-' && strpos($raw_method,'PIUTANG') !== false) {
      $jenis_bayar = 'PIUTANG';
    } elseif ($raw_method !== '-' && (strpos($raw_method,'TUNAI') !== false || strpos($raw_method,'CASH') !== false)) {
      $jenis_bayar = 'TUNAI';
    } else {
      $transfer_keywords = [
        'TRANSFER','TRF','TF','TR','BANK','REK','BCA','MANDIRI','BRI','BNI',
        'QRIS','QR','DEBIT','KARTU','CARD','VISA','MASTER',
        'OVO','GOPAY','GO-PAY','DANA','LINKAJA','LINK AJA','SHOPEEPAY',
        'E-WALLET','EWALLET','WALLET','MBANKING','M-BANKING','VIRTUAL ACCOUNT','VA'
      ];
      $is_transfer = false;
      $haystack = ($raw_method === '-') ? '' : $raw_method;
      foreach ($transfer_keywords as $kw) {
        if ($haystack !== '' && strpos($haystack, $kw) !== false) { $is_transfer = true; break; }
      }
      if ($is_transfer) $jenis_bayar = 'TRANSFER';
      else if ($sisa <= 0) $jenis_bayar = 'TRANSFER';
    }
  } else {
    $jenis_bayar = ($sisa > 0) ? 'PIUTANG' : $jenis_bayar;
  }
  $ketbyr = 'JENIS BAYAR : ' . $jenis_bayar;

  // gambar cap
  $img_lunas  = isset($lunas)  ? $lunas  : (function_exists('info') ? base_url().'uploads/'.info()['stamp_l']  : '');
  $img_blunas = isset($blunas) ? $blunas : (function_exists('info') ? base_url().'uploads/'.info()['stamp_b'] : '');
  $stamp_layer = 'above';
?>
  <div class="paper">
    <?php if (!empty($logo_path)): ?>
      <div class="logo-wrap">
        <img class="logo" src="<?= $logo_path; ?>" alt="">
      </div>
    <?php endif; ?>

    <div class="center bold"><?= html_escape($title); ?></div>
    <?php if (!empty($desc)): ?>
      <div class="center muted"><?= html_escape($desc); ?></div>
    <?php endif; ?>
    <?php if (!empty($phone)): ?>
      <div class="center"><?= html_escape($phone); ?></div>
    <?php endif; ?>

    <div class="rule2"></div>

    <div class="center big bold"><?= html_escape($cetak->id_transaksi); ?></div>

    <div class="mt-6">
      <div class="row"><?= line_58('Kasir    : '. $marketing['nama_lengkap']); ?></div>
      <div class="row"><?= line_58('Tanggal  : '. tgl_indo($cetak->tgl_trx)); ?></div>
      <div class="row"><?= line_58('Jam      : '. invoice_order_time($cetak)); ?></div>
      <div class="row"><?= line_58('Pelanggan: '. trim($panggilan.' '.$k_nama)); ?></div>
    </div>

    <div class="rule2"></div>

    <?php
      $idx = 0; $totalb = 0; $count = count($detail);
      foreach ($detail as $val):
        $idx++;
        $disc = $val['jumlah'] * $val['harga'] * $val['diskon'] / 100;
        $totalb = $val['jumlah'] * $val['harga'] - $disc;
        $nama_bhn = $val['nbahan']; $ukuran = $val['ukuran'];
        $qty = $val['jumlah']; $ket = trim($val['keterangan']);
        $satuan = 'pcs';

        // === FINISHING DATA (sesuai inspirasi print_invoice.php) ===
        // Ambil dari $val['detail'] → object dengan property ->data berupa list {title, isi}
        $finishingData = [];
        if (isset($val['detail']) && $val['detail'] !== '') {
          $decoded = json_decode($val['detail']);
          if (is_object($decoded) && isset($decoded->data) && is_array($decoded->data)) {
            $finishingData = $decoded->data; // array of objects
          }
        }
        $hasNotes = !empty($finishingData);
    ?>
      <div class="row"><?= line_58($nama_bhn); ?></div>
      <div class="row"><?= line_58('Ukuran:'.$ukuran, 'Qty:'.$qty); ?></div>

      <?php if ($ket !== ''): ?>
        <div class="row"><?= line_58('Ket:'.$ket); ?></div>
      <?php endif; ?>

      <?php if ($hasNotes): ?>
        <div class="row"><?= line_58('Catatan:'); ?></div>
        <?php foreach ($finishingData as $fn): 
              $t = isset($fn->title) ? trim($fn->title) : '';
              $i = isset($fn->isi)   ? trim($fn->isi)   : '';
              $lineTxt = trim($t . ($i !== '' ? ' '.$i : ''));
              if ($lineTxt === '') continue;
        ?>
          <div class="row"><?= line_58(''.$lineTxt); ?></div>
        <?php endforeach; ?>
      <?php endif; ?>

      <div class="lr">
        <div class="l"><?= (int)$qty.' '.$satuan.' x '.number_format($val['harga'],0,',','.'); ?></div>
        <div class="r"><?= number_format($totalb,0,',','.'); ?></div>
      </div>
      <?php if ($idx < $count): ?><div class="rule"></div><?php endif; ?>
    <?php endforeach; ?>

    <div class="rule2"></div>

    <div class="sum-area">
      <div class="sum-rows">
      <div class="lr-sum bold"><div class="l">TOTAL</div><div class="r"><?= rp($subtotal); ?></div></div>

<?php
  $tdetail_total = isset($tdetail) ? $tdetail : (isset($total->total) ? $total->total : 0);
  $tdetailX = (object)['jumlah_bayar' => $jumlah_bayar, 'kembalian' => $kembalian, 'total' => $tdetail_total, 'pajak'=> $pajak];

  if ($sisa == 0) {
    if ($tdetailX->jumlah_bayar > $total->total) {
      $jumlah_bayar = $tdetailX->jumlah_bayar; $sisa_show = $tdetailX->kembalian;
    } else {
      $jumlah_bayar = $total->total; $sisa_show = $tdetailX->kembalian;
    }
?>
      <div class="lr-sum"><div class="l">BAYAR</div><div class="r"><?= rp($total->total); ?></div></div>
      <div class="lr-sum"><div class="l">KEMBALIAN</div><div class="r"><?= rp($sisa_show); ?></div></div>
<?php } else { ?>
      <div class="lr-sum"><div class="l">BAYAR</div><div class="r"><?= rp($total->total); ?></div></div>
      <div class="lr-sum"><div class="l">SISA</div><div class="r"><?= rp($sisa); ?></div></div>
<?php } ?>
      </div>

      <?php if (!empty($img_lunas) && !empty($img_blunas)): ?>
        <?php if ($sisa <= 0): ?>
          <img class="stamp <?= $stamp_layer === 'below' ? 'below' : 'above'; ?>" src="<?= $img_lunas; ?>" alt="">
        <?php else: ?>
          <img class="stamp <?= $stamp_layer === 'below' ? 'below' : 'above'; ?>" src="<?= $img_blunas; ?>" alt="">
        <?php endif; ?>
      <?php endif; ?>

    </div>

    <div class="rule2"></div>

	<?php if (!empty($qr_available)): ?>
	<div class="qr-wrap">
	  <?php if (!empty($qr_is_tracking)): ?><div class="qr-label"><?=htmlspecialchars($qr_label, ENT_QUOTES, 'UTF-8');?></div><?php endif; ?>
      <img class="qr" src="<?= $qris_path; ?>" alt="">
    </div>
	<?php endif; ?>

    <div class="mt-6 center">
      Terima kasih<br>
      Barang yang sudah dibeli<br>
      Tidak dapat dibatalkan!<br>
      Barang tidak diambil > 1 bulan<br>
      BUKAN TANGGUNG JAWAB KAMI!!!
    </div>

    <div class="mt-6 center muted"><?= $ketbyr; ?></div>
  </div>
</body>
</html>
