<?php
// ============================================================
//  MediCore — Low Stock Alert Qty Management
//  File: product/stock-alert.php
// ============================================================
$page  = 'product/stock-alert';
$title = 'Low Stock Alert Qty';
require_once '../includes/header.php';
require_once '../includes/requisition-tabs.php';

$cur = $settings['currency'];

$companies = db_rows("SELECT id,name FROM companies ORDER BY name");
$generics  = db_rows("SELECT id,name FROM generics  ORDER BY name");
?>

<!-- ── Page actions ───────────────────────────────── -->
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:10px">
  <input type="text" id="f-search" placeholder="🔍 Search product name…"
         oninput="delayLoad()"
    style="padding:6px 10px;border:1px solid var(--border);border-radius:var(--rsm);
           font-family:inherit;font-size:12px;outline:none;width:200px">

  <select id="f-company" onchange="load()"
    style="padding:6px 9px;border:1px solid var(--border);border-radius:var(--rsm);
           font-family:inherit;font-size:12px;outline:none">
    <option value="">All Companies</option>
    <?php foreach ($companies as $c): ?>
    <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
    <?php endforeach; ?>
  </select>

  <select id="f-generic" onchange="load()"
    style="padding:6px 9px;border:1px solid var(--border);border-radius:var(--rsm);
           font-family:inherit;font-size:12px;outline:none">
    <option value="">All Categories</option>
    <?php foreach ($generics as $g): ?>
    <option value="<?= $g['id'] ?>"><?= htmlspecialchars($g['name']) ?></option>
    <?php endforeach; ?>
  </select>

  <label style="font-size:11.5px;display:flex;align-items:center;gap:4px">
    <input type="checkbox" id="f-no-alert" onchange="load()">
    Alert Qty = 0 only
  </label>

  <div style="margin-left:auto;display:flex;gap:8px">
    <button class="btn btn-sm" onclick="exportExcel()">📤 Export Excel</button>
    <button class="btn btn-sm" onclick="document.getElementById('import-file').click()">
      📥 Import Excel
    </button>
    <input type="file" id="import-file" accept=".csv,.xlsx,.xls" style="display:none"
           onchange="importExcel(this)">
  </div>
</div>

<!-- ── Bulk update bar ─────────────────────────────── -->
<div id="bulk-bar"
     style="display:none;align-items:center;gap:10px;margin-bottom:10px;
            padding:8px 12px;background:var(--brand-xlight);
            border:1px solid var(--brand-light);border-radius:var(--rsm)">
  <span id="bulk-count" style="font-size:12px;font-weight:700;color:var(--brand)"></span>
  <span style="font-size:11.5px;color:var(--text2)">Set Alert Qty to:</span>
  <input type="number" id="bulk-value" min="0" value="10"
         style="width:80px;text-align:center">
  <button class="btn btn-sm btn-primary" onclick="bulkUpdate()">✅ Apply</button>
  <button class="btn btn-sm" onclick="clearSelection()">✕ Clear Selection</button>
</div>

<!-- ── Table ──────────────────────────────────────── -->
<div class="card" style="padding:0">
  <div class="tw">
    <table id="stock-table">
      <thead>
        <tr>
          <th style="width:36px;text-align:center">
            <input type="checkbox" id="chk-all" onchange="toggleAll(this.checked)">
          </th>
          <th>Product</th>
          <th>Company</th>
          <th style="text-align:center">Current Stock</th>
          <th style="text-align:center">Pcs/Box</th>
          <th style="text-align:center;width:140px">Alert Qty (pcs)</th>
          <th style="text-align:center">Status</th>
          <th style="text-align:center;width:70px">Action</th>
        </tr>
      </thead>
      <tbody id="prod-body">
        <tr><td colspan="8" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="prod-footer"
       style="padding:8px 14px;font-size:11px;color:var(--text3);
              border-top:1px solid var(--border)"></div>
</div>

<script>
const CUR  = '<?= addslashes($cur) ?>';
const API  = '../api/products.php';
let srchTimer = null;
let selected  = new Set();

