<?php
if (! $_SERVER['REQUEST_METHOD'] === 'POST') {
exit("not permitted bad request");
}
//initialising the user session if not already started
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
if (!isset($_SESSION["cart"])) {
$_SESSION["cart"] = [];
}
function additemtocart($item){
//checking if the item is already in the cart, adding it if not, setting the counter up if yes
if (array_key_exists($item,$_SESSION["cart"])) {
$_SESSION["cart"][$item]++;
}else{
$_SESSION["cart"][$item] = 1;
}
echo(json_encode(true));
}
function subtractitemsfromcart($item){
//checking if the item is already in the cart, subtracting one if not, calling the removefromcart function if count is 0
if (array_key_exists($item,$_SESSION["cart"])) {
$_SESSION["cart"][$item]--;
if ($_SESSION["cart"][$item] <= 0) {
removefromcart($item);
}else{
echo(json_encode(true));
}
}else{
echo(json_encode(false));
}
}
//completely removing an ite mfrom the cart
function removefromcart($item){
if (array_key_exists($item,$_SESSION["cart"])) {
unset($_SESSION["cart"][$item]);
echo(json_encode(true));
}else{
echo(json_encode(false));
}
}
//getting the request data
$requestData = json_decode(file_get_contents('php://input'), true);
if (isset($requestData["add"])) {
additemtocart($requestData["add"]);
}
if (isset($requestData["subtract"])) {
subtractitemsfromcart($requestData["subtract"]);
}
if (isset($requestData["remove"])) {
removefromcart($requestData["remove"]);
}
if (isset($requestData["print"])) {
$cart = $_SESSION["cart"];
echo(json_encode($cart));
}
?>