<?php
// ============================================================
//  MediCore — Create Requisition (Manual)
//  File: product/requisition.php
// ============================================================
$page  = 'product/requisition';
$title = 'Create Requisition';
require_once '../includes/header.php';
$today = date('Y-m-d');
require_once '../includes/requisition-tabs.php';

$cfg      = $settings;
$cur      = $cfg['currency'];
$reqPrefix= $cfg['req_prefix'] ?? 'REQ';
$today    = today();
$nextREQ  = next_ref($reqPrefix, 'requisitions', 'ref');

ensure_soft_delete('products');

// Load suppliers for right panel
$suppliers = db_rows("SELECT id, name, phone FROM suppliers ORDER BY name");

// ── Default product list ────────────────────────────────────────
// Manual Requisition is deliberately NOT restricted to low-stock items
// the way Smart Requisition is — that filtering already lives on the
// Smart Requisition tab, and "manual" means you can pick anything.
// The full catalog (33,000+ rows on a real pharmacy install) is served
// through the paginated api/requisitions.php "browse" action — the same
// pattern used on Product List — so the page never has to render every
// row at once; the search box above still reaches any product on demand.
$pageSize = 50;
$totalProductCount = (int) db_val(
    "SELECT COUNT(*) FROM products WHERE is_active = 1 AND is_deleted = 0"
);
$totalPages = (int) max(1, ceil($totalProductCount / $pageSize));
// Photo columns dropped — this page never renders product photos, so
// there's no reason to ship them (image can be up to ~700KB/row).
$prodCols = products_columns_except(['image', 'image_thumb']);
$products = db_rows(
    "SELECT $prodCols,
            g.name  AS generic_name,
            c.name  AS company_name,
            (SELECT s.name FROM purchases po
               JOIN purchase_items pi2 ON pi2.purchase_id = po.id
               JOIN suppliers s ON s.id = po.supplier_id
              WHERE pi2.product_id = p.id
              ORDER BY po.date DESC LIMIT 1) AS last_supplier,
            (SELECT po.supplier_id FROM purchases po
               JOIN purchase_items pi2 ON pi2.purchase_id = po.id
              WHERE pi2.product_id = p.id
              ORDER BY po.date DESC LIMIT 1) AS last_supplier_id,
            COALESCE((SELECT SUM(si.qty)/3 FROM sale_items si
               JOIN sales s2 ON s2.id = si.sale_id
              WHERE si.product_id = p.id
                AND s2.date >= DATE_SUB(NOW(), INTERVAL 90 DAY)),0) AS avg_monthly,
            COALESCE((SELECT SUM(ri.qty_box * p.qty_in_box)
               FROM requisition_items ri
               JOIN requisitions r ON r.id = ri.requisition_id
              WHERE ri.product_id = p.id
                AND r.status IN ('active','ordered')),0) AS pending_qty
       FROM products p
  LEFT JOIN generics  g ON g.id = p.generic_id
  LEFT JOIN companies c ON c.id = p.company_id
      WHERE p.is_active = 1
        AND p.is_deleted = 0
      ORDER BY p.name ASC
      LIMIT $pageSize"
);

// ── Post-process: days-of-stock-remaining + minimal suggested boxes ──
foreach ($products as &$p) {
    $stock   = (int)$p['stock_pcs'];
    $alert   = (int)$p['low_stock_alert'];
    $avg     = (float)$p['avg_monthly'];
    $pending = (int)$p['pending_qty'];
    $minQty  = (int)$p['min_qty'];
    $qib     = max(1, (int)$p['qty_in_box']);

    $avgDaily = $avg > 0 ? $avg / 30 : 0;
    $p['days_remaining'] = $avgDaily > 0 ? round($stock / $avgDaily, 1) : null;

    $sugPcsRaw = max($alert * 2, (int)ceil($avg * 1.5)) - $stock - $pending;
    $sugPcs    = max(0, $sugPcsRaw);
    if ($sugPcs > 0 && $minQty > 0) $sugPcs = max($sugPcs, $minQty);
    $p['sug_boxes']     = $sugPcs > 0 ? max(1, (int)ceil($sugPcs / $qib)) : 0;
    $p['covered_by_po'] = $sugPcsRaw <= 0 && $pending > 0;
}
unset($p);

$rangeStart = $totalProductCount ? 1 : 0;
$rangeEnd   = count($products);
?>