function delayLoad() { clearTimeout(srchTimer); srchTimer = setTimeout(load, 280); }

// ── Load ──────────────────────────────────────────────────────
async function load() {
  const tbody = document.getElementById('prod-body');
  tbody.innerHTML = '<tr><td colspan="8" class="empty-state loading-row"><span class="spin"></span>Loading…</td></tr>';

  const r = await apiPost(API, {
    action:   'list',
    q:        document.getElementById('f-search').value.trim(),
    company_id: document.getElementById('f-company').value,
    generic_id: document.getElementById('f-generic').value,
  });

  if (!r.success) {
    if (handleApiError(r, tbody, 8)) return;
    tbody.innerHTML = `<tr><td colspan="8" class="empty-state" style="color:var(--danger)">
      ⚠ Error: ${esc(r.error || 'Failed to load products.')}
      <br><button class="btn btn-sm" style="margin-top:8px" onclick="load()">↻ Retry</button>
    </td></tr>`;
    return;
  }

  let rows = r.data || [];
  if (document.getElementById('f-no-alert').checked) {
    rows = rows.filter(p => !p.low_stock_alert || parseInt(p.low_stock_alert) === 0);
  }

  renderTable(rows);
}

function renderTable(rows) {
  const tbody  = document.getElementById('prod-body');
  const footer = document.getElementById('prod-footer');

  if (!rows.length) {
    tbody.innerHTML = `<tr><td colspan="8" class="empty-state">
      📭 No Records Found — try adjusting filters or search.
    </td></tr>`;
    footer.textContent = '';
    return;
  }

  footer.innerHTML = `<strong>${rows.length}</strong> product(s)`;

  tbody.innerHTML = rows.map(p => {
    const stock = parseInt(p.stock_pcs) || 0;
    const alert = parseInt(p.low_stock_alert) || 0;
    const qib    = parseInt(p.qty_in_box) || 1;

    let stCl, stBg, stLabel;
    if (stock <= 0)            { stCl='var(--danger)'; stBg='#fde8e8'; stLabel='🔴 Out of Stock'; }
    else if (alert>0 && stock<alert) { stCl='#ea580c'; stBg='#ffedd5'; stLabel='🟠 Below Alert'; }
    else                        { stCl='var(--accent)'; stBg='#d4f0e6'; stLabel='🟢 Sufficient'; }

    return `<tr data-id="${p.id}">
      <td style="text-align:center">
        <input type="checkbox" class="row-chk" data-id="${p.id}"
               onchange="onCheck(this)" ${selected.has(p.id)?'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.form?'· '+esc(p.form):''}
        </div>
      </td>
      <td style="font-size:11.5px;color:var(--text2)">${esc(p.company_name||'—')}</td>
      <td class="mono" style="text-align:center;font-weight:700;color:${stCl}">${stock}</td>
      <td class="mono" style="text-align:center;color:var(--text3)">${qib}</td>
      <td style="text-align:center">
        <input type="number" class="alert-input" data-id="${p.id}" data-orig="${alert}"
               value="${alert}" min="0"
               style="width:90px;text-align:center"
               onkeydown="if(event.key==='Enter')saveAlert(${p.id},this)">
        <button class="btn btn-sm" style="padding:2px 6px;margin-left:3px"
                onclick="saveAlert(${p.id}, this.previousElementSibling)"
                title="Save">💾</button>
      </td>
      <td style="text-align:center">
        <span class="badge" style="background:${stBg};color:${stCl};font-weight:700;font-size:10.5px">
          ${stLabel}
        </span>
      </td>
      <td style="text-align:center">
        ${alert>0 && stock<alert
          ? `<button class="btn btn-sm btn-primary" style="padding:2px 7px;font-size:10px"
                     onclick="quickAddToReq(${p.id},'${esc(p.name).replace(/'/g,"\\'")}')"
                     title="Add to requisition">➕ Req</button>`
          : '<span style="color:var(--text3)">—</span>'}
      </td>
    </tr>`;
  }).join('');
}

