<?php
// ============================================================
//  MediCore — Categories
//  File: product/categories.php
//  Mirrors product/generics.php exactly — a simple id+name lookup
//  used to group/filter/report on products.
// ============================================================
$page  = 'product/categories';
$title = 'Product Categories';
require_once '../includes/header.php';

$total = (int) db_val("SELECT COUNT(*) FROM categories");
?>

<!-- ── Page action buttons ────────────────────────── -->
<script>
document.getElementById('ph-actions').innerHTML = `
  <input type="text" id="srch" placeholder="🔍  Search category…"
    style="padding:5px 10px;border:1px solid var(--border);border-radius:var(--rsm);
           font-family:inherit;font-size:12px;width:200px;outline:none">
  <button class="btn btn-primary btn-sm" onclick="openAdd()">➕ Add Category</button>`;
</script>

<!-- ── Summary card ───────────────────────────────── -->
<div style="display:grid;grid-template-columns:200px 1fr;gap:10px;margin-bottom:12px">
  <div class="sc" style="border-top:3px solid var(--teal)">
    <div class="slabel">Total Categories</div>
    <div class="sval b" style="color:var(--teal)" id="cnt-total"><?= $total ?></div>
  </div>
  <div class="al al-i" style="margin-bottom:0">
    💡 Categories group products for easier searching, filtering, and reporting (e.g. Antibiotic, Painkiller, Supplement). A category cannot be deleted if products are assigned to it.
  </div>
</div>

<!-- ── Table ──────────────────────────────────────── -->
<div class="card" style="padding:0">
  <div class="tw">
    <table id="cat-table">
      <thead>
        <tr>
          <th style="width:44px">#</th>
          <th>Category Name</th>
          <th style="text-align:right">Products</th>
          <th>Added</th>
          <th style="text-align:center;width:130px">Actions</th>
        </tr>
      </thead>
      <tbody id="cat-body">
        <tr><td colspan="5" class="empty-state">Loading…</td></tr>
      </tbody>
    </table>
  </div>
  <div id="cat-footer"
       style="padding:8px 14px;font-size:11px;color:var(--text3);
              border-top:1px solid var(--border)"></div>
</div>

<script>
const API = '../api/categories.php';
let timer      = null;
let curPage    = 1;
let curQuery   = '';
let curPageSize = 50;

// ── Load (paginated) ─────────────────────────────────────────
async function load(q = '', page = 1) {
  curQuery = q;
  curPage  = page;

  const tbody = document.getElementById('cat-body');
  tbody.innerHTML = '<tr><td colspan="5" class="empty-state">Loading…</td></tr>';

  const r = await apiPost(API, { action: 'list', q, page, page_size: curPageSize });
  if (!r.success) {
    tbody.innerHTML = `<tr><td colspan="5" class="empty-state" style="color:var(--danger)">
      Error: ${r.error}</td></tr>`;
    return;
  }

  const rows = r.data;
  document.getElementById('cnt-total').textContent = r.total ?? rows.length;

  const footer = document.getElementById('cat-footer');
  if (!rows.length) {
    tbody.innerHTML = '<tr><td colspan="5" class="empty-state">No categories found.</td></tr>';
    footer.innerHTML = '';
    return;
  }

  const startIdx = ((r.page || 1) - 1) * (r.page_size || curPageSize);

  tbody.innerHTML = rows.map((c, i) => `
    <tr data-id="${c.id}">
      <td style="color:var(--text3)">${startIdx + i + 1}</td>
      <td style="font-weight:600">${esc(c.name)}</td>
      <td style="text-align:right">
        ${parseInt(c.product_count) > 0
          ? `<span class="badge" style="background:var(--teal-light);color:var(--teal)">${c.product_count}</span>`
          : `<span style="color:var(--text3)">0</span>`}
      </td>
      <td style="color:var(--text3);font-size:11px">${c.created_at?.substring(0,10) || '—'}</td>
      <td style="text-align:center;white-space:nowrap">
        <button class="btn btn-sm btn-teal"  onclick="openEdit(${c.id})">✏ Edit</button>
        <button class="btn btn-sm btn-danger" onclick="del(${c.id},'${esc(c.name).replace(/'/g,"\\'")}',${c.product_count})">🗑</button>
      </td>
    </tr>`).join('');

  const total      = r.total ?? rows.length;
  const totalPages = r.total_pages ?? 1;
  const page_      = r.page ?? 1;
  const rangeStart = startIdx + 1;
  const rangeEnd   = startIdx + rows.length;

  footer.innerHTML = `
    <div style="display:flex;align-items:center;justify-content:space-between;gap:10px">
      <span>Showing ${rangeStart}–${rangeEnd} of ${total} categor${total === 1 ? 'y' : 'ies'}</span>
      <div style="display:flex;align-items:center;gap:10px">
        <div style="display:flex;align-items:center;gap:5px">
          <span>Show</span>
          <select 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">
            ${[10,20,50,100,200].map(n =>
              `<option value="${n}" ${n===curPageSize?'selected':''}>${n}</option>`).join('')}
          </select>
        </div>
        <div style="display:flex;align-items:center;gap:6px">
          <button class="btn btn-sm" ${page_<=1?'disabled':''} onclick="load(curQuery, 1)">« First</button>
          <button class="btn btn-sm" ${page_<=1?'disabled':''} onclick="load(curQuery, curPage-1)">‹ Prev</button>
          <span style="padding:0 6px">Page ${page_} of ${totalPages}</span>
          <button class="btn btn-sm" ${page_>=totalPages?'disabled':''} onclick="load(curQuery, curPage+1)">Next ›</button>
          <button class="btn btn-sm" ${page_>=totalPages?'disabled':''} onclick="load(curQuery, totalPages)">Last »</button>
        </div>
      </div>
    </div>`;
}

