<?php
// admin/receipt.php
// Prints a thermal-formatted 80mm receipt for an order.
// Auto-invokes window.print() on load so staff can just click
// the printer confirm dialog and the ticket comes out.

require_once __DIR__ . '/auth.php';
require_login();
require_permission('orders');
require_once __DIR__ . '/../config.php';

$id = intval($_GET['id'] ?? 0);
if (!$id) { http_response_code(400); exit('Missing order id'); }

$pdo = db();
$order = $pdo->prepare('SELECT * FROM orders WHERE id = ?');
$order->execute([$id]);
$order = $order->fetch();
if (!$order) { http_response_code(404); exit('Order not found'); }

$lines = $pdo->prepare('SELECT * FROM order_items WHERE order_id = ? ORDER BY id');
$lines->execute([$id]);
$lines = $lines->fetchAll();

// Settings for the receipt header
$s = $pdo->query("SELECT key_name, value FROM settings WHERE key_name IN
    ('receipt_header_en','receipt_header_ar',
     'receipt_address_en','receipt_address_ar',
     'receipt_phone',
     'receipt_footer_en','receipt_footer_ar',
     'currency_decimals')")
    ->fetchAll(PDO::FETCH_KEY_PAIR);

$decimals = intval($s['currency_decimals'] ?? 3);
$currency = $order['currency'] ?: 'KD';

// Build the payment line for the receipt body. The label is what
// staff handing over the order most needs to know:
//
//   "PAID — Card"          → already paid; no action needed
//   "PAID — KNET"          → same, but call out KNET specifically
//   "Cash on delivery"     → collect cash from the driver/customer
//   "Pay at counter"       → collect at the counter before handover
//   "Awaiting payment"     → red flag; do not prepare yet
//   "Payment FAILED"       → red flag; order shouldn't be fulfilled
//   "WhatsApp confirmed"   → legacy; no payment data captured
//
// Returns an associative array with the label and a CSS class
// hint so the template can color it appropriately.
function payment_label_for_receipt(array $order): array {
    $m = $order['payment_method'] ?? '';
    $s = $order['payment_status'] ?? '';

    if ($m === 'knet_card') {
        if ($s === 'paid')    return ['label' => 'PAID — Card / KNET', 'class' => 'pay-paid'];
        if ($s === 'failed')  return ['label' => 'Payment FAILED',     'class' => 'pay-fail'];
        if ($s === 'pending') return ['label' => 'Awaiting payment',   'class' => 'pay-warn'];
        return ['label' => 'Card / KNET', 'class' => 'pay-warn'];
    }
    if ($m === 'cash')    return ['label' => 'Cash on delivery',  'class' => 'pay-warn'];
    if ($m === 'counter') return ['label' => 'Pay at counter',    'class' => 'pay-warn'];
    return ['label' => 'WhatsApp confirmed', 'class' => 'pay-legacy'];
}
$payment = payment_label_for_receipt($order);

function h($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
function money($n, $dec) { return number_format(floatval($n), $dec); }
?><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Receipt <?= h($order['order_number']) ?></title>
<style>
/* Base styles for the on-screen preview AND print. Thermal printers
   typically respect CSS sizing when fed through a browser's print
   driver, so we size everything in mm where print matters and px
   for screen viewing. */
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
  font-family: 'Courier New', 'Consolas', monospace;
  color: #000;
  background: #f5f5f5;
  padding: 20px;
  font-size: 12px;
  line-height: 1.4;
}
.receipt {
  width: 80mm;
  max-width: 80mm;
  margin: 0 auto;
  padding: 6mm 4mm;
  background: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);  /* screen only — hidden in print */
}

/* Centered text helper */
.c { text-align: center; }
.r { text-align: right; }
.b { font-weight: bold; }
.small { font-size: 10px; }
.big { font-size: 16px; font-weight: bold; letter-spacing: 1px; }
.huge { font-size: 20px; font-weight: bold; letter-spacing: 2px; }

/* Header block */
.header { text-align: center; margin-bottom: 10px; }
.header .name-en { font-size: 14px; font-weight: bold; letter-spacing: 1.5px; text-transform: uppercase; margin-bottom: 2px; }
.header .name-ar { font-size: 14px; font-weight: bold; margin-bottom: 4px; direction: rtl; font-family: 'Amiri', 'Traditional Arabic', serif; }
.header .meta { font-size: 10px; margin: 1px 0; }

