<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['product_id']) && isset($_POST['change'])) {
        $productId = (string)$_POST['product_id'];
        $change = (int)$_POST['change'];

        // Ensure that the cart session exists
        if (isset($_SESSION['cart']) && is_array($_SESSION['cart'])) {
            // Check if the product is in the cart
            $found = false;

            foreach ($_SESSION['cart'] as &$product) {
                if ($product['id'] === $productId) {
                    // Update the quantity
                    $product['qty'] += $change;
                    $product['subtotal'] = $product['qty'] * $product['price'];

                    // Ensure the quantity is non-negative
                    if ($product['qty'] < 0) {
                        $product['qty'] = 0;
                    }

                    $found = true;
                    break; // Product found, exit the loop
                }
            }

            if ($found) {
                // Update the session with the new data
                $_SESSION['cart'] = array_values($_SESSION['cart']); // Reindex the array
               header('Content-Type: application/json');
                echo json_encode(array('success' => true, 'newQuantity' => $product['qty'], 'newSubtotal' => $product['subtotal']));
            } else {
               header('Content-Type: application/json');
                // Product not found in the cart, return an error response
                echo json_encode(array('success' => false, 'error' => 'Product not found in the cart'));
            }
        } else {
           header('Content-Type: application/json');
            // Cart session doesn't exist, return an error response
            echo json_encode(array('success' => false, 'error' => 'Cart is empty or unavailable'));
        }
    } else {
       header('Content-Type: application/json');
        // Invalid request parameters, return an error response
        echo json_encode(array('success' => false, 'error' => 'Invalid request parameters'));
    }
}

?>
