<?php
// public/qr_sheets.php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['admin', 'staff']);

$pdo = db();
$title = "QR Sheets - IMS";

/**
 * Settings (via URL params):
 * - product_id: choose a specific product (0 = all)
 * - copies: number of QR stickers per product page (default 12)
 * - cols: number of columns in the grid (default 3)
 * - only_active: 1=active only (default), 0=include inactive
 *
 * QR physical size:
 * - We print QR at ~2 inches using CSS: qr_print_in = 2 (default 2)
 * - We generate a higher-res QR image (qr_img_px = 600 by default) so it stays sharp.
 */
$product_id = (int)($_GET['product_id'] ?? 0);
$copies     = max(1, (int)($_GET['copies'] ?? 12));
$cols       = max(1, (int)($_GET['cols'] ?? 3));
$only_active = (int)($_GET['only_active'] ?? 1);

// Print size ~ 2 inches
$qr_print_in = (float)($_GET['qr_in'] ?? 2.0);     // printed size in inches
if ($qr_print_in < 1.0) $qr_print_in = 1.0;
if ($qr_print_in > 4.0) $qr_print_in = 4.0;

// Image resolution (bigger = sharper)
$qr_img_px = (int)($_GET['qr_px'] ?? 600);
if ($qr_img_px < 300) $qr_img_px = 300;
if ($qr_img_px > 1200) $qr_img_px = 1200;

$margin = max(0, (int)($_GET['margin'] ?? 1));

// Fetch products for dropdown (include supplier/category info for display)
$sqlList = "
  SELECT
    p.id, p.sku, p.name, p.is_active,
    s.name AS supplier_name,
    c.name AS category_name
  FROM products p
  LEFT JOIN suppliers s ON s.id = p.supplier_id
  LEFT JOIN product_categories c ON c.id = p.category_id
  WHERE 1=1
";
$paramsList = [];
if ($only_active === 1) {
  $sqlList .= " AND p.is_active = 1 ";
}
$sqlList .= " ORDER BY p.name ASC ";

$stmt = $pdo->prepare($sqlList);
$stmt->execute($paramsList);
$allProducts = $stmt->fetchAll();

// Which products to print?
$products = [];
if ($product_id > 0) {
  foreach ($allProducts as $ap) {
    if ((int)$ap['id'] === $product_id) {
      $products[] = $ap;
      break;
    }
  }
} else {
  $products = $allProducts; // all products
}

// Helper: QR URL (no JS; reliable)
function qr_url(string $data, int $px, int $margin): string {
    return "https://api.qrserver.com/v1/create-qr-code/?size={$px}x{$px}&margin={$margin}&data=" . urlencode($data);
}

