<?php
require_once __DIR__ . '/config/config.php';
require_permission('items.manage');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $cat = $_POST['category_id'] ?: null;
    $unit = $_POST['unit_id'] ?: null;
    $reorder = $_POST['reorder_level'] ?: 0;
    $trackExpiry = isset($_POST['track_expiry']) ? 1 : 0;
    $id = $_POST['id'] ?? null;

    if ($name === '') {
        flash('error', 'Item name is required.');
    } elseif ($id) {
        // Code is immutable once assigned - only these fields can change
        $pdo->prepare("UPDATE items SET name=?, category_id=?, unit_id=?, reorder_level=?, track_expiry=? WHERE id=?")
            ->execute([$name, $cat, $unit, $reorder, $trackExpiry, $id]);
        flash('success', 'Item updated.');
    } else {
        $pdo->prepare("INSERT INTO items (name, category_id, unit_id, reorder_level, track_expiry) VALUES (?,?,?,?,?)")
            ->execute([$name, $cat, $unit, $reorder, $trackExpiry]);
        $newId = $pdo->lastInsertId();
        // Auto-generate the item code from its own id, e.g. ITM-00001
        $pdo->prepare("UPDATE items SET code = ? WHERE id = ?")->execute([generate_item_code($pdo, $newId), $newId]);
        flash('success', 'Item added.');
    }
    redirect('items.php');
}

if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE items SET is_active = 1 - is_active WHERE id=?")->execute([$_GET['toggle']]);
    redirect('items.php');
}

$edit = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM items WHERE id=?");
    $stmt->execute([$_GET['edit']]);
    $edit = $stmt->fetch();
}

$categories = $pdo->query("SELECT * FROM categories ORDER BY name")->fetchAll();
$units = $pdo->query("SELECT * FROM units ORDER BY name")->fetchAll();

$search = trim($_GET['q'] ?? '');
$sql = "SELECT i.*, c.name cat_name, u.abbreviation unit_abbr, COALESCE(s.quantity,0) stock_qty
        FROM items i
        LEFT JOIN categories c ON c.id=i.category_id
        LEFT JOIN units u ON u.id=i.unit_id
        LEFT JOIN main_store_stock s ON s.item_id=i.id";
$params = [];
if ($search !== '') {
    $sql .= " WHERE i.name LIKE ? OR i.code LIKE ?";
    $params = ["%$search%", "%$search%"];
}
$sql .= " ORDER BY i.name";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$items = $stmt->fetchAll();

$pageTitle = 'Items';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<div class="flex items-center justify-between mb-6">
  <h1 class="text-2xl font-bold">Item Catalogue</h1>
  <button onclick="openItemDrawer()" class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg">+ Add Item</button>
</div>

<div class="bg-white rounded-xl shadow-sm border border-slate-200">
  <div class="p-4 border-b border-slate-200">
    <form method="GET"><input name="q" value="<?= e($search) ?>" placeholder="Search items..." class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm"></form>
  </div>
  <div class="overflow-x-auto"><table class="w-full text-sm">
    <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
      <th class="text-left px-5 py-2">Code</th><th class="text-left px-5 py-2">Name</th>
      <th class="text-left px-5 py-2">Category</th><th class="text-left px-5 py-2">Stock</th>
      <th class="text-left px-5 py-2">Expiry Tracked</th><th class="text-left px-5 py-2">Status</th>
      <th class="text-right px-5 py-2">Actions</th></tr></thead>
    <tbody>
    <?php foreach ($items as $it): ?>
      <tr class="border-t border-slate-100 <?= $it['stock_qty'] <= $it['reorder_level'] ? 'bg-amber-50' : '' ?>">
        <td class="px-5 py-2.5 font-mono text-xs text-slate-500"><?= e($it['code']) ?></td>
        <td class="px-5 py-2.5"><?= e($it['name']) ?></td>
        <td class="px-5 py-2.5"><?= e($it['cat_name']) ?></td>
        <td class="px-5 py-2.5"><?= number_format($it['stock_qty'],2) ?> <?= e($it['unit_abbr']) ?></td>
        <td class="px-5 py-2.5"><?= $it['track_expiry'] ? '<span class="text-emerald-600">Yes</span>' : '<span class="text-slate-300">No</span>' ?></td>
        <td class="px-5 py-2.5">
          <span class="px-2 py-0.5 rounded-full text-xs <?= $it['is_active'] ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-200 text-slate-500' ?>">
            <?= $it['is_active'] ? 'Active' : 'Inactive' ?>
          </span>
        </td>
        <td class="px-5 py-2.5 text-right space-x-3">
          <button onclick='openItemDrawer(JSON.parse(this.dataset.item))' data-item="<?= e(json_encode($it)) ?>" class="text-blue-600 hover:underline">Edit</button>
          <a href="?toggle=<?= $it['id'] ?>&q=<?= urlencode($search) ?>" class="text-slate-500 hover:underline"><?= $it['is_active'] ? 'Deactivate' : 'Activate' ?></a>
        </td>
      </tr>
    <?php endforeach; ?>
    <?php if (empty($items)): ?><tr><td colspan="7" class="px-5 py-6 text-center text-slate-400">No items found.</td></tr><?php endif; ?>
    </tbody>
  </table></div>
