<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8">
<title>Receipt <?= e($sale['invoice_no']) ?></title>
<style>
<?php
$paperWidth = setting('print_paper_width','80mm');
$maxW = match($paperWidth) {
    '58mm' => '220px',
    'a4'   => '700px',
    default => '300px', // 80mm
};
?>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Courier New',monospace;font-size:12px;max-width:<?= $maxW ?>;margin:0 auto;padding:10px}
.center{text-align:center}.bold{font-weight:bold}.line{border-top:1px dashed #000;margin:6px 0}
table{width:100%}td{padding:1px 2px}
.right{text-align:right}.total-row td{font-weight:bold;border-top:1px solid #000}
@media print{body{margin:0}.no-print{display:none}@page{margin:0}}
</style></head><body>
<div class="center bold" style="font-size:14px">
<?php if (!empty(setting('shop_logo')) && setting('receipt_show_logo','1') === '1'): ?>
<img src="<?= UPLOAD_URL ?>/<?= e(setting('shop_logo')) ?>"
     alt="Logo" style="max-height:60px;max-width:200px;display:block;margin:0 auto 4px">
<?php endif; ?>
<?= e(setting('shop_name')) ?></div>
<div class="center"><?= e(setting('shop_address')) ?></div>
<div class="center"><?= e(setting('shop_phone')) ?></div>
<div class="line"></div>
<div><b>Invoice:</b> <?= e($sale['invoice_no']) ?></div>
<div><b>Date:</b> <?= fDate($sale['sale_date'],'d/m/Y H:i') ?></div>
<div><b>Cashier:</b> <?= e($sale['cashier_name']) ?></div>
<div>
  <b>Customer:</b> <?= e($sale['customer_name'] ?: 'Walk-in') ?>
  <?php if(empty($sale['customer_id']) && !empty($sale['cust_phone'])): ?>
  &nbsp;<b>Tel:</b> <?= e($sale['cust_phone']) ?>
  <?php elseif(!empty($sale['cust_phone'])): ?>
  &nbsp;(<?= e($sale['cust_phone']) ?>)
  <?php endif; ?>
</div>
<div class="line"></div>
<table>
<tr><td class="bold">Item</td><td class="right bold">Qty</td><td class="right bold">Price</td><td class="right bold">Total</td></tr>
<tr><td colspan="4"><div class="line" style="margin:2px 0"></div></td></tr>
<?php foreach ($items as $item): ?>
<tr>
  <td><?= e(mb_strimwidth($item['product_name'],0,18,'..')) ?></td>
  <td class="right"><?= $item['quantity'] ?></td>
  <td class="right"><?= number_format($item['selling_price'],2) ?></td>
  <td class="right"><?= number_format($item['total'],2) ?></td>
</tr>
<?php endforeach; ?>
<tr><td colspan="4"><div class="line" style="margin:2px 0"></div></td></tr>
<tr><td colspan="3">Subtotal</td><td class="right"><?= number_format($sale['subtotal'],2) ?></td></tr>
<?php if($sale['discount']>0): ?>
<tr><td colspan="3">Discount</td><td class="right">-<?= number_format($sale['discount'],2) ?></td></tr>
<?php endif; ?>
<?php if($sale['tax']>0): ?>
<tr><td colspan="3">Tax</td><td class="right"><?= number_format($sale['tax'],2) ?></td></tr>
<?php endif; ?>
<tr class="total-row"><td colspan="3">TOTAL</td><td class="right"><?= number_format($sale['total'],2) ?></td></tr>
</table>
<div class="line"></div>

<?php
// Calculate totals
$totalPaid   = array_sum(array_column($payments, 'amount'));
$changeDue   = round($totalPaid - (float)$sale['total'] + (float)$sale['balance'], 2);
$balanceDue  = (float)$sale['balance'];
$creditAmt   = 0;
foreach ($payments as $p) {
    if ($p['payment_method'] === 'credit') $creditAmt += (float)$p['amount'];
}
?>

<?php foreach ($payments as $p): ?>
<div style="display:flex;justify-content:space-between">
  <span>
    <?= ucfirst(str_replace('_',' ', $p['payment_method'])) ?>
    <?php if ($p['payment_method']==='card' && $p['reference']): ?>
      <small>(<?= e($p['reference']) ?>)</small>
    <?php elseif ($p['payment_method']==='credit' && $p['reference']): ?>
      <small style="color:#c07000">(<?= e($p['reference']) ?>)</small>
    <?php endif; ?>
  </span>
  <span><?= number_format($p['amount'],2) ?></span>
</div>
<?php endforeach; ?>

<?php if ($changeDue > 0.005): ?>
<div style="display:flex;justify-content:space-between">
  <span>Change</span>
  <span>-<?= number_format($changeDue,2) ?></span>
</div>
<?php endif; ?>

<?php if ($balanceDue > 0.005): ?>
<div style="display:flex;justify-content:space-between;font-weight:bold;margin-top:3px;
            border-top:1px dashed #000;padding-top:3px">
  <span>Balance Due</span>
  <span><?= number_format($balanceDue,2) ?></span>
</div>
<?php endif; ?>

<div class="line"></div>
<?php if (!empty(setting('receipt_footer'))): ?>
<div class="center"><?= e(setting('receipt_footer')) ?></div>
<br>
<?php endif; ?>
<div class="line"></div>
<div class="center" style="font-size:10px;line-height:1.4">
  <b>MJ SYSTEMS(PVT)LTD | MJPOS 10.5.2V</b><br><b>2026 All Rights Reserved Developed by DAMITHMJ</b><br>
  <b>www.mjsystems.com | Info@mjsystems.com</b><br>
  <b>T.P 077 034 5904</b>
</div>
<br>
<div class="center no-print">
  <button onclick="window.print()" style="padding:6px 16px;cursor:pointer">Print</button>
  <button onclick="window.close()" style="padding:6px 16px;cursor:pointer;margin-left:8px">Close</button>
  <div id="printStatusMsg" style="font-size:11px;color:#666;margin-top:8px"></div>
</div>
<script>
(function(){
  var AUTO_PRINT = <?= setting('print_auto_enabled','1')==='1' ? 'true' : 'false' ?>;
  var AUTO_CLOSE = <?= setting('print_auto_close','1')==='1' ? 'true' : 'false' ?>;
  var COPIES     = <?= max(1, (int) setting('print_copies', 1)) ?>;

  var statusEl = document.getElementById('printStatusMsg');
  var printsLeft = COPIES;

  function doPrint() {
    if (printsLeft <= 0) {
      if (AUTO_CLOSE) {
        if (statusEl) statusEl.textContent = 'Closing…';
        setTimeout(function(){ window.close(); }, 600);
      }
      return;
    }
    printsLeft--;
    if (statusEl) {
      statusEl.textContent = COPIES > 1
        ? 'Printing copy ' + (COPIES - printsLeft) + ' of ' + COPIES + '…'
        : 'Printing…';
    }
    window.print();
    // Give the print dialog/spooler a moment before firing the next copy
    setTimeout(doPrint, 700);
  }

  window.onload = function () {
    if (AUTO_PRINT) {
      doPrint();
    } else if (statusEl) {
      statusEl.textContent = 'Auto-print is off — click "Print" above.';
    }
  };
})();
</script>
</body></html>