<?php
// 1. Hook the registration function to the 'rest_api_init' action
add_action('rest_api_init', 'add_product_quantity_in_cart_api_register_routes');

function add_product_quantity_in_cart_api_register_routes()
{
    $namespace = 'api/v1'; // Namespace for your custom route prefixed with /wp-json/
    $route = '/add-product-quantity-in-cart';          // The specific route segment

    register_rest_route($namespace, $route, array(
        'methods' => 'POST', // HTTP method (GET, POST, etc.)
        'callback' => 'add_product_quantity_in_cart_api_callback', // Function to execute
        'permission_callback' => '__return_true', // Authentication check (true for public)
    ));
}

// 2. The Callback Function
function add_product_quantity_in_cart_api_callback($request)
{
    global $wpdb;
    $params = $request->get_params();

    $user = get_user_by('login', $params['username']);

    $data = [];
    if($params['productId'] != null) {

        try {
            $quantity = addProductQuantity($params['productId'], $user->ID, $params['orderId']);
            $data = [
                "add_quantity" => true,
                "quantity" => $quantity
            ];
        } catch(Exception $ex) {
            $data = [
                "add_quantity" => false,
                "error" => $ex->getMessage()
            ];
        }
    }
    return new WP_REST_Response($data, 200);
}