<!-- ── Page hints ─────────────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML = `
  <div style="position:relative">
    <input type="text" id="prod-search" placeholder="🔍  Search full catalog to add a product…"
      style="padding:5px 10px;border:1px solid var(--border);
             border-radius:var(--rsm);font-family:inherit;
             font-size:12px;width:260px;outline:none"
      autocomplete="off">
    <div id="search-dd" style="display:none;position:absolute;top:100%;left:0;right:0;
         background:var(--surface);border:1px solid var(--border);border-top:none;
         border-radius:0 0 var(--rsm) var(--rsm);box-shadow:var(--shmd);
         z-index:300;max-height:320px;overflow-y:auto"></div>
  </div>
  <select id="filter-stock" onchange="filterProducts(document.getElementById('prod-search').value)"
    style="padding:5px 9px;border:1px solid var(--border);border-radius:var(--rsm);
           font-family:inherit;font-size:12px;outline:none">
    <option value="all">Loaded List</option>
    <option value="out">Out of Stock Only</option>
  </select>`;
</script>

<!-- ── Two-column layout ──────────────────────────── -->
<div style="display:grid;grid-template-columns:1fr 300px;
            gap:12px;align-items:start">

  <!-- ════ LEFT — Product list ════════════════════ -->
  <div class="card" style="padding:0">
    <div class="ch" style="padding:10px 14px">
      <div class="ct">📋 Products</div>
      <div style="display:flex;gap:8px;align-items:center">
        <span id="sel-count"
              style="font-size:11px;color:var(--text3)">0 selected</span>
        <button class="btn btn-sm"
                onclick="selectAll()"
                style="font-size:11px">✓ All</button>
        <button class="btn btn-sm"
                onclick="clearAll()"
                style="font-size:11px">✕ Clear</button>
      </div>
    </div>
    <div id="showing-text" style="padding:0 14px 8px;font-size:11px;color:var(--text3)">
      Showing <?= $rangeStart ?>–<?= $rangeEnd ?> of <?= number_format($totalProductCount) ?> product(s), alphabetically.
      Use the search box above to jump straight to any other product.
    </div>

    <div class="tw" style="max-height:calc(100vh - 280px);overflow-y:auto">
      <table id="prod-table">
        <thead>
          <tr>
            <th style="width:36px;text-align:center">
              <input type="checkbox" id="chk-all"
                     onchange="toggleAll(this.checked)"
                     title="Select all visible">
            </th>
            <th>Product</th>
            <th style="text-align:center;width:70px">Stock</th>
            <th style="text-align:center;width:60px">Alert</th>
            <th style="text-align:center;width:60px" title="Days of stock remaining at current sales pace">Days Left</th>
            <th style="text-align:center;width:70px">Pending</th>
            <th style="text-align:right;width:90px">TP+VAT</th>
            <th>Last Supplier</th>
            <th style="text-align:center;width:80px">Boxes</th>
          </tr>
        </thead>
        <tbody id="prod-body">
          <?php if (!$products): ?>
          <tr><td colspan="9" class="empty-state">
            No active products found. Use the search box above to look one up.
          </td></tr>
          <?php endif; ?>
          <?php foreach ($products as $p):
            $stock    = (int)$p['stock_pcs'];
            $alert    = (int)$p['low_stock_alert'];
            $hasPrice = (float)$p['btp_vat'] > 0;
            $daysLeft = $p['days_remaining'];
            $sugBoxes = (int)$p['sug_boxes'];
            $covered  = $p['covered_by_po'];
            $pending  = (int)$p['pending_qty'];
            $rowCl    = $stock <= 0 ? 'row-out' : 'row-low';
            $sBg      = $stock <= 0 ? '#fde8e8' : '#fff3dc';
            $sCl      = $stock <= 0 ? 'var(--danger)' : 'var(--warn)';
          ?>
          <tr class="prod-row <?= $rowCl ?>"
              data-id="<?= $p['id'] ?>"
              data-name="<?= htmlspecialchars($p['name']) ?>"
              data-stock="<?= $stock ?>"
              data-price="<?= $p['btp_vat'] ?>"
              data-supplier-id="<?= $p['last_supplier_id'] ?>"
              data-supplier="<?= htmlspecialchars($p['last_supplier'] ?? '') ?>"
              data-has-price="<?= $hasPrice ? '1' : '0' ?>"
              data-suggested="<?= $sugBoxes ?>">
            <td style="text-align:center">
              <input type="checkbox" class="row-chk"
                     data-id="<?= $p['id'] ?>"
                     onchange="onCheck(this)">
            </td>
            <td>
              <div style="font-weight:600;font-size:12px">
                <?= form_icon_name($p['form'] ?? '', $p['name']) ?>
              </div>
              <div style="font-size:10px;color:var(--text3)">
                <?= htmlspecialchars($p['strength'] ?? '') ?>
                <?= $p['company_name'] ? ' · ' . htmlspecialchars($p['company_name']) : '' ?>
                <?= $p['rack'] ? ' · Rack: ' . htmlspecialchars($p['rack']) : '' ?>
              </div>
              <?php if (!$hasPrice): ?>
              <div style="font-size:10px;color:var(--warn);font-weight:600">
                ⚠ No TP+VAT price set
              </div>
              <?php endif; ?>
              <?php if ($covered): ?>
              <div style="font-size:10px;color:var(--accent);font-weight:600">
                ✓ covered by pending PO
              </div>
              <?php endif; ?>
            </td>
            <td style="text-align:center">
              <span class="badge"
                    style="background:<?= $sBg ?>;color:<?= $sCl ?>">
                <?= $stock ?>
              </span>
            </td>
            <td style="text-align:center;color:var(--text2);font-size:11.5px">
              <?= $alert ?>
            </td>
            <td style="text-align:center">
              <?php if ($daysLeft === null): ?>
                <span style="color:var(--text3);font-size:11px">—</span>
              <?php else: ?>
                <span style="font-weight:700;font-size:11px;color:<?= $daysLeft <= 3 ? 'var(--danger)' : ($daysLeft <= 7 ? '#ea580c' : 'var(--text2)') ?>">
                  <?= number_format($daysLeft, 1) ?>d
                </span>
              <?php endif; ?>
            </td>
            <td style="text-align:center">
              <?= $pending > 0
                ? "<span class='badge' style='background:#e8eaf6;color:var(--brand);font-size:10.5px'>$pending pcs</span>"
                : '<span style="color:var(--text3);font-size:11px">—</span>' ?>
            </td>
            <td class="mono" style="text-align:right;font-size:11.5px">
              <?= (float)$p['btp_vat'] > 0
                ? $cur . number_format($p['btp_vat'], 2)
                : '<span style="color:var(--text3)">—</span>' ?>
            </td>
            <td style="font-size:11px;color:var(--text2)">
              <?= htmlspecialchars($p['last_supplier'] ?? '—') ?>
            </td>
            <td style="text-align:center">
              <input type="number"
                     class="box-qty"
                     data-id="<?= $p['id'] ?>"
                     value="<?= max(1, $sugBoxes) ?>" min="0"
                     style="width:60px;text-align:center;
                            display:none"
                     oninput="onQtyChange(<?= $p['id'] ?>)">
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <!-- ── Pagination bar ──────────────────────────── -->
    <div id="pager" style="display:flex;align-items:center;justify-content:space-between;
                padding:10px 14px;border-top:1px solid var(--border);
                font-size:11.5px;color:var(--text3);flex-wrap:wrap;gap:8px">
      <span id="pager-info">Page 1 of <?= $totalPages ?></span>
      <div style="display:flex;align-items:center;gap:10px">
        <div style="display:flex;align-items:center;gap:5px">
          <span>Show</span>
          <select id="pg-size" onchange="changePageSize(this.value)"
                  style="padding:3px 6px;border:1px solid var(--border);border-radius:var(--rsm);
                         font-family:inherit;font-size:11px;outline:none">
            <?php foreach ([10,20,50,100,200] as $n): ?>
            <option value="<?= $n ?>" <?= $n === $pageSize ? 'selected' : '' ?>><?= $n ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div style="display:flex;gap:6px">
          <button type="button" class="btn btn-sm" id="pg-first"
                  onclick="goToPage(1)" <?= $totalPages <= 1 ? 'disabled' : '' ?>>« First</button>
          <button type="button" class="btn btn-sm" id="pg-prev"
                  onclick="goToPage(curPage-1)" <?= $totalPages <= 1 ? 'disabled' : '' ?>>‹ Prev</button>
          <button type="button" class="btn btn-sm" id="pg-next"
                  onclick="goToPage(curPage+1)" <?= $totalPages <= 1 ? 'disabled' : '' ?>>Next ›</button>
          <button type="button" class="btn btn-sm" id="pg-last"
                  onclick="goToPage(totalPages)" <?= $totalPages <= 1 ? 'disabled' : '' ?>>Last »</button>
        </div>
      </div>
    </div>
  </div><!-- /left -->

  <!-- ════ RIGHT — Summary + Save ════════════════ -->
  <div style="display:flex;flex-direction:column;gap:10px;
              position:sticky;top:12px">

    <!-- Supplier selector -->
    <div class="card">
      <div class="ch"><div class="ct">🏢 Supplier</div></div>
      <div style="padding-top:4px;display:flex;flex-direction:column;gap:8px">
        <div class="fg">
          <select id="req-supplier" onchange="onSupplierChange()"
                  style="width:100%">
            <option value="">— Select Supplier —</option>
            <?php foreach ($suppliers as $s): ?>
            <option value="<?= $s['id'] ?>"
                    data-phone="<?= htmlspecialchars($s['phone']) ?>">
              <?= htmlspecialchars($s['name']) ?>
            </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div id="sup-info"
             style="display:none;font-size:11px;color:var(--text2);
                    background:var(--brand-xlight);padding:7px 10px;
                    border-radius:var(--rsm)">
          <span id="sup-phone"></span>
        </div>
      </div>
    </div>

    <!-- Requisition details -->
    <div class="card">
      <div class="ch"><div class="ct">🧾 Details</div></div>
      <div style="padding-top:4px;display:flex;flex-direction:column;gap:8px">
        <div class="fg">
          <label>REQ Number</label>
          <input id="req-no" value="<?= htmlspecialchars($nextREQ) ?>"
                 style="font-family:'JetBrains Mono',monospace;
                        font-weight:700;background:var(--surface2)">
        </div>
        <div class="fg">
          <label>Date</label>
          <input id="req-date" type="date" value="<?= $today ?>">
        </div>
        <div class="fg">
          <label>Notes</label>
          <textarea id="req-notes" rows="2"
            style="padding:6px 9px;border:1px solid var(--border);
                   border-radius:var(--rsm);font-family:inherit;
                   font-size:11.5px;resize:vertical;outline:none;
                   background:var(--surface);color:var(--text)"
            placeholder="Optional notes…"></textarea>
        </div>
      </div>
    </div>

    <!-- Selected items summary -->
    <div class="card"
         style="background:var(--brand-xlight);
                border:1px solid var(--brand-light)">
      <div class="ch">
        <div class="ct" style="color:var(--brand)">📊 Summary</div>
      </div>
      <div id="summary-list"
           style="font-size:11.5px;max-height:200px;
                  overflow-y:auto;margin-bottom:8px">
        <div class="empty-state" style="padding:12px 0;font-size:11px">
          Select products from the list
        </div>
      </div>
      <div style="border-top:1px solid var(--brand-light);
                  padding-top:8px;display:flex;
                  justify-content:space-between;font-size:13px">
        <span style="color:var(--brand);font-weight:600">
          Total (<span id="tot-items">0</span> items)
        </span>
        <span class="mono" id="tot-amount"
              style="font-weight:800;color:var(--brand)">
          <?= $cur ?>0.00
        </span>
      </div>
    </div>

    <!-- Warnings -->
    <div id="warn-box" style="display:none">
      <div class="al al-w">
        <strong>⚠ Price warnings:</strong>
        <div id="warn-list"
             style="font-size:11px;margin-top:4px;
                    line-height:1.7"></div>
      </div>
    </div>

    <!-- Save button -->
    <button id="save-btn" onclick="saveReq()"
            class="btn btn-primary"
            style="width:100%;padding:11px;font-size:14px;font-weight:700">
      📝 Create Requisition
    </button>

    <div id="save-err"
         style="display:none;background:#fde8e8;
                border:1px solid #f5a0a0;color:var(--danger);
                padding:8px 12px;border-radius:var(--rsm);
                font-size:12px"></div>

  </div><!-- /right -->