?><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title><?= htmlspecialchars($title) ?></title>
  <style>
    body { font-family: Arial, sans-serif; margin: 18px; color: #111; }
    .topbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
    .filters { margin: 12px 0 16px; padding: 12px; border: 1px solid #ddd; border-radius: 10px; }
    .row { display: flex; flex-wrap: wrap; gap: 10px; }
    .row > div { flex: 1 1 260px; min-width: 260px; }
    select, input { width: 100%; padding: 9px; border: 1px solid #ccc; border-radius: 8px; }
    button { padding: 10px 14px; border: 1px solid #222; background: #222; color: #fff; border-radius: 8px; cursor: pointer; }
    button.secondary { background: #fff; color: #111; }
    .hint { font-size: 12px; color: #666; margin-top: 6px; }
    .count { font-size: 13px; color: #444; margin-top: 8px; }

    /* One product per page */
    .sheet {
      page-break-after: always;
      break-after: page;
      border: 1px dashed #bbb;
      padding: 12px;
      border-radius: 10px;
      margin-bottom: 18px;
    }
    .sheet:last-child { page-break-after: auto; break-after: auto; }

    .header {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      gap: 12px;
      margin-bottom: 10px;
    }
    .product-name { font-size: 18px; font-weight: 700; line-height: 1.2; }
    .product-sku { font-size: 13px; font-weight: 700; letter-spacing: 1px; margin-top: 4px; }
    .meta { font-size: 12px; color: #666; margin-top: 4px; }

    /* QR grid */
    .grid {
      display: grid;
      grid-template-columns: repeat(<?= (int)$cols ?>, 1fr);
      gap: 10px;
      margin-top: 10px;
    }

    .sticker {
      border: 1px solid #e1e1e1;
      border-radius: 10px;
      padding: 8px;
      text-align: center;
      overflow: hidden;
    }

    /* IMPORTANT: physical print size of QR */
    .sticker img {
      width: <?= htmlspecialchars((string)$qr_print_in) ?>in;
      height: <?= htmlspecialchars((string)$qr_print_in) ?>in;
      object-fit: contain;
      display: block;
      margin: 0 auto;
      border-radius: 6px;
    }

    .sticker .sku {
      font-size: 11px;
      font-weight: 700;
      margin-top: 6px;
      letter-spacing: 1px;
    }
    .sticker .name {
      font-size: 10px;
      color: #444;
      margin-top: 3px;
      line-height: 1.2;
      max-height: 2.4em;
      overflow: hidden;
    }
    .small-muted { font-size: 12px; color: #666; }

    @media print {
      body { margin: 0; }
      .filters, .topbar, .hint, .count { display: none; }
      .sheet { border: none; margin: 0; border-radius: 0; }
      .sticker { border: 1px solid #ddd; }
    }
  </style>
</head>
<body>

  <div class="topbar">
    <h2 style="margin:0;"><?= htmlspecialchars($title) ?></h2>
    <div>
      <button onclick="window.print()">Print / Save PDF</button>
    </div>
  </div>

  <div class="filters">
    <form method="GET">
      <div class="row">
        <div>
          <label><b>Select Product</b></label>
          <select name="product_id">
            <option value="0" <?= $product_id === 0 ? 'selected' : '' ?>>All Products (1 page per product)</option>
            <?php foreach ($allProducts as $p): ?>
              <?php
                $sid = (int)$p['id'];
                $supplier = trim((string)($p['supplier_name'] ?? ''));
                $category = trim((string)($p['category_name'] ?? ''));
                $label = trim((string)$p['name']) . " • " . trim((string)$p['sku']);
                if ($supplier !== '') $label .= " • " . $supplier;
                if ($category !== '') $label .= " • " . $category;
              ?>
              <option value="<?= $sid ?>" <?= $product_id === $sid ? 'selected' : '' ?>>
                <?= htmlspecialchars($label) ?>
              </option>
            <?php endforeach; ?>
          </select>
          <div class="hint">Tip: click the dropdown then type to jump quickly (e.g., type “PRD” or product name).</div>
        </div>

        <div>
          <label>Copies per product page</label>
          <input type="number" min="1" name="copies" value="<?= (int)$copies ?>">
        </div>

        <div>
          <label>Columns</label>
          <input type="number" min="1" name="cols" value="<?= (int)$cols ?>">
        </div>

        <div>
          <label>Only Active Products</label>
          <select name="only_active">
            <option value="1" <?= $only_active === 1 ? 'selected' : '' ?>>Yes</option>
            <option value="0" <?= $only_active === 0 ? 'selected' : '' ?>>No (include inactive)</option>
          </select>
        </div>

        <div>
          <label>QR print size (inches)</label>
          <input type="number" step="0.1" min="1" max="4" name="qr_in" value="<?= htmlspecialchars((string)$qr_print_in) ?>">
          <div class="hint">Set to 2.0 for ~2 inch QR sticker.</div>
        </div>

        <div>
          <label>QR image quality (px)</label>
          <input type="number" step="50" min="300" max="1200" name="qr_px" value="<?= (int)$qr_img_px ?>">
          <div class="hint">Higher px = sharper print. Default 600.</div>
        </div>
      </div>

      <div style="display:flex; gap:10px; margin-top: 12px;">
        <button type="submit">Generate</button>
        <button type="button" class="secondary" onclick="window.location='qr_sheets.php'">Reset</button>
      </div>

      <div class="count">
        Found: <b><?= count($products) ?></b> product(s).
        <?= ($product_id > 0) ? "Printing selected product only." : "Each product will print as <b>1 PDF page</b>." ?>
      </div>

      <div class="hint">
        To create the PDF: click <b>Print / Save PDF</b> → Destination: <b>Save as PDF</b>.
      </div>
    </form>
  </div>

  <?php if (!$products): ?>
    <p class="small-muted">No products found.</p>
  <?php else: ?>

    <?php foreach ($products as $p): ?>
      <?php
        $sku = (string)$p['sku'];
        $name = (string)$p['name'];
        $supplier = trim((string)($p['supplier_name'] ?? ''));
        $category = trim((string)($p['category_name'] ?? ''));
        $qr = qr_url($sku, $qr_img_px, $margin);
      ?>

      <section class="sheet">
        <div class="header">
          <div>
            <div class="product-name"><?= htmlspecialchars($name) ?></div>
            <div class="product-sku"><?= htmlspecialchars($sku) ?></div>
            <div class="meta">
              <?php if ($supplier !== ''): ?>Supplier: <?= htmlspecialchars($supplier) ?> • <?php endif; ?>
              <?php if ($category !== ''): ?>Category: <?= htmlspecialchars($category) ?> • <?php endif; ?>
              Copies: <?= (int)$copies ?> • Columns: <?= (int)$cols ?> • QR: <?= htmlspecialchars((string)$qr_print_in) ?>in
            </div>
          </div>
          <div class="small-muted" style="text-align:right;">
            IMS QR Sheet
          </div>
        </div>

        <div class="grid">
          <?php for ($i=0; $i<$copies; $i++): ?>
            <div class="sticker">
              <img src="<?= htmlspecialchars($qr) ?>" alt="QR <?= htmlspecialchars($sku) ?>">
              <div class="sku"><?= htmlspecialchars($sku) ?></div>
              <div class="name"><?= htmlspecialchars($name) ?></div>
            </div>
          <?php endfor; ?>
        </div>
      </section>
    <?php endforeach; ?>

  <?php endif; ?>

</body>
</html>