// ── Inline save ───────────────────────────────────────────────
async function saveAlert(id, inputEl) {
  const val = parseInt(inputEl.value) || 0;
  inputEl.disabled = true;
  const r = await apiPost(API, { action: 'set_alert', id, low_stock_alert: val });
  inputEl.disabled = false;
  if (r.success) {
    inputEl.dataset.orig = val;
    inputEl.style.background = 'var(--accent-xlight)';
    setTimeout(() => inputEl.style.background = '', 800);
  } else {
    if (!handleSessionAlert(r)) alert('⚠ ' + (r.error || 'Save failed.'));
    inputEl.value = inputEl.dataset.orig;
  }
}

function handleSessionAlert(r) {
  if (r.session_expired) {
    alert('🔒 Session expired. Please log in again.');
    window.location.href = '<?= base_url("login.php") ?>';
    return true;
  }
  return false;
}

// ── Selection / bulk update ────────────────────────────────────
function onCheck(chk) {
  const id = parseInt(chk.dataset.id);
  if (chk.checked) selected.add(id); else selected.delete(id);
  updateBulkBar();
}
function toggleAll(checked) {
  document.querySelectorAll('.row-chk').forEach(chk => {
    chk.checked = checked;
    const id = parseInt(chk.dataset.id);
    if (checked) selected.add(id); else selected.delete(id);
  });
  updateBulkBar();
}
function clearSelection() {
  selected.clear();
  document.querySelectorAll('.row-chk').forEach(c=>c.checked=false);
  document.getElementById('chk-all').checked = false;
  updateBulkBar();
}
function updateBulkBar() {
  const bar = document.getElementById('bulk-bar');
  if (selected.size > 0) {
    bar.style.display = 'flex';
    document.getElementById('bulk-count').textContent = `${selected.size} selected`;
  } else {
    bar.style.display = 'none';
  }
}

async function bulkUpdate() {
  const val = parseInt(document.getElementById('bulk-value').value) || 0;
  if (!selected.size) return;
  if (!confirm(`Set Alert Qty = ${val} for ${selected.size} product(s)?`)) return;

  const r = await apiPost(API, {
    action: 'bulk_set_alert',
    ids: Array.from(selected),
    low_stock_alert: val,
  });
  if (r.success) {
    clearSelection();
    load();
  } else {
    if (!handleSessionAlert(r)) alert('⚠ ' + (r.error || 'Bulk update failed.'));
  }
}

// ── Export / Import ────────────────────────────────────────────
function exportExcel() {
  window.open(`${API}?action=export_alert_csv`, '_blank');
}

async function importExcel(input) {
  const file = input.files[0];
  if (!file) return;
  const text = await file.text();
  // Expect CSV: product_id,name,alert_qty
  const lines = text.split(/\r?\n/).filter(l=>l.trim());
  const updates = [];
  for (let i=1;i<lines.length;i++) { // skip header
    const parts = lines[i].split(',');
    const id  = parseInt(parts[0]);
    const qty = parseInt(parts[2]);
    if (id && !isNaN(qty)) updates.push({id, low_stock_alert: qty});
  }
  if (!updates.length) { alert('No valid rows found in file.'); return; }
  if (!confirm(`Import alert quantities for ${updates.length} product(s)?`)) return;

  const r = await apiPost(API, { action: 'import_alert_csv', updates });
  if (r.success) { alert(`✅ Updated ${r.count} product(s).`); load(); }
  else { if (!handleSessionAlert(r)) alert('⚠ ' + (r.error || 'Import failed.')); }
  input.value = '';
}

// ── Quick add to requisition ────────────────────────────────────
function quickAddToReq(id, name) {
  // Store in sessionStorage and redirect to manual requisition
  let queue = JSON.parse(sessionStorage.getItem('req_quick_add') || '[]');
  if (!queue.includes(id)) queue.push(id);
  sessionStorage.setItem('req_quick_add', JSON.stringify(queue));
  alert(`✅ "${name}" added to requisition queue.\nOpening Manual Requisition…`);
  window.location.href = 'requisition.php?quick=1';
}

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

document.addEventListener('DOMContentLoaded', load);
</script>

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