</div><!-- /grid -->

<!-- ── Search dropdown styles ─────────────────────── -->
<style>
.search-row {
  display:grid;
  grid-template-columns:1fr auto auto;
  gap:8px;align-items:center;
  padding:9px 12px;font-size:12px;cursor:pointer;
  border-bottom:1px solid var(--border);transition:background .1s;
}
.search-row:last-child { border-bottom:none; }
.search-row:hover      { background:var(--brand-xlight); }
.search-row.already-in { opacity:.6; }
.search-badge {
  font-size:10px;padding:2px 7px;border-radius:10px;white-space:nowrap;
}
#pg-first:disabled, #pg-prev:disabled, #pg-next:disabled, #pg-last:disabled {
  opacity:.45;cursor:not-allowed;
}
</style>

<script>
const CUR       = '<?= addslashes($cur) ?>';
const API       = '../api/requisitions.php';
const PROD_API  = '../api/products.php';
const TOTAL_COUNT = <?= (int)$totalProductCount ?>;
let curPageSize = <?= (int)$pageSize ?>;
let curPage    = 1;
let totalPages = <?= (int)$totalPages ?>;
let selected   = {};

function onCheck(chk) {
  const row = chk.closest('tr');
  const id  = parseInt(chk.dataset.id);
  const qtyInput = row.querySelector('.box-qty');

  if (chk.checked) {
    qtyInput.style.display = 'inline-block';
    if (!row.dataset.touched) {
      const sug = parseInt(row.dataset.suggested);
      if (!Number.isNaN(sug)) qtyInput.value = sug;
    }
    selected[id] = {
      name:     row.dataset.name,
      form:     row.dataset.form,
      qty:      parseInt(qtyInput.value) || 0,
      price:    parseFloat(row.dataset.price) || 0,
      hasPrice: row.dataset.hasPrice === '1',
      suppId:   row.dataset.supplierId,
      suppName: row.dataset.supplier,
    };
    const suppSel = document.getElementById('req-supplier');
    if (!suppSel.value && row.dataset.supplierId) {
      suppSel.value = row.dataset.supplierId;
      onSupplierChange();
    }
  } else {
    qtyInput.style.display = 'none';
    delete selected[id];
  }
  updateSummary();
}

