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

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

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

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

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

    $sql = "INSERT INTO wp_extra_wishlist_products (productId, userId) 
            VALUES (" . $params['productId'] . ", " . $user->ID . ") 
            ;";
    
    try {
        $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!";
            $data = [
                'add_product' => true
            ];
        }
        
    } catch (Exception $ex) {
        
    }

    return new WP_REST_Response($data, 200);
}
