<?php
// ============================================================
//  MediCore — Purchase Print
//  File: purchase/print.php
//  Format (A4 / Thermal 80mm / Thermal 58mm) is chosen via the
//  toggle in the print bar below — same mechanism and shared
//  localStorage preference as sale/print.php, falling back to
//  Settings > Printer's print_format on a device's first visit.
// ============================================================
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 purchase ID');

$po = db_row("SELECT * FROM purchases WHERE id = ?", [$id]);
if (!$po) die('Purchase order not found');

$items = db_rows(
    "SELECT pi.*, p.barcode, p.rack, p.form
       FROM purchase_items pi
  LEFT JOIN products p ON p.id = pi.product_id
      WHERE pi.purchase_id = ?
      ORDER BY pi.id",
    [$id]
);

$cfg  = get_settings();
$cur  = $cfg['currency'];
$paid = (float)$po['paid'];
$due  = (float)$po['due'];
$total= (float)$po['final_price'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>PO: <?= htmlspecialchars($po['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;
    }
    .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 16px;border:none;border-radius:5px;
      cursor:pointer;font-size:12px;font-weight:600;
    }
    .btn-blue  { background:#2d3a8c;color:#fff; }
    .btn-green { background:#166534;color:#fff; }
    .btn-grey  { 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 layout ─────────── */
    .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; }
    .inv-head {
      background:#2d3a8c;color:#fff;
      padding:16px 22px;
      display:flex;justify-content:space-between;align-items:center;
    }
    .inv-head .shop-name { font-size:17px;font-weight:700; }
    .inv-head .shop-sub  { font-size:11px;opacity:.8;margin-top:2px; }
    .inv-head .inv-right { text-align:right; }
    .inv-head .inv-type  { font-size:10px;opacity:.7;letter-spacing:2px;text-transform:uppercase; }
    .inv-head .inv-num   { font-size:16px;font-weight:700;font-family:'Courier New',monospace; }

    .inv-meta {
      display:grid;grid-template-columns:1fr 1fr 1fr;
      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; }

    .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:nth-child(even) { background:#fafbff; }
    .r  { text-align:right; }
    .c  { text-align:center; }
    .mono { font-family:'Courier New',monospace; }

    .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; }
    .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; }

    .inv-foot {
      background:#f9fafb;padding:10px 16px;border-top:1px solid #e5e7eb;
      display:flex;justify-content:space-between;font-size:10px;color:#999;
    }
    .status-badge {
      display:inline-block;padding:3px 10px;border-radius:4px;
      font-size:10px;font-weight:700;letter-spacing:1px;margin-top:6px;
    }

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

    /* ── Thermal receipt (80mm / 58mm) ── */
    .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 bar (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 class="btn-blue" onclick="window.print()">🖨 Print</button>
  <button class="btn-green" onclick="exportPDF()">📄 Save as PDF</button>
  <button class="btn-grey" onclick="window.close()">✕ Close</button>
  <span style="font-size:11px;color:#555;margin-left:4px">
    PO: <strong><?= htmlspecialchars($po['invoice']) ?></strong>
  </span>
</div>

<!-- ════════════════════════════════════════════════
     A4 PURCHASE ORDER
════════════════════════════════════════════════ -->
<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; ?>
    </div>
    <div class="inv-right">
      <div class="inv-type">Purchase Order</div>
      <div class="inv-num"><?= htmlspecialchars($po['invoice']) ?></div>
      <?php
        $stColor = $due <= 0 ? '#4ade80' : ($paid > 0 ? '#fbbf24' : '#f87171');
        $stLabel = $due <= 0 ? 'PAID'    : ($paid > 0 ? 'PARTIAL' : 'DUE');
      ?>
      <span class="status-badge"
            style="background:<?= $stColor ?>;color:#111">
        <?= $stLabel ?>
      </span>
    </div>
  </div>

  <!-- Meta -->
  <div class="inv-meta">
    <div class="mc">
      <div class="ml">Supplier</div>
      <div class="mv"><?= htmlspecialchars($po['supplier_name'] ?? '—') ?></div>
    </div>
    <div class="mc">
      <div class="ml">Purchase Date</div>
      <div class="mv"><?= htmlspecialchars($po['date']) ?></div>
    </div>
    <div class="mc">
      <div class="ml">Supplier Invoice #</div>
      <div class="mv"><?= htmlspecialchars($po['inv_no'] ?: '—') ?></div>
    </div>
  </div>

  <!-- Items -->
  <table class="inv-items">
    <thead>
      <tr>
        <th style="width:28px">#</th>
        <th>Product</th>
        <th class="c">Boxes</th>
        <th class="c">Qty/Box</th>
        <th class="c">Total Pcs</th>
        <th class="r">BTP</th>
        <th class="r">VAT</th>
        <th class="r">TP+VAT</th>
        <th class="r">MRP/pc</th>
        <th class="c">Free</th>
        <th class="c">Expiry</th>
        <th class="r">Total</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($items as $i => $it): ?>
      <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['rack']): ?>
          <div style="font-size:10px;color:#888">Rack: <?= htmlspecialchars($it['rack']) ?></div>
          <?php endif; ?>
        </td>
        <td class="c mono"><?= $it['boxes'] ?></td>
        <td class="c mono"><?= $it['qty_in_box'] ?></td>
        <td class="c mono" style="font-weight:700"><?= $it['qty_pcs'] ?></td>
        <td class="r mono"><?= $cur . number_format($it['btp'], 2) ?></td>
        <td class="r mono"><?= $cur . number_format($it['vat'], 2) ?></td>
        <td class="r mono" style="font-weight:700;color:#2d3a8c">
          <?= $cur . number_format($it['btp_vat'], 2) ?>
        </td>
        <td class="r mono"><?= $cur . number_format($it['sale_price'], 2) ?></td>
        <td class="c mono" style="color:#1a9e6e">
          <?= (int)$it['free'] > 0 ? '+'.$it['free'] : '—' ?>
        </td>
        <td class="c" style="color:#e07b00"><?= $it['exp'] ?: '—' ?></td>
        <td class="r mono" style="font-weight:700">
          <?= $cur . number_format($it['total_price'], 2) ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>

  <!-- Totals -->
  <div class="inv-totals">
    <div class="inv-note">
      <?= count($items) ?> item(s) purchased<br>
      Mode: <?= $po['mode'] === 'unit_trvat' ? 'Unit TP + VAT' : 'Net Value' ?>
      <?php if ($po['notes']): ?>
      <br><em><?= htmlspecialchars($po['notes']) ?></em>
      <?php endif; ?>
    </div>
    <div class="totals-box">
      <div class="t-row">
        <span>Total BTP</span>
        <span class="mono"><?= $cur . number_format($po['total_btp'] ?? 0, 2) ?></span>
      </div>
      <div class="t-row">
        <span>Total VAT</span>
        <span class="mono"><?= $cur . number_format($po['total_vat'] ?? 0, 2) ?></span>
      </div>
      <?php if ((float)($po['discount_pct'] ?? 0) > 0): ?>
      <div class="t-row" style="color:#dc2626">
        <span>Discount (<?= number_format($po['discount_pct'], 1) ?>%)</span>
        <span class="mono">
          - <?= $cur . number_format(
            (float)($po['total_btp'] + $po['total_vat']) * $po['discount_pct'] / 100, 2
          ) ?>
        </span>
      </div>
      <?php endif; ?>
      <div class="t-row final">
        <span>Grand Total</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><!-- /invoice -->

<!-- ════════════════════════════════════════════════
     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; ?>

  <div class="rc-dash"></div>
  <div class="rc-center rc-bold">PURCHASE ORDER</div>

  <div class="rc-row"><span>PO #:</span><span class="rc-bold"><?= htmlspecialchars($po['invoice']) ?></span></div>
  <div class="rc-row"><span>Date:</span><span><?= htmlspecialchars($po['date']) ?></span></div>
  <div class="rc-row"><span>Supplier:</span><span><?= htmlspecialchars($po['supplier_name'] ?? '—') ?></span></div>
  <?php if ($po['inv_no']): ?>
  <div class="rc-row"><span>Supplier Inv:</span><span><?= htmlspecialchars($po['inv_no']) ?></span></div>
  <?php endif; ?>

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

  <?php foreach ($items as $it): ?>
  <div class="rc-item">
    <div class="rc-item-name"><?= form_icon_name($it['form'] ?? '', $it['product_name']) ?></div>
    <div class="rc-row rc-sm">
      <span>
        <?= $it['boxes'] ?> box x <?= $it['qty_in_box'] ?> = <?= $it['qty_pcs'] ?> pcs
        @ <?= $cur . number_format($it['btp_vat'], 2) ?>
      </span>
      <span class="rc-bold"><?= $cur . number_format($it['total_price'], 2) ?></span>
    </div>
    <?php if ((int)$it['free'] > 0 || $it['exp']): ?>
    <div class="rc-row rc-sm">
      <span><?= (int)$it['free'] > 0 ? 'Free: +'.$it['free'] : '' ?></span>
      <span><?= $it['exp'] ? 'Exp: '.$it['exp'] : '' ?></span>
    </div>
    <?php endif; ?>
  </div>
  <?php endforeach; ?>

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

  <div class="rc-row"><span>Total BTP</span><span><?= $cur . number_format($po['total_btp'] ?? 0, 2) ?></span></div>
  <div class="rc-row"><span>Total VAT</span><span><?= $cur . number_format($po['total_vat'] ?? 0, 2) ?></span></div>
  <?php if ((float)($po['discount_pct'] ?? 0) > 0): ?>
  <div class="rc-row">
    <span>Discount (<?= number_format($po['discount_pct'], 1) ?>%)</span>
    <span>
      -<?= $cur . number_format(
        (float)($po['total_btp'] + $po['total_vat']) * $po['discount_pct'] / 100, 2
      ) ?>
    </span>
  </div>
  <?php endif; ?>
  <div class="rc-row rc-bold rc-lg"><span>GRAND 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>

  <div class="rc-center rc-sm"><?= count($items) ?> item(s) · Mode: <?= $po['mode'] === 'unit_trvat' ? 'Unit TP+VAT' : 'Net Value' ?></div>
  <?php if ($po['notes']): ?>
  <div class="rc-center rc-sm"><em><?= htmlspecialchars($po['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">*** Internal Copy ***</div>

</div>

<script>
const FMT_KEY = 'medicore_print_format_purchase';
const SERVER_DEFAULT_FORMAT = '<?= addslashes($cfg['purchase_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]}; }`;
}

function exportPDF() {
  // Use browser's built-in PDF save
  window.print();
}

document.addEventListener('DOMContentLoaded', () => {
  // Same shared preference as sale/print.php: per-device localStorage
  // choice wins if this browser has printed before; otherwise fall
  // back to the shop-wide default from Settings > Printer.
  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);

  // Auto print if ?autoprint=1
  if (new URLSearchParams(window.location.search).get('autoprint') === '1') {
    setTimeout(window.print, 400);
  }
});
</script>

</body>
</html>
