feat: initial foundation for collaborative canteen ordering system in vanilla PHP
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Core\Database\Database;
|
||||
use PDO;
|
||||
|
||||
class Product
|
||||
{
|
||||
public static function all(): array
|
||||
{
|
||||
$db = Database::getConnection();
|
||||
$stmt = $db->query("SELECT * FROM products ORDER BY name ASC");
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
public static function find(int $id): ?array
|
||||
{
|
||||
$db = Database::getConnection();
|
||||
$stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
public static function count(): int
|
||||
{
|
||||
$db = Database::getConnection();
|
||||
return (int)$db->query("SELECT COUNT(*) FROM products")->fetchColumn();
|
||||
}
|
||||
|
||||
public static function lowStockCount(int $threshold = 25): int
|
||||
{
|
||||
$db = Database::getConnection();
|
||||
$stmt = $db->prepare("SELECT COUNT(*) FROM products WHERE stock <= ?");
|
||||
$stmt->execute([$threshold]);
|
||||
return (int)$stmt->fetchColumn();
|
||||
}
|
||||
|
||||
public static function create(array $data): int
|
||||
{
|
||||
$db = Database::getConnection();
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO products (sku, name, description, price, stock, category)
|
||||
VALUES (:sku, :name, :description, :price, :stock, :category)
|
||||
");
|
||||
$stmt->execute([
|
||||
':sku' => $data['sku'],
|
||||
':name' => $data['name'],
|
||||
':description' => $data['description'] ?? '',
|
||||
':price' => $data['price'],
|
||||
':stock' => (int)($data['stock'] ?? 0),
|
||||
':category' => $data['category'] ?? 'General',
|
||||
]);
|
||||
return (int)$db->lastInsertId();
|
||||
}
|
||||
|
||||
public static function update(int $id, array $data): bool
|
||||
{
|
||||
$db = Database::getConnection();
|
||||
$stmt = $db->prepare("
|
||||
UPDATE products
|
||||
SET sku = :sku, name = :name, description = :description,
|
||||
price = :price, stock = :stock, category = :category
|
||||
WHERE id = :id
|
||||
");
|
||||
return $stmt->execute([
|
||||
':id' => $id,
|
||||
':sku' => $data['sku'],
|
||||
':name' => $data['name'],
|
||||
':description' => $data['description'] ?? '',
|
||||
':price' => $data['price'],
|
||||
':stock' => (int)($data['stock'] ?? 0),
|
||||
':category' => $data['category'] ?? 'General',
|
||||
]);
|
||||
}
|
||||
|
||||
public static function deductStock(int $id, int $quantity): bool
|
||||
{
|
||||
$db = Database::getConnection();
|
||||
$stmt = $db->prepare("UPDATE products SET stock = MAX(0, stock - ?) WHERE id = ?");
|
||||
return $stmt->execute([$quantity, $id]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user