</div>

<!-- Slide-out drawer for Add/Edit Item -->
<div id="itemDrawerBackdrop" class="hidden fixed inset-0 bg-black/40 z-40" onclick="closeItemDrawer()"></div>
<div id="itemDrawer" class="fixed top-0 right-0 h-full w-full max-w-md bg-white shadow-2xl z-50 translate-x-full transition-transform duration-300 overflow-y-auto">
  <div class="flex items-center justify-between px-6 py-4 border-b border-slate-200">
    <h2 id="itemDrawerTitle" class="font-semibold text-lg">Add Item</h2>
    <button onclick="closeItemDrawer()" class="text-slate-400 hover:text-slate-600 text-xl leading-none">✕</button>
  </div>
  <form method="POST" class="p-6 space-y-4">
    <input type="hidden" name="id" id="f_id">
    <div id="codeDisplayWrap" class="hidden">
      <label class="text-xs text-slate-500 block mb-1">Item Code</label>
      <p id="codeDisplay" class="font-mono text-sm text-slate-500 bg-slate-50 border border-slate-200 rounded-lg px-3 py-2"></p>
    </div>
    <div>
      <label class="text-xs text-slate-500 block mb-1">Item Name</label>
      <input name="name" id="f_name" required placeholder="Item name" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
    </div>
    <div>
      <label class="text-xs text-slate-500 block mb-1">Category</label>
      <select name="category_id" id="f_category" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <option value="">-- Category --</option>
        <?php foreach ($categories as $c): ?><option value="<?= $c['id'] ?>"><?= e($c['name']) ?></option><?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="text-xs text-slate-500 block mb-1">Unit</label>
      <select name="unit_id" id="f_unit" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <option value="">-- Unit --</option>
        <?php foreach ($units as $un): ?><option value="<?= $un['id'] ?>"><?= e($un['name']) ?> (<?= e($un['abbreviation']) ?>)</option><?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="text-xs text-slate-500 block mb-1">Reorder Level</label>
      <input type="number" step="0.01" name="reorder_level" id="f_reorder" value="0" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
    </div>
    <label class="flex items-center gap-2 text-sm">
      <input type="checkbox" name="track_expiry" id="f_expiry">
      Track expiry dates for this item (adds an expiry field when receiving goods)
    </label>
    <div class="flex gap-2 pt-2">
      <button type="submit" class="flex-1 bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2.5 rounded-lg">Save Item</button>
      <button type="button" onclick="closeItemDrawer()" class="flex-1 bg-slate-100 hover:bg-slate-200 text-sm font-medium px-4 py-2.5 rounded-lg">Cancel</button>
    </div>
  </form>
</div>

<script>
function openItemDrawer(item) {
  const backdrop = document.getElementById('itemDrawerBackdrop');
  const drawer = document.getElementById('itemDrawer');
  const codeWrap = document.getElementById('codeDisplayWrap');

  document.getElementById('f_id').value = item ? item.id : '';
  document.getElementById('f_name').value = item ? item.name : '';
  document.getElementById('f_category').value = item ? (item.category_id || '') : '';
  document.getElementById('f_unit').value = item ? (item.unit_id || '') : '';
  document.getElementById('f_reorder').value = item ? item.reorder_level : 0;
  document.getElementById('f_expiry').checked = !!(item && (item.track_expiry == 1));
  document.getElementById('itemDrawerTitle').textContent = item ? 'Edit Item' : 'Add Item';

  if (item && item.code) {
    document.getElementById('codeDisplay').textContent = item.code;
    codeWrap.classList.remove('hidden');
  } else {
    codeWrap.classList.add('hidden');
  }

  backdrop.classList.remove('hidden');
  drawer.classList.remove('translate-x-full');
}
function closeItemDrawer() {
  document.getElementById('itemDrawerBackdrop').classList.add('hidden');
  document.getElementById('itemDrawer').classList.add('translate-x-full');
}
<?php if ($edit): ?>
  document.addEventListener('DOMContentLoaded', () => openItemDrawer(<?= json_encode($edit, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>));
<?php endif; ?>
</script>
<?php include __DIR__ . '/includes/footer.php'; ?>
