<?php
// Start or resume the session
session_start();

// Check if the request is a POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Retrieve the food ID and quantity change from the request body
  $requestData = json_decode(file_get_contents('php://input'), true);
  $foodId = $requestData['foodId'];
  $foodName = $requestData['foodName'];
  $foodPrice = $requestData['foodPrice'];
  $quantityChange = $requestData['quantityChange'];

  // Check if the food ID and quantity change are valid
  if (isset($foodId, $foodName, $foodPrice, $quantityChange)) {
    // Retrieve the cart items from the session
    $cartItems = isset($_SESSION['cart']) ? $_SESSION['cart'] : [];

    // Check if the item already exists in the cart
    $existingItemKey = null;
    foreach ($cartItems as $key => $item) {
      if ($item['food_id'] == $foodId) {
        $existingItemKey = $key;
        break;
      }
    }

    // Update the quantity if the item already exists
    if ($existingItemKey !== null) {
      $cartItems[$existingItemKey]['quantity'] += $quantityChange;
    } else {
      // Add the item to the cart array in the session
      $cartItems[] = [
        'food_id' => $foodId,
        'food_name' => $foodName,
        'food_price' => $foodPrice,
        'quantity' => 1
      ];
    }

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

    // Return a success response
    http_response_code(200);
    echo json_encode(['message' => 'Item added to cart successfully.']);
  } else {
    // Return an error response for invalid input
    http_response_code(400);
    echo json_encode(['error' => 'Invalid request data.']);
  }
} else {
  // Return an error response for invalid request method
  http_response_code(405);
  echo json_encode(['error' => 'Invalid request method.']);
}
?>
