<?php
session_start();

// Check if item data is received via POST
if (isset($_POST['item'])) {
    // Retrieve item details from POST data
    $item = $_POST['item'];

    // Ensure item details are valid (you may want to add more validation as per your application's needs)
    $id = isset($item['id']) ? (int) $item['id'] : 0;
    $name = isset($item['name']) ? htmlspecialchars($item['name']) : '';
    $category = isset($item['category']) ? htmlspecialchars($item['category']) : '';
    $buyingPrice = isset($item['buyingPrice']) ? (float) $item['buyingPrice'] : 0.0;
    $quantity = isset($item['quantity']) ? (int) $item['quantity'] : 0;
$availability = isset($item['availability']) ? htmlspecialchars((string) $item['availability'], ENT_QUOTES, 'UTF-8') : '';
    $unit = isset($item['unit'])  ? htmlspecialchars($item['unit']) : '';

    // Example: Check if item already exists in the session cart (you may have a different logic)
    $cart = isset($_SESSION['purchaseCart']) ? $_SESSION['purchaseCart'] : [];

    // If the item already exists in the cart, update its quantity and buying price
    $found = false;
    foreach ($cart as &$cartItem) {
        if ($cartItem['id'] === $id) {
            // Update quantity and buying price
            $cartItem['quantity'] += $quantity;
            $cartItem['buyingPrice'] = $buyingPrice; // Update buying price
            $found = true;
            break;
        }
    }

    // If the item is not found in the cart, add it as a new item
    if (!$found) {
        $newItem = [
            'id' => $id,
            'name' => $name,
            'category' => $category,
            'buyingPrice' => $buyingPrice,
            'quantity' => $quantity,
            'unit' => $unit,
            'availability' => $availability
        ];
        $cart[] = $newItem;
    }

    // Update the session cart
    $_SESSION['purchaseCart'] = $cart;

    // Response (you can customize this as needed)
    echo json_encode(['status' => 'success', 'message' => 'Item added to cart']);
} else {
    // Invalid request handling (you may want to log this or provide an error response)
    echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
}
?>
item[id]: 19
item[name]: beans
item[unit]: grams
item[category]: Ingredient
item[buyingPrice]: 0.00
item[quantity]: 1000
item[availability]: No