function changePageSize(size) {
  curPageSize = parseInt(size) || 50;
  load(curQuery, 1);
}

// ── Search ────────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
  load();
  const s = document.getElementById('srch');
  s.addEventListener('input', () => {
    clearTimeout(timer);
    timer = setTimeout(() => load(s.value.trim(), 1), 250);
  });
  s.addEventListener('keydown', e => { if (e.key === 'Escape') { s.value = ''; load('', 1); } });
});

// ── Modal form ────────────────────────────────────────────────
function form(c = {}) {
  return `
  <div style="display:flex;flex-direction:column;gap:10px">
    <div class="fg">
      <label>Category Name *</label>
      <input id="f-name" value="${esc(c.name || '')}"
             placeholder="e.g. Antibiotic">
      <span style="font-size:10px;color:var(--text3);margin-top:2px">
        Used to group products for search, filters, and reports
      </span>
    </div>
    <div id="f-err" style="color:var(--danger);font-size:11px;display:none"></div>
  </div>
  <div style="display:flex;gap:8px;justify-content:flex-end;
              margin-top:14px;padding-top:12px;border-top:1px solid var(--border)">
    <button class="btn" onclick="closeModal()">Cancel</button>
    <button class="btn btn-primary" onclick="save(${c.id || 0})">
      ${c.id ? '💾 Save Changes' : '➕ Add Category'}
    </button>
  </div>`;
}

function openAdd() {
  showModal(form(), '➕ Add Category');
  setTimeout(() => document.getElementById('f-name')?.focus(), 50);
}

async function openEdit(id) {
  const r = await apiPost(API, { action: 'detail', id });
  if (!r.success) { alert('Could not load category.'); return; }
  showModal(form(r.data), '✏ Edit Category');
  setTimeout(() => document.getElementById('f-name')?.focus(), 50);
}

// ── Save ──────────────────────────────────────────────────────
async function save(id) {
  const name  = document.getElementById('f-name').value.trim();
  const errEl = document.getElementById('f-err');

  if (!name) {
    errEl.textContent = '⚠ Category name is required.';
    errEl.style.display = 'block';
    document.getElementById('f-name').focus();
    return;
  }

  const r = await apiPost(API, { action: id ? 'edit' : 'add', id, name });

  if (r.success) {
    closeModal();
    load(document.getElementById('srch')?.value || '', curPage);
  } else {
    errEl.textContent = '⚠ ' + (r.error || 'Save failed.');
    errEl.style.display = 'block';
  }
}

// ── Delete ────────────────────────────────────────────────────
async function del(id, name, productCount) {
  if (parseInt(productCount) > 0) {
    alert(`⚠ Cannot delete "${name}".\n\n${productCount} product(s) use this category.\nReassign them first.`);
    return;
  }
  if (!confirm(`Delete category "${name}"?`)) return;

  const r = await apiPost(API, { action: 'delete', id });
  if (r.success) {
    load(document.getElementById('srch')?.value || '', curPage);
  } else {
    alert('⚠ ' + (r.error || 'Delete failed.'));
  }
}

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

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