<?php namespace CodeClouds\Unify\Actions;

use \CodeClouds\Unify\Model\Connection as Connection_Model;
use \CodeClouds\Unify\Model\PlatformApiModel;
use \CodeClouds\Unify\Service\Helper;
use \CodeClouds\Unify\Service\Request;

/**
 * Plugin's Tools.
 * @package CodeClouds\Unify
 */
class PlatformApi
{
    private static $home_url = UNIFY_WP_HOME_URL;
    private static $platform_endpoint = UNIFY_PLATFORM_ENDPOINT;
    private static $weightType = ['lbs' => 'lbWeight', 'kg' => 'kgWeight', 'g' => 'gWeight', 'oz' => 'ozWeight'];
    public static function validate_pro_license()
    {
        $unify_pro_license_key = (empty(Request::any('unify_pro_license_key'))) ? '' : Request::any('unify_pro_license_key');
        $unify_domain = (empty(Request::any('unify_domain'))) ? '' : Request::any('unify_domain');
        $testing_domain = (empty(Request::any('unify_domain'))) ? '' : 'https://' . Request::any('unify_domain') . '/';
        $custom_messages = Helper::getDataFromFile('Messages');
        if (!empty($unify_pro_license_key)) {
            $paramArray = ['license_key' => $unify_pro_license_key, 'domain_name' => $unify_domain];
            $isValid = PlatformApiModel::callPlatformToProcess($paramArray, $testing_domain);
            if (!empty($isValid) && ! is_wp_error( $isValid ) && (json_decode($isValid['body'])->success == 1)) {
                $pro_license = Helper::getProLicenseFromUnify();
                if (empty($pro_license)) {
                    $result = \add_option('codeclouds_unify_pro_license', $paramArray);
                    Helper::getProLicenseFromUnify($paramArray);
                } else {
                    $result = \update_option('codeclouds_unify_pro_license', $paramArray);
                    Helper::getProLicenseFromUnify($paramArray);
                }
                echo json_encode(['status' => 1, 'msg' => $isValid['message'], 'redirect' => admin_url('admin.php?page=unify-upgrade-to-pro')]);
            } else {
                echo json_encode(['status' => 0, 'msg' => $isValid['message']]);
            }
        } else {
            echo json_encode(['status' => 0, 'msg' => $isValid['message']]);
        }
        exit();
    }

    /**
     * Fetching all the Integrations
     * @return array
     */

    public static function getAllintegrations()
    {
        $configurationData = [];
        $all_connection = [];
        $connection_args = ['post_type' => 'unify_connections', 'posts_per_page' => -1, 'post_status' => ['publish', 'active']];
        $connections = new \WP_Query($connection_args);
        if (!empty($connections->posts)) {
            foreach ($connections->posts as $key => $value) {
                $all_connection[$key] = (array) $value;
                $metas = Connection_Model::get_post_meta($value->ID);
                foreach ($metas as $k => $val) {
                    if (in_array($k, ['unify_connection_crm', 'unify_connection_endpoint', 'unify_connection_api_username', 'unify_connection_api_password', 'unify_connection_campaign_id', 'unify_connection_shipping_id', 'unify_connection_offer_model', 'unify_order_note', 'unify_response_crm_type_enable'])) {
                        $all_connection[$key][$k] = $val[0];
                    }
                }
            }
        }
        $settings = \get_option('woocommerce_codeclouds_unify_settings');
        $crm_set = (!empty($settings) && !empty($settings['connection'])) ? $settings['connection'] : '';
        foreach ($all_connection as $k => $conn) {
            $active_conn = (!empty($crm_set) && ($crm_set == $conn['ID'])) ? 'active' : '';
            $configurationData['integration'][] = ["id" => $conn['ID'], "name" => empty($conn['post_title']) ? '(No title set)' : $conn['post_title'], "type" => empty($conn['unify_connection_crm']) ? '(No connection set)' : ucfirst($conn['unify_connection_crm']), "meta" => ["is_active" => $active_conn, "campaign_id" => empty($conn['unify_connection_campaign_id']) ? '' : $conn['unify_connection_campaign_id'], "default_shipping_id" => empty($conn['unify_connection_shipping_id']) ? '' : $conn['unify_connection_shipping_id'], "crm_api_username" => empty($conn['unify_connection_api_username']) ? '' : $conn['unify_connection_api_username'], "crm_api_endpoint" => empty($conn['unify_connection_endpoint']) ? '' : $conn['unify_connection_endpoint'], "is_ll_billing_model_enabled" => empty($conn['unify_connection_offer_model']) ? '' : $conn['unify_connection_offer_model'], "response_crm_type" => empty($conn['unify_response_crm_type_enable'] == 1) ? 'Latest' : 'Legacy']];
        }
        return $configurationData;
    }