/* Dashed separator like a thermal ticket */
.sep {
  border: none;
  border-top: 1px dashed #000;
  margin: 8px 0;
}

/* Order-meta block */
.order-meta { margin-bottom: 6px; font-size: 11px; }
.order-meta .row { display: flex; justify-content: space-between; padding: 1px 0; }
.order-meta .label { color: #333; }

/* Items table */
.items { margin: 8px 0; }
.item {
  margin-bottom: 8px;
  page-break-inside: avoid;
}
.item .line1 { display: flex; justify-content: space-between; font-weight: bold; font-size: 12px; }
.item .name { flex: 1; padding-right: 8px; }
.item .price { white-space: nowrap; }
.item .name-ar { font-size: 11px; direction: rtl; text-align: right; margin-top: 1px; font-family: 'Amiri', 'Traditional Arabic', serif; }
.item .sub { font-size: 10px; color: #444; margin-top: 2px; padding-left: 8px; }

/* Totals */
.totals { margin-top: 10px; }
.totals .row { display: flex; justify-content: space-between; padding: 2px 0; }
.totals .grand { font-size: 14px; font-weight: bold; padding-top: 4px; border-top: 1px solid #000; margin-top: 4px; }

/* Customer block */
.customer { margin-top: 10px; font-size: 11px; }
.customer .row { margin: 2px 0; }
.notes { margin-top: 6px; padding: 6px; border: 1px dashed #000; font-size: 11px; }

/* Payment line — visually prominent on thermal paper. We use a
   solid black box around the label so it stands out even in the
   monochrome thermal rendering. Color hints are kept subtle for
   on-screen viewing; the print version reduces to plain box. */
.payment-line { margin-top: 8px; padding: 6px 8px; border: 2px solid #000;
                text-align: center; font-size: 12px; font-weight: bold;
                text-transform: uppercase; letter-spacing: 0.5px; }
.payment-line.pay-paid   { background: #dcfce7; }   /* green — already paid */
.payment-line.pay-warn   { background: #fef3c7; }   /* amber — collect on hand-off */
.payment-line.pay-fail   { background: #fee2e2; color: #991b1b; }
.payment-line.pay-legacy { background: #f1f5f9; font-weight: normal; font-size: 11px; }
@media print {
  /* Force solid borders, drop subtle backgrounds — thermal printer
     renders backgrounds inconsistently. Border + uppercase text
     is enough to communicate the importance. */
  .payment-line { background: #fff !important; }
  .payment-line.pay-fail { background: #fff !important; }
}

.footer { margin-top: 12px; text-align: center; font-size: 10px; line-height: 1.5; }

/* Print-only adjustments. The thermal driver reads @page to size
   the paper and strips our screen shadow + background. */
@media print {
  @page { size: 80mm auto; margin: 0; }
  body { background: #fff; padding: 0; }
  .receipt { box-shadow: none; padding: 3mm; width: 80mm; }
  .no-print { display: none !important; }
}

/* Print controls — hidden when printing */
.print-controls {
  width: 80mm; max-width: 80mm; margin: 10px auto; text-align: center;
}
.print-controls button {
  padding: 10px 20px; background: #2563eb; color: #fff; border: none;
  border-radius: 6px; font-size: 14px; cursor: pointer; margin: 0 4px;
  font-family: inherit;
}
.print-controls button:hover { background: #1d4ed8; }
.print-controls button.secondary { background: #64748b; }
</style>
</head>
<body>

<div class="receipt">

  <!-- HEADER -->
  <div class="header">
    <?php if (!empty($s['receipt_header_en'])): ?>
      <div class="name-en"><?= h($s['receipt_header_en']) ?></div>
    <?php endif; ?>
    <?php if (!empty($s['receipt_header_ar'])): ?>
      <div class="name-ar"><?= h($s['receipt_header_ar']) ?></div>
    <?php endif; ?>
    <?php if (!empty($s['receipt_address_en'])): ?>
      <div class="meta"><?= h($s['receipt_address_en']) ?></div>
    <?php endif; ?>
    <?php if (!empty($s['receipt_address_ar'])): ?>
      <div class="meta" style="direction:rtl"><?= h($s['receipt_address_ar']) ?></div>
    <?php endif; ?>
    <?php if (!empty($s['receipt_phone'])): ?>
      <div class="meta"><?= h($s['receipt_phone']) ?></div>
    <?php endif; ?>
  </div>

  <hr class="sep">

  <!-- ORDER META -->
  <div class="order-meta">
    <div class="row">
      <span class="label">Order #</span>
      <span class="b"><?= h($order['order_number']) ?></span>
    </div>
    <div class="row">
      <span class="label">Date</span>
      <span><?= h(date('Y-m-d H:i', strtotime($order['created_at']))) ?></span>
    </div>
  </div>

  <hr class="sep">

  <!-- ITEMS -->
  <div class="items">
    <?php foreach ($lines as $l):
      $extras = !empty($l['extras_json']) ? json_decode($l['extras_json'], true) : [];
      $hasAr  = !empty($l['name_ar_snapshot']);
      $sizeEn = $l['size_label'];
      $sizeAr = $l['size_label_ar'];
    ?>
      <div class="item">
        <div class="line1">
          <div class="name"><?= intval($l['quantity']) ?>× <?= h($l['name_snapshot']) ?></div>
          <div class="price"><?= money($l['subtotal'], $decimals) ?></div>
        </div>
        <?php if ($hasAr): ?>
          <div class="name-ar"><?= h($l['name_ar_snapshot']) ?></div>
        <?php endif; ?>
        <?php if ($sizeEn || $sizeAr): ?>
          <div class="sub"><?= h($sizeEn) ?><?= $sizeAr ? ' / ' . h($sizeAr) : '' ?></div>
        <?php endif; ?>
        <?php if (!empty($extras)): ?>
          <div class="sub">+ <?= h(implode(', ', array_column($extras, 'name'))) ?></div>
        <?php endif; ?>
      </div>
    <?php endforeach; ?>
  </div>

  <hr class="sep">

  <!-- TOTALS -->
  <div class="totals">
    <div class="row grand">
      <span>TOTAL</span>
      <span><?= h($currency) ?> <?= money($order['total'], $decimals) ?></span>
    </div>
  </div>

  <hr class="sep">

  <!-- CUSTOMER -->
  <div class="customer">
    <div class="row"><span class="b">Customer:</span> <?= h($order['customer_name']) ?></div>
    <div class="row"><span class="b">WhatsApp:</span> <?= h($order['customer_phone']) ?></div>
    <?php if (!empty($order['customer_notes'])): ?>
      <div class="notes"><span class="b">Notes:</span><br><?= h($order['customer_notes']) ?></div>
    <?php endif; ?>
  </div>

  <!-- PAYMENT — boxed so it stands out on the printed receipt.
       Staff handing over reads this first to know whether to
       collect cash, card, or nothing. -->
  <div class="payment-line <?= h($payment['class']) ?>"><?= h($payment['label']) ?></div>

  <hr class="sep">

  <!-- FOOTER -->
  <div class="footer">
    <?php if (!empty($s['receipt_footer_en'])): ?>
      <div><?= h($s['receipt_footer_en']) ?></div>
    <?php endif; ?>
    <?php if (!empty($s['receipt_footer_ar'])): ?>
      <div style="direction:rtl;margin-top:2px"><?= h($s['receipt_footer_ar']) ?></div>
    <?php endif; ?>
    <div style="margin-top:6px" class="small"><?= h($order['order_number']) ?></div>
  </div>

</div>

<div class="print-controls no-print">
  <button onclick="window.print()">🖨 Print again</button>
  <button class="secondary" onclick="window.close()">Close</button>
</div>

<script>
// Auto-trigger print on load. The browser shows its print dialog;
// staff picks the TM-T88VII and confirms. If you want silent
// printing (kiosk mode), add --kiosk-printing to Chrome's launch.
window.addEventListener('load', () => {
  // Small delay so fonts render and layout settles before print preview
  setTimeout(() => window.print(), 300);
});
</script>

</body>
</html>
