<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Cetak Struk Bluetooth (Android)</title>
  <script src="https://unpkg.com/escpos-web-bluetooth@latest/dist/index.umd.js"></script>
  <style>
    body {
      font-family: 'Courier New', Courier, monospace;
      font-size: 12px;
    }
    #printBtn {
      padding: 10px 15px;
      font-size: 14px;
    }
  </style>
</head>
<body>

<h3>Struk Penjualan</h3>
<button id="printBtn">Cetak via Bluetooth</button>

<script>
  const receiptData = {
    logo: "<?= base_url('uploads/' . ($receipt['logo'] ?? '')) ?>",
    header: <?= json_encode($receipt['header'] ?? 'TOKO KAMI') ?>,
    footer: <?= json_encode($receipt['footer'] ?? "Terima kasih telah berbelanja\nSemoga bermanfaat") ?>,
    date: "<?= date('d/m/Y H:i', strtotime($sale['created_at'] ?? $sale['tanggal'])) ?>",
    cashier: "<?= esc($sale['user_name'] ?? '-') ?>",
    code: "<?= esc($sale['kode'] ?? '-') ?>",
    customer: "<?= esc($sale['customer_name'] ?? '-') ?>",
    jenisPesan: "<?= esc($sale['jenis_pesan'] ?? '-') ?>",
    noMeja: "<?= esc($sale['no_meja'] ?? '-') ?>",
    items: <?= json_encode($details) ?>,
    subtotal: <?= (int) ($sale['total'] ?? 0) ?>,
    diskonPersen: <?= (float) ($sale['diskon_persen'] ?? 0) ?>,
    diskonNominal: <?= (int) ($sale['diskon_nominal'] ?? 0) ?>,
    taxPercent: <?= (float) ($sale['pajak_persen'] ?? 0) ?>,
    taxNominal: <?= (int) ($sale['pajak_nominal'] ?? 0) ?>,
    grandTotal: <?= ((int) ($sale['total'] ?? 0)) + ((int) ($sale['pajak_nominal'] ?? 0)) ?>,
    paid: <?= (int) ($sale['dibayar'] ?? 0) ?>,
    change: <?= (int) ($sale['kembalian'] ?? 0) ?>
  };

  async function printReceipt() {
    try {
      const device = await escpos.WebBluetooth().requestDevice();
      const printer = await escpos.WebBluetooth().getPrinter(device);
      const encoder = new escpos.Encoder();

      let result = encoder.initialize().align('center');

      if (receiptData.header) result = result.text(receiptData.header);
      result = result.newline();

      if (receiptData.logo) {
        try {
          const res = await fetch(receiptData.logo);
          const blob = await res.blob();
          const bitmap = await createImageBitmap(blob);
          result = result.image(bitmap, 'd24');
        } catch (err) {
          console.warn('Gagal memuat logo:', err);
        }
      }

      result = result.text('-----------------------------')
        .align('left')
        .text(`Tanggal    : ${receiptData.date}`)
        .text(`Kasir      : ${receiptData.cashier}`)
        .text(`Transaksi #: ${receiptData.code}`)
        .text(`Pelanggan  : ${receiptData.customer}`)
        .text(`Pesanan    : ${receiptData.jenisPesan}`)
        
      
      if (receiptData.jenisPesan.toLowerCase() === 'dine_in') {
        result = result.text(`No. Meja   : ${receiptData.noMeja}`);
      }

      result = result.text('-----------------------------');

      receiptData.items.forEach(item => {
        result = result
          .text(item.nama_item)
          .text(`${item.qty} x ${formatNumber(item.harga)} = ${formatNumber(item.subtotal)}`);
      });

      result = result
        .text('-----------------------------')
        .text(`Subtotal     : ${formatNumber(receiptData.subtotal)}`);

        if (receiptData.diskonNominal && receiptData.diskonNominal > 0) {
          result = result.text(`Diskon (${receiptData.diskonPersen}%) : ${formatNumber(receiptData.diskonNominal)}`);
        }

      if (receiptData.taxNominal > 0) {
        result = result.text(`Pajak (${receiptData.taxPercent}%) : ${formatNumber(receiptData.taxNominal)}`);
      }

      result = result
        .text(`Total        : ${formatNumber(receiptData.grandTotal)}`)
        .text(`Dibayar      : ${formatNumber(receiptData.paid)}`)
        .text(`Kembalian    : ${formatNumber(receiptData.change)}`)
        .text('-----------------------------')
        .align('center')
        .text(receiptData.footer)
        .newline()
        .newline()
        .cut('full');

      await printer.print(result.encode());
    } catch (error) {
      alert("Gagal mencetak: " + error.message);
      console.error(error);
    }
  }

  function formatNumber(num) {
    return new Intl.NumberFormat('id-ID').format(num);
  }

  document.getElementById('printBtn').addEventListener('click', printReceipt);
</script>

</body>
</html>
