<?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['productId'];
    $foodName = $requestData['productName'];
    $foodPrice = $requestData['sellingPrice'];
    $cat = $requestData['cat'];
    $quantityChange = $requestData['quantityChange'];

    // Check if the food ID, name, price, category, and quantity change are valid
    if (isset($foodId, $foodName, $foodPrice, $cat, $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 && $item['food_price'] == $foodPrice) {
                $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,
                'cat' => $cat,
                'quantity' => $quantityChange
            ];
        }

        // Update the cart items in the session
        $_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.']);
}
?>
