36782-vm/cart_actions.php
2025-12-12 14:13:03 +00:00

64 lines
2.0 KiB
PHP

<?php
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
require_once 'includes/lang.php';
require_once 'includes/auth.php';
require_login();
require_once 'includes/helpers.php';
// Initialize cart if it doesn't exist
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = [];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? '';
switch ($action) {
case 'add':
$product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
$quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1;
if ($product_id > 0 && $quantity > 0) {
// If product is already in cart, update quantity
if (isset($_SESSION['cart'][$product_id])) {
$_SESSION['cart'][$product_id] += $quantity;
} else {
$_SESSION['cart'][$product_id] = $quantity;
}
}
break;
case 'update':
$product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
$quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 0;
if ($product_id > 0) {
if ($quantity > 0) {
$_SESSION['cart'][$product_id] = $quantity;
} else {
// Remove item if quantity is 0 or less
unset($_SESSION['cart'][$product_id]);
}
}
break;
case 'remove':
$product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
if ($product_id > 0) {
unset($_SESSION['cart'][$product_id]);
}
break;
}
if ($action === 'add' && isset($product_id)) {
header('Location: related_suggestions.php?product_id=' . $product_id . '&qty=' . $quantity);
} else {
// Redirect back to the appropriate page
$redirect_url = $_POST['redirect_to'] ?? 'index.php';
header('Location: ' . $redirect_url);
}
exit;
}