    /**
     * Fetching all the product mapping
     * @return array
     */

    public static function getProductMappings()
    {
        $configurationData = [];
        $args = ['post_type' => 'product', 'posts_per_page' => -1];
        $loop = new \WP_Query($args);
        while ($loop->have_posts()):
            $loop->the_post();
            $product = wc_get_product(get_the_ID());
            $variants = [];
            if ($product->is_type('variable') == 1) {
                $variants = self::getVariantsByProductID($product);
                if (!empty($variants)) {
                    foreach ($variants as $key => $value) {
                        $configurationData = self::makeProductArray($configurationData, $key, $value);
                    }
                }
            } else {
                $configurationData = self::makeProductArray($configurationData, '', '');
            }
        endwhile;
        return $configurationData;
    }

    /**
     * Making the product Array
     * @param array|array
     * @return array
     */

    public static function makeProductArray($configurationData, $store_variant_id, $variant_crm_id)
    {
        $product_id = get_the_ID();
        $product_title = get_the_title();
        $configurationData['products'][] = ["store_product_id" => $product_id, "store_product_title" => $product_title, "store_variant_id" => empty($store_variant_id) ? '' : $store_variant_id, "crm_product_id" => get_post_meta($product_id, 'codeclouds_unify_connection', true), "meta" => ["shipping" => get_post_meta($product_id, 'codeclouds_unify_shipping', true), "offer_id" => get_post_meta($product_id, 'codeclouds_unify_offer_id', true), "billing_model_id" => get_post_meta($product_id, 'codeclouds_unify_billing_model_id', true), "group_id" => get_post_meta($product_id, 'codeclouds_unify_group_id', true), "crm_variation_id" => empty($variant_crm_id) ? '' : $variant_crm_id]];
        return $configurationData;
    }

    /**
     * Get an array list of variants By ProductID.
     * @param object $product
     * @return array
     */
    public static function getVariantsByProductID($product)
    {
        $variants = [];
        $pvariation = $product->get_available_variations();
        if (!empty($pvariation)) {
            foreach ($pvariation as $k => $v) {
                $variants[$v['variation_id']] = get_post_meta($v['variation_id'], 'unify_crm_variation_prod_id', true);
            }
        }
        return $variants;
    }

