<?php
// Receipt print layout (80mm)
// Vars: $title, $meta, $company, $footer, $body
$format = 'receipt';
$autoPrint = isset($_GET['autoprint']) && (string)$_GET['autoprint'] === '1';
$closeAfterPrint = isset($_GET['close_after_print']) && (string)$_GET['close_after_print'] === '1';
?><!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= e($title ?? '') ?></title>
  <link rel="stylesheet" href="<?= e(asset('assets/vendor/fonts/cairo/cairo.css')) ?>">
  <link rel="stylesheet" href="<?= e(asset('assets/print/print_receipt.css')) ?>">
</head>
<body>
  <div class="no-print print-toolbar" style="display:flex;gap:8px;justify-content:center;align-items:center;margin:10px 0 16px">
    <button type="button" onclick="window.print()" style="padding:7px 12px;font-family:Cairo;border:1px solid #d8dee8;border-radius:10px;background:#f8fafc;cursor:pointer;font-size:13px;font-weight:700;min-width:92px">طباعة</button>
    <button type="button" onclick="window.close()" style="padding:7px 12px;font-family:Cairo;border:1px solid #d8dee8;border-radius:10px;background:#fff;cursor:pointer;font-size:13px;font-weight:700;min-width:92px">إغلاق</button>
  </div>

  <div class="page receipt">
    <?php require __DIR__ . '/partials/header.php'; ?>
    <div class="print-body">
      <?= $body ?>
    </div>
    <?php require __DIR__ . '/partials/footer.php'; ?>
  </div>

<?php if ($autoPrint): ?>
<script>
(function(){
  let printed = false;
  function finish(){
    if (printed) return;
    printed = true;
    if (<?= $closeAfterPrint ? 'true' : 'false' ?>) {
      setTimeout(function(){ window.close(); }, 250);
    }
  }
  window.addEventListener('afterprint', finish);
  const media = window.matchMedia ? window.matchMedia('print') : null;
  if (media && typeof media.addEventListener === 'function') {
    media.addEventListener('change', function(e){ if (!e.matches) finish(); });
  } else if (media && typeof media.addListener === 'function') {
    media.addListener(function(e){ if (!e.matches) finish(); });
  }
  window.addEventListener('load', function(){
    setTimeout(function(){ window.print(); }, 150);
    if (<?= $closeAfterPrint ? 'true' : 'false' ?>) {
      setTimeout(finish, 4000);
    }
  });
})();
</script>
<?php endif; ?>
</body>
</html>
