<?php
require_once __DIR__ . '/config/config.php';
require_permission('main_store.view');
$u = current_user();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['adjust'])) {
    require_permission('main_store.adjust');
    $itemId = $_POST['item_id'];
    $qty = (float)$_POST['qty'];
    $notes = trim($_POST['notes'] ?? '');
    if ($qty == 0) {
        flash('error', 'Adjustment quantity cannot be zero.');
    } else {
        main_store_adjustment($pdo, $itemId, $qty, $u['id'], $notes ?: 'Manual adjustment');
        flash('success', 'Stock adjustment recorded.');
    }
    redirect('main_store.php');
}

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

$allItems = $pdo->query("SELECT id, name FROM items WHERE is_active=1 ORDER BY name")->fetchAll();

$pageTitle = 'Main Store';
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">Main Store Stock</h1>
  <?php if (has_permission($pdo, $u, 'main_store.adjust')): ?>
  <button onclick="document.getElementById('adjModal').classList.remove('hidden')"
    class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg">+ Stock Adjustment</button>
  <?php endif; ?>
</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">Item</th>
      <th class="text-left px-5 py-2">Category</th><th class="text-left px-5 py-2">Qty on Hand</th>
      <th class="text-left px-5 py-2">Avg Cost</th><th class="text-left px-5 py-2">Reorder Level</th></tr></thead>
    <tbody>
    <?php foreach ($stock as $s): $low = $s['qty'] <= $s['reorder_level']; ?>
      <tr class="border-t border-slate-100 <?= $low ? 'bg-amber-50' : '' ?>">
        <td class="px-5 py-2.5"><?= e($s['code']) ?></td>
        <td class="px-5 py-2.5 font-medium"><?= e($s['name']) ?> <?= $low ? '<span class="text-amber-600 text-xs">⚠ low</span>' : '' ?></td>
        <td class="px-5 py-2.5"><?= e($s['cat_name']) ?></td>
        <td class="px-5 py-2.5"><?= number_format($s['qty'],2) ?> <?= e($s['unit_abbr']) ?></td>
        <td class="px-5 py-2.5">₦<?= number_format($s['avg_cost'],2) ?></td>
        <td class="px-5 py-2.5"><?= number_format($s['reorder_level'],2) ?></td>
      </tr>
    <?php endforeach; ?>
    <?php if (empty($stock)): ?><tr><td colspan="6" class="px-5 py-6 text-center text-slate-400">No items found.</td></tr><?php endif; ?>
    </tbody>
  </table></div>
</div>

<!-- Adjustment Modal -->
<div id="adjModal" class="hidden fixed inset-0 bg-black/40 flex items-center justify-center z-50 px-4">
  <div class="bg-white rounded-xl shadow-xl p-6 w-full max-w-md">
    <h2 class="font-semibold text-lg mb-4">Manual Stock Adjustment</h2>
    <form method="POST" class="space-y-3">
      <input type="hidden" name="adjust" value="1">
      <select name="item_id" required class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <option value="">-- Select item --</option>
        <?php foreach ($allItems as $it): ?><option value="<?= $it['id'] ?>"><?= e($it['name']) ?></option><?php endforeach; ?>
      </select>
      <input type="number" step="0.01" name="qty" required placeholder="Quantity (use negative to reduce)" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <textarea name="notes" placeholder="Reason for adjustment" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm"></textarea>
      <div class="flex gap-2">
        <button type="submit" class="flex-1 bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg">Save</button>
        <button type="button" onclick="document.getElementById('adjModal').classList.add('hidden')" class="flex-1 bg-slate-100 hover:bg-slate-200 text-sm font-medium px-4 py-2 rounded-lg">Cancel</button>
      </div>
    </form>
  </div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
