<?php
$t = $trx;
$display_date = !empty($t->trx_date) ? $t->trx_date : $t->created_at;
$date_format  = 'd/m/Y H:i';
if (!empty($t->layout_json)) {
    $layout = is_string($t->layout_json) ? json_decode($t->layout_json, TRUE) : $t->layout_json;
    foreach ((array)$layout as $el) {
        if (($el['label'] ?? '') === 'date' && !empty($el['date_format'])) {
            $date_format = $el['date_format']; break;
        }
    }
}
$formatted_date = date($date_format, strtotime($display_date));

// Ambil paper_width dari template (default 58)
$paper_width = 58;
if (!empty($t->layout_json)) {
    // paper_width disimpan di template, bukan di layout_json.
    // Gunakan join yang sudah ada jika tersedia.
}
// Coba ambil dari property template jika di-join
if (isset($t->paper_width)) $paper_width = (int)$t->paper_width;
$cols = ($paper_width === 80) ? 42 : 32;
?>

<style>
.print-container { max-width: 480px; margin: 0 auto; display: flex; flex-direction: column; gap: 14px; }

/* Preview struk berbasis template */
.receipt-render-box { background:#fff; border:1px solid #ddd; border-radius:10px; padding:14px; }
.receipt-render-title { font-size:12px; font-weight:600; color:#555; margin-bottom:10px; }
.receipt-paper-print {
  margin: 0 auto;
  font-family:'Courier New', monospace;
  font-size: 11px;
  line-height: 1.6;
  background: #FFFEF8;
  border: 1px dashed #e0d9c0;
  border-radius: 4px;
  padding: 12px 10px 24px;
  min-height: 120px;
  overflow: hidden;
  white-space: pre;
}
.receipt-paper-print.paper-58 { width: 218px; }
.receipt-paper-print.paper-80 { width: 302px; }
.receipt-paper-print .r-bold   { font-weight: bold; }
.receipt-paper-print .r-center { text-align: center; display: block; white-space: pre; }
.receipt-paper-print .r-right  { text-align: right;  display: block; white-space: pre; }
.receipt-paper-print .r-left   { text-align: left;   display: block; white-space: pre; }
.receipt-paper-print .r-line   { color: #bbb; display: block; letter-spacing: -1px; }
.receipt-paper-print .r-size2  { font-size: 13px; }
.receipt-paper-print .r-size3  { font-size: 15px; }

.env-badges { display:flex; gap:6px; flex-wrap:wrap; margin-bottom:6px; }
.env-badge { padding:3px 10px; border-radius:20px; font-size:11px; font-weight:600; }
.env-https   { background:#E8F5E9; color:#2E7D32; border:1px solid #A5D6A7; }
.env-http    { background:#FFF8E1; color:#F57F17; border:1px solid #FFE082; }
.env-android { background:#E3F2FD; color:#1565C0; border:1px solid #90CAF9; }
.env-ios     { background:#FCE4EC; color:#880E4F; border:1px solid #F48FB1; }
.env-desktop { background:#F3E5F5; color:#6A1B9A; border:1px solid #CE93D8; }
</style>

<div class="print-container">

  <!-- Info Ringkas -->
  <div class="card" style="padding:14px 16px;">
    <div style="display:flex;justify-content:space-between;align-items:flex-start;flex-wrap:wrap;gap:8px;">
      <div>
        <div style="font-size:11px;color:#888;text-transform:uppercase;letter-spacing:.5px;">Invoice</div>
        <div style="font-weight:700;font-size:17px;font-family:monospace;"><?= htmlspecialchars($t->invoice_no) ?></div>
      </div>
      <div style="text-align:right;">
        <div style="font-size:11px;color:#888;text-transform:uppercase;letter-spacing:.5px;">Total</div>
        <div style="font-weight:700;font-size:20px;color:var(--primary);">
          Rp&nbsp;<?= number_format($t->total, 0, '.', '.') ?>
        </div>
      </div>
    </div>
    <div style="font-size:12px;color:#666;margin-top:8px;display:flex;gap:16px;flex-wrap:wrap;">
      <span>&#x1F4C5; <?= htmlspecialchars($formatted_date) ?></span>
      <span>&#x1F464; <?= htmlspecialchars($t->cashier) ?></span>
      <span>&#x1F3EA; <?= htmlspecialchars($t->store_name ?? '-') ?></span>
    </div>
    <?php if (!empty($t->note)): ?>
      <div style="font-size:12px;color:#888;margin-top:4px;">&#x1F4DD; <?= htmlspecialchars($t->note) ?></div>
    <?php endif; ?>
  </div>

  <!-- Preview Struk (render dari template) -->
  <div class="receipt-render-box">
    <div class="receipt-render-title">&#x1F441; Preview Struk</div>
    <div id="receiptPaperPrint" class="receipt-paper-print paper-<?= $paper_width ?>">
      <span style="color:#ccc;font-family:sans-serif;font-size:12px;">Memuat preview...</span>
    </div>
    <div id="paperInfoPrint" style="font-size:10px;color:#bbb;text-align:center;margin-top:6px;">
      <?= $paper_width ?>mm &middot; <?= $cols ?> karakter/baris
    </div>
  </div>

  <!-- Environment -->
  <div class="card" style="padding:12px 16px;">
    <div style="font-size:12px;font-weight:600;color:#555;margin-bottom:8px;">&#x1F4E1; Device</div>
    <div class="env-badges" id="envBadges"></div>
    <div id="envWarning"></div>
  </div>

  <!-- Tombol Cetak -->
  <div class="card" style="padding:12px 16px;">
    <div style="font-size:12px;font-weight:600;color:#555;margin-bottom:10px;">&#x1F5A8; Cetak via RawBT</div>

    <button id="btnIntent" class="btn btn-primary btn-block" onclick="doPrint('intent')">
      &#x1F4F1; Cetak via RawBT Intent URI
      <span style="font-size:11px;opacity:.75;font-weight:400;">(Rekomendasi &middot; HTTPS-safe)</span>
    </button>

    <div id="httpSection" style="margin-top:10px;">
      <div style="display:flex;gap:8px;align-items:center;">
        <input type="text" id="deviceIp" class="form-control"
          placeholder="IP Android mis: 192.168.1.5"
          value="127.0.0.1" style="flex:1;font-size:13px;">
        <button id="btnHTTP" class="btn btn-success" onclick="doPrint('http')"
          style="white-space:nowrap;">&#x1F310; HTTP</button>
      </div>
      <div style="font-size:11px;color:#999;margin-top:4px;">
        Hanya untuk akses HTTP. RawBT HTTP API harus aktif (port 8080).
      </div>
    </div>

    <div id="printStatus" class="alert" style="display:none;margin-top:10px;"></div>
  </div>

  <!-- Navigasi -->
  <div style="display:flex;gap:8px;flex-wrap:wrap;">
    <a href="<?= site_url('receipt/edit/'.$t->id) ?>" class="btn btn-warning" style="flex:1;justify-content:center;">&#x270F;&#xFE0F; Edit</a>
    <a href="<?= site_url('receipt') ?>" class="btn btn-light" style="flex:1;justify-content:center;">&#x2190; Daftar</a>
    <a href="<?= site_url('receipt/create') ?>" class="btn btn-primary" style="flex:1;justify-content:center;">+ Baru</a>
  </div>

</div>

<script>
const TRX_ID     = <?= (int)$t->id ?>;
const APP_URL    = '<?= site_url() ?>';
const PAPER_MM   = <?= (int)$paper_width ?>;
let   COLS       = <?= (int)$cols ?>;
const AUTO_PRINT = (new URLSearchParams(location.search)).get('auto') === '1';

let customFieldVals = <?= json_encode($t->custom_fields ?? []) ?>;

/* Deteksi environment */
(function() {
  const isHTTPS   = location.protocol === 'https:';
  const isAndroid = /Android/i.test(navigator.userAgent);
  const isIOS     = /iPhone|iPad|iPod/i.test(navigator.userAgent);
  const isDesktop = !isAndroid && !isIOS;

  document.getElementById('envBadges').innerHTML =
    '<span class="env-badge ' + (isHTTPS ? 'env-https' : 'env-http') + '">' + (isHTTPS ? '\uD83D\uDD12 HTTPS' : '\uD83D\uDD13 HTTP') + '</span>'
    + (isAndroid ? '<span class="env-badge env-android">\uD83D\uDCF1 Android</span>' : '')
    + (isIOS     ? '<span class="env-badge env-ios">\uD83C\uDF4E iOS</span>'         : '')
    + (isDesktop ? '<span class="env-badge env-desktop">\uD83D\uDCBB Desktop</span>' : '');

  if (isHTTPS) {
    document.getElementById('httpSection').style.opacity = '0.4';
    document.getElementById('btnHTTP').disabled = true;
    showWarn('\u26A0\uFE0F App berjalan di <b>HTTPS</b> \u2014 Metode HTTP diblokir browser. Gunakan tombol <b>Intent URI</b>.');
  }
  if (isIOS) {
    document.getElementById('btnIntent').disabled = true;
    showWarn('\u2139\uFE0F RawBT hanya tersedia di Android. Cetak dari perangkat Android.');
  }
})();

function showWarn(msg) {
  document.getElementById('envWarning').innerHTML =
    '<div class="alert alert-warning" style="margin-top:8px;font-size:12px;">' + msg + '</div>';
}

/* Render preview dari template */
function escH(s) { return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
function wrapText(str, w) { if(!str)return['']; const out=[]; for(let i=0;i<str.length;i+=w)out.push(str.slice(i,i+w)); return out; }
function fmtNum(num, format, prefix) {
  prefix = prefix||'';
  switch(format){
    case 'rupiah':     return 'Rp '+num.toLocaleString('id-ID');
    case 'number_sep': return prefix+num.toLocaleString('id-ID');
    case 'number':     return prefix+Math.round(num).toString();
    default:           return prefix+(num%1===0?Math.round(num).toString():num.toFixed(2));
  }
}

async function loadAndRenderPreview() {
  try {
    const res  = await fetch(APP_URL + 'receipt/preview_data', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({
        template_id:   <?= (int)$t->template_id ?>,
        store_id:      <?= (int)$t->store_id ?>,
        invoice_no:    <?= json_encode($t->invoice_no) ?>,
        cashier:       <?= json_encode($t->cashier) ?>,
        trx_date:      <?= json_encode(!empty($t->trx_date) ? date('Y-m-d\TH:i', strtotime($t->trx_date)) : date('Y-m-d\TH:i')) ?>,
        discount:      <?= (float)$t->discount ?>,
        tax:           <?= (float)$t->tax ?>,
        note:          <?= json_encode($t->note ?? '') ?>,
        items:         <?= json_encode($t->items ?? []) ?>,
        custom_fields: customFieldVals,
      }),
    });
    const json = await res.json();
    if (json.status !== 'ok') return;
    renderPreviewHTML(json.elements, json.data);
  } catch(e) { console.error('preview error', e); }
}

function renderPreviewHTML(elements, data) {
  const paper  = document.getElementById('receiptPaperPrint');
  const sorted = [...elements].sort((a,b)=>(parseInt(a.y)||0)-(parseInt(b.y)||0));
  let html = '';
  sorted.forEach(el => {
    const type   = el.element_type;
    const align  = el.align || 'left';
    const bold   = el.bold  ? ' r-bold' : '';
    const fsize  = parseInt(el.font_size)||1;
    const fsClass= fsize===2?' r-size2':(fsize===3?' r-size3':'');
    const cls    = 'r-'+align+bold+fsClass;

    if (type === 'line')   { html += '<span class="r-line r-left">'+'\u2500'.repeat(COLS)+'</span>'; return; }
    if (type === 'spacer') { html += '<span class="r-left"> </span>'; return; }

    /* ── STORE HEADER (logo + alamat) ── */
    if (type === 'store_header') {
      const align  = el.header_align || 'center';
      const repl   = (s) => s ? Object.keys(data).reduce((acc, k) => acc.replace(new RegExp('\\{\\{'+k+'\\}\\}','g'), data[k]||''), s) : '';
      const logoTx = repl(el.logo_text    || '');
      const compNm = repl(el.company_name || '');
      const addr1  = repl(el.address_line1|| '');
      const addr2  = repl(el.address_line2|| '');
      const npwp   = el.npwp   || '';
      const phone  = el.phone  || '';
      const scode  = repl(el.store_code   || '');
      if (logoTx) html += `<span class="r-center r-bold r-size2">${escH(logoTx)}</span>`;
      if (compNm) wrapText(compNm, COLS).forEach(l => html += `<span class="r-${align}">${escH(l)}</span>`);
      if (addr1)  wrapText(addr1,  COLS).forEach(l => html += `<span class="r-${align}">${escH(l)}</span>`);
      if (addr2)  wrapText(addr2,  COLS).forEach(l => html += `<span class="r-${align}">${escH(l)}</span>`);
      if (npwp)   html += `<span class="r-${align}">NPWP: ${escH(npwp)}</span>`;
      if (phone)  html += `<span class="r-${align}">Telp: ${escH(phone)}</span>`;
      if (scode)  html += `<span class="r-${align}">${escH(scode)}</span>`;
      if (el.show_divider) html += `<span class="r-line r-left">${'\u2500'.repeat(COLS)}</span>`;
      return;
    }

    if (type === 'text') {
      let val = el.value || '';
      Object.keys(data).forEach(k => { val = val.replace(new RegExp('\\{\\{'+k+'\\}\\}','g'), data[k]||''); });
      if (el.label === 'items') {
        val.split('\n').forEach(line => { if(line) html += '<span class="r-left">'+escH(line)+'</span>'; });
      } else {
        wrapText(val, Math.floor(COLS/Math.max(1,fsize-0.5))).forEach(l => { html += '<span class="'+cls+'">'+escH(l)+'</span>'; });
      }
      return;
    }
    if (type === 'input') {
      const iname = el.input_name || el.label || '';
      const raw   = data[iname] !== undefined ? data[iname] : (customFieldVals[iname]||'');
      const disp  = el.input_label ? el.input_label+': '+raw : raw;
      html += '<span class="'+cls+'">'+escH(disp)+'</span>';
      return;
    }
    if (type === 'row2') {
      const c1=el.col1||{}, c2=el.col2||{};
      const v1=String(customFieldVals[c1.input_name||'']||'');
      const v2=String(customFieldVals[c2.input_name||'']||'');
      const w1=Math.round(COLS*(c1.width||50)/100), w2=COLS-w1;
      html += '<span class="r-left">'+escH(v1.substring(0,w1).padEnd(w1)+v2.substring(0,w2).padStart(w2))+'</span>';
      return;
    }
    if (type === 'multiply') {
      const a=parseFloat(customFieldVals[el.input_a||'']||0), b=parseFloat(customFieldVals[el.input_b||'']||0);
      html += '<span class="'+cls+'">'+escH((el.display_label||'Total').padEnd(16)+fmtNum(a*b,el.format||'rupiah',el.prefix||''))+'</span>';
      return;
    }
  });
  paper.innerHTML = html || '<span style="color:#ccc;font-family:sans-serif">Template kosong</span>';
}

/* Handler cetak */
async function doPrint(method) {
  const btnId = method === 'intent' ? 'btnIntent' : 'btnHTTP';
  const btn   = document.getElementById(btnId);
  const orig  = btn.innerHTML;
  btn.disabled = true;
  btn.innerHTML = '\u23F3 Memproses...';
  setStatus('info', '\u23F3 Mengambil data dari server...');

  try {
    const res  = await fetch(APP_URL + 'receipt/get_rawbt/' + TRX_ID);
    if (!res.ok) throw new Error('Server error ' + res.status);
    const json = await res.json();
    if (json.status !== 'ok') throw new Error(json.message || 'Gagal');

    const base64 = json.base64;
    setStatus('info', '\u23F3 Mengirim ke RawBT...');

    if (method === 'intent') {
      setStatus('ok', '\u2705 Membuka RawBT... Pastikan app RawBT terinstall.');
      setTimeout(() => { window.location.href = 'rawbt:data:application/octet-stream;base64,' + base64; }, 300);
    } else {
      const ip  = document.getElementById('deviceIp').value.trim() || '127.0.0.1';
      const raw = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
      const r   = await fetch('http://'+ip+':8080', {
        method: 'POST', headers: {'Content-Type':'application/octet-stream'}, body: raw,
      });
      if (!r.ok) throw new Error('RawBT error HTTP '+r.status);
      setStatus('ok', '\u2705 Terkirim ke RawBT ('+ip+':8080)!');
    }
  } catch(e) {
    setStatus('error', '\u274C ' + e.message);
  } finally {
    btn.disabled = false;
    btn.innerHTML = orig;
  }
}

function setStatus(type, msg) {
  const el = document.getElementById('printStatus');
  el.className     = 'alert alert-' + type;
  el.style.display = 'block';
  el.innerHTML     = msg;
}

/* Init: render preview lalu auto-print jika ?auto=1 */
loadAndRenderPreview().then(() => {
  if (AUTO_PRINT) {
    setTimeout(() => doPrint('intent'), 800);
  }
});
</script>
