<?php
// ============================================================
//  MediCore — Print Invoice
//  File: sale/print.php
// ============================================================
require_once '../includes/db.php';
require_once '../includes/auth.php';
require_once '../includes/form_icons.php';
require_login();

$id = (int)($_GET['id'] ?? 0);
if (!$id) die('Invalid invoice ID');

$sale  = db_row("SELECT * FROM sales WHERE id = ?", [$id]);
$saleMode = $sale['sale_mode'] ?? 'retail';
$isWholesale = $saleMode === 'wholesale';
if (!$sale) die('Invoice not found');

$items = db_rows(
    "SELECT si.*, p.barcode, p.form, p.strength
       FROM sale_items si
  LEFT JOIN products p ON p.id = si.product_id
      WHERE si.sale_id = ?
      ORDER BY si.id",
    [$id]
);

$cfg = get_settings();
$cur = $cfg['currency'];

$due   = (float)$sale['due'];
$paid  = (float)$sale['paid'];
$total = (float)$sale['final_price'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Invoice — <?= htmlspecialchars($sale['invoice']) ?></title>
  <!-- @page size is rewritten by setPrintFormat() below to match the
       chosen format (A4 / 80mm thermal / 58mm thermal). -->
  <style id="page-size-style">@page { size: A4; margin: 10mm; }</style>
  <style>
    * { margin:0; padding:0; box-sizing:border-box; }
    body {
      font-family: 'Segoe UI', Arial, sans-serif;
      font-size: 12px; color: #111;
      background: #eef0f4;
      padding: 20px;
    }

    /* ── Top print bar ── */
    .print-bar {
      display:flex; gap:10px; margin-bottom:16px; flex-wrap:wrap;
      padding:10px 14px; background:#f0f4ff;
      border-radius:6px; align-items:center;
    }
    .print-bar button {
      padding:7px 18px; background:#2d3a8c; color:#fff;
      border:none; border-radius:5px; cursor:pointer;
      font-size:12px; font-weight:600;
    }
    .print-bar button.sec {
      background:#fff; color:#2d3a8c;
      border:1px solid #2d3a8c;
    }
    @media print { .print-bar { display:none; } }

    /* ── Format toggle ── */
    .fmt-group {
      display:flex; gap:3px; background:#e5e7eb;
      border-radius:6px; padding:3px;
    }
    .fmt-opt {
      padding:6px 12px !important; font-size:11.5px !important;
      background:transparent !important; color:#444 !important;
      border-radius:4px !important; font-weight:600 !important;
    }
    .fmt-opt.active {
      background:#2d3a8c !important; color:#fff !important;
    }
    .fmt-opt.sm { padding:5px 10px !important; font-size:11px !important; }

    /* ── A4 invoice wrapper ── */
    .invoice {
      display:none;
      max-width: 720px; margin: 0 auto;
      background:#fff;
      border: 1px solid #ddd; border-radius: 8px;
      overflow: hidden;
    }
    body.fmt-a4 .invoice { display:block; }

    /* ── Header ── */
    .inv-head {
      background: #2d3a8c; color: #fff;
      padding: 18px 22px;
      display: flex; justify-content: space-between; align-items: center;
    }
    .inv-head .shop-name { font-size: 18px; font-weight: 700; }
    .inv-head .shop-sub  { font-size: 11px; opacity: .8; margin-top: 3px; }
    .inv-head .inv-label {
      text-align:right;
    }
    .inv-head .inv-label .word {
      font-size: 11px; opacity: .7; letter-spacing: 2px;
      text-transform: uppercase;
    }
    .inv-head .inv-label .num  {
      font-size: 17px; font-weight: 700;
      font-family: 'Courier New', monospace;
    }

    /* ── Meta row ── */
    .inv-meta {
      display: grid; grid-template-columns: 1fr 1fr 1fr;
      gap: 0; border-bottom: 1px solid #e5e7eb;
    }
    .inv-meta .mc {
      padding: 10px 16px; border-right: 1px solid #e5e7eb;
    }
    .inv-meta .mc:last-child { border-right: none; }
    .inv-meta .ml { font-size: 10px; color: #888; margin-bottom: 2px; }
    .inv-meta .mv { font-weight: 600; }

    /* ── Items table ── */
    .inv-items { width:100%; border-collapse:collapse; }
    .inv-items thead tr {
      background:#f3f4fb; border-bottom:2px solid #d1d5db;
    }
    .inv-items th {
      padding:8px 10px; text-align:left; font-size:11px;
      font-weight:700; color:#2d3a8c; text-transform:uppercase;
      letter-spacing:.5px;
    }
    .inv-items td {
      padding:8px 10px; border-bottom:1px solid #f0f0f0;
      font-size:12px;
    }
    .inv-items tbody tr:last-child td { border-bottom:none; }
    .inv-items tbody tr:nth-child(even) { background:#fafbff; }
    .r  { text-align:right; }
    .c  { text-align:center; }
    .mono { font-family:'Courier New',monospace; }

    /* ── Totals ── */
    .inv-totals {
      display:grid; grid-template-columns:1fr 240px;
      border-top:2px solid #e5e7eb;
    }
    .inv-note {
      padding:14px 16px; font-size:11px; color:#666;
      border-right:1px solid #e5e7eb; align-self:end;
    }
    .totals-box { padding:12px 16px; }
    .t-row {
      display:flex; justify-content:space-between;
      padding:4px 0; font-size:12px;
    }
    .t-row.final {
      border-top:2px solid #2d3a8c; margin-top:6px;
      padding-top:8px; font-weight:700; font-size:14px;
      color:#2d3a8c;
    }
    .t-row.paid-row { color:#1a9e6e; }
    .t-row.due-row  { color:#dc2626; font-weight:700; }

    /* ── Footer ── */
    .inv-foot {
      background:#f9fafb; padding:10px 16px;
      border-top:1px solid #e5e7eb;
      display:flex; justify-content:space-between;
      align-items:center; font-size:10px; color:#999;
    }

    @media print {
      body { padding:8px; background:#fff; }
      .invoice { border:1px solid #ccc; }
    }

    /* ── Thermal receipt ── */
    .receipt {
      display:none;
      margin: 0 auto; background:#fff;
      font-family:'Courier New', monospace; color:#000;
      padding:8px 6px; box-shadow:0 0 10px rgba(0,0,0,.15);
    }
    body.fmt-thermal80 .receipt { display:block; width:80mm; font-size:11.5px; }
    body.fmt-thermal58 .receipt { display:block; width:58mm; font-size:10px; }
    @media print { .receipt { box-shadow:none; } }

    .receipt .rc-center { text-align:center; }
    .receipt .rc-bold   { font-weight:700; }
    .receipt .rc-lg      { font-size:1.15em; }
    .receipt .rc-sm      { font-size:.85em; color:#333; }
    .receipt .rc-dash {
      border-top:1px dashed #000; margin:5px 0;
    }
    .receipt .rc-row {
      display:flex; justify-content:space-between;
      gap:6px; padding:1px 0;
    }
    .receipt .rc-item { margin:3px 0; }
    .receipt .rc-item-name { font-weight:600; }
  </style>
</head>
<body>

<!-- Print controls (hidden on print) -->
<div class="print-bar">
  <div class="fmt-group">
    <button id="fmt-btn-a4" class="fmt-opt" onclick="setPrintFormat('a4')">📄 A4</button>
    <button id="fmt-btn-thermal" class="fmt-opt" onclick="setPrintFormat(lastThermalWidth)">🧾 Thermal</button>
  </div>
  <div id="thermal-width-group" class="fmt-group" style="display:none">
    <button id="fmt-btn-80" class="fmt-opt sm" onclick="setPrintFormat('thermal80')">80mm</button>
    <button id="fmt-btn-58" class="fmt-opt sm" onclick="setPrintFormat('thermal58')">58mm</button>
  </div>
  <button onclick="window.print()">🖨 Print Invoice</button>
  <button class="sec" onclick="window.close()">✕ Close</button>
  <span style="font-size:11px;color:#555">
    Invoice: <strong><?= htmlspecialchars($sale['invoice']) ?></strong>
  </span>
</div>

<!-- ════════════════════════════════════════════════
     A4 INVOICE
════════════════════════════════════════════════ -->
<div class="invoice">

  <!-- Header -->
  <div class="inv-head">
    <div>
      <div class="shop-name"><?= htmlspecialchars($cfg['shop_name']) ?></div>
      <div class="shop-sub"><?= htmlspecialchars($cfg['address']) ?></div>
      <?php if ($cfg['phone']): ?>
      <div class="shop-sub">📞 <?= htmlspecialchars($cfg['phone']) ?></div>
      <?php endif; ?>
      <?php if ($cfg['reg_no']): ?>
      <div class="shop-sub">Reg: <?= htmlspecialchars($cfg['reg_no']) ?></div>
      <?php endif; ?>
    </div>
    <div class="inv-label">
      <div class="word">Invoice</div>
      <div class="num"><?= htmlspecialchars($sale['invoice']) ?></div>
      <?php
        $stColor = $due <= 0 ? '#4ade80' : ($paid > 0 ? '#fbbf24' : '#f87171');
        $stLabel = $due <= 0 ? 'PAID'    : ($paid > 0 ? 'PARTIAL' : 'DUE');
      ?>
      <div style="display:flex;gap:5px;justify-content:flex-end;
                  margin-top:6px;flex-wrap:wrap">
        <div style="padding:3px 10px;background:<?= $isWholesale?'#d4f0e6':'#e8eaf6' ?>;
                    color:<?= $isWholesale?'#166534':'#1e40af' ?>;border-radius:4px;
                    font-size:10px;font-weight:700;letter-spacing:1px">
          <?= $isWholesale ? '📦 WHOLESALE' : '🏪 RETAIL' ?>
        </div>
        <div style="padding:3px 10px;background:<?= $stColor ?>;color:#111;
                    border-radius:4px;font-size:10px;font-weight:700;letter-spacing:1px">
          <?= $stLabel ?>
        </div>
      </div>
    </div>
  </div>

  <!-- Meta row -->
  <div class="inv-meta">
    <div class="mc">
      <div class="ml">Bill To</div>
      <div class="mv"><?= htmlspecialchars($sale['customer_name'] ?: 'Walk-in Customer') ?></div>
    </div>
    <div class="mc">
      <div class="ml">Invoice Date</div>
      <div class="mv"><?= htmlspecialchars($sale['date']) ?></div>
    </div>
    <div class="mc">
      <div class="ml">Payment Method</div>
      <div class="mv"><?= htmlspecialchars($sale['payment_type']) ?></div>
    </div>
  </div>

  <!-- Items -->
  <table class="inv-items">
    <thead>
      <tr>
        <th style="width:30px">#</th>
        <th>Medicine / Product</th>
        <th class="c">Qty</th>
        <th class="r">Unit Price</th>
        <th class="c">Disc%</th>
        <th class="r">Total</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($items as $i => $it):
        $lineTotal = (float)($it['after_disc'] ?: $it['total']);
      ?>
      <tr>
        <td style="color:#999"><?= $i + 1 ?></td>
        <td>
          <div style="font-weight:600"><?= form_icon_name($it['form'] ?? '', $it['product_name']) ?></div>
          <?php if ($it['strength'] || $it['form']): ?>
          <div style="font-size:10px;color:#888">
            <?= htmlspecialchars(trim($it['strength'].' '.$it['form'])) ?>
          </div>
          <?php endif; ?>
        </td>
        <td class="c mono"><?= $it['qty'] ?></td>
        <td class="r mono"><?= $cur . number_format($it['price'], 2) ?></td>
        <td class="c"
            style="<?= (float)$it['discount_pct']>0 ? ($isWholesale?'color:#166534;font-weight:700;background:#d4f0e6;border-radius:4px':'color:#dc2626') : '' ?>">
          <?= (float)$it['discount_pct'] > 0
              ? number_format($it['discount_pct'], 1) . '%' : '—' ?>
        </td>
        <td class="r mono" style="font-weight:600">
          <?= $cur . number_format($lineTotal, 2) ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>

  <!-- Totals + note -->
  <div class="inv-totals">
    <div class="inv-note">
      <?php if ($cfg['invoice_note']): ?>
        <?= htmlspecialchars($cfg['invoice_note']) ?>
      <?php endif; ?>
      <?php if ($sale['notes']): ?>
        <br><em><?= htmlspecialchars($sale['notes']) ?></em>
      <?php endif; ?>
    </div>
    <div class="totals-box">
      <div class="t-row">
        <span>Sub Total</span>
        <span class="mono"><?= $cur . number_format($sale['sub_total'], 2) ?></span>
      </div>
      <?php if ((float)$sale['discount_amt'] > 0): ?>
      <div class="t-row" style="color:#dc2626">
        <span>Discount (<?= number_format($sale['discount_pct'], 1) ?>%)</span>
        <span class="mono">- <?= $cur . number_format($sale['discount_amt'], 2) ?></span>
      </div>
      <?php endif; ?>
      <div class="t-row final">
        <span>Total Amount</span>
        <span class="mono"><?= $cur . number_format($total, 2) ?></span>
      </div>
      <div class="t-row paid-row">
        <span>Paid</span>
        <span class="mono"><?= $cur . number_format($paid, 2) ?></span>
      </div>
      <?php if ($due > 0): ?>
      <div class="t-row due-row">
        <span>Due</span>
        <span class="mono"><?= $cur . number_format($due, 2) ?></span>
      </div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Footer -->
  <div class="inv-foot">
    <span><?= htmlspecialchars($cfg['shop_name']) ?></span>
    <span>Printed: <?= date('d M Y, h:i A') ?></span>
    <span>MediCore PMS</span>
  </div>

</div>

<!-- ════════════════════════════════════════════════
     THERMAL RECEIPT (80mm / 58mm)
════════════════════════════════════════════════ -->
<div class="receipt">

  <div class="rc-center rc-bold rc-lg"><?= htmlspecialchars($cfg['shop_name']) ?></div>
  <?php if ($cfg['address']): ?>
  <div class="rc-center rc-sm"><?= htmlspecialchars($cfg['address']) ?></div>
  <?php endif; ?>
  <?php if ($cfg['phone']): ?>
  <div class="rc-center rc-sm">Tel: <?= htmlspecialchars($cfg['phone']) ?></div>
  <?php endif; ?>
  <?php if ($cfg['reg_no']): ?>
  <div class="rc-center rc-sm">Reg: <?= htmlspecialchars($cfg['reg_no']) ?></div>
  <?php endif; ?>

  <div class="rc-dash"></div>

  <div class="rc-row"><span>Invoice:</span><span class="rc-bold"><?= htmlspecialchars($sale['invoice']) ?></span></div>
  <div class="rc-row"><span>Date:</span><span><?= htmlspecialchars($sale['date']) ?></span></div>
  <div class="rc-row"><span>Customer:</span><span><?= htmlspecialchars($sale['customer_name'] ?: 'Walk-in') ?></span></div>
  <div class="rc-row"><span>Payment:</span><span><?= htmlspecialchars($sale['payment_type']) ?></span></div>
  <div class="rc-row"><span>Type:</span><span><?= $isWholesale ? 'Wholesale' : 'Retail' ?></span></div>

  <div class="rc-dash"></div>

  <?php foreach ($items as $it):
    $lineTotal = (float)($it['after_disc'] ?: $it['total']);
  ?>
  <div class="rc-item">
    <div class="rc-item-name">
      <?= form_icon_name($it['form'] ?? '', $it['product_name']) ?><?= $it['strength'] ? ' '.htmlspecialchars($it['strength']) : '' ?>
    </div>
    <div class="rc-row rc-sm">
      <span>
        <?= $it['qty'] ?> x <?= $cur.number_format($it['price'], 2) ?><?php
          if ((float)$it['discount_pct'] > 0) echo ' ('.number_format($it['discount_pct'],1).'% off)';
        ?>
      </span>
      <span class="rc-bold"><?= $cur . number_format($lineTotal, 2) ?></span>
    </div>
  </div>
  <?php endforeach; ?>

  <div class="rc-dash"></div>

  <div class="rc-row"><span>Sub Total</span><span><?= $cur . number_format($sale['sub_total'], 2) ?></span></div>
  <?php if ((float)$sale['discount_amt'] > 0): ?>
  <div class="rc-row"><span>Discount (<?= number_format($sale['discount_pct'], 1) ?>%)</span><span>-<?= $cur . number_format($sale['discount_amt'], 2) ?></span></div>
  <?php endif; ?>
  <div class="rc-row rc-bold rc-lg"><span>TOTAL</span><span><?= $cur . number_format($total, 2) ?></span></div>
  <div class="rc-row"><span>Paid</span><span><?= $cur . number_format($paid, 2) ?></span></div>
  <?php if ($due > 0): ?>
  <div class="rc-row rc-bold"><span>Due</span><span><?= $cur . number_format($due, 2) ?></span></div>
  <?php endif; ?>

  <div class="rc-dash"></div>

  <?php if ($cfg['invoice_note']): ?>
  <div class="rc-center rc-sm"><?= htmlspecialchars($cfg['invoice_note']) ?></div>
  <?php endif; ?>
  <?php if ($sale['notes']): ?>
  <div class="rc-center rc-sm"><em><?= htmlspecialchars($sale['notes']) ?></em></div>
  <?php endif; ?>
  <div class="rc-center rc-sm" style="margin-top:6px">Printed: <?= date('d M Y, h:i A') ?></div>
  <div class="rc-center rc-bold">*** Thank You ***</div>

</div>

<script>
const FMT_KEY = 'medicore_print_format';
const SERVER_DEFAULT_FORMAT = '<?= addslashes($cfg['print_format'] ?? 'a4') ?>';
let lastThermalWidth = 'thermal80';

function setPrintFormat(fmt) {
  if (fmt === 'thermal80' || fmt === 'thermal58') lastThermalWidth = fmt;
  localStorage.setItem(FMT_KEY, fmt);
  applyFormat(fmt);
}

function applyFormat(fmt) {
  document.body.className = 'fmt-' + fmt;
  const isThermal = fmt === 'thermal80' || fmt === 'thermal58';

  document.getElementById('thermal-width-group').style.display = isThermal ? 'flex' : 'none';
  document.getElementById('fmt-btn-a4').classList.toggle('active', fmt === 'a4');
  document.getElementById('fmt-btn-thermal').classList.toggle('active', isThermal);
  document.getElementById('fmt-btn-80').classList.toggle('active', fmt === 'thermal80');
  document.getElementById('fmt-btn-58').classList.toggle('active', fmt === 'thermal58');

  const pageSizes  = { a4: 'A4', thermal80: '80mm auto', thermal58: '58mm auto' };
  const pageMargin = { a4: '10mm', thermal80: '2mm', thermal58: '2mm' };
  document.getElementById('page-size-style').textContent =
    `@page { size: ${pageSizes[fmt]}; margin: ${pageMargin[fmt]}; }`;
}

document.addEventListener('DOMContentLoaded', () => {
  // Per-device localStorage choice wins if the browser has printed here
  // before; otherwise fall back to the shop-wide default from
  // Settings > Printer (print_format).
  let saved = localStorage.getItem(FMT_KEY) || SERVER_DEFAULT_FORMAT;
  if (!['a4','thermal80','thermal58'].includes(saved)) saved = 'a4';
  if (saved === 'thermal80' || saved === 'thermal58') lastThermalWidth = saved;
  applyFormat(saved);
});
</script>

</body>
</html>
