35289-vm/app/Controllers/CartController.php
Flatlogic Bot 163c483584 atual
2025-10-28 01:29:21 +00:00

108 lines
3.2 KiB
PHP

<?php
session_start();
require_once __DIR__ . '/../Models/Product.php';
class CartController {
public function __construct() {
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
}
public function add() {
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['product_id'])) {
$productId = (int)$_POST['product_id'];
$quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1;
if ($quantity <= 0) {
header('Location: /product.php?slug=' . $_POST['product_slug'] . '&error=Invalid quantity');
exit();
}
$product = Product::findById($productId);
if ($product) {
if (isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId]['quantity'] += $quantity;
} else {
$_SESSION['cart'][$productId] = [
'product_id' => $productId,
'name' => $product['name'],
'price' => $product['price'],
'image' => $product['image'],
'slug' => $product['slug'],
'quantity' => $quantity,
];
}
}
header('Location: /cart.php');
exit();
}
}
public function update() {
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['product_id'])) {
$productId = (int)$_POST['product_id'];
$quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 0;
if ($quantity > 0 && isset($_SESSION['cart'][$productId])) {
$_SESSION['cart'][$productId]['quantity'] = $quantity;
} else {
unset($_SESSION['cart'][$productId]);
}
}
header('Location: /cart.php');
exit();
}
public function remove() {
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['product_id'])) {
$productId = (int)$_POST['product_id'];
unset($_SESSION['cart'][$productId]);
}
header('Location: /cart.php');
exit();
}
public static function getCartContents() {
return $_SESSION['cart'] ?? [];
}
public static function getCartItemCount() {
$count = 0;
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $item) {
$count += $item['quantity'];
}
}
return $count;
}
public static function getCartTotal() {
$total = 0;
if (isset($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $item) {
$total += $item['price'] * $item['quantity'];
}
}
return $total;
}
}
// Handle cart actions
if (isset($_POST['action'])) {
$cartController = new CartController();
switch ($_POST['action']) {
case 'add':
$cartController->add();
break;
case 'update':
$cartController->update();
break;
case 'remove':
$cartController->remove();
break;
}
}
?>