fetch("SELECT name, stock FROM products WHERE product_id = :id", ['id' => $_POST['product_id']]); $newStock = max(0, ($product['stock'] ?? 0) + $adjustment); db()->update('products', ['stock' => $newStock], 'product_id = :id', ['id' => $_POST['product_id']]); setFlash('success', $product['name'] . ' stock adjusted by ' . ($adjustment > 0 ? '+' : '') . $adjustment . '. New stock: ' . $newStock); } header('Location: /admin/inventory.php'); exit; } if ($action === 'update_threshold' && !empty($_POST['product_id'])) { $threshold = intval($_POST['low_stock_threshold'] ?? 10); db()->update('products', ['low_stock_threshold' => $threshold], 'product_id = :id', ['id' => $_POST['product_id']]); setFlash('success', 'Low stock threshold updated'); header('Location: /admin/inventory.php'); exit; } if ($action === 'bulk_adjust') { $adjustments = $_POST['adjustments'] ?? []; $count = 0; foreach ($adjustments as $productId => $adj) { $adj = intval($adj); if ($adj != 0) { db()->query( "UPDATE products SET stock = GREATEST(0, stock + :adj) WHERE product_id = :id", ['adj' => $adj, 'id' => $productId] ); $count++; } } if ($count > 0) { setFlash('success', "Adjusted stock for $count products"); } header('Location: /admin/inventory.php'); exit; } } // Filters $filter = $_GET['filter'] ?? ''; $search = $_GET['search'] ?? ''; $category = $_GET['category'] ?? ''; $where = ['1=1']; $params = []; if ($search) { $where[] = '(name LIKE :search OR sku LIKE :search OR barcode LIKE :search)'; $params['search'] = '%' . $search . '%'; } if ($category) { $where[] = 'category = :category'; $params['category'] = $category; } if ($filter === 'low') { $where[] = 'stock <= low_stock_threshold AND stock > 0'; } elseif ($filter === 'out') { $where[] = 'stock <= 0'; } elseif ($filter === 'in') { $where[] = 'stock > low_stock_threshold'; } $whereClause = implode(' AND ', $where); $products = db()->fetchAll( "SELECT product_id, name, sku, barcode, category, stock, low_stock_threshold, price, is_active FROM products WHERE {$whereClause} ORDER BY stock ASC, name ASC", $params ); // Get categories for filter $categories = db()->fetchAll( "SELECT DISTINCT category FROM products WHERE category IS NOT NULL AND category != '' ORDER BY category" ); // Stats $totalProducts = db()->count('products', 'is_active = 1'); $lowStockCount = db()->count('products', 'stock <= low_stock_threshold AND stock > 0 AND is_active = 1'); $outOfStockCount = db()->count('products', 'stock <= 0 AND is_active = 1'); $totalStock = db()->fetch("SELECT SUM(stock) as total FROM products WHERE is_active = 1")['total'] ?? 0; $inventoryValue = db()->fetch("SELECT SUM(stock * price) as total FROM products WHERE is_active = 1")['total'] ?? 0; ?>