<?php
session_start();

// Retrieve the request payload
$requestPayload = json_decode(file_get_contents('php://input'), true);

// Extract the food ID and quantity change from the payload
$foodId = $requestPayload['foodId'];
$quantityChange = $requestPayload['quantityChange'];

// Retrieve the cart items from the PHP session
$cartItems = $_SESSION['cart'] ?? [];

// Find the cart item with the given food ID
$cartItemIndex = array_search($foodId, array_column($cartItems, 'food_id'));

if ($cartItemIndex !== false) {
  // Update the quantity of the cart item
  $cartItems[$cartItemIndex]['quantity'] += $quantityChange;

  // Remove the cart item if the quantity becomes zero or less
  if ($cartItems[$cartItemIndex]['quantity'] <= 0) {
    array_splice($cartItems, $cartItemIndex, 1);
  }
}

// Update the cart items in the PHP session
$_SESSION['cart'] = $cartItems;

// Send a success response
http_response_code(200);
echo json_encode(['message' => 'Cart item updated successfully']);
?>