    /**
     * Get an array list of all the integration posts and products.
     * @return json
     */
    public static function configurationDataCollection()
    {
        $configurationData = [];
        $pro_license = Helper::getProLicenseFromUnify();
        $configurationData['license_key'] = (!empty($pro_license['license_key'])) ? $pro_license['license_key'] : '';
        $integrations = self::getAllintegrations();
        $products = self::getProductMappings();
        $getFinalproducts = self::getFinalproducts($products);
        $response = '';
        $response_array = [];
        $testing_domain = (empty($pro_license['domain_name'])) ? '' : 'https://' . $pro_license['domain_name'] . '/';
        if (!empty($getFinalproducts) && $getFinalproducts['product_count_crm_mapped'] > 0) {
            $output = array_merge($configurationData, $getFinalproducts['products']);
            $response = PlatformApiModel::callToPostWpConfig(json_encode($output), $testing_domain);
            if (!empty($response) && ! is_wp_error( $response ) && (json_decode($response['body'])->status == 1)) {
                $response_array = ['status' => 1, 'msg' => $response['message'], 'redirect' => admin_url('admin.php?page=unify-dashboard')];
                self::addFlagconfigTransferredFromButton();
            } else {
                $response_array = ['status' => 0, 'msg' => '<h4 class="unify-wp-head " >Transfer Failed</h4><p class="unify-wp-cnt m-0 p-0 transfer_fail">Try again after some time.</p>'];
            }
        } else {
            $response_array = ['status' => 1, 'msg' => '', 'redirect' => admin_url('admin.php?page=unify-dashboard')];
            self::addFlagconfigTransferredFromButton();
        }
        // phpcs:disable WordPress.Security.NonceVerification.Missing -- This is an API endpoint with proper validation
        if (isset($_POST['from-button']) == 1) {
            echo json_encode($response_array);
        }
        // phpcs:enable WordPress.Security.NonceVerification.Missing
        exit();
    }

    /**
     * Keep a flag in DB if data transferred
     */
    public static function addFlagconfigTransferredFromButton()
    {
        $config_transferred = \get_option('config_transferred_from_button');
        if (empty($config_transferred)) {
            $result = \add_option('config_transferred_from_button', 1);
        }
    }

    /**
     * Remove the products from products array which are not mapped to crm products
     */
    public static function getFinalproducts($products)
    {
        $count = 0;
        if (!empty($products)) {
            foreach ($products['products'] as $key => $value) {
                if ($value['crm_product_id'] == '') {
                    unset($products['products'][$key]);
                }
            }
        }
        return ['product_count_crm_mapped' => count($products['products']), 'products' => $products];
    }

    /**
     * Posting cart data
     */
    public static function toUnify()
    {
        $pro_license = Helper::getProLicenseFromUnify();
        if (empty($pro_license)) {
            return;
        }

        global $woocommerce;
        if (!session_id()) {
            session_start();
        }

        $domainByParamKey = self::getDomainByParamKey();
        $dynamic_domain = ($domainByParamKey === '') ? $pro_license['domain_name'] : $domainByParamKey;
        $dynamic_domain = 'https://' . $dynamic_domain . '/';
        $cart_data = self::prepareCartData();
        $session_cart_token = isset($_SESSION['unify_cart_token']) ? sanitize_text_field(wp_unslash($_SESSION['unify_cart_token'])) : '';
        if (empty($session_cart_token)) {
            $cart_token = $cart_data->token;
            $_SESSION['unify_cart_token'] = $cart_token;
        } else {
            $cart_token = $session_cart_token;
        }
        $cart_data = urlencode(json_encode($cart_data));
        $prepared_array = ['cart_data' => $cart_data, 'wc_store_token' => $pro_license['license_key'], 'base_url' => self::$home_url, 'redirection' => self::$home_url, 'cart_token' => $cart_token];
        $response = PlatformApiModel::sendStoreData($dynamic_domain, $prepared_array);
        
        if (!empty($response) && !is_wp_error($response)) {
            $res_success = json_decode($response['body'], true);
            $embed = $res_success['render_type'];
            $session_affiliate_params = isset($_SESSION['affiliate_params']) ? sanitize_text_field(wp_unslash($_SESSION['affiliate_params'])) : '';
            if (!empty($session_affiliate_params)) {
                $modified_params = self::replaceUrlParamName($session_affiliate_params);
                $url = $dynamic_domain . "checkout/?cart_token=" . $cart_token . '&' . $modified_params . '#/';
            } else {
                $url = $dynamic_domain . 'checkout?cart_token=' . $cart_token . '#/';
            }
            if ($res_success['status'] == 1) {
                if ($embed == 0) {
                    header('Location: ' . $url);
                    die();
                } else {
                    echo do_shortcode('[unify_checkout token="' . $url . '"]');
                }
            } else {
                header('Location: ' . $woocommerce
                        ->cart
                        ->get_cart_url());
                die();
            }
        } else {
            self::toUnifyGetMethod();
        }
    }
    public static function toUnifyGetMethod()
    {
        $cart_data = self::prepareCartData();
        $session_cart_token = isset($_SESSION['unify_cart_token']) ? sanitize_text_field(wp_unslash($_SESSION['unify_cart_token'])) : '';
        if (empty($session_cart_token)) {
            $cart_token = $cart_data->token;
            $_SESSION['unify_cart_token'] = $cart_token;
        } else {
            $cart_token = $session_cart_token;
        }
        $pro_license = Helper::getProLicenseFromUnify();
        $prepared_array = ['cart_data' => $cart_data, 'wc_store_token' => $pro_license['license_key'], 'base_url' => self::$home_url, 'redirection' => self::$home_url, 'debug' => 'yes'];
        $data = urlencode(gzcompress($prepared_array, 9));
        $response = PlatformApiModel::sendStoreDataGet($data);
        $dynamic_domain = self::$platform_endpoint;
        $url = $dynamic_domain . 'checkout?debug=yes&cart_token=' . $cart_token . '#/';
        header('Location: ' . $url);
        die();
    }
    public static function unify_remove_sidebar($is_active_sidebar, $index)
    {
        if (!is_checkout()) {
            return $is_active_sidebar;
        }
        return false;
    }