function onQtyChange(id) {
  row_touch(id);
  if (selected[id]) {
    const inp = document.querySelector(`.box-qty[data-id="${id}"]`);
    selected[id].qty = Math.max(0, parseInt(inp?.value) || 0);
    updateSummary();
  }
}
function row_touch(id) {
  const row = document.querySelector(`tr[data-id="${id}"]`);
  if (row) row.dataset.touched = '1';
}

function toggleAll(checked) {
  document.querySelectorAll('.prod-row:not([style*="display:none"]) .row-chk')
    .forEach(chk => {
      if (chk.checked !== checked) {
        chk.checked = checked;
        onCheck(chk);
      }
    });
}

function selectAll() {
  document.getElementById('chk-all').checked = true;
  toggleAll(true);
}
function clearAll() {
  document.getElementById('chk-all').checked = false;
  toggleAll(false);
}

function updateSummary() {
  const ids     = Object.keys(selected);
  const listEl  = document.getElementById('summary-list');
  const totAmt  = document.getElementById('tot-amount');
  const totItms = document.getElementById('tot-items');
  const selCnt  = document.getElementById('sel-count');
  const warnBox = document.getElementById('warn-box');
  const warnList= document.getElementById('warn-list');

  selCnt.textContent = `${ids.length} selected`;
  totItms.textContent = ids.length;

  if (!ids.length) {
    listEl.innerHTML =
      '<div class="empty-state" style="padding:12px 0;font-size:11px">' +
      'Select products from the list</div>';
    totAmt.textContent  = CUR + '0.00';
    warnBox.style.display = 'none';
    return;
  }

  let total = 0;
  const warnings = [];

  listEl.innerHTML = ids.map(id => {
    const it      = selected[id];
    const lineAmt = it.qty * it.price;
    total += lineAmt;
    if (!it.hasPrice) warnings.push(it.name);
    return `<div style="display:flex;justify-content:space-between;
                        padding:4px 0;border-bottom:1px solid var(--brand-light)">
      <div>
        <div style="font-weight:600;font-size:11.5px">${formIconName(it.form, it.name)}</div>
        <div style="font-size:10px;color:var(--text3)">${it.qty} box(es)</div>
      </div>
      <div class="mono" style="font-weight:700;color:var(--brand);
                                white-space:nowrap;margin-left:8px">
        ${it.price > 0 ? CUR + lineAmt.toFixed(2) : '?'}
      </div>
    </div>`;
  }).join('');

  totAmt.textContent = CUR + total.toFixed(2);

  if (warnings.length) {
    warnList.innerHTML = warnings.map(n =>
      `• ${esc(n)} — no TP+VAT set`).join('<br>');
    warnBox.style.display = 'block';
  } else {
    warnBox.style.display = 'none';
  }
}

