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

// Check if the session cart exists, create it if not
if (!isset($_SESSION['cart'])) {
    $_SESSION['cart'] = array();
}

// Check if required POST values are set
if (isset($_POST['productId'], $_POST['productName'], $_POST['buyingPrice'], $_POST['quantity'])) {
    // Get data from the AJAX request
    $productId = $_POST['productId'];
    $productName = $_POST['productName'];
    $buyingPrice = $_POST['buyingPrice'];
    $quantity = $_POST['quantity'];

    // Check if the item already exists in the cart
    $itemIndex = array_search($productId, array_column($_SESSION['cart'], 'product_id'));

    if ($itemIndex !== false) {
        // Update the quantity if the item exists
        $_SESSION['cart'][$itemIndex]['quantity'] += $quantity;

        // Recalculate the subtotal for the updated item
        $_SESSION['cart'][$itemIndex]['subtotal'] = $_SESSION['cart'][$itemIndex]['quantity'] * $_SESSION['cart'][$itemIndex]['buying_price'];

        echo 'Quantity updated successfully.';
    } else {
        // Add the item to the cart if it doesn't exist
        $cartItem = array(
            'product_id' => $productId,
            'product_name' => $productName,
            'buying_price' => $buyingPrice,
            'quantity' => $quantity,
            'subtotal' => $quantity * $buyingPrice
        );

        array_push($_SESSION['cart'], $cartItem);
        echo 'Item added to cart successfully.';
    }

    // Calculate subtotal
    $subTotal = 0;
    foreach ($_SESSION['cart'] as $item) {
        $subTotal += $item['subtotal'];
    }

    // Display the cart information only if it contains items
    if (!empty($_SESSION['cart'])) {
        echo ' Subtotal: $' . number_format($subTotal, 2);
    } else {
        echo ' Cart is empty.';
    }
} else {
    // Handle the case where required POST values are not set
    echo 'Error: Required POST values are not set.';
}


?>