    /**
     * Preparing attribute array if product is variant
     */

    public static function prepareAttributeArray($data)
    {
        $attribute_Arr = [];
        $data = explode(',', $data);
        foreach ($data as $val) {
            $val = explode(':', $val);
            $attribute_Arr[] = ["name" => trim($val[0]), "value" => trim($val[1])];
        }
        return $attribute_Arr;
    }

    /**
     * Preparing cart data
     */

    public static function prepareCartData()
    {
        $cart_data = WC()
            ->cart
            ->get_cart();
        $prod = [];
        $key = 0;
        $sum = 0;
        $weight_unit = get_option('woocommerce_weight_unit');
        $finalWeight = 0;
        foreach ($cart_data as $cart_item_key => $cart_item) {
            $product_id = $cart_item['product_id'];
            $_id = ($cart_item['variation_id'] > 0) ? $cart_item['variation_id'] : $product_id;
            $prod[$key]['id'] = $_id;
            $prod[$key]['variant_id'] = $_id;
            $prod[$key]['product_id'] = $product_id;
            $prod[$key]['title'] = $cart_item['data']->get_name();
            $prod[$key]['product_title'] = $cart_item['data']->get_name();
            $prod[$key]['sku'] = $cart_item['data']->get_sku();
            $prod[$key]['options_with_values'] = !empty($cart_item['data']->attribute_summary) ? self::prepareAttributeArray($cart_item['data']->attribute_summary) : [];
            $prod[$key]['quantity'] = $cart_item['quantity'];
            $prod[$key]['price'] = $cart_item['data']->get_price() * 100;
            $prod[$key]['original_price'] = $cart_item['data']->get_price() * 100;
            if (!empty($cart_item['data']->get_weight())) {
                $finalWeight = self::
                        {
                    self::$weightType[$weight_unit]
                }
                ($cart_item['data']->get_weight());
            }
            /** fetch all product's categories */
            $prod[$key]['categories'] = get_the_terms(  $product_id ,'product_cat');
            $prod[$key]['default_currency_price'] = ($cart_item['variation_id'] > 0) ? get_post_meta($cart_item['variation_id'], '_price', true) : get_post_meta($product_id, '_price', true);
            $prod[$key]['grams'] = $finalWeight;
            $prod[$key]['image'] = self::getProductImage(has_post_thumbnail($_id)? $_id : $product_id);
            $prod[$key]['url'] = get_permalink($product_id);
            $sum += ($prod[$key]['grams']*$cart_item['quantity']);
            $key++;
        }
        $items['items'] = $prod;
        $items['total_weight'] = $sum;
        $items['item_count'] = WC()
            ->cart->cart_contents_count;
        $items['original_total_price'] = WC()
            ->cart->cart_contents_total * 100;
        $items['items_subtotal_price'] = WC()
            ->cart->cart_contents_total * 100;
        $items['currency'] = get_woocommerce_currency();
        $items['token'] = self::generateCartToken();
        return json_decode(json_encode($items), false);
    }