function filterProducts(q) {
  const stockFilter = document.getElementById('filter-stock').value;
  q = (q || '').toLowerCase();

  document.querySelectorAll('.prod-row').forEach(row => {
    const name  = row.dataset.name.toLowerCase();
    const stock = parseInt(row.dataset.stock);

    const matchQ = !q || name.includes(q);
    const matchS = stockFilter === 'all' || (stockFilter === 'out' && stock <= 0);

    row.style.display = matchQ && matchS ? '' : 'none';
  });
}

// ── Pagination ─────────────────────────────────────────────────
function buildRowHtml(p) {
  const stock    = parseInt(p.stock_pcs) || 0;
  const alert    = parseInt(p.low_stock_alert) || 0;
  const hasPrice = parseFloat(p.btp_vat || 0) > 0;
  const daysLeft = p.days_remaining;
  const sugBoxes = parseInt(p.sug_boxes) || 0;
  const covered  = !!p.covered_by_po;
  const pending  = parseInt(p.pending_qty) || 0;
  const rowCl    = stock <= 0 ? 'row-out' : 'row-low';
  const sBg      = stock <= 0 ? '#fde8e8' : '#fff3dc';
  const sCl      = stock <= 0 ? 'var(--danger)' : 'var(--warn)';

  const sel        = selected[p.id];
  const isChecked  = !!sel;
  const qtyVal     = sel ? sel.qty : Math.max(1, sugBoxes);

  const daysHtml = (daysLeft === null || daysLeft === undefined)
    ? `<span style="color:var(--text3);font-size:11px">—</span>`
    : `<span style="font-weight:700;font-size:11px;color:${daysLeft <= 3 ? 'var(--danger)' : (daysLeft <= 7 ? '#ea580c' : 'var(--text2)')}">${Number(daysLeft).toFixed(1)}d</span>`;

  const pendingHtml = pending > 0
    ? `<span class="badge" style="background:#e8eaf6;color:var(--brand);font-size:10.5px">${pending} pcs</span>`
    : '<span style="color:var(--text3);font-size:11px">—</span>';

  const priceHtml = parseFloat(p.btp_vat) > 0
    ? CUR + parseFloat(p.btp_vat).toFixed(2)
    : '<span style="color:var(--text3)">—</span>';

  return `<tr class="prod-row ${rowCl}"
      data-id="${p.id}"
      data-name="${esc(p.name)}"
      data-form="${esc(p.form || '')}"
      data-stock="${stock}"
      data-price="${p.btp_vat || 0}"
      data-supplier-id="${p.last_supplier_id || ''}"
      data-supplier="${esc(p.last_supplier || '')}"
      data-has-price="${hasPrice ? '1' : '0'}"
      data-suggested="${sugBoxes}">
    <td style="text-align:center">
      <input type="checkbox" class="row-chk" data-id="${p.id}" onchange="onCheck(this)" ${isChecked ? 'checked' : ''}>
    </td>
    <td>
      <div style="font-weight:600;font-size:12px">${formIconName(p.form, p.name)}</div>
      <div style="font-size:10px;color:var(--text3)">
        ${esc(p.strength||'')}${p.company_name ? ' · ' + esc(p.company_name) : ''}
        ${p.rack ? ' · Rack: ' + esc(p.rack) : ''}
      </div>
      ${!hasPrice ? `<div style="font-size:10px;color:var(--warn);font-weight:600">⚠ No TP+VAT price set</div>` : ''}
      ${covered ? `<div style="font-size:10px;color:var(--accent);font-weight:600">✓ covered by pending PO</div>` : ''}
    </td>
    <td style="text-align:center">
      <span class="badge" style="background:${sBg};color:${sCl}">${stock}</span>
    </td>
    <td style="text-align:center;color:var(--text2);font-size:11.5px">${alert}</td>
    <td style="text-align:center">${daysHtml}</td>
    <td style="text-align:center">${pendingHtml}</td>
    <td class="mono" style="text-align:right;font-size:11.5px">${priceHtml}</td>
    <td style="font-size:11px;color:var(--text2)">${esc(p.last_supplier || '—')}</td>
    <td style="text-align:center">
      <input type="number" class="box-qty" data-id="${p.id}" value="${qtyVal}" min="0"
             style="width:60px;text-align:center;display:${isChecked ? 'inline-block' : 'none'}"
             oninput="onQtyChange(${p.id})">
    </td>
  </tr>`;
}

