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

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

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

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

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

    $_SESSION['order_id'] = createNewOrder($_SESSION['user_id']);
    //$_SESSION['order_id'] = 1;
    //echo '$_SESSION["order_id"]: ' . $_SESSION['order_id'] . '<br>';

    $sql = "INSERT INTO wp_extra_cart_products (productId, orderId, userId, quantity) 
            VALUES (" . $params['productId'] . ", " . $_SESSION['order_id'] . ", " . $user->ID . ", 1) 
            ;";

    $result = $wpdb->query($sql);
    
    if ($result === false) {
        $error_message = $wpdb->last_error;
        if (strpos($error_message, "Duplicate entry") === 0) {
            $error_message = "Already added!";
        }
        $data = [
            "add_product" => false,
            "error" => $error_message
        ];

    } else {
        //echo "Product added successfully!";
        $count = getCartProductsCount($_SESSION['user_id'], $_SESSION['order_id']);
        $data = [
            "add_product" => true,
            "count" => $count
        ];
    }


    return new WP_REST_Response($data, 200);

}