    /**
     * Generating cart token
     */

    public static function generateCartToken()
    {
        return md5(time() . base_convert(wp_rand(), 10, 36) . substr('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', wp_rand(0, 52)));
    }

    /**
     * Get Pproduct image by product ID
     */

    public static function getProductImage($product_id)
    {
        if (has_post_thumbnail($product_id)) {
            $attachment_ids[0] = get_post_thumbnail_id($product_id);
            $attachment = wp_get_attachment_image_src($attachment_ids[0], 'full');
            $attachment = $attachment[0];
        } else {
            $attachment = '/images/default-product.png';
        }
        return $attachment;
    }

    /**
     * Adding embedded checkout iframe
     */

    public static function unify_checkout_hook($attr)
    {
        // Sanitize and validate the token parameter to prevent XSS
        $token = isset($attr['token']) ? esc_url($attr['token']) : '';
        
        // Additional validation to ensure it's a valid URL
        if (empty($token) || !filter_var($token, FILTER_VALIDATE_URL)) {
            return '<p>Error: Invalid or missing token parameter.</p>';
        }
        
        return '<iframe align="center" scrolling="no" width="100%" height="500px" id="unify_iframe" src="' . esc_attr($token) . '" style="border: none;overflow:hidden;" allow="payment"></iframe>';
    }

    /**
     * Remove Cart Data
     */
    public static function unify_woocommerce_clear_cart_url()
    {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- This is a legitimate cart clearing URL parameter
        if (isset($_GET['clear-cart'])) {
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
            global $woocommerce;
            $woocommerce
                ->cart
                ->empty_cart();
            if (!empty($_SESSION['affiliate_params'])) {
                unset($_SESSION['affiliate_params']);
            }
            if (!empty($_SESSION['unify_cart_token'])) {
                unset($_SESSION['unify_cart_token']);
            }
        }
    }

    /**
     * Modify Product Response
     */
    public static function custom_change_product_response($response, $object, $request)
    {
        if (!empty($response->data['variations']) && is_array($response->data['variations'])) {
            $response->data['product_variations'] = [];
            foreach ($response->data['variations'] as $key => $vId) {
                $variation = new \WC_Product_Variation($vId);
                $response->data['product_variations'][$key]['id'] = $vId;
                $response->data['product_variations'][$key]['product_id'] = $response->data['id'];
                $response->data['product_variations'][$key]['price'] = $variation->is_on_sale() ? (float) $variation->get_sale_price() : (float) $variation->get_regular_price();
                $count = 1;
                foreach ($variation->get_variation_attributes() as $attribute_name => $attribute) {
                    if (!empty($attribute)) {
                        $attribute_name = str_replace('attribute_', '', $attribute_name);
                        $response->data['product_variations'][$key]['option' . $count] = term_exists($attribute, $attribute_name) ? get_term_by('slug', $attribute, $attribute_name)->name : $attribute;
                        $count++;
                    }
                }
            }
        }
        return $response;
    }