function renderMainRows(rows) {
  const tbody = document.getElementById('prod-body');
  if (!rows || !rows.length) {
    tbody.innerHTML = `<tr><td colspan="9" class="empty-state">No products found.</td></tr>`;
    return;
  }
  tbody.innerHTML = rows.map(buildRowHtml).join('');
}

function updatePagerUI() {
  document.getElementById('pager-info').textContent = `Page ${curPage} of ${totalPages}`;
  document.getElementById('pg-first').disabled = curPage <= 1;
  document.getElementById('pg-prev').disabled  = curPage <= 1;
  document.getElementById('pg-next').disabled  = curPage >= totalPages;
  document.getElementById('pg-last').disabled  = curPage >= totalPages;

  const start = TOTAL_COUNT === 0 ? 0 : (curPage - 1) * curPageSize + 1;
  const end   = Math.min(curPage * curPageSize, TOTAL_COUNT);
  document.getElementById('showing-text').textContent =
    `Showing ${start}–${end} of ${TOTAL_COUNT.toLocaleString()} product(s), alphabetically. ` +
    `Use the search box above to jump straight to any other product.`;
}

async function goToPage(targetPage) {
  targetPage = Math.max(1, Math.min(totalPages, targetPage));
  const r = await apiPost(API, { action: 'browse', page: targetPage, page_size: curPageSize }).catch(() => null);
  if (!r || !r.success) return;

  curPage    = r.page;
  totalPages = r.total_pages;
  renderMainRows(r.data);
  updatePagerUI();

  const chkAll = document.getElementById('chk-all');
  if (chkAll) chkAll.checked = false;

  document.getElementById('prod-table').closest('.tw').scrollTop = 0;
}

function changePageSize(size) {
  curPageSize = parseInt(size) || 50;
  goToPage(1);
}

const searchEl = document.getElementById('prod-search');
const searchDD = document.getElementById('search-dd');
let searchTimer = null;

searchEl.addEventListener('input', () => {
  const q = searchEl.value.trim();
  clearTimeout(searchTimer);
  if (!q) { searchDD.style.display = 'none'; filterProducts(''); return; }
  searchTimer = setTimeout(() => runSearch(q), 250);
});
searchEl.addEventListener('keydown', e => {
  if (e.key === 'Escape') { searchEl.value = ''; searchDD.style.display = 'none'; filterProducts(''); }
});
document.addEventListener('click', e => {
  if (!searchEl.contains(e.target) && !searchDD.contains(e.target))
    searchDD.style.display = 'none';
});

