public function add() { if (!isset($_POST['id']) || !isset($_POST['quantity'])) { header("Location: /products/all"); } if (!$this->isLogged()) { header("Location: /users/login"); } $productId = $_POST['id']; $quantityWanted = $_POST['quantity']; $userId = (string) $_SESSION['id']; $product = new ProductModel(); $viewModel = new InformationViewModel(); if (!$product->exists($productId)) { $viewModel->error = "Product {$productId} does not exist"; } $quantityAvailable = $product->details($productId)->getQuantity(); if ($quantityWanted > $quantityAvailable) { $viewModel->error = "Not enough stock"; } $shoppingCart = new CartModel(); if ($shoppingCart->add($userId, $productId, $quantityWanted)) { $viewModel->success = "Product {$productId} added to cart successfully"; } else { $viewModel->error = "Cannot add product {$productId} to cart"; } return new View($viewModel); }
public function sell($productId, $amount) { $productModel = new ProductModel(); $viewModel = new InformationViewModel(); if (!$productModel->exists($productId)) { $viewModel->error = "Product {$productId} does not exist"; return new View($viewModel); } if ($amount < 0) { $viewModel->error = "You can sell at least one item"; return new View($viewModel); } try { $productModel->sell($_SESSION['id'], $productId, $amount); $viewModel->success = "Product {$productId} sold successfully"; } catch (\Exception $e) { $viewModel->error = $e->getMessage(); } return new View($viewModel); }