    /**
     * Modify Order
     */
    public static function modify_data_after_order($order_id)
    {
        $order = new \WC_Order($order_id);
        $user = $order->get_user();
        if (!$user) {
            $userdata = get_user_by('email', $order->get_billing_email());
            $userId = empty($userdata->ID) ? wc_create_new_customer($order->get_billing_email()) : $userdata->ID;
            update_post_meta($order_id, '_customer_user', $userId);
        }
        $notes = json_decode($order->get_meta('notes'), true);
        if (empty($notes) && !is_array($notes)) {
            $notes = [];
        }
        foreach ($notes as $note) {
            $order->add_order_note($note['name'] . ' => ' . $note['value']);
        }
        delete_post_meta($order_id, 'notes');
    }
    public static function woocommerce_add_multiple_products_to_cart()
    {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- This handles WooCommerce add-to-cart functionality
        $add_to_cart = isset($_REQUEST['add-to-cart']) ? sanitize_text_field(wp_unslash($_REQUEST['add-to-cart'])) : '';
        if (!class_exists('WC_Form_Handler') || empty($add_to_cart) || false === strpos($add_to_cart, ',')) {
            return;
        }
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        remove_action('wp_loaded', array(
            'WC_Form_Handler',
            'add_to_cart_action',
        ), 20);
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- This continues WooCommerce add-to-cart functionality
        $product_ids = explode(',', $add_to_cart);
        $count = count($product_ids);
        $number = 0;
        foreach ($product_ids as $product_id) {
            if (++$number === $count) {
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                $_REQUEST['add-to-cart'] = $product_id;
                return \WC_Form_Handler::add_to_cart_action();
            }
            $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($product_id));
            $was_added_to_cart = false;
            $adding_to_cart = wc_get_product($product_id);
            if (!$adding_to_cart) {
                continue;
            }
            $add_to_cart_handler = apply_filters('woocommerce_add_to_cart_handler', $adding_to_cart->product_type, $adding_to_cart);
            if ('simple' !== $add_to_cart_handler) {
                continue;
            }
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $quantity = empty($_REQUEST['quantity']) ? 1 : wc_stock_amount(sanitize_text_field(wp_unslash($_REQUEST['quantity'])));
            $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
            $passed_validation && WC()
                ->cart
                ->add_to_cart($product_id, $quantity);
        }
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
    }

    /**
     * Pro Js.
     */
    public static function checkout_Pro_js()
    {
        wp_enqueue_script('iframe-resize', 'https://storage.googleapis.com/unify-uploads/v3/lib/assets/store-front/embedded/v3.0.0/embedded.min.js?v=' . UNIFY_JS_VERSION, [], '1.0', false);
        wp_register_script('checkoutProjs', plugins_url('/../assets/js/checkout-pro.js', __FILE__), '', UNIFY_JS_VERSION, true);
        wp_enqueue_script('checkoutProjs');
        wp_localize_script('checkoutProjs', 'clearCart', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('unify_clear_cart_nonce'),
        ));
    }

    /**
     * Remove admin menu if pro activated
     */
    public static function remove_free_menu()
    {
        remove_submenu_page('unify-dashboard', 'unify-tools');
        remove_submenu_page('unify-dashboard', 'unify-connection');
        remove_submenu_page('unify-dashboard', 'unify-tools');
        remove_submenu_page('unify-dashboard', 'unify-upgrade-to-pro');
        remove_submenu_page('unify-dashboard', 'unify-settings');
        global $submenu;
        $submenu['unify-dashboard'][1] = array(
            '<div id="unify-hub-submenu">Go to Unify Hub</div>',
            'manage_options',
            UNIFY_PLATFORM_LOGIN,
        );
    }

    /**
     * Dynamic selection of domain by param key
     */
    public static function getDomainByParamKey()
    {
        $endpoint = '';
        $action = !empty(Request::get('version')) ? Request::get('version') : '';
        if (!empty($action)) {
            switch (strtolower($action)) {
                case "platform":
                    $endpoint = 'platform.unify.to';
                    break;
                case "sandbox":
                    $endpoint = 'platform-sandbox.unify.to';
                    break;
                default:
                    $endpoint = $action . '-dot-unify-app-cc.appspot.com';
                    break;
            }
        } else {
            $endpoint = '';
        }
        return $endpoint;
    }
    public static function unify_collect_query_params()
    {
        if (!session_id()) {
            session_start();
        }

        // phpcs:disable WordPress.Security.NonceVerification.Missing -- This collects affiliate parameters from URL
        $query_string = isset($_SERVER['QUERY_STRING']) ? sanitize_text_field(wp_unslash($_SERVER['QUERY_STRING'])) : '';
        if (!empty($query_string)) {
            $_SESSION['affiliate_params'] = $query_string;
        }
        // phpcs:enable WordPress.Security.NonceVerification.Missing
    }
    public static function downgrading()
    {
        // Verify nonce for downgrade action
        if (isset($_POST['unify_plugin_downgrade']) && isset($_POST['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'unify_downgrade_nonce')):
            delete_option('codeclouds_unify_pro_license');
            delete_option('upgrde_request_sent');
            delete_option('config_transferred_from_button');
            Helper::dropUnifyOptionsDataTable();
            echo json_encode(['status' => 1]);
        else:
            echo json_encode(['status' => 0, 'msg' => 'Security verification failed']);
        endif;
        exit;
    }
    public static function requestCancellation()
    {
        $request = Request::post('x');
        parse_str($request, $output);
        $user_ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '';
        $param['ip'] = $user_ip;
        $param['name'] = sanitize_text_field($output['first_name']) . " " . sanitize_text_field($output['last_name']);
        $param['email'] = sanitize_text_field($output['email']);
        $param['mobile'] = sanitize_text_field($output['mobile']);
        $param['reason'] = sanitize_text_field($output['reason']);
        $param['store_url'] = site_url();
        $messages = Helper::getDataFromFile('Messages');
        $helper = new Helper();
        $endpoint = $helper->getHubEndpoint();
        $objPlatform = new PlatformApiModel();
        $request_cancellation = $objPlatform->requestCancellation($param, $endpoint);
        if(is_wp_error( $request_cancellation )){
            $error_msg = $messages['COMMON']['ERROR'];
            echo json_encode(['status' => 0, 'msg' => $error_msg]);
        }
        else{
            $response = json_decode($request_cancellation->body, true);
            if ($response['success']) {
                $msg = $messages['REQUEST_UNIFY_PRO']['CANCELLATION_MAIL_SENT'];
                echo json_encode(['status' => 1, 'msg' => $msg]);
            } else {
                $error_msg = $messages['COMMON']['ERROR'];
                echo json_encode(['status' => 0, 'msg' => $error_msg]);
            }
        }
        exit();
    }

    /*
     * Replace URL param name AIC to referred_id
     */

    public static function replaceUrlParamName($paramVals)
    {
        parse_str($paramVals, $params);
        if (array_key_exists('aic', $params)) {
            $keys = array_keys($params);
            $keys[array_search('aic', $keys)] = 'referred_id';
            $data = array_combine($keys, $params);
            return http_build_query($data);
        }
        return http_build_query($params);
    }

    /**Replace weight */

    public static function lbWeight($from)
    {
        $weightFromGram = ($from * 453.59237);
        $weight_from = round($weightFromGram, 2);
        return $weight_from;
    }
    public static function kgWeight($from)
    {
        $weightFromGram = ($from * 1000);
        $weight_from = round($weightFromGram, 2);
        return $weight_from;
    }
    public static function gWeight($from)
    {
        $weight_from = round($from, 2);
        return $weight_from;
    }
    public static function ozWeight($from)
    {
        $weightFromGram = ($from * 28.35);
        $weight_from = round($weightFromGram, 2);
        return $weight_from;
    }
}