async function runSearch(q) {
  filterProducts(q);

  const r = await apiPost(PROD_API, { action: 'list', q, page_size: 12 }).catch(() => null);
  if (!r || !r.success || !r.data.length) {
    searchDD.innerHTML = `<div style="padding:10px 12px;font-size:12px;color:var(--text3)">
      No matches for "${esc(q)}"</div>`;
    searchDD.style.display = 'block';
    return;
  }

  searchDD.innerHTML = r.data.map(p => {
    const already = !!document.querySelector(`tr[data-id="${p.id}"]`);
    const stock   = parseInt(p.stock_pcs);
    const isOut   = stock <= 0;
    const sBg     = isOut ? '#fde8e8' : '#d4f0e6';
    const sCl     = isOut ? 'var(--danger)' : 'var(--accent)';
    return `<div class="search-row${already ? ' already-in' : ''}"
                 onclick='addSearchedProduct(${JSON.stringify(p).replace(/'/g,"&apos;")})'>
      <div style="min-width:0">
        <div style="font-weight:600;font-size:12px">${formIconName(p.form, p.name)}</div>
        <div style="font-size:10px;color:var(--text3)">
          ${esc(p.strength||'')}${p.company_name ? ' · ' + esc(p.company_name) : ''}
        </div>
      </div>
      <span class="search-badge" style="background:${sBg};color:${sCl}">
        ${isOut ? 'Out' : stock + ' pcs'}
      </span>
      <span class="search-badge" style="background:var(--brand-xlight);color:var(--brand)">
        ${already ? '✓ in list' : '+ Add'}
      </span>
    </div>`;
  }).join('');
  searchDD.style.display = 'block';
}

function addSearchedProduct(p) {
  searchDD.style.display = 'none';

  let row = document.querySelector(`tr[data-id="${p.id}"]`);
  if (!row) {
    const stock = parseInt(p.stock_pcs) || 0;
    const alert = parseInt(p.low_stock_alert) || 0;
    const qib   = Math.max(1, parseInt(p.qty_in_box) || 1);
    const minQ  = parseInt(p.min_qty) || 0;
    let sugBoxes = 0;
    if (alert > 0 && stock < alert) {
      let sugPcs = Math.max(0, alert - stock);
      if (sugPcs > 0 && minQ > 0) sugPcs = Math.max(sugPcs, minQ);
      sugBoxes = sugPcs > 0 ? Math.max(1, Math.ceil(sugPcs / qib)) : 0;
    }
    const stockBg = stock <= 0 ? '#fde8e8' : (alert > 0 && stock < alert ? '#fff3dc' : '#d4f0e6');
    const stockCl = stock <= 0 ? 'var(--danger)' : (alert > 0 && stock < alert ? 'var(--warn)' : 'var(--accent)');
    const hasPrice = parseFloat(p.btp_vat || 0) > 0;

    const tr = document.createElement('tr');
    tr.className = 'prod-row';
    tr.dataset.id = p.id;
    tr.dataset.name = p.name;
    tr.dataset.form = p.form || '';
    tr.dataset.stock = stock;
    tr.dataset.price = p.btp_vat || 0;
    tr.dataset.supplierId = '';
    tr.dataset.supplier = '';
    tr.dataset.hasPrice = hasPrice ? '1' : '0';
    tr.dataset.suggested = sugBoxes;
    tr.innerHTML = `
      <td style="text-align:center">
        <input type="checkbox" class="row-chk" data-id="${p.id}" onchange="onCheck(this)">
      </td>
      <td>
        <div style="font-weight:600;font-size:12px">${formIconName(p.form, p.name)}</div>
        <div style="font-size:10px;color:var(--text3)">
          ${esc(p.strength||'')}${p.company_name ? ' · ' + esc(p.company_name) : ''}
          ${p.rack ? ' · Rack: ' + esc(p.rack) : ''}
        </div>
        ${!hasPrice ? `<div style="font-size:10px;color:var(--warn);font-weight:600">⚠ No TP+VAT price set</div>` : ''}
      </td>
      <td style="text-align:center">
        <span class="badge" style="background:${stockBg};color:${stockCl}">${stock}</span>
      </td>
      <td style="text-align:center;color:var(--text2);font-size:11.5px">${alert || '—'}</td>
      <td style="text-align:center"><span style="color:var(--text3);font-size:11px">—</span></td>
      <td style="text-align:center"><span style="color:var(--text3);font-size:11px">—</span></td>
      <td class="mono" style="text-align:right;font-size:11.5px">
        ${hasPrice ? CUR + parseFloat(p.btp_vat).toFixed(2) : '<span style="color:var(--text3)">—</span>'}
      </td>
      <td style="font-size:11px;color:var(--text2)">—</td>
      <td style="text-align:center">
        <input type="number" class="box-qty" data-id="${p.id}" value="${Math.max(1, sugBoxes)}" min="0"
               style="width:60px;text-align:center;display:none" oninput="onQtyChange(${p.id})">
      </td>`;
    document.getElementById('prod-body').appendChild(tr);
    row = tr;
  }

  const chk = row.querySelector('.row-chk');
  if (!chk.checked) { chk.checked = true; onCheck(chk); }
  row.scrollIntoView({ behavior: 'smooth', block: 'center' });
  row.style.outline = '2px solid var(--brand)';
  setTimeout(() => row.style.outline = '', 1200);

  searchEl.value = '';
  filterProducts('');
}

