<?php 
add_action('rest_api_init', function () {
    register_rest_route('spacetree', '/license/licenses/list', array(
        'methods' => 'GET',
        'callback' => 'license_get_list_products_callback',
        'permission_callback' => '',
    ));
    /**
     * validate user 
     */
    register_rest_route('spacetree', '/license/my-account/checkout', array(
        'methods' => 'POST',
        'callback' => 'license_my_account_checkout_callback',
        'permission_callback' => '',
    ));

});

/**
 * type: fetch products
 * return: it return arary of woocommerce products with category spacetree
 */
function license_get_list_products_callback( \WP_REST_Request $req ) {
    
    // Check if WooCommerce is active or installed
    if (class_exists('WooCommerce')) {
        // WooCommerce is active or installed
        $products = array();
        
        // Get products with category "spacetree"
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1,
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'slug',
                    'terms' => 'spacetree',
                ),
            ),
        );
        
        $query = new WP_Query($args);
        
        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $product_id = get_the_ID();
                # get license details

                
                if( 1 == 1 ){
                    $query->the_post();
                    $product = wc_get_product(get_the_ID());
                    $products[] = array(
                        'id' => $product->get_id(),
                        'name' => $product->get_name(),
                        'description' => $product->get_description(),
                        'short_description' => $product->get_short_description(),
                        'tags' => wp_get_post_terms(get_the_ID(), 'product_tag', array('fields' => 'names')),
                        'image_url' => get_the_post_thumbnail_url(get_the_ID(), 'full'),
                        'sale_price' => $product->get_sale_price(),
                        'regular_price' => $product->get_regular_price(),
                        'price_currency' => html_entity_decode(get_woocommerce_currency_symbol()),
                        'license'        => (object) [
                            "expires_in"        => $product->get_meta('_spacetree-license-expires-in'),
                            "license_type"      => $product->get_meta('_spacetree-license-type'),
                            "license_domains"   => $product->get_meta('_spacetree-license-items')
                        ]
                    );
                }
            }
            wp_reset_postdata();
            
            // Send products as JSON response
            wp_send_json([
                "success" => (object) [
                    "message"   => 'No products found with category "spacetree"',
                    "has_json"  => true,
                    "json"      => (object) [
                        "total"     => 0,
                        "products"  => (array) $products
                    ]
                ]
            ]);

        } else {
            // No products found with category "spacetree"

            wp_send_json([
                "success" => (object) [
                    "message"   => 'No products found with category "spacetree"',
                    "has_json"  => true,
                    "json"      => (object) [
                        "total"     => 0,
                        "products"  => (array) []
                    ]
                ]
            ]);
        }
    } else {
        // WooCommerce is not active or installed
        wp_send_json([
            "error" => (object) [
                "message"  => 'WooCommerce plugin is not active or installed'
            ]
        ]);
    }

}

/**
 * type: WC_checkout for user validation
 */
function license_my_account_checkout_callback( \WP_REST_Request $req ) {
    $post_data      = $req->get_body_params();
    $post           = $post_data['process'];  
    $data           = (object) json_decode($post); 

    if( $data->method == "woo-my-account"){
        
        $user       = (object) $data->user;
        $user_check = get_user_by('email', $user->email);
        
        if ( $user_check ) {
            # User found
            $wp_user_id = $user_check->ID; 
            update_user_meta($wp_user_id, '_spacetree_user_id', $user->_id);
            update_user_meta($wp_user_id, '_spacetree_uid', $user->_uid);
            
            return wp_send_json((object) [ 
                "success" => (object) [
                    "message" => "user generated successfully",
                    "status"  => 200,
                    "user_id" => $wp_user_id  
                ]
            ]);
            
        } else {
            # add new user
            $wp_user_id = wp_insert_user(array(
                'user_login' => $user->email,
                'user_email' => $user->email,
                'role' => 'subscriber',
                'user_pass' => wp_generate_password(), // Generate a random password
                'meta_input' => array( // Add meta data
                    '_spacetree_uid'       => $user->_uid, // Replace with the actual meta key you want to use
                    '_spacetree_user_id'   => $user->_id,
                    'billing_first_name'   => $user->first_name,
                    'billing_last_name'    => $user->last_name,
                    'billing_country'      => $user->country,
                    'billing_postcode'     => $user->zipcode,
                    'billing_address_1'    => $user->address,
                    'shipping_first_name'   => $user->first_name,
                    'shipping_last_name'    => $user->last_name,
                    'shipping_country'      => $user->country,
                    'shipping_postcode'     => $user->zipcode,
                    'shipping_address_1'    => $user->address,
                    'first_name'           => $user->first_name,
                    'last_name'            => $user->last_name
                )
            ));
            
            return wp_send_json((object) [ 
                "success" => (object) [
                    "message" => "user generated successfully",
                    "status"  => 200,
                    "user_id" => $wp_user_id  
                ]
            ]);
            

        }
        
    } 

}