function onSupplierChange() {
  const sel   = document.getElementById('req-supplier');
  const opt   = sel.options[sel.selectedIndex];
  const phone = opt?.dataset?.phone || '';
  const info  = document.getElementById('sup-info');
  const pEl   = document.getElementById('sup-phone');

  if (sel.value) {
    pEl.textContent     = phone ? '📞 ' + phone : '';
    info.style.display  = phone ? 'block' : 'none';
  } else {
    info.style.display  = 'none';
  }
}

async function saveReq() {
  const errEl   = document.getElementById('save-err');
  const saveBtn = document.getElementById('save-btn');
  errEl.style.display = 'none';

  const suppId = document.getElementById('req-supplier').value;
  const ids    = Object.keys(selected).filter(id => selected[id].qty > 0);
  const zeroed = Object.keys(selected).filter(id => selected[id].qty <= 0);

  if (!suppId) {
    errEl.textContent   = '⚠ Please select a supplier.';
    errEl.style.display = 'block'; return;
  }
  if (!ids.length) {
    errEl.textContent   = zeroed.length
      ? '⚠ Selected item(s) are at 0 boxes — set a quantity or select a different product.'
      : '⚠ Select at least one product.';
    errEl.style.display = 'block'; return;
  }

  let total = 0;
  const items = ids.map(id => {
    const it   = selected[id];
    const line = it.qty * it.price;
    total += line;
    return {
      product_id:   parseInt(id),
      product_name: it.name,
      qty_box:      it.qty,
      btp_vat:      it.price,
      total_price:  line,
    };
  });

  const suppSel = document.getElementById('req-supplier');
  const suppName= suppSel.options[suppSel.selectedIndex]?.text || '';

  saveBtn.disabled    = true;
  saveBtn.textContent = '⏳ Saving…';

  const r = await apiPost(API, {
    action:       'save',
    ref:          document.getElementById('req-no').value.trim(),
    supplier_id:  suppId,
    supplier_name:suppName,
    date:         document.getElementById('req-date').value,
    total_price:  total,
    notes:        document.getElementById('req-notes').value.trim(),
    items,
  });

  saveBtn.disabled    = false;
  saveBtn.textContent = '📝 Create Requisition';

  if (!r.success) {
    errEl.textContent   = '⚠ ' + (r.error || 'Save failed.');
    errEl.style.display = 'block'; return;
  }

  showModal(`
  <div style="text-align:center;padding:10px 0">
    <div style="font-size:34px;margin-bottom:8px">✅</div>
    <div style="font-size:15px;font-weight:700;color:var(--accent);margin-bottom:4px">
      Requisition Created!
    </div>
    <div class="mono"
         style="font-size:17px;font-weight:800;color:var(--brand);margin-bottom:14px">
      ${esc(r.ref)}
    </div>
    <div style="font-size:12px;color:var(--text2);margin-bottom:16px">
      ${ids.length} product(s) · ${suppName}
    </div>
    <div style="display:flex;gap:8px;justify-content:center">
      <button class="btn btn-primary"
              onclick="closeModal();location.reload()">
        ➕ New Requisition
      </button>
      <a class="btn" href="req-record.php">📋 View All</a>
    </div>
  </div>`, 'Requisition Saved');
}

function esc(s) {
  return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;')
                      .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

document.addEventListener('DOMContentLoaded', () => {
  const params = new URLSearchParams(window.location.search);
  if (params.get('quick') !== '1') return;

  const queue = JSON.parse(sessionStorage.getItem('req_quick_add') || '[]');
  if (!queue.length) return;

  let found = 0;
  queue.forEach(id => {
    const chk = document.querySelector(`.row-chk[data-id="${id}"]`);
    if (chk && !chk.checked) {
      chk.checked = true;
      onCheck(chk);
      found++;
      if (found === 1) chk.closest('tr')?.scrollIntoView({behavior:'smooth', block:'center'});
    }
  });

  sessionStorage.removeItem('req_quick_add');

  if (found > 0) {
    const banner = document.createElement('div');
    banner.className = 'al al-s';
    banner.style.marginBottom = '10px';
    banner.innerHTML = `✅ ${found} product(s) added from Low Stock Alert list.`;
    document.querySelector('.content')?.prepend(banner);
  }
});
</script>

<?php require_once '../includes/footer.php'; ?>
