<?php
/*
Plugin Name: WordPress China-Mobile
Plugin URI:  https://brightline.com.sg/roamwifi/
Description: China-Mobile Plugin
Version:     1.0.0
Author:      Jay
Author URI:  https://brightline.com.sg/roamwifi/
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/

if(!defined( 'ABSPATH' )) {
    die;
}

require_once plugin_dir_path( __FILE__ ) . '../wpcompleteautomatc/google-api-php-client/vendor/autoload.php';
//require_once plugin_dir_path( __FILE__ ) . '../google-api-php-client/vendor/autoload.php';

use Google\Client;

class wpcmproductload {
    //properties
    //private $wp_location_trading_hour_days = array();
    
    //magic function (triggered on initialization)
    public function __construct(){
        //run all shortcodes
        add_action('init', array($this, 'register_main_shortcodes')); //shortcodes
        
        //add_action('init', array($this, 'my_script_enqueuer'));
        
        add_action("wp_ajax_chkesim", array($this, 'check_esim'));
        add_action("wp_ajax_nopriv_chkesim", array($this, 'check_esim'));
        
        add_action("wp_ajax_chkdest", array($this, 'check_destination'));
        add_action("wp_ajax_nopriv_chkdest", array($this, 'check_destination'));
        
        add_action("wp_ajax_chkplan", array($this, 'check_dataplan'));
        add_action("wp_ajax_nopriv_chkplan", array($this, 'check_dataplan'));
        
        add_action("wp_ajax_chkprice", array($this, 'check_planprice'));
        add_action("wp_ajax_nopriv_chkprice", array($this, 'check_planprice'));
        
        //add_action("wp_ajax_chkoutpln", array($this, 'plancheckout'));
        add_action("wp_ajax_chkoutpln", array($this, 'complete_form'));
        add_action("wp_ajax_nopriv_chkoutpln", array($this, 'complete_form'));
        
        add_action("wp_ajax_esimchecktest", array($this, 'esim_status_check_test'));
        add_action("wp_ajax_nopriv_esimchecktest", array($this, 'esim_status_check_test'));

        add_action("wp_ajax_chkstatusesim", array($this, 'esim_status_check_result'));
        add_action("wp_ajax_nopriv_chkstatusesim", array($this, 'esim_status_check_result'));

        add_action("wp_ajax_chinamobilegoogleredirect", array($this, 'chinamobilegoogleredirect'));
		
        add_action("wp_ajax_chinamobilegooglepermissionlink", array($this, 'chinamobilegooglepermissionlink'));
		add_action("wp_ajax_nopriv_chinamobilegooglepermissionlink", array($this, 'chinamobilegooglepermissionlink'));
		
        //add_action("wp_ajax_chinamobiletestgoogle", array($this, 'chinamobiletestgoogle'));

        add_action("wp_ajax_chinamobilegooglerefresh", array($this, 'chinamobilegooglerefresh'));
        add_action("wp_ajax_nopriv_chinamobilegooglerefresh", array($this, 'chinamobilegooglerefresh'));

        add_action("wp_ajax_chinamobilestripeactions", array($this, 'chinamobilestripeactions'));
        add_action("wp_ajax_nopriv_chinamobilestripeactions", array($this, 'chinamobilestripeactions'));
    }

    function chinamobilestripeactions() {
        //http://localhost/brightline_v5/wp-admin/admin-ajax.php?action=chinamobilestripeactions

        echo 'Stripe<br/>';

        setting_update("chinamobiletestlog", 'Stripe Test 1');

        echo setting_var("chinamobiletestlog") . '<br/>';

        /*
        date_default_timezone_set("Asia/Singapore");

        global $wpdb;
        $cur_time = date("Y-m-d H:i:s");

        $google_token_expire = setting_var("chinamobile_google_next_token_call");
        $google_cur_time = date("Y-m-d H:i:s");

        //check token expire
        if(strtotime($google_token_expire) <= strtotime($google_cur_time)) {
            $this->chinamobile_googlerefreshtoken();
        }

        $google_content = array();
        $google_content_item = array();

        $google_content_item = array(
            '1',
            '2',
            '3'
        );

        $google_content[] = $google_content_item;

        $this->chinamobile_googlesheetsinsert($google_content);
        */

        exit;
    }

    function chinamobilegooglerefresh() {
        //http://localhost/brightline_v5/wp-admin/admin-ajax.php?action=chinamobilegooglerefresh
		//require_once plugin_dir_path( __FILE__ ) . 'google-api-php-client/vendor/autoload.php';
		
		date_default_timezone_set("Asia/Singapore");

        global $wpdb;
        
        $api_data = array(
            'order_sn' => '9799999989'
        );

        $url = get_site_url() . "/wp-admin/admin-ajax.php?action=ajaxcmmobileiccid";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_data));
        curl_setopt($ch, CURLOPT_HEADER, 0);

        $result = curl_exec($ch);
        $result_arr = json_decode($result, true);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if($http_code != 200) {
            //error
        }
        else {
            echo '<pre>';
            print_r($result_arr);
            echo '</pre>';
			
			sleep(10);

			unlink($result_arr['atth_file_path']);
            
            /*if($result_arr['status'] == 'success') {
                echo '<pre>';
                print_r($result_arr);
                echo '</pre>';
            }
            else {
				//error
            }*/
        }
		
		
		/*
        $cur_time = date("Y-m-d H:i:s");

        $google_token_expire = setting_var("chinamobile_google_next_token_call");
        $google_cur_time = date("Y-m-d H:i:s");
		
		//$accessToken = setting_var("chinamobile_google_access_token");
		//echo $accessToken . '<br/>';
		//echo $cur_time . '<br/>';
		//echo $google_token_expire . '<br/>';
		
        //check token expire
        if(strtotime($google_token_expire) <= strtotime($google_cur_time)) {
            $this->chinamobile_googlerefreshtoken();
        }

        ///////////////////////////////////////////////////////////////

        //Access Google Sheets
        $accessToken = setting_var("chinamobile_google_access_token");
        $config_path = plugin_dir_path( __FILE__ ) . 'client_secret_247568518546-v7mnllgea39hb945a9qlipd9i350f8c1.apps.googleusercontent.com.json';
		
		//$google_token_expire = setting_var("chinamobile_google_next_token_call");
		//echo $accessToken . '<br/>';
		//echo $cur_time . '<br/>';
		//echo $google_token_expire . '<br/>';
		
        // $client = new Client();
        // $client->setApplicationName('Google Sheets API');
        // $client->setScopes([Google_Service_Sheets::SPREADSHEETS]);
        // $client->setAuthConfig($config_path);
        // $client->setAccessType('offline');
        // $client->setAccessToken($accessToken);

        //////
        // $client = new Client();
        // $client->setApplicationName('Google Drive API');
        // $client->setScopes('https://www.googleapis.com/auth/drive');
        // $client->setAuthConfig($config_path);
        // //$client->setAccessType('offline');
        // $client->setAccessToken($accessToken);

        // $drive_service = new Drive($client);
        // $empty_file_meta_data = new DriveFile();
        //////////

        $client = new Client();
        $client->setApplicationName('Google Drive API');
        $client->setScopes('https://www.googleapis.com/auth/drive');
        $client->setAuthConfig($config_path);
        $client->setAccessType('offline');
        $client->setAccessToken($accessToken);

		*/

        //$service = new Drive($client);

		//echo $accessToken . '<br/>';
		//echo $cur_time . '<br/>';
		//echo $google_token_expire . '<br/>';
		
		/*
		$optParams = array(
            'q' => "mimeType contains 'application/vnd.google-apps.folder'",
        );
        
        $results = $service->files->listFiles($optParams);
		
		echo "<pre>";
            print_r($results->getFiles());
        echo "</pre>";
		*/
		
        // Get all Image files only
        // $optParams = array(
        //     'q' => "mimeType contains 'image/'",
        // );

        // Get all Google Sheets only
        // $optParams = array(
        //     'q' => "mimeType contains 'application/vnd.google-apps.spreadsheet'",
        // );

        // Get all Folders only
        // $optParams = array(
        //     'q' => "mimeType contains 'application/vnd.google-apps.folder'",
        // );

        //$pagesize = 1;

        // $optParams = array(
        //     'q' => "'".$esim_folder."' in parents and mimeType contains 'image/'",
        //     'pageSize' => $pagesize,
        //     'orderBy' => "name asc"
        // );

        
		
		
/*
        // if(count($results->getFiles()) > 0) {
        //     if(count($results->getFiles()) == 1) {
        //         foreach($results->getFiles() as $file) {
        //             $return_arr['name'] = $file->getName();
        //             $return_arr['id'] = $file->getId();
        //         }
        //     }
        //     else {
        //         foreach($results->getFiles() as $file) {
        //             $item_arr['name'] = $file->getName();
        //             $item_arr['id'] = $file->getId();

        //             $return_arr[] = $item_arr;
        //         }
        //     }
        // }

        
		*/
		
        //$this->cm_google_sheets_update();

        /*
        date_default_timezone_set("Asia/Singapore");

        global $wpdb;
        $cur_time = date("Y-m-d H:i:s");

        $google_token_expire = setting_var("chinamobile_google_next_token_call");
        $google_cur_time = date("Y-m-d H:i:s");

        //check token expire
        if(strtotime($google_token_expire) <= strtotime($google_cur_time)) {
            $this->chinamobile_googlerefreshtoken();
        }

        $google_content = array();
        $google_content_item = array();

        $google_content_item = array(
            '1',
            '2',
            '3'
        );

        $google_content[] = $google_content_item;

        $this->chinamobile_googlesheetsinsert($google_content);
        */

        exit;
    }

    function chinamobile_googlesheetsinsert($content) {
        date_default_timezone_set("Asia/Singapore");

        global $wpdb;

        $accessToken = setting_var("chinamobile_google_access_token");
        $config_path = plugin_dir_path( __FILE__ ) . 'client_secret_247568518546-v7mnllgea39hb945a9qlipd9i350f8c1.apps.googleusercontent.com.json';

        $client = new Client();
        $client->setApplicationName('Google Sheets API');
        $client->setScopes([Google_Service_Sheets::SPREADSHEETS]);
        $client->setAuthConfig($config_path);
        $client->setAccessType('offline');
        $client->setAccessToken($accessToken);

        $service = new Google_Service_Sheets($client);
        $spreadsheet_id = setting_var("chinamobile_google_sheets_id");

        $range = 'orders';

        $values = $content;

        $body = new Google_Service_Sheets_ValueRange([
            'values' => $values
        ]);

        $params = [
            'valueInputOption' => 'RAW'
        ];

        $result = $service->spreadsheets_values->append(
            $spreadsheet_id,
            $range,
            $body,
            $params
        );

        //log_record('google_sheets_insert', 'Google Sheets Insert Process Log', 'Success', json_encode($result));

        if($result->updates->updatedRows > 0) {
            return $result->updates->updatedRows;
        }
        else {
            return "0";
        }
    }

    function chinamobile_googlerefreshtoken() {
        global $wpdb;

        date_default_timezone_set("Asia/Singapore");

        $google_client_secret = setting_var("chinamobile_google_clientsecret");
        $google_refresh_token = setting_var("chinamobile_google_refresh_token");
        $google_client_id = setting_var("chinamobile_google_clientid");
        $google_margin = setting_var("chinamobile_google_expire_margin");

        $url = "https://oauth2.googleapis.com/token";
        $api_data = array(
            "client_secret" => $google_client_secret,
            "grant_type" => "refresh_token",
            "refresh_token" => $google_refresh_token,
            "client_id" => $google_client_id
        );

        $cur_datetime = date("Y-m-d H:i:s");

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_data));
        curl_setopt($ch, CURLOPT_HEADER, 0);

        $result = curl_exec($ch);
        $result_arr = json_decode($result, true);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        if($http_code != 200) {
            //error
            //email notification

            return false;
        }
        else {
            $new_sed = (int)$result_arr['expires_in'] - (int)$google_margin;
            $next_datetime = date("Y-m-d H:i:s", strtotime($cur_datetime) + $new_sed);

            setting_update("chinamobile_google_access_token", $result_arr['access_token']);
            setting_update("chinamobile_google_token_expires", $result_arr['expires_in']);
            setting_update("chinamobile_google_token_type", $result_arr['token_type']);
            setting_update("chinamobile_google_last_token_call", $cur_datetime);
            setting_update("chinamobile_google_next_token_call", $next_datetime);

            return true;
        }
    }

    function chinamobiletestgoogle() {
        //http://localhost/brightline_v5/wp-admin/admin-ajax.php?action=chinamobiletestgoogle

        date_default_timezone_set("Asia/Singapore");

        global $wpdb;

        //setting_update("chinamobile_google_code", 'Code Test');
        //setting_update("chinamobile_google_scope", 'Scope Test');

        echo setting_var("chinamobile_google_code") . '<br/>';
        echo setting_var("chinamobile_google_scope") . '<br/>';
        echo setting_var("chinamobile_google_callback") . '<br/>';
        echo setting_var("chinamobile_google_clientid") . '<br/>';
        echo setting_var("chinamobile_google_clientsecret") . '<br/>';
        echo setting_var("chinamobile_google_apikey") . '<br/>';
        echo setting_var("chinamobile_google_access_token") . '<br/>';
        echo setting_var("chinamobile_google_token_expires") . '<br/>';
        echo setting_var("chinamobile_google_refresh_token") . '<br/>';
        echo setting_var("chinamobile_google_token_type") . '<br/>';
        echo setting_var("chinamobile_google_last_token_call") . '<br/>';
        echo setting_var("chinamobile_google_next_token_call") . '<br/>';
        echo setting_var("chinamobile_google_expire_margin") . '<br/>';
        echo setting_var("chinamobile_google_sheets_id") . '<br/>';

        exit;
    }

    function chinamobilegooglepermissionlink($redirectstatus = '', $redirectmsg = '') {
        //http://localhost/brightline_v5/wp-admin/admin-ajax.php?action=chinamobilegooglepermissionlink

        date_default_timezone_set("Asia/Singapore");

        $cur_site = site_url(); //http://localhost/brightline_v5

        $url_auth = "https://accounts.google.com/o/oauth2/v2/auth?";
        
        $url_auth .= "redirect_uri=".$cur_site."/wp-admin/admin-ajax.php?action=chinamobilegoogleredirect";
        
        $url_auth .= "&prompt=consent&response_type=code&client_id=247568518546-v7mnllgea39hb945a9qlipd9i350f8c1.apps.googleusercontent.com&scope=https://www.googleapis.com/auth/spreadsheets+https://www.googleapis.com/auth/drive+https://www.googleapis.com/auth/userinfo.email&access_type=offline";

        echo "<h1>Google Permission Request</h1>";
        echo '<a href="'.$url_auth.'">Request Google By Click This Link Now</a>';

        exit;
    }

    function chinamobilegoogleredirect() {
        //http://localhost/brightline_v5/wp-admin/admin-ajax.php?action=chinamobilegoogleredirect

        date_default_timezone_set("Asia/Singapore");

        $auth_url = '';
        $auth_code = '';
        $auth_scope = '';

        if(!empty($_SERVER[REQUEST_URI])) {
            $auth_url = htmlentities($_SERVER[REQUEST_URI], ENT_QUOTES);
        }

        if(!empty($_GET['code'])) {
            $auth_code = htmlentities($_GET['code'], ENT_QUOTES);
        }

        if(!empty($_GET['scope'])) {
            $auth_scope = htmlentities($_GET['scope'], ENT_QUOTES);
        }

        setting_update("chinamobile_google_code", $auth_code);
        setting_update("chinamobile_google_scope", $auth_scope);
        setting_update("chinamobile_google_callback", $auth_url);
        
        //Generate first token
        $url = "https://oauth2.googleapis.com/token";
        $google_client_id = setting_var("chinamobile_google_clientid");
        $google_client_secret = setting_var("chinamobile_google_clientsecret");
        $google_margin = setting_var("chinamobile_google_expire_margin");

        $cur_site = site_url(); //http://localhost/brightline_v5

        $cur_datetime = date("Y-m-d H:i:s");
        
        $api_data = array(
            "code" => $auth_code,
            "client_id" => $google_client_id,
            "client_secret" => $google_client_secret,
            "redirect_uri" => $cur_site . "/wp-admin/admin-ajax.php?action=chinamobilegoogleredirect",
            "grant_type" => "authorization_code"
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($api_data));
        curl_setopt($ch, CURLOPT_HEADER, 0);

        $result = curl_exec($ch);
        $result_arr = json_decode($result, true);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if($http_code != 200) {
            //error

            $callback_status = "failed";
            $callback_msg = "Google Permission Successfully Granted";
        }
        else {
            $new_sed = (int)$result_arr['expires_in'] - (int)$google_margin;
            $next_datetime = date("Y-m-d H:i:s", strtotime($cur_datetime) + $new_sed);

            setting_update("chinamobile_google_access_token", $result_arr['access_token']);
            setting_update("chinamobile_google_token_expires", $result_arr['expires_in']);
            setting_update("chinamobile_google_refresh_token", $result_arr['refresh_token']);
            setting_update("chinamobile_google_token_type", $result_arr['token_type']);
            setting_update("chinamobile_google_last_token_call", $cur_datetime);
            setting_update("chinamobile_google_next_token_call", $next_datetime);

            $callback_status = "success";
            $callback_msg = "Google Permission Successfully Granted";
        }

        $callback_msg = urlencode($callback_msg);

        $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;

        $redirect_to = admin_url('edit.php?post_type=shop_order' . $callback_param);
        wp_safe_redirect($redirect_to);
        exit;
    }
    
    function my_script_enqueuer() {
        //wp_register_script( "my_voter_script", WP_PLUGIN_URL.'/my_plugin/my_voter_script.js', array('jquery') );
        //wp_localize_script( 'cmproductload', 'maincmAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        

        //wp_enqueue_script( 'jquery' );
        //wp_enqueue_script( 'cmproductload' );
    }

    //Register all shortcodes here...
    public function register_main_shortcodes(){
        add_shortcode('main_cmproductload', array($this, 'main_shortcode_output'));
        add_shortcode('cmproduct_order_completion', array($this, 'cm_order_completion'));
        add_shortcode('cmgoogle_sheets', array($this, 'cm_google_sheets_update'));
        
        add_shortcode('cmcronjob_orders', array($this, 'china_mobile_cronjob'));
        add_shortcode('cmstatus_esim_check', array($this, 'china_mobile_esim_status_check'));
    }
    
    public function cm_google_sheets_update($order_info = array()) {
        date_default_timezone_set("Asia/Singapore");

        global $wpdb;
        //$cur_time = date("Y-m-d H:i:s");

        $google_token_expire = setting_var("chinamobile_google_next_token_call");
        $google_cur_time = date("Y-m-d H:i:s");

        //check token expire
        if(strtotime($google_token_expire) <= strtotime($google_cur_time)) {
            $this->chinamobile_googlerefreshtoken();
        }

        $google_content = array();
        $google_content_item = array();

        if(empty($order_info)) {
            // $google_content_item = array(
            //     '11',
            //     '12',
            //     '13',
            //     '14',
            //     '15',
            //     '16',
            //     '17',
            //     '18',
            //     '19',
            //     '20'
            // );
        }
        else {
            $google_content_item = array(
                $order_info['worderid'], //website order no
                $order_info['worderttl'], //order total
                $order_info['worderstatus'], //order status
                $order_info['infosku'], //sku
                $order_info['infoesim'], //esim
                $order_info['infodes'], //destination
                $order_info['infoplan'], //plan
                $order_info['infoemail'], //email
                $order_info['chinaorderid'], //china mobile order no
                $order_info['chinastatus'] //china mobile order status
            );
        }

        $google_content[] = $google_content_item;

        //Access Google Sheets
        $accessToken = setting_var("chinamobile_google_access_token");
        $config_path = plugin_dir_path( __FILE__ ) . 'client_secret_247568518546-v7mnllgea39hb945a9qlipd9i350f8c1.apps.googleusercontent.com.json';

        $client = new Client();
        $client->setApplicationName('Google Sheets API');
        $client->setScopes([Google_Service_Sheets::SPREADSHEETS]);
        $client->setAuthConfig($config_path);
        $client->setAccessType('offline');
        $client->setAccessToken($accessToken);

        $service = new Google_Service_Sheets($client);
        $spreadsheet_id = setting_var("chinamobile_google_sheets_id");

        $range = 'orders';

        $values = $google_content;

        $body = new Google_Service_Sheets_ValueRange([
            'values' => $values
        ]);

        $params = [
            'valueInputOption' => 'RAW'
        ];

        $result = $service->spreadsheets_values->append(
            $spreadsheet_id,
            $range,
            $body,
            $params
        );

        if($result->updates->updatedRows > 0) {
            return $result->updates->updatedRows;
        }
        else {
            return "0";
        }
    }
    
    public function cm_order_completion() {
        $ourput = '';
        
        if(!empty($_GET['action']) && !empty($_GET['orderid']) && !empty($_GET['status']) && !empty($_GET['trans']) && $_GET['action'] == 'transaction') {
            $action_val = htmlentities($_GET['action'], ENT_QUOTES);
            $orderid_val = (int)htmlentities($_GET['orderid'], ENT_QUOTES);
            $status_val = htmlentities($_GET['status'], ENT_QUOTES);
            $trans_val = htmlentities($_GET['trans'], ENT_QUOTES);
            
            $order_private_key = get_post_meta($orderid_val, '_order_cm_private_key', true);
            $order_private_count = (int)get_post_meta($orderid_val, '_order_cm_private_count', true);
            
            if($order_private_key == $trans_val) {
                if($status_val == 'success') {
                    if($order_private_count == 0) {
                        $email_admin_error = false;
                        $email_details = "";

                        //processing, on-hold, cancelled, completed
                        $order = new WC_Order($orderid_val);
                        $order->update_status('completed');

                        $get_order_sku = '';
                        $get_order_esim = '';

                        foreach($order->get_items() as $item_id => $item) {
                            $get_order_sku = $item->get_meta('SKU', true);
                            $get_order_esim = $item->get_meta('eSim', true);

                            //echo $item->get_meta('eSim', true) . '<br/>';
                            //echo $item->get_meta('Destination Name', true) . '<br/>';
                            //echo $item->get_meta('Plan', true) . '<br/>';
                            //echo $item->get_meta('Email', true) . '<br/>';
                            //echo $item->get_meta('SKU', true) . '<br/>';

                            //echo '<pre>';
                            //print_r($item->get_meta_data());
                            //echo '</pre>';
                        }

                        if(!empty($get_order_sku) && !empty($get_order_esim)) {
                            //create order in China Mobile and update the order notes
                            //$api_secret = '950c543a19c9485b98222096bdf55abd';
                            //$api_key = 'f10743ea54cf4f86a084adf1e54a5695';
                            $api_secret = get_option('chinamobile_api_appsecret');
                            $api_key = get_option('chinamobile_api_appkey');

                            $access_func = 'APP_getAccessToken_SBO/v1';
                            $access_tokent = '';
                            $access_data = array(
                                "id" => $api_key, 
                                "type" => "106"
                            );

                            $access_res = $this->china_mobile_api_call($api_secret, $api_key, $access_func, $access_tokent, $access_data);
                            //if($access_res['status'] == 'success' && $access_res['data']['code'] == '0000000') {
                            if($access_res['status'] == 'success') {
                                $order_func = 'APP_createOrder_SBO/v1';
                                $order_tokent = $access_res['data']['accessToken'];
                                $order_data = array(
                                    "accessToken" => $access_res['data']['accessToken'],
                                    "thirdOrderId" => $orderid_val, //Order ID Woocommerce
                                    "includeCard" => "0", //0: Does not contain
                                    "is_Refuel" => "1", //1: It's not
                                    "dataBundleId" => $get_order_sku, //Global 146 Destinations - $7.23
                                    "cardForm" => "2",
                                    "quantity" => "1",
                                    "ICCID" => $get_order_esim,
                                    "sendLang" => "2"
                                );
                                
                                //"setActiveTime" => date("Ymd", time() + 86400)
                                
                                $order_res = $this->china_mobile_api_call($api_secret, $api_key, $order_func, $order_tokent, $order_data);

                                if($order_res['status'] == 'success') {
                                    $note_str = "China Mobile Order Complete. Order Info: Code: " . 
                                        $order_res['data']['code'] . ", Description: " . $order_res['data']['description'] . 
                                        ", OrderID: " . $order_res['data']['orderID'] . ", Total Amount: " . $order_res['data']['totalAmount'] . 
                                        ", Qty: " . $order_res['data']['quantity'] . ", Price: " . $order_res['data']['price'] . 
                                        ", Currency: " . $order_res['data']['currency'];
                                    $order->add_order_note($note_str);
                                    
                                    update_post_meta($order->id, '_order_cm_private_count', '1');
                                    
                                    $google_values = array(
                                        'worderid' => $order->id, //website order no
                                        'worderttl' => $order->get_currency() . ' ' . $order->get_total(), //order total
                                        'worderstatus' => 'Completed', //order status
                                        'infosku' => get_post_meta($order->id, '_order_info_cm_sku', true), //SKU
                                        'infoesim' => get_post_meta($order->id, '_order_info_cm_esim', true), //esim
                                        'infodes' => get_post_meta($order->id, '_order_info_cm_destination', true), //destination
                                        'infoplan' => get_post_meta($order->id, '_order_info_cm_plan', true), //plan
                                        'infoemail' => get_post_meta($order->id, '_order_info_cm_email', true), //email
                                        'chinaorderid' => $order_res['data']['orderID'], //china mobile order no
                                        'chinastatus' => $order_res['data']['description'] //china mobile order status
                                    );
                                    
                                    $sc_first_trial_result = $this->cm_google_sheets_update($google_values);

                                    if($sc_first_trial_result > 0) {
                                        //done
                                    }
                                    else {
                                        //Second trial
                                        $this->cm_google_sheets_update($google_values);
                                    }
                                }
                                else {
                                    $note_str = "China Mobile Order Failed. Error: " . $order_res['data']['code'] . " - " . $order_res['data']['description'];
                                    $order->add_order_note($note_str);
                                    
                                    $order->add_order_note("APP_createOrder_SBO: " . json_encode($order_data));
                                    
                                    $email_admin_error = true;
                                    $email_details .= "Website Order ID: #" . $orderid_val . "<br/>";
                                    $email_details .= "eSim: " . $get_order_esim . "<br/>";
                                    $email_details .= "Plan: " . $get_order_sku . "<br/>";
                                    $email_details .= "Error: " . $order_res['data']['code'] . " - " . $order_res['data']['description'] . "<br/>";
                                    
                                    $google_values = array(
                                        'worderid' => $order->id, //website order no
                                        'worderttl' => $order->get_currency() . ' ' . $order->get_total(), //order total
                                        'worderstatus' => 'Completed', //order status
                                        'infosku' => get_post_meta($order->id, '_order_info_cm_sku', true), //SKU
                                        'infoesim' => get_post_meta($order->id, '_order_info_cm_esim', true), //esim
                                        'infodes' => get_post_meta($order->id, '_order_info_cm_destination', true), //destination
                                        'infoplan' => get_post_meta($order->id, '_order_info_cm_plan', true), //plan
                                        'infoemail' => get_post_meta($order->id, '_order_info_cm_email', true), //email
                                        'chinaorderid' => '', //china mobile order no
                                        'chinastatus' => $order_res['data']['code'] . " - " . $order_res['data']['description'] //china mobile order status
                                    );
                                    
                                    $fa_first_trial_result = $this->cm_google_sheets_update($google_values);

                                    if($fa_first_trial_result > 0) {
                                        //done
                                    }
                                    else {
                                        //Second trial
                                        $this->cm_google_sheets_update($google_values);
                                    }
                                }
                            }
                            else {
                                $note_str = "China Mobile Order Failed. Error: " . $access_res['data']['code'] . " - " . $access_res['data']['description'];
                                $order->add_order_note($note_str);
                                
                                $order->add_order_note("APP_getAccessToken_SBO: " . json_encode($access_data));
                                
                                $email_admin_error = true;
                                $email_details .= "Website Order ID: #" . $orderid_val . "<br/>";
                                $email_details .= "eSim: " . $get_order_esim . "<br/>";
                                $email_details .= "Plan: " . $get_order_sku . "<br/>";
                                $email_details .= "Error: " . $access_res['data']['code'] . " - " . $access_res['data']['description'] . "<br/>";
                            }
                        }
                        else {
                            $note_str = "China Mobile Order Failed. Cannot found eSim and Product SKU - Package ID";
                            $order->add_order_note($note_str);

                            $email_admin_error = true;
                            $email_details .= "Error: China Mobile Order Failed. Cannot found eSim and Product SKU - Package ID.<br/>";
                        }

                        if($email_admin_error) {
                            //email admin for the error
                            $wc_emails = WC()->mailer()->get_emails();
                            $email_rec = $wc_emails['WC_Email_Cancelled_Order']->recipient;
                            $email_sub = "China Mobile - Order Failed - #" . $orderid_val;
                            $email_head = "China Mobile - Order Failed - #" . $orderid_val;
                            $email_msg = "Order Failed - Details:<br/>";
                            $email_msg .= $email_details;

                            $this->send_email_cm_failed($email_rec, $email_sub, $email_head, $email_msg);
                        }
                    }
                    
                    $ourput .= 'Thank you for your purchased. The order is successfully placed.';
                }
                else if($status_val == 'failed') {
                    //processing, on-hold, cancelled, completed
                    $order = new WC_Order($orderid_val);
                    $order->update_status('cancelled');
                    
                    $ourput .= 'Very sorry, your order has been cancelled.';
                }
                else {
                    $ourput .= 'Very sorry, your order has been declined.';
                }
            }
            else {
                $ourput .= 'Very sorry, your transaction has been declined.';
            }
        }
        else {
            $ourput .= 'Very sorry, we cannot found your order.';
        }
        
        echo '<h2 style="text-align:center;">';
            echo $ourput;
        echo '</h2>';
    }
    
    public function china_mobile_cronjob() {
        global $wpdb;
        
        $orders_arr = array();
        $final_email_content_arr = array();
        $last_order_id = '';
        $last_order_run = '';
        $email_admin_error = false;
        
        $cronjob_last_id = get_option('chinamobile_api_cronjob_last_id');
        
        $qry_orders = "SELECT * FROM ".$wpdb->prefix."posts WHERE post_type='shop_order' AND post_status='wc-completed' AND ID>'".$cronjob_last_id."' ORDER BY ID ASC";
        $rs_orders = $wpdb->get_results($qry_orders, ARRAY_A);
        
        if($rs_orders) {
            foreach($rs_orders as $rs_order) {
                $orders_arr[] = $rs_order['ID'];
            }
        }
        
        if(count($orders_arr) > 0) {
            $orders_str = implode(",", $orders_arr);
            
            $qry_pvcounts = "SELECT * FROM ".$wpdb->prefix."postmeta WHERE post_id IN(".$orders_str.") AND meta_key='_order_cm_private_count' AND meta_value='0'";
            $rs_pvcounts = $wpdb->get_results($qry_pvcounts, ARRAY_A);
        
            if($rs_pvcounts) {
                foreach($rs_pvcounts as $rs_pvcount) {
                    $order = new WC_Order($rs_pvcount['post_id']);
                    
                    //echo 'Order ID: ' . $order->id . '<br/>';
                    //echo '_eSim: ' . get_post_meta($order->id, '_order_info_cm_esim', true) . '<br/>';
                    
                    //$order_private_key = get_post_meta($order->id, '_order_cm_private_key', true);
                    //$order_private_count = (int)get_post_meta($order->id, '_order_cm_private_count', true);
                    
                    $email_admin_error = false;
                    $email_details = "";
                    $get_order_sku = '';
                    $get_order_esim = '';

                    foreach($order->get_items() as $item_id => $item) {
                        $get_order_sku = $item->get_meta('SKU', true);
                        $get_order_esim = $item->get_meta('eSim', true);
                        
                        //echo 'SKU: ' . $get_order_sku . '<br/>';
                        //echo 'eSim: ' . $get_order_esim . '<br/>';
                    }
                    
                    //$this->cm_google_sheets_update();
                    //echo '==========<br/>';
                    
                    
                    if(!empty($get_order_sku) && !empty($get_order_esim)) {
                        //create order in China Mobile and update the order notes
                        $api_secret = get_option('chinamobile_api_appsecret');
                        $api_key = get_option('chinamobile_api_appkey');

                        $access_func = 'APP_getAccessToken_SBO/v1';
                        $access_tokent = '';
                        $access_data = array(
                            "id" => $api_key, 
                            "type" => "106"
                        );

                        $access_res = $this->china_mobile_api_call($api_secret, $api_key, $access_func, $access_tokent, $access_data);
                        //if($access_res['status'] == 'success' && $access_res['data']['code'] == '0000000') {
                        if($access_res['status'] == 'success') {
                            $order_func = 'APP_createOrder_SBO/v1';
                            $order_tokent = $access_res['data']['accessToken'];
                            $order_data = array(
                                "accessToken" => $access_res['data']['accessToken'],
                                "thirdOrderId" => $order->id, //Order ID Woocommerce
                                "includeCard" => "0", //0: Does not contain
                                "is_Refuel" => "1", //1: It's not
                                "dataBundleId" => $get_order_sku, //Global 146 Destinations - $7.23
                                "cardForm" => "2",
                                "quantity" => "1",
                                "ICCID" => $get_order_esim,
                                "sendLang" => "2"
                            );

                            //"setActiveTime" => date("Ymd", time() + 86400)

                            $order_res = $this->china_mobile_api_call($api_secret, $api_key, $order_func, $order_tokent, $order_data);

                            if($order_res['status'] == 'success') {
                                $note_str = "China Mobile Order Complete. Order Info: Code: " . 
                                    $order_res['data']['code'] . ", Description: " . $order_res['data']['description'] . 
                                    ", OrderID: " . $order_res['data']['orderID'] . ", Total Amount: " . $order_res['data']['totalAmount'] . 
                                    ", Qty: " . $order_res['data']['quantity'] . ", Price: " . $order_res['data']['price'] . 
                                    ", Currency: " . $order_res['data']['currency'];
                                $order->add_order_note($note_str);

                                update_post_meta($order->id, '_order_cm_private_count', '1');

                                $google_values = array(
                                    'worderid' => $order->id, //website order no
                                    'worderttl' => $order->get_currency() . ' ' . $order->get_total(), //order total
                                    'worderstatus' => 'Completed', //order status
                                    'infosku' => get_post_meta($order->id, '_order_info_cm_sku', true), //SKU
                                    'infoesim' => get_post_meta($order->id, '_order_info_cm_esim', true), //esim
                                    'infodes' => get_post_meta($order->id, '_order_info_cm_destination', true), //destination
                                    'infoplan' => get_post_meta($order->id, '_order_info_cm_plan', true), //plan
                                    'infoemail' => get_post_meta($order->id, '_order_info_cm_email', true), //email
                                    'chinaorderid' => $order_res['data']['orderID'], //china mobile order no
                                    'chinastatus' => $order_res['data']['description'] //china mobile order status
                                );

                                $su_first_trial_result = $this->cm_google_sheets_update($google_values);
                                
                                if($su_first_trial_result > 0) {
                                    //done
                                }
                                else {
                                    //Second trial
                                    $this->cm_google_sheets_update($google_values);
                                }

                                $final_email_content_arr[] = $google_values;
                            }
                            else {
                                $note_str = "China Mobile Order Failed. Error: " . $order_res['data']['code'] . " - " . $order_res['data']['description'];
                                $order->add_order_note($note_str);

                                $order->add_order_note("APP_createOrder_SBO: " . json_encode($order_data));
                                
                                //$email_admin_error = true;
                                //$email_details .= "Website Order ID: #" . $orderid_val . "<br/>";
                                //$email_details .= "eSim: " . $get_order_esim . "<br/>";
                                //$email_details .= "Plan: " . $get_order_sku . "<br/>";
                                //$email_details .= "Error: " . $order_res['data']['code'] . " - " . $order_res['data']['description'] . "<br/>";

                                $google_values = array(
                                    'worderid' => $order->id, //website order no
                                    'worderttl' => $order->get_currency() . ' ' . $order->get_total(), //order total
                                    'worderstatus' => 'Completed', //order status
                                    'infosku' => get_post_meta($order->id, '_order_info_cm_sku', true), //SKU
                                    'infoesim' => get_post_meta($order->id, '_order_info_cm_esim', true), //esim
                                    'infodes' => get_post_meta($order->id, '_order_info_cm_destination', true), //destination
                                    'infoplan' => get_post_meta($order->id, '_order_info_cm_plan', true), //plan
                                    'infoemail' => get_post_meta($order->id, '_order_info_cm_email', true), //email
                                    'chinaorderid' => '', //china mobile order no
                                    'chinastatus' => $order_res['data']['code'] . " - " . $order_res['data']['description'] //china mobile order status
                                );

                                $fa_first_trial_result = $this->cm_google_sheets_update($google_values);
                                
                                if($fa_first_trial_result > 0) {
                                    //done
                                }
                                else {
                                    //Second trial
                                    $this->cm_google_sheets_update($google_values);
                                }

                                $final_email_content_arr[] = $google_values;
                            }
                        }
                        else {
                            $note_str = "China Mobile Order Failed. Error: " . $access_res['data']['code'] . " - " . $access_res['data']['description'];
                            $order->add_order_note($note_str);
                            
                            $order->add_order_note("APP_getAccessToken_SBO: " . json_encode($access_data));
                            
                            $order_summary_arr = array(
                                'worderid' => $order->id, //website order no
                                'worderttl' => $order->get_currency() . ' ' . $order->get_total(), //order total
                                'worderstatus' => 'Completed', //order status
                                'infosku' => get_post_meta($order->id, '_order_info_cm_sku', true), //SKU
                                'infoesim' => get_post_meta($order->id, '_order_info_cm_esim', true), //esim
                                'infodes' => get_post_meta($order->id, '_order_info_cm_destination', true), //destination
                                'infoplan' => get_post_meta($order->id, '_order_info_cm_plan', true), //plan
                                'infoemail' => get_post_meta($order->id, '_order_info_cm_email', true), //email
                                'chinaorderid' => '', //china mobile order no
                                'chinastatus' => "China Mobile Order Failed. Error: " . $access_res['data']['code'] . " - " . $access_res['data']['description'] //china mobile order status
                            );

                            $final_email_content_arr[] = $order_summary_arr;
                            
                            //$email_admin_error = true;
                            //$email_details .= "Website Order ID: #" . $orderid_val . "<br/>";
                            //$email_details .= "eSim: " . $get_order_esim . "<br/>";
                            //$email_details .= "Plan: " . $get_order_sku . "<br/>";
                            //$email_details .= "Error: " . $access_res['data']['code'] . " - " . $access_res['data']['description'] . "<br/>";
                        }
                    }
                    else {
                        $note_str = "China Mobile Order Failed. Cannot found eSim and Product SKU - Package ID";
                        $order->add_order_note($note_str);
                        
                        $order_summary_arr = array(
                            'worderid' => $order->id, //website order no
                            'worderttl' => $order->get_currency() . ' ' . $order->get_total(), //order total
                            'worderstatus' => 'Completed', //order status
                            'infosku' => get_post_meta($order->id, '_order_info_cm_sku', true), //SKU
                            'infoesim' => get_post_meta($order->id, '_order_info_cm_esim', true), //esim
                            'infodes' => get_post_meta($order->id, '_order_info_cm_destination', true), //destination
                            'infoplan' => get_post_meta($order->id, '_order_info_cm_plan', true), //plan
                            'infoemail' => get_post_meta($order->id, '_order_info_cm_email', true), //email
                            'chinaorderid' => '', //china mobile order no
                            'chinastatus' => "Error: China Mobile Order Failed. Cannot found eSim and Product SKU - Package ID." //china mobile order status
                        );

                        $final_email_content_arr[] = $order_summary_arr;
                        
                        //$email_admin_error = true;
                        //$email_details .= "Error: China Mobile Order Failed. Cannot found eSim and Product SKU - Package ID.<br/>";
                    }
                }
            }
            
            if(count($final_email_content_arr) > 0) {
                $ttl_email_loop = count($final_email_content_arr);
                
                $build_html_table = '<table>';
                    $build_html_table .= '<tr>';
                        $build_html_table .= '<td>';
                            $build_html_table .= '<b>Order No</b>';
                        $build_html_table .= '</td>';
                        $build_html_table .= '<td>';
                            $build_html_table .= '<b>Order Status</b>';
                        $build_html_table .= '</td>';
                        $build_html_table .= '<td>';
                            $build_html_table .= '<b>SKU</b>';
                        $build_html_table .= '</td>';
                        $build_html_table .= '<td>';
                            $build_html_table .= '<b>eSIM ICCID</b>';
                        $build_html_table .= '</td>';
                        $build_html_table .= '<td>';
                            $build_html_table .= '<b>Destination</b>';
                        $build_html_table .= '</td>';
                        $build_html_table .= '<td>';
                            $build_html_table .= '<b>Plan</b>';
                        $build_html_table .= '</td>';
                        $build_html_table .= '<td>';
                            $build_html_table .= '<b>China Mobile Order</b>';
                        $build_html_table .= '</td>';
                        $build_html_table .= '<td>';
                            $build_html_table .= '<b>China Mobile Order Status</b>';
                        $build_html_table .= '</td>';
                    $build_html_table .= '</tr>';
                    
                    for($e=0; $e<$ttl_email_loop; $e++) {
                        //$final_email_content_arr[$e]['worderttl'];
                        //$final_email_content_arr[$e]['infoemail'];
                        
                        $build_html_table .= '<tr>';
                            $build_html_table .= '<td>';
                                $build_html_table .= $final_email_content_arr[$e]['worderid'];
                            $build_html_table .= '</td>';
                            $build_html_table .= '<td>';
                                $build_html_table .= $final_email_content_arr[$e]['worderstatus'];
                            $build_html_table .= '</td>';
                            $build_html_table .= '<td>';
                                $build_html_table .= $final_email_content_arr[$e]['infosku'];
                            $build_html_table .= '</td>';
                            $build_html_table .= '<td>';
                                $build_html_table .= $final_email_content_arr[$e]['infoesim'];
                            $build_html_table .= '</td>';
                            $build_html_table .= '<td>';
                                $build_html_table .= $final_email_content_arr[$e]['infodes'];
                            $build_html_table .= '</td>';
                            $build_html_table .= '<td>';
                                $build_html_table .= $final_email_content_arr[$e]['infoplan'];
                            $build_html_table .= '</td>';
                            $build_html_table .= '<td>';
                                $build_html_table .= $final_email_content_arr[$e]['chinaorderid'];
                            $build_html_table .= '</td>';
                            $build_html_table .= '<td>';
                                $build_html_table .= $final_email_content_arr[$e]['chinastatus'];
                            $build_html_table .= '</td>';
                        $build_html_table .= '</tr>';
                    }
                    
                $build_html_table .= '</table>';
                
                $wc_emails = WC()->mailer()->get_emails();
                $email_rec = $wc_emails['WC_Email_New_Order']->recipient;
                //$email_rec = $wc_emails['WC_Email_Cancelled_Order']->recipient;
                $email_sub = "Conjob Run - China Mobile Orders";
                $email_head = "Conjob Run - China Mobile Orders";
                $email_msg = "Below is the order(s) process in background cronjob:<br/><br/>";
                $email_msg .= $build_html_table;

                $this->send_email_cm_failed($email_rec, $email_sub, $email_head, $email_msg);
            }
        }
        
        //update last order number
        $qry_max_orders = "SELECT ID, NOW() AS currun FROM ".$wpdb->prefix."posts WHERE post_type='shop_order' ORDER BY ID DESC LIMIT 1";
        $rs_max_orders = $wpdb->get_results($qry_max_orders, ARRAY_A);
        
        if($rs_max_orders) {
            foreach($rs_max_orders as $rs_max_order) {
                $last_order_id = $rs_max_order['ID'];
                $last_order_run = $rs_max_order['currun'];
            }
            
            //update the last order id by cronjob
            update_option('chinamobile_api_cronjob_last_id', $last_order_id);
            update_option('chinamobile_api_cronjob_last_run', $last_order_run);
        }
    }
    
    public function china_mobile_api_call($api_secret, $api_key, $api_func, $api_tokent = '', $api_data = array()) {
        
        /*
        //$api_secret = '950c543a19c9485b98222096bdf55abd';
        //$api_key = 'f10743ea54cf4f86a084adf1e54a5695';
        $api_secret = get_option('chinamobile_api_appsecret');
        $api_key = get_option('chinamobile_api_appkey');
        
        $access_func = 'APP_getAccessToken_SBO/v1';
        $access_tokent = '';
        $access_data = array(
            "id" => $api_key, 
            "type" => "106"
        );

        $access_res = $this->china_mobile_api_call($api_secret, $api_key, $access_func, $access_tokent, $access_data);
        */
        
        
        $output_result = array();
        
        $api_host = get_option('chinamobile_api_host');
        $url = $api_host . $api_func;

        //date_default_timezone_set('Asia/Shanghai');
        date_default_timezone_set('UTC');
        $now = date('Y-m-d\TH:i:s\Z');
        $nonce = uniqid();
        //$api_secret = '950c543a19c9485b98222096bdf55abd';
        //$api_key = 'f10743ea54cf4f86a084adf1e54a5695';
        
        $combine_str = $nonce . $now . $api_secret;
        $combine_str_utf = utf8_decode($combine_str);

        $passwordDigest = base64_encode(hash('sha256', $combine_str_utf, true));

        $header = array(
            'Content-Type: application/json',
            'Authorization: WSSE realm="SDP", profile="UsernameToken", type="Appkey"',
            'X-WSSE: UsernameToken Username="'.$api_key.'", PasswordDigest="'.$passwordDigest.'", Nonce="'.$nonce.'", Created="'.$now.'"'
        );

        //$api_data = array(
        //    "id" => "f10743ea54cf4f86a084adf1e54a5695", 
        //    "type" => "106"
        //);

        $data = json_encode($api_data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);

        if(curl_errno($ch)) {
            $error_msg = curl_error($ch);
            
            $output_result['status'] = 'error';
            $output_result['msg'] = $error_msg;
            $output_result['data'] = array();
        }
        else {
            $result_arr = json_decode($result, true);
            
            if($result_arr['code'] == '0000000') {
                $output_result['status'] = 'success';
                $output_result['msg'] = '';
                $output_result['data'] = $result_arr;
            }
            else {
                $output_result['status'] = 'failed';
                $output_result['msg'] = '';
                $output_result['data'] = $result_arr;
            }
        }

        curl_close($ch);

        return $output_result;
    }
    
    public function send_email_cm_failed($email, $subject, $heading, $message) {
        $email_header = array('Content-Type: text/html; charset=UTF-8');
        
        //Get woocommerce mailer from instance
        $mailer = WC()->mailer();

        //Wrap message using woocommerce html email template
        $wrapped_message = $mailer->wrap_message($heading, $message);

        //Create new WC_Email instance
        $wc_email = new WC_Email;

        //Style the wrapped message with woocommerce inline styles
        $html_message = $wc_email->style_inline($wrapped_message);

        //Send the email using wordpress mail function
        $mailer->send($email, $subject, $html_message, $email_header);
    }

    public function complete_form() {
        if(!wp_verify_nonce($_POST['nonce'], "check_form_nonce")) {
            die();
        }
        
        if(!empty($_POST['proid']) && !empty($_POST['esim'])) {
            require_once plugin_dir_path( __FILE__ ) . 'stripe' . DIRECTORY_SEPARATOR . 'init.php';
            
            global $wpdb;
            $result = array();
            
            $stripe_secret_key = get_option('chinamobile_api_randomkey');
            \Stripe\Stripe::setApiKey($stripe_secret_key);
            
            $proid = htmlentities($_POST['proid'], ENT_QUOTES);
            $esim = htmlentities($_POST['esim'], ENT_QUOTES);
            $emailaddr = htmlentities($_POST['chkemail'], ENT_QUOTES);
            
            //Voucher code
            $vou_code = htmlentities($_POST['vou_code'], ENT_QUOTES);
            $vou_num = (int)htmlentities($_POST['vou_num'], ENT_QUOTES);
            $vou_status = htmlentities($_POST['vou_status'], ENT_QUOTES);
            $vou_type = htmlentities($_POST['vou_type'], ENT_QUOTES);
            $vou_val = htmlentities($_POST['vou_val'], ENT_QUOTES);
            
            $do_discount = false;
            $rs_vou_iccid_type = '';
            $rs_vou_type = '';
            $rs_vou_val = '';
            $rs_vou_code = '';
            
            if(is_user_logged_in()) {
                $current_user = wp_get_current_user();
                $user_id = $current_user->ID;
            }
            else {
                $username_arr = explode("@", $emailaddr);
                $username = $username_arr[0];
                
                $password = 'newAcc#w8rd';
                
                if(username_exists($username)) {
                    $username = $username . $this->generateRandomString(6);
                }
                
                $chk_user = get_user_by('email', $emailaddr);
                if(!$chk_user) {
                    $user_id = wp_create_user($username, $password, $emailaddr);
                    
                    $user = new WP_User($user_id);
                    $user->set_role('customer');
                }
                else {
                    $user_id = $chk_user->ID;
                }
            }

            $product = wc_get_product($proid);
            $prod_sku = $product->get_sku();

            // $qry_proinfo = "SELECT * FROM ".$wpdb->prefix."woocommerce_cm_products WHERE cm_pack_id='".$prod_sku."'";

            /*
            $address = array(
                'first_name' => $current_user->user_firstname,
                'last_name' => $current_user->user_lastname,
                'company'  => '',
                'email' => $current_user->user_email,
                'phone' => get_user_meta($current_user, 'phone_number', true),
                'address_1' => get_user_meta($current_user->ID, 'billing_address_1', true),
                'address_2' => get_user_meta($current_user->ID, 'billing_address_2', true), 
                'city' => get_user_meta($current_user->ID, 'billing_city', true),
                'state' => get_user_meta($current_user->ID, 'billing_state', true),
                'postcode' => get_user_meta($current_user->ID, 'billing_postcode', true),
                'country' => get_user_meta($current_user->ID, 'billing_country', true)
            );
            */
            
            if($vou_status == '1') {
                //////////////////////////
                // original code
                // $qry_vou = "SELECT *, DATE_FORMAT(vou_expiry_date, '%Y-%m-%d') AS new_expiry_date FROM " . $wpdb->prefix . "automatc_vouchers v
                //     LEFT JOIN " . $wpdb->prefix . "automatc_vouchers_iccid i ON(v.vou_id=i.vou_iccid_vouid)
                //     WHERE v.vou_code='" . $vou_code . "' AND i.vou_iccid_no='" . $esim . "'  AND v.vou_active='1' AND i.vou_iccid_id='".$vou_num."'";
                // $rs_vou = $wpdb->get_row($qry_vou, ARRAY_A);
                // $vou_count = $wpdb->num_rows;

                // if($vou_count > 0) {
                //     $do_discount = true;

                //     $rs_vou_iccid_type = $rs_vou['vou_iccid_type'];
                //     $rs_vou_type = $rs_vou['vou_discount_type'];
                //     $rs_vou_val = $rs_vou['vou_discount_val'];
                //     $rs_vou_code = $rs_vou['vou_code'];

                //     //Plus voucher code use counter
                //     $rs_vou_code_counter = (int)$rs_vou['vou_iccid_used_count'] + 1;
                //     $rs_vou_code_id = $rs_vou['vou_iccid_id'];

                //     $wpdb->update($wpdb->prefix . "vouchers_iccid", 
                //         array(
                //             'vou_iccid_used_count' => $rs_vou_code_counter
                //         ), 
                //         array('vou_iccid_id' => $rs_vou_code_id)
                //     ); 
                // }
                /////////////////////////////

                if(!empty($vou_code) && !empty($esim)) {
                    $voucher = strtolower($vou_code);

                    $qry_vou_filter = "SELECT *, DATE_FORMAT(vou_expiry_date, '%Y-%m-%d') AS new_expiry_date 
                        FROM " . $wpdb->prefix . "automatc_vouchers WHERE vou_code='" . $voucher . "' AND vou_active='1'";
                    $rs_vou_filter = $wpdb->get_row($qry_vou_filter, ARRAY_A);
                    $vou_filter_count = $wpdb->num_rows;

                    if($vou_filter_count > 0) {
                        // $prod_sku
                        $qry_vou_chk_packages = "SELECT * FROM " . $wpdb->prefix . "automatc_vouchers_packages 
                            WHERE vou_package_vouid='".$rs_vou_filter['vou_id']."' AND vou_package_pack_id='".$prod_sku."'";
                        $rs_vou_chk_packages = $wpdb->get_row($qry_vou_chk_packages, ARRAY_A);
                        $vou_chk_packages_count = $wpdb->num_rows;
                                
                        if($rs_vou_filter['vou_iccid_type'] == 'all') {
                            $qry_openall = "SELECT * FROM " . $wpdb->prefix . "automatc_vouchers_iccid_openall 
                                WHERE vou_all_iccid_no='".$esim."' AND vou_all_iccid_vouid='".$rs_vou_filter['vou_id']."'";
                            $rs_openall = $wpdb->get_row($qry_openall, ARRAY_A);
                            $rs_openall_count = $wpdb->num_rows;

                            if($rs_openall_count > 0) {
                                $ttl_limit = (int)$rs_vou_filter['vou_used_count'];
                                $use_counter = (int)$rs_openall['vou_all_iccid_used_count'];

                                if($rs_vou_filter['vou_expiry_type'] == 'opendate') {
                                    if($ttl_limit > $use_counter) {
                                        if($rs_vou_filter['vou_package_ctrl'] == 'yes') {
                                            if($vou_chk_packages_count > 0) {
                                                $do_discount = true;

                                                $rs_vou_iccid_type = $rs_vou_filter['vou_iccid_type'];
                                                $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                                $rs_vou_code = $rs_vou_filter['vou_code'];

                                                //Plus voucher code use counter
                                                $rs_vou_code_counter = $use_counter + 1;
                                                $rs_vou_code_id = $rs_openall['vou_all_iccid_id'];

                                                $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                                    array(
                                                        'vou_all_iccid_used_count' => $rs_vou_code_counter
                                                    ), 
                                                    array('vou_all_iccid_id' => $rs_vou_code_id)
                                                ); 
                                            }
                                        }
                                        else {
                                            $do_discount = true;

                                            $rs_vou_iccid_type = $rs_vou_filter['vou_iccid_type'];
                                            $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                            $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                            $rs_vou_code = $rs_vou_filter['vou_code'];

                                            //Plus voucher code use counter
                                            $rs_vou_code_counter = $use_counter + 1;
                                            $rs_vou_code_id = $rs_openall['vou_all_iccid_id'];

                                            $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                                array(
                                                    'vou_all_iccid_used_count' => $rs_vou_code_counter
                                                ), 
                                                array('vou_all_iccid_id' => $rs_vou_code_id)
                                            ); 
                                        }

                                        // $voucher_arr['discount_status'] = '1';
                                        // $voucher_arr['discount_type'] = $rs_vou_filter['vou_discount_type'];
                                        // $voucher_arr['discount_val'] = $rs_vou_filter['vou_discount_val'];
                                        // $voucher_arr['discount_num'] = $rs_openall['vou_all_iccid_id'];
                                    }
                                    else {
                                        //no action
                                    }
                                }
                                else {
                                    date_default_timezone_set("Asia/Singapore");
                                    $today = date("Y-m-d");

                                    if(date("Y-m-d", strtotime($rs_vou_filter['new_expiry_date'])) >= date("Y-m-d", strtotime($today))) {
                                        if($ttl_limit > $use_counter) {
                                            if($rs_vou_filter['vou_package_ctrl'] == 'yes') {
                                                if($vou_chk_packages_count > 0) {
                                                    $do_discount = true;

                                                    $rs_vou_iccid_type = $rs_vou_filter['vou_iccid_type'];
                                                    $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                    $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                                    $rs_vou_code = $rs_vou_filter['vou_code'];

                                                    //Plus voucher code use counter
                                                    $rs_vou_code_counter = $use_counter + 1;
                                                    $rs_vou_code_id = $rs_openall['vou_all_iccid_id'];

                                                    $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                                        array(
                                                            'vou_all_iccid_used_count' => $rs_vou_code_counter
                                                        ), 
                                                        array('vou_all_iccid_id' => $rs_vou_code_id)
                                                    ); 
                                                }
                                            }
                                            else {
                                                $do_discount = true;

                                                $rs_vou_iccid_type = $rs_vou_filter['vou_iccid_type'];
                                                $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                                $rs_vou_code = $rs_vou_filter['vou_code'];

                                                //Plus voucher code use counter
                                                $rs_vou_code_counter = $use_counter + 1;
                                                $rs_vou_code_id = $rs_openall['vou_all_iccid_id'];

                                                $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                                    array(
                                                        'vou_all_iccid_used_count' => $rs_vou_code_counter
                                                    ), 
                                                    array('vou_all_iccid_id' => $rs_vou_code_id)
                                                ); 
                                            }

                                            // $voucher_arr['discount_status'] = '1';
                                            // $voucher_arr['discount_type'] = $rs_vou_filter['vou_discount_type'];
                                            // $voucher_arr['discount_val'] = $rs_vou_filter['vou_discount_val'];
                                            // $voucher_arr['discount_num'] = $rs_openall['vou_all_iccid_id'];
                                        }
                                        else {
                                            //no action
                                        }
                                    }
                                    else {
                                        //no action
                                    }
                                }
                            }
                            else {
                                // register the iccid and proceed the discount
                                if($rs_vou_filter['vou_expiry_type'] == 'opendate') {
                                    $register_res = $wpdb->insert($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                        array(
                                            'vou_all_iccid_vouid' => $rs_vou_filter['vou_id'],
                                            'vou_all_iccid_no' => $esim,
                                            'vou_all_iccid_used_count' => '0',
                                            'vou_all_iccid_cdate' => date("Y-m-d H:i:s")
                                        )
                                    );

                                    if($register_res === false) {
                                        //no action
                                    }
                                    else {
                                        $new_register_id = $wpdb->insert_id;

                                        if($rs_vou_filter['vou_package_ctrl'] == 'yes') {
                                            if($vou_chk_packages_count > 0) {
                                                $do_discount = true;

                                                $rs_vou_iccid_type = $rs_vou_filter['vou_iccid_type'];
                                                $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                                $rs_vou_code = $rs_vou_filter['vou_code'];

                                                $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                                    array(
                                                        'vou_all_iccid_used_count' => '1'
                                                    ), 
                                                    array('vou_all_iccid_id' => $new_register_id)
                                                ); 
                                            }
                                        }
                                        else {
                                            $do_discount = true;

                                            $rs_vou_iccid_type = $rs_vou_filter['vou_iccid_type'];
                                            $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                            $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                            $rs_vou_code = $rs_vou_filter['vou_code'];

                                            $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                                array(
                                                    'vou_all_iccid_used_count' => '1'
                                                ), 
                                                array('vou_all_iccid_id' => $new_register_id)
                                            ); 
                                        }
                                        
                                        //Plus voucher code use counter
                                        // $rs_vou_code_counter = $use_counter + 1;
                                        // $rs_vou_code_id = $rs_openall['vou_all_iccid_id'];

                                        // $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                        //     array(
                                        //         'vou_iccid_used_count' => $rs_vou_code_counter
                                        //     ), 
                                        //     array('vou_iccid_id' => $rs_vou_code_id)
                                        // ); 
                                        
                                        // $register_id = $wpdb->insert_id;

                                        // $voucher_arr['discount_status'] = '1';
                                        // $voucher_arr['discount_type'] = $rs_vou_filter['vou_discount_type'];
                                        // $voucher_arr['discount_val'] = $rs_vou_filter['vou_discount_val'];
                                        // $voucher_arr['discount_num'] = $register_id;
                                    }
                                }
                                else {
                                    date_default_timezone_set("Asia/Singapore");
                                    $today = date("Y-m-d");

                                    if(date("Y-m-d", strtotime($rs_vou_filter['new_expiry_date'])) >= date("Y-m-d", strtotime($today))) {
                                        // register the iccid and proceed the discount
                                        $register_spe = $wpdb->insert($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                            array(
                                                'vou_all_iccid_vouid' => $rs_vou_filter['vou_id'],
                                                'vou_all_iccid_no' => $esim,
                                                'vou_all_iccid_used_count' => '0',
                                                'vou_all_iccid_cdate' => date("Y-m-d H:i:s")
                                            )
                                        );

                                        if($register_spe === false) {
                                            //no action
                                        }
                                        else {
                                            $new_register_id = $wpdb->insert_id;

                                            if($rs_vou_filter['vou_package_ctrl'] == 'yes') {
                                                if($vou_chk_packages_count > 0) {
                                                    $do_discount = true;

                                                    $rs_vou_iccid_type = $rs_vou_filter['vou_iccid_type'];
                                                    $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                    $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                                    $rs_vou_code = $rs_vou_filter['vou_code'];

                                                    $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                                        array(
                                                            'vou_all_iccid_used_count' => '1'
                                                        ), 
                                                        array('vou_all_iccid_id' => $new_register_id)
                                                    ); 
                                                }
                                            }
                                            else {
                                                $do_discount = true;

                                                $rs_vou_iccid_type = $rs_vou_filter['vou_iccid_type'];
                                                $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                                $rs_vou_code = $rs_vou_filter['vou_code'];

                                                $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                                    array(
                                                        'vou_all_iccid_used_count' => '1'
                                                    ), 
                                                    array('vou_all_iccid_id' => $new_register_id)
                                                ); 
                                            }

                                            //Plus voucher code use counter
                                            // $rs_vou_code_counter = $use_counter + 1;
                                            // $rs_vou_code_id = $rs_openall['vou_all_iccid_id'];

                                            // $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                            //     array(
                                            //         'vou_iccid_used_count' => $rs_vou_code_counter
                                            //     ), 
                                            //     array('vou_iccid_id' => $rs_vou_code_id)
                                            // ); 
                                            
                                            // $register_spe_id = $wpdb->insert_id;

                                            // $voucher_arr['discount_status'] = '1';
                                            // $voucher_arr['discount_type'] = $rs_vou_filter['vou_discount_type'];
                                            // $voucher_arr['discount_val'] = $rs_vou_filter['vou_discount_val'];
                                            // $voucher_arr['discount_num'] = $register_spe_id;
                                        }
                                    }
                                    else {
                                        //no action
                                    }
                                }
                            }
                        }
                        else {
                            //original process
                            $qry_vou = "SELECT *, DATE_FORMAT(vou_expiry_date, '%Y-%m-%d') AS new_expiry_date FROM " . $wpdb->prefix . "automatc_vouchers v
                                LEFT JOIN " . $wpdb->prefix . "automatc_vouchers_iccid i ON(v.vou_id=i.vou_iccid_vouid)
                                WHERE v.vou_code='" . $voucher . "' AND i.vou_iccid_no='" . $esim . "'  AND v.vou_active='1'";
                            $rs_vou = $wpdb->get_row($qry_vou, ARRAY_A);
                            $vou_count = $wpdb->num_rows;

                            if($vou_count > 0) {
                                date_default_timezone_set("Asia/Singapore");
                                $today = date("Y-m-d");
                                // date("Y-m-d H:i:s");

                                $ttl_limit = (int)$rs_vou['vou_used_count'];
                                $use_counter = (int)$rs_vou['vou_iccid_used_count'];

                                if($rs_vou['vou_expiry_type'] == 'opendate') {
                                    if($ttl_limit > $use_counter) {
                                        if($rs_vou['vou_package_ctrl'] == 'yes') {
                                            if($vou_chk_packages_count > 0) {
                                                $do_discount = true;

                                                $rs_vou_iccid_type = $rs_vou['vou_iccid_type'];
                                                $rs_vou_type = $rs_vou['vou_discount_type'];
                                                $rs_vou_val = $rs_vou['vou_discount_val'];
                                                $rs_vou_code = $rs_vou['vou_code'];

                                                //Plus voucher code use counter
                                                $rs_vou_code_counter = $use_counter + 1;
                                                $rs_vou_code_id = $rs_vou['vou_iccid_id'];

                                                $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid", 
                                                    array(
                                                        'vou_iccid_used_count' => $rs_vou_code_counter
                                                    ), 
                                                    array('vou_iccid_id' => $rs_vou_code_id)
                                                ); 
                                            }
                                        }
                                        else {
                                            $do_discount = true;

                                            $rs_vou_iccid_type = $rs_vou['vou_iccid_type'];
                                            $rs_vou_type = $rs_vou['vou_discount_type'];
                                            $rs_vou_val = $rs_vou['vou_discount_val'];
                                            $rs_vou_code = $rs_vou['vou_code'];

                                            //Plus voucher code use counter
                                            $rs_vou_code_counter = $use_counter + 1;
                                            $rs_vou_code_id = $rs_vou['vou_iccid_id'];

                                            $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid", 
                                                array(
                                                    'vou_iccid_used_count' => $rs_vou_code_counter
                                                ), 
                                                array('vou_iccid_id' => $rs_vou_code_id)
                                            ); 
                                        }

                                        // $voucher_arr['discount_status'] = '1';
                                        // $voucher_arr['discount_type'] = $rs_vou['vou_discount_type'];
                                        // $voucher_arr['discount_val'] = $rs_vou['vou_discount_val'];
                                        // $voucher_arr['discount_num'] = $rs_vou['vou_iccid_id'];
                                    }
                                    else {
                                        //no action
                                    }
                                }
                                else {
                                    if(date("Y-m-d", strtotime($rs_vou['new_expiry_date'])) >= date("Y-m-d", strtotime($today))) {
                                        if($ttl_limit > $use_counter) {
                                            if($rs_vou['vou_package_ctrl'] == 'yes') {
                                                if($vou_chk_packages_count > 0) {
                                                    $do_discount = true;

                                                    $rs_vou_iccid_type = $rs_vou['vou_iccid_type'];
                                                    $rs_vou_type = $rs_vou['vou_discount_type'];
                                                    $rs_vou_val = $rs_vou['vou_discount_val'];
                                                    $rs_vou_code = $rs_vou['vou_code'];

                                                    //Plus voucher code use counter
                                                    $rs_vou_code_counter = $use_counter + 1;
                                                    $rs_vou_code_id = $rs_vou['vou_iccid_id'];

                                                    $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid", 
                                                        array(
                                                            'vou_iccid_used_count' => $rs_vou_code_counter
                                                        ), 
                                                        array('vou_iccid_id' => $rs_vou_code_id)
                                                    ); 
                                                }
                                            }
                                            else {
                                                $do_discount = true;

                                                $rs_vou_iccid_type = $rs_vou['vou_iccid_type'];
                                                $rs_vou_type = $rs_vou['vou_discount_type'];
                                                $rs_vou_val = $rs_vou['vou_discount_val'];
                                                $rs_vou_code = $rs_vou['vou_code'];

                                                //Plus voucher code use counter
                                                $rs_vou_code_counter = $use_counter + 1;
                                                $rs_vou_code_id = $rs_vou['vou_iccid_id'];

                                                $wpdb->update($wpdb->prefix . "automatc_vouchers_iccid", 
                                                    array(
                                                        'vou_iccid_used_count' => $rs_vou_code_counter
                                                    ), 
                                                    array('vou_iccid_id' => $rs_vou_code_id)
                                                ); 
                                            }

                                            // $voucher_arr['discount_status'] = '1';
                                            // $voucher_arr['discount_type'] = $rs_vou['vou_discount_type'];
                                            // $voucher_arr['discount_val'] = $rs_vou['vou_discount_val'];
                                            // $voucher_arr['discount_num'] = $rs_vou['vou_iccid_id'];
                                        }
                                        else {
                                            //no action
                                        }
                                    }
                                    else {
                                        //no action
                                    }
                                }
                            }
                            else {
                                //no action
                            }
                        }
                    }
                    else {
                        //no action
                    }
                }
                else {
                    //no action
                }
            }

            // $product = wc_get_product($proid);
            // $prod_sku = $product->get_sku();

            $qry_proinfo = "SELECT * FROM ".$wpdb->prefix."woocommerce_cm_products WHERE cm_pack_id='".$prod_sku."'";
            $rs_get_proinfo = $wpdb->get_results($qry_proinfo, ARRAY_A);

            $rs_dest_val = '';
            $rs_pack_val = '';
            if($rs_get_proinfo) {
                foreach($rs_get_proinfo as $rs_get_proinfoitem) {
                    $rs_dest_val = $rs_get_proinfoitem['cm_destination'];
                    $rs_pack_val = $rs_get_proinfoitem['cm_packname'];
                }
            }

            $order = wc_create_order();
            $order->set_customer_id($user_id);
            
            //$order->set_address($address, 'billing');
            //$order->set_address($address, 'shipping');

            //Apply Voucher code
            if($do_discount && !empty($rs_vou_type) && !empty($rs_vou_val)) {
                $product_obj = get_product( $proid );
                $sale_price = $product_obj->get_price();

                // Here we calculate the final price with the discount
                if($rs_vou_type == 'price') {
                    $final_price = $sale_price - $rs_vou_val;

                    if($final_price < 0) {
                        $final_price = 0.00;
                    }

                    $final_price = number_format((float)$final_price, 2, '.', '');
                }
                else if($rs_vou_type == 'percent') {
                    $final_price = $sale_price - (($sale_price/100)*$rs_vou_val);

                    if($final_price < 0) {
                        $final_price = 0.00;
                    }

                    $final_price = number_format((float)$final_price, 2, '.', '');
                }
                else {
                    $final_price = $sale_price;
                }

                // $final_price = round($sale_price * ((100-$discount['amount']) / 100), 2);

                // Create the price params that will be passed with add_product(), if you have taxes you will need to calculate them here too
                // $price_params = array( 'totals' => array( 'subtotal' => $sale_price, 'total' => $final_price ) );

                $args = array( 
                    'variation' => array(
                        'eSim' => $esim, 
                        'Destination Name' => $rs_dest_val, 
                        'Plan' => $rs_pack_val,
                        'Email' => $emailaddr,
                        'SKU' => $prod_sku,
                        'Voucher Code' => $rs_vou_code,
                        'Discount Type' => $rs_vou_type,
                        'Discount' => $rs_vou_val
                    ),
                    'totals' => array(
                        'subtotal' => $sale_price,
                        'total' => $final_price
                    )
                ); 

                // $order->add_product(get_product($proid), 1, $args);

                $order->add_product( get_product( $proid ), 1, $args ); // pid 8 & qty 1
                // $order->add_coupon( $discount['code'], ($discount['amount']/100) ); // not pennies (use dollars amount)
                // $order->set_total( ($discount['amount']/100) , 'order_discount'); // not pennies (use dollar amount)
            }
            else {
                $args = array( 
                    'variation' => array(
                        'eSim' => $esim, 
                        'Destination Name' => $rs_dest_val, 
                        'Plan' => $rs_pack_val,
                        'Email' => $emailaddr,
                        'SKU' => $prod_sku
                    ),
                ); 

                $order->add_product(get_product($proid), 1, $args);
            }

            $order->calculate_totals();
            
            //processing, on-hold, cancelled, completed
            //$order->update_status('processing');
            $order->save();
            
            update_post_meta( $order->id, '_payment_method', 'stripe' );
            update_post_meta( $order->id, '_payment_method_title', 'Stripe' );
            
            //Set for security purpose
            $private_key_str = $this->generateRandomString(15);
            update_post_meta($order->id, '_order_cm_private_key', $private_key_str);
            update_post_meta($order->id, '_order_cm_private_count', '0');
            
            update_post_meta($order->id, '_order_info_cm_esim', $esim);
            update_post_meta($order->id, '_order_info_cm_destination', $rs_dest_val);
            update_post_meta($order->id, '_order_info_cm_plan', $rs_pack_val);
            update_post_meta($order->id, '_order_info_cm_email', $emailaddr);
            update_post_meta($order->id, '_order_info_cm_sku', $prod_sku);

            //Voucher code
            if($do_discount && !empty($rs_vou_type) && !empty($rs_vou_val)) {
                update_post_meta($order->id, '_order_info_cm_voucher_code', $rs_vou_code);
                update_post_meta($order->id, '_order_info_cm_discount_type', $rs_vou_type);
                update_post_meta($order->id, '_order_info_cm_discount', $rs_vou_val);
            }
            
            //$order_private_key = get_post_meta($order->id, '_order_cm_private_key', true);
            
            // Store Order ID in session so it can be re-used after payment failure
            //WC()->session->order_awaiting_payment = $order->id;
            
            //$order->get_currency();
            //$order->get_formatted_order_total();
            //$order->get_total();
            
            $api_callbackone = get_option('chinamobile_api_callbackone');
            $api_callbacktwo = get_option('chinamobile_api_callbacktwo');
            
            $success_url = $api_callbackone . "?action=transaction&orderid=" . $order->id . "&status=success&trans=" . $private_key_str;
            $fail_url = $api_callbacktwo . "?action=transaction&orderid=" . $order->id . "&status=failed&trans=" . $private_key_str;
            
            $stripe_item_name = $rs_pack_val . ' - ' . $esim;
            $stripe_total = $order->get_total() * 100;
            
            //Stripe session
            //https://docs.stripe.com/payments/checkout/managing-limited-inventory?ui=stripe-hosted
            //https://docs.stripe.com/api/checkout/sessions/create
            //https://docs.stripe.com/error-handling?lang=php#catch-exceptions
            //https://docs.stripe.com/api/checkout/sessions/expire
            //https://stackoverflow.com/questions/69600941/are-stripes-checkout-sessions-stored-forever
            //https://medium.com/@anitha_s/how-to-create-a-billing-portal-session-and-checkout-session-in-stripe-using-node-js-39eb8ba67757
            //https://stackoverflow.com/questions/62797608/how-to-set-a-timeout-for-a-stripe-session-checkout
            $checkout_session = \Stripe\Checkout\Session::create([
                "mode" => "payment",
                "payment_intent_data" => ["description" => "Order ID:" . $order->id],
                "success_url" => $success_url,
                "cancel_url" => $fail_url,
                "locale" => "auto",
                "line_items" => [
                    [
                        "quantity" => 1,
                        "price_data" => [
                            "currency" => $order->get_currency(),
                            "unit_amount" => $stripe_total,
                            "product_data" => [
                                "name" => $stripe_item_name
                            ]
                        ]
                    ]       
                ],
                "client_reference_id" => $order->id
            ]);
            
            //print the $checkout_session object and get the session id, https://stripe.com/docs/api/checkout/sessions/create
            $result['status'] = 'pass';
            $result['url'] = $checkout_session->url;
            
            echo json_encode($result);
        
            die();
        }
    }

    public function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
        $charactersLength = strlen($characters);
        $randomString = '';
        
        for($i=0; $i<$length; $i++) {
            $randomString .= $characters[random_int(0, $charactersLength - 1)];
        }
        
        return $randomString;
    }

    public function check_esim() {
        if(!wp_verify_nonce($_POST['nonce'], "check_esim_nonce")) {
            die();
        }
        
        global $wpdb;
        
        $esim = htmlentities($_POST['esim'], ENT_QUOTES);
        $voucher = trim(htmlentities($_POST['voucher'], ENT_QUOTES));
        $result = array();
        $voucher_arr = array();
        
        //$api_secret = '950c543a19c9485b98222096bdf55abd';
        //$api_key = 'f10743ea54cf4f86a084adf1e54a5695';
        $api_secret = get_option('chinamobile_api_appsecret');
        $api_key = get_option('chinamobile_api_appkey');
        
        $access_func = 'APP_getAccessToken_SBO/v1';
        $access_tokent = '';
        $access_data = array(
            "id" => $api_key, 
            "type" => "106"
        );

        // undo
        $access_res = $this->china_mobile_api_call($api_secret, $api_key, $access_func, $access_tokent, $access_data);
        
        // test
        // $access_res = array(
        //     'status' => 'success'
        // );

        if($access_res['status'] == 'success') {
            // undo
            $esim_func = 'SBO_queryEsimCardInfo/v1';
            $esim_tokent = $access_res['data']['accessToken'];
            $esim_arr = array(
                "iccid" => $esim, 
                "accessToken" => $access_res['data']['accessToken']
            );

            // undo
            $esim_res = $this->china_mobile_api_call($api_secret, $api_key, $esim_func, $esim_tokent, $esim_arr);
            
            // test
            // $esim_res = array(
            //     'status' => 'success'
            // );
            
            if($esim_res['status'] == 'success') {
                $select_html = '';
            
                $qry_get_des = "SELECT DISTINCT(cm_region), cm_region_val FROM ".$wpdb->prefix."woocommerce_cm_products ORDER BY cm_region";
                $rs_get_des = $wpdb->get_results($qry_get_des, ARRAY_A);

                $select_html = '<option value="">Please Select Region</option>';

                if($rs_get_des) {
                    foreach($rs_get_des as $rs_get_desitem) {
                        $select_html .= '<option value="'.$rs_get_desitem['cm_region_val'].'">' . $rs_get_desitem['cm_region'] . '</option>';
                    }
                }

                //Voucher Code
                if(!empty($voucher)) {
                    $voucher = strtolower($voucher);

                    $qry_vou_filter = "SELECT *, DATE_FORMAT(vou_expiry_date, '%Y-%m-%d') AS new_expiry_date 
                        FROM " . $wpdb->prefix . "automatc_vouchers WHERE vou_code='" . $voucher . "' AND vou_active='1'";
                    $rs_vou_filter = $wpdb->get_row($qry_vou_filter, ARRAY_A);
                    $vou_filter_count = $wpdb->num_rows;

                    if($vou_filter_count > 0) {
                        if($rs_vou_filter['vou_iccid_type'] == 'all') {
                            $qry_openall = "SELECT * FROM " . $wpdb->prefix . "automatc_vouchers_iccid_openall 
                                WHERE vou_all_iccid_no='".$esim."' AND vou_all_iccid_vouid='".$rs_vou_filter['vou_id']."'";
                            $rs_openall = $wpdb->get_row($qry_openall, ARRAY_A);
                            $rs_openall_count = $wpdb->num_rows;

                            if($rs_openall_count > 0) {
                                $ttl_limit = (int)$rs_vou_filter['vou_used_count'];
                                $use_counter = (int)$rs_openall['vou_all_iccid_used_count'];

                                if($rs_vou_filter['vou_expiry_type'] == 'opendate') {
                                    if($ttl_limit > $use_counter) {
                                        $voucher_arr['discount_status'] = '1';
                                        $voucher_arr['discount_type'] = $rs_vou_filter['vou_discount_type'];
                                        $voucher_arr['discount_val'] = $rs_vou_filter['vou_discount_val'];
                                        $voucher_arr['discount_num'] = $rs_openall['vou_all_iccid_id'];
                                    }
                                    else {
                                        //no voucher
                                        $voucher_arr['discount_status'] = '2';
                                    }
                                }
                                else {
                                    date_default_timezone_set("Asia/Singapore");
                                    $today = date("Y-m-d");

                                    if(date("Y-m-d", strtotime($rs_vou_filter['new_expiry_date'])) >= date("Y-m-d", strtotime($today))) {
                                        if($ttl_limit > $use_counter) {
                                            $voucher_arr['discount_status'] = '1';
                                            $voucher_arr['discount_type'] = $rs_vou_filter['vou_discount_type'];
                                            $voucher_arr['discount_val'] = $rs_vou_filter['vou_discount_val'];
                                            $voucher_arr['discount_num'] = $rs_openall['vou_all_iccid_id'];
                                        }
                                        else {
                                            //no voucher
                                            $voucher_arr['discount_status'] = '2';
                                        }
                                    }
                                    else {
                                        //no voucher
                                        $voucher_arr['discount_status'] = '2';
                                    }
                                }
                            }
                            else {
                                // register the iccid and proceed the discount
                                if($rs_vou_filter['vou_expiry_type'] == 'opendate') {
                                    $register_res = $wpdb->insert($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                        array(
                                            'vou_all_iccid_vouid' => $rs_vou_filter['vou_id'],
                                            'vou_all_iccid_no' => $esim,
                                            'vou_all_iccid_used_count' => '0',
                                            'vou_all_iccid_cdate' => date("Y-m-d H:i:s")
                                        )
                                    );

                                    if($register_res === false) {
                                        //no voucher
                                        $voucher_arr['discount_status'] = '2';
                                    }
                                    else {
                                        $register_id = $wpdb->insert_id;

                                        $voucher_arr['discount_status'] = '1';
                                        $voucher_arr['discount_type'] = $rs_vou_filter['vou_discount_type'];
                                        $voucher_arr['discount_val'] = $rs_vou_filter['vou_discount_val'];
                                        $voucher_arr['discount_num'] = $register_id;
                                    }
                                }
                                else {
                                    date_default_timezone_set("Asia/Singapore");
                                    $today = date("Y-m-d");

                                    if(date("Y-m-d", strtotime($rs_vou_filter['new_expiry_date'])) >= date("Y-m-d", strtotime($today))) {
                                        // register the iccid and proceed the discount
                                        $register_spe = $wpdb->insert($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                            array(
                                                'vou_all_iccid_vouid' => $rs_vou_filter['vou_id'],
                                                'vou_all_iccid_no' => $esim,
                                                'vou_all_iccid_used_count' => '0',
                                                'vou_all_iccid_cdate' => date("Y-m-d H:i:s")
                                            )
                                        );

                                        if($register_spe === false) {
                                            //no voucher
                                            $voucher_arr['discount_status'] = '2';
                                        }
                                        else {
                                            $register_spe_id = $wpdb->insert_id;

                                            $voucher_arr['discount_status'] = '1';
                                            $voucher_arr['discount_type'] = $rs_vou_filter['vou_discount_type'];
                                            $voucher_arr['discount_val'] = $rs_vou_filter['vou_discount_val'];
                                            $voucher_arr['discount_num'] = $register_spe_id;
                                        }
                                    }
                                    else {
                                        //no voucher
                                        $voucher_arr['discount_status'] = '2';
                                    }
                                }
                            }
                        }
                        else {
                            //original process
                            $qry_vou = "SELECT *, DATE_FORMAT(vou_expiry_date, '%Y-%m-%d') AS new_expiry_date FROM " . $wpdb->prefix . "automatc_vouchers v
                                LEFT JOIN " . $wpdb->prefix . "automatc_vouchers_iccid i ON(v.vou_id=i.vou_iccid_vouid)
                                WHERE v.vou_code='" . $voucher . "' AND i.vou_iccid_no='" . $esim . "'  AND v.vou_active='1'";
                            $rs_vou = $wpdb->get_row($qry_vou, ARRAY_A);
                            $vou_count = $wpdb->num_rows;

                            if($vou_count > 0) {
                                date_default_timezone_set("Asia/Singapore");
                                $today = date("Y-m-d");
                                // date("Y-m-d H:i:s");

                                $ttl_limit = (int)$rs_vou['vou_used_count'];
                                $use_counter = (int)$rs_vou['vou_iccid_used_count'];

                                if($rs_vou['vou_expiry_type'] == 'opendate') {
                                    if($ttl_limit > $use_counter) {
                                        $voucher_arr['discount_status'] = '1';
                                        $voucher_arr['discount_type'] = $rs_vou['vou_discount_type'];
                                        $voucher_arr['discount_val'] = $rs_vou['vou_discount_val'];
                                        $voucher_arr['discount_num'] = $rs_vou['vou_iccid_id'];
                                    }
                                    else {
                                        //no voucher
                                        $voucher_arr['discount_status'] = '2';
                                    }
                                }
                                else {
                                    if(date("Y-m-d", strtotime($rs_vou['new_expiry_date'])) >= date("Y-m-d", strtotime($today))) {
                                        if($ttl_limit > $use_counter) {
                                            $voucher_arr['discount_status'] = '1';
                                            $voucher_arr['discount_type'] = $rs_vou['vou_discount_type'];
                                            $voucher_arr['discount_val'] = $rs_vou['vou_discount_val'];
                                            $voucher_arr['discount_num'] = $rs_vou['vou_iccid_id'];
                                        }
                                        else {
                                            //no voucher
                                            $voucher_arr['discount_status'] = '2';
                                        }
                                    }
                                    else {
                                        //no voucher
                                        $voucher_arr['discount_status'] = '2';
                                    }
                                }
                            }
                            else {
                                //no voucher
                                $voucher_arr['discount_status'] = '2';
                            }
                        }
                    }
                    else {
                        //no voucher
                        $voucher_arr['discount_status'] = '2';
                    }
                }
                else {
                    //no voucher
                    $voucher_arr['discount_status'] = '2';
                }

                $result['status'] = 'pass';
                $result['html'] = $select_html;
                $result['result'] = $esim;
                $result['vou'] = $voucher_arr;
            }
            else {
                $result['status'] = 'fail';
                $result['html'] = '';
                $result['result'] = '<div class="badnews">This eSIM ICCID is incorrect or from another provider. Please refer to below link on where to find your eSIM ICCID.</div>';
                $result['vou'] = $voucher_arr;
            }
        }
        else {
            $result['status'] = 'fail';
            $result['html'] = '';
            $result['result'] = '<div class="badnews">This eSIM ICCID is incorrect or from another provider. Please refer to below link on where to find your eSIM ICCID.</div>';
            $result['vou'] = $voucher_arr;
        }

        echo json_encode($result);
        
        die();
    }
    
    /*public function check_esim() {
        if(!wp_verify_nonce($_POST['nonce'], "check_esim_nonce")) {
            die();
        }
        
        global $wpdb;
        
        $esim = htmlentities($_POST['esim'], ENT_QUOTES);
        $result = array();
        
        //$api_secret = '950c543a19c9485b98222096bdf55abd';
        //$api_key = 'f10743ea54cf4f86a084adf1e54a5695';

        //remove after test
        // $api_secret = get_option('chinamobile_api_appsecret');
        // $api_key = get_option('chinamobile_api_appkey');
        
        // $access_func = 'APP_getAccessToken_SBO/v1';
        // $access_tokent = '';
        // $access_data = array(
        //     "id" => $api_key, 
        //     "type" => "106"
        // );

        // $access_res = $this->china_mobile_api_call($api_secret, $api_key, $access_func, $access_tokent, $access_data);

        $access_res = array();
        $access_res['status'] = 'success';

        //if($access_res['status'] == 'success' && $access_res['data']['code'] == '0000000') {
        if($access_res['status'] == 'success') {
            //remove after test
            // $esim_func = 'SBO_queryEsimCardInfo/v1';
            // $esim_tokent = $access_res['data']['accessToken'];
            // $esim_arr = array(
            //     "iccid" => $esim, 
            //     "accessToken" => $access_res['data']['accessToken']
            // );

            // $esim_res = $this->china_mobile_api_call($api_secret, $api_key, $esim_func, $esim_tokent, $esim_arr);
            
            $esim_res = array();
            $esim_res['status'] = 'success';

            //{"data":
            //{
            //"smdpAddress":"ecprsp.eastcompeace.com",
            //"activationCode":"DBE0895F4E4646E3A37F2E29E11F22AA",
            //"state":"Disable",
            //"eid":"89043051202200005220001570931464",
            //"installTime":"2022-11-26 16:31:30",
            //"installDevice":"Galaxy S21 5G",
            //"installCount":"3",
            //"updateTime":"2023-07-31 12:19:54",
            //"downloadUrl":"LPA:1$ecprsp.eastcompeace.com$DBE0895F4E4646E3A37F2E29E11F22AA"
            //},
            //"code":"0000000","msg":"成功"}

            if($esim_res['status'] == 'success') {
                $select_html = '';
            
                $qry_get_des = "SELECT DISTINCT(cm_region), cm_region_val FROM ".$wpdb->prefix."woocommerce_cm_products ORDER BY cm_region";
                $rs_get_des = $wpdb->get_results($qry_get_des, ARRAY_A);

                $select_html = '<option value="">Please Select Region</option>';

                if($rs_get_des) {
                    foreach($rs_get_des as $rs_get_desitem) {
                        $select_html .= '<option value="'.$rs_get_desitem['cm_region_val'].'">' . $rs_get_desitem['cm_region'] . '</option>';
                    }
                }

                $result['status'] = 'pass';
                $result['html'] = $select_html;
                $result['result'] = $esim;
            }
            else {
                $result['status'] = 'fail';
                $result['html'] = '';
                $result['result'] = '<div class="badnews">This eSIM ICCID is incorrect or from another provider. Please refer to below link on where to find your eSIM ICCID.</div>';
            }
        }
        else {
            $result['status'] = 'fail';
            $result['html'] = '';
            $result['result'] = '<div class="badnews">This eSIM ICCID is incorrect or from another provider. Please refer to below link on where to find your eSIM ICCID.</div>';
        }

        echo json_encode($result);
        
        die();
    }*/

    public function check_destination() {
        if(!wp_verify_nonce($_POST['nonce'], "check_dest_nonce")) {
            die();
        }
        
        global $wpdb;
        
        $regval = htmlentities($_POST['regval'], ENT_QUOTES);
        $result = array();
        $region_arr = array();
        $cover_arr = array();
        
        if(!empty($regval)) {
            $select_html = '';
            
            $qry_get_des = "SELECT * FROM ".$wpdb->prefix."woocommerce_cm_products WHERE cm_region_val='".$regval."' ORDER BY cm_destination";
            $rs_get_des = $wpdb->get_results($qry_get_des, ARRAY_A);
            
            $select_html = '<option value="">Please Select Destination</option>';
            
            if($rs_get_des) {
                foreach($rs_get_des as $rs_get_desitem) {
                    $cover_arr[$rs_get_desitem['cm_destination_val']] = '<div class="hidesupportinfoblock '.$rs_get_desitem['cm_destination_val'].'_infoblock"><h4>'.$rs_get_desitem['cm_destination'].' - Covered Countries</h4><p>' . $rs_get_desitem['cm_cover'] . '</p></div>';
                    $region_arr[$rs_get_desitem['cm_destination_val']] = $rs_get_desitem['cm_destination'];
                }
            }
            
            $region_key_arr = array_keys($region_arr);
            $region_key_ttl = count($region_key_arr);
            
            if($region_key_ttl > 0) {
                for($k=0; $k<$region_key_ttl; $k++) {
                    $select_html .= '<option value="'.$region_key_arr[$k].'">' . $region_arr[$region_key_arr[$k]] . '</option>';
                }
            }
            
            $result['status'] = 'pass';
            $result['html'] = $select_html;
            $result['cover'] = implode("", $cover_arr);
        }
        else {
            $result['status'] = 'fail';
            $result['html'] = '';
            $result['cover'] = '';
        }
        
        echo json_encode($result);
        
        die();
    }
    
    public function check_dataplan() {
        if(!wp_verify_nonce($_POST['nonce'], "check_plan_nonce")) {
            die();
        }
        
        global $wpdb;
        
        $destval = htmlentities($_POST['destval'], ENT_QUOTES);
        $result = array();
        
        if(!empty($destval)) {
            $select_html = '';
            
            $qry_plan = "SELECT cm_pack_id, cm_packname FROM ".$wpdb->prefix."woocommerce_cm_products WHERE cm_destination_val='".$destval."' ORDER BY id";
            $rs_get_plan = $wpdb->get_results($qry_plan, ARRAY_A);
            
            $select_html = '<option value="">Please Select Data Plans</option>';
            
            if($rs_get_plan) {
                foreach($rs_get_plan as $rs_get_planitem) {
                    $select_html .= '<option value="'.$rs_get_planitem['cm_pack_id'].'">' . $rs_get_planitem['cm_packname'] . '</option>';
                }
            }
            
            $result['status'] = 'pass';
            $result['html'] = $select_html;
        }
        else {
            $result['status'] = 'fail';
            $result['html'] = '';
        }
        
        echo json_encode($result);
        
        die();
    }
    
    public function check_planprice() {
        if(!wp_verify_nonce($_POST['nonce'], "check_price_nonce")) {
            die();
        }
        
        global $wpdb;
        
        $planval = htmlentities($_POST['planval'], ENT_QUOTES);

        $esim = htmlentities($_POST['esim'], ENT_QUOTES);
        $vou_code = htmlentities($_POST['vou_code'], ENT_QUOTES);
        $vou_num = (int)htmlentities($_POST['vou_num'], ENT_QUOTES);
        $vou_status = htmlentities($_POST['vou_status'], ENT_QUOTES);
        $vou_type = htmlentities($_POST['vou_type'], ENT_QUOTES);
        $vou_val = htmlentities($_POST['vou_val'], ENT_QUOTES);

        $result = array();
        $data = array();
        $do_discount = false;
        $rs_vou_type = '';
        $rs_vou_val = '';

        if(!empty($planval)) {
            // planval: D2212221204387202195
            $qry_price = "SELECT * FROM ".$wpdb->prefix."woocommerce_cm_products WHERE cm_pack_id='".$planval."'";
            $rs_get_price = $wpdb->get_results($qry_price, ARRAY_A);
            
            if($rs_get_price) {
                if($vou_status == '1') {
                    //////////////////////////
                    // original
                    // $qry_vou = "SELECT *, DATE_FORMAT(vou_expiry_date, '%Y-%m-%d') AS new_expiry_date FROM " . $wpdb->prefix . "automatc_vouchers v
                    //     LEFT JOIN " . $wpdb->prefix . "automatc_vouchers_iccid i ON(v.vou_id=i.vou_iccid_vouid)
                    //     WHERE v.vou_code='" . $vou_code . "' AND i.vou_iccid_no='" . $esim . "'  AND v.vou_active='1' AND i.vou_iccid_id='".$vou_num."'";
                    // $rs_vou = $wpdb->get_row($qry_vou, ARRAY_A);
                    // $vou_count = $wpdb->num_rows;

                    // if($vou_count > 0) {
                    //     $do_discount = true;

                    //     $rs_vou_type = $rs_vou['vou_discount_type'];
                    //     $rs_vou_val = $rs_vou['vou_discount_val'];
                    // }
                    ///////////////////////////////

                    if(!empty($vou_code) && !empty($esim)) {
                        $voucher = strtolower($vou_code);
    
                        $qry_vou_filter = "SELECT *, DATE_FORMAT(vou_expiry_date, '%Y-%m-%d') AS new_expiry_date 
                            FROM " . $wpdb->prefix . "automatc_vouchers WHERE vou_code='" . $voucher . "' AND vou_active='1'";
                        $rs_vou_filter = $wpdb->get_row($qry_vou_filter, ARRAY_A);
                        $vou_filter_count = $wpdb->num_rows;
    
                        if($vou_filter_count > 0) {
                            // $rs_vou_filter['vou_id']
                            // $rs_vou_filter['vou_package_ctrl']

                            $qry_vou_chk_packages = "SELECT * FROM " . $wpdb->prefix . "automatc_vouchers_packages 
                                WHERE vou_package_vouid='".$rs_vou_filter['vou_id']."' AND vou_package_pack_id='".$planval."'";
                            $rs_vou_chk_packages = $wpdb->get_row($qry_vou_chk_packages, ARRAY_A);
                            $vou_chk_packages_count = $wpdb->num_rows;
                            
                            if($rs_vou_filter['vou_iccid_type'] == 'all') {
                                $qry_openall = "SELECT * FROM " . $wpdb->prefix . "automatc_vouchers_iccid_openall 
                                    WHERE vou_all_iccid_no='".$esim."' AND vou_all_iccid_vouid='".$rs_vou_filter['vou_id']."'";
                                $rs_openall = $wpdb->get_row($qry_openall, ARRAY_A);
                                $rs_openall_count = $wpdb->num_rows;
    
                                if($rs_openall_count > 0) {
                                    $ttl_limit = (int)$rs_vou_filter['vou_used_count'];
                                    $use_counter = (int)$rs_openall['vou_all_iccid_used_count'];
    
                                    if($rs_vou_filter['vou_expiry_type'] == 'opendate') {
                                        if($ttl_limit > $use_counter) {
                                            if($rs_vou_filter['vou_package_ctrl'] == 'yes') {
                                                if($vou_chk_packages_count > 0) {
                                                    $do_discount = true;

                                                    $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                    $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                                }
                                            }
                                            else {
                                                $do_discount = true;

                                                $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                            }
                                            
                                            // $voucher_arr['discount_status'] = '1';
                                            // $voucher_arr['discount_type'] = $rs_vou_filter['vou_discount_type'];
                                            // $voucher_arr['discount_val'] = $rs_vou_filter['vou_discount_val'];
                                            // $voucher_arr['discount_num'] = $rs_openall['vou_all_iccid_id'];
                                        }
                                        else {
                                            //no action
                                        }
                                    }
                                    else {
                                        date_default_timezone_set("Asia/Singapore");
                                        $today = date("Y-m-d");
    
                                        if(date("Y-m-d", strtotime($rs_vou_filter['new_expiry_date'])) >= date("Y-m-d", strtotime($today))) {
                                            if($ttl_limit > $use_counter) {
                                                if($rs_vou_filter['vou_package_ctrl'] == 'yes') {
                                                    if($vou_chk_packages_count > 0) {
                                                        $do_discount = true;

                                                        $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                        $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                                    }
                                                }
                                                else {
                                                    $do_discount = true;

                                                    $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                    $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                                }
                                                
                                                // $voucher_arr['discount_status'] = '1';
                                                // $voucher_arr['discount_type'] = $rs_vou_filter['vou_discount_type'];
                                                // $voucher_arr['discount_val'] = $rs_vou_filter['vou_discount_val'];
                                                // $voucher_arr['discount_num'] = $rs_openall['vou_all_iccid_id'];
                                            }
                                            else {
                                                //no action
                                            }
                                        }
                                        else {
                                            //no action
                                        }
                                    }
                                }
                                else {
                                    // register the iccid and proceed the discount
                                    if($rs_vou_filter['vou_expiry_type'] == 'opendate') {
                                        $register_res = $wpdb->insert($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                            array(
                                                'vou_all_iccid_vouid' => $rs_vou_filter['vou_id'],
                                                'vou_all_iccid_no' => $esim,
                                                'vou_all_iccid_used_count' => '0',
                                                'vou_all_iccid_cdate' => date("Y-m-d H:i:s")
                                            )
                                        );
    
                                        if($register_res === false) {
                                            //no action
                                        }
                                        else {
                                            if($rs_vou_filter['vou_package_ctrl'] == 'yes') {
                                                if($vou_chk_packages_count > 0) {
                                                    $do_discount = true;

                                                    $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                    $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                                }
                                            }
                                            else {
                                                $do_discount = true;

                                                $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                            }

                                            // $register_id = $wpdb->insert_id;
    
                                            // $voucher_arr['discount_status'] = '1';
                                            // $voucher_arr['discount_type'] = $rs_vou_filter['vou_discount_type'];
                                            // $voucher_arr['discount_val'] = $rs_vou_filter['vou_discount_val'];
                                            // $voucher_arr['discount_num'] = $register_id;
                                        }
                                    }
                                    else {
                                        date_default_timezone_set("Asia/Singapore");
                                        $today = date("Y-m-d");
    
                                        if(date("Y-m-d", strtotime($rs_vou_filter['new_expiry_date'])) >= date("Y-m-d", strtotime($today))) {
                                            // register the iccid and proceed the discount
                                            $register_spe = $wpdb->insert($wpdb->prefix . "automatc_vouchers_iccid_openall", 
                                                array(
                                                    'vou_all_iccid_vouid' => $rs_vou_filter['vou_id'],
                                                    'vou_all_iccid_no' => $esim,
                                                    'vou_all_iccid_used_count' => '0',
                                                    'vou_all_iccid_cdate' => date("Y-m-d H:i:s")
                                                )
                                            );
    
                                            if($register_spe === false) {
                                                //no action
                                            }
                                            else {
                                                if($rs_vou_filter['vou_package_ctrl'] == 'yes') {
                                                    if($vou_chk_packages_count > 0) {
                                                        $do_discount = true;

                                                        $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                        $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                                    }
                                                }
                                                else {
                                                    $do_discount = true;

                                                    $rs_vou_type = $rs_vou_filter['vou_discount_type'];
                                                    $rs_vou_val = $rs_vou_filter['vou_discount_val'];
                                                }

                                                // $register_spe_id = $wpdb->insert_id;
    
                                                // $voucher_arr['discount_status'] = '1';
                                                // $voucher_arr['discount_type'] = $rs_vou_filter['vou_discount_type'];
                                                // $voucher_arr['discount_val'] = $rs_vou_filter['vou_discount_val'];
                                                // $voucher_arr['discount_num'] = $register_spe_id;
                                            }
                                        }
                                        else {
                                            //no action
                                        }
                                    }
                                }
                            }
                            else {
                                //original process
                                $qry_vou = "SELECT *, DATE_FORMAT(vou_expiry_date, '%Y-%m-%d') AS new_expiry_date FROM " . $wpdb->prefix . "automatc_vouchers v
                                    LEFT JOIN " . $wpdb->prefix . "automatc_vouchers_iccid i ON(v.vou_id=i.vou_iccid_vouid)
                                    WHERE v.vou_code='" . $voucher . "' AND i.vou_iccid_no='" . $esim . "'  AND v.vou_active='1'";
                                $rs_vou = $wpdb->get_row($qry_vou, ARRAY_A);
                                $vou_count = $wpdb->num_rows;
    
                                if($vou_count > 0) {
                                    date_default_timezone_set("Asia/Singapore");
                                    $today = date("Y-m-d");
                                    // date("Y-m-d H:i:s");
    
                                    $ttl_limit = (int)$rs_vou['vou_used_count'];
                                    $use_counter = (int)$rs_vou['vou_iccid_used_count'];
    
                                    if($rs_vou['vou_expiry_type'] == 'opendate') {
                                        if($ttl_limit > $use_counter) {
                                            if($rs_vou['vou_package_ctrl'] == 'yes') {
                                                if($vou_chk_packages_count > 0) {
                                                    $do_discount = true;

                                                    $rs_vou_type = $rs_vou['vou_discount_type'];
                                                    $rs_vou_val = $rs_vou['vou_discount_val'];
                                                }
                                            }
                                            else {
                                                $do_discount = true;

                                                $rs_vou_type = $rs_vou['vou_discount_type'];
                                                $rs_vou_val = $rs_vou['vou_discount_val'];
                                            }

                                            // $voucher_arr['discount_status'] = '1';
                                            // $voucher_arr['discount_type'] = $rs_vou['vou_discount_type'];
                                            // $voucher_arr['discount_val'] = $rs_vou['vou_discount_val'];
                                            // $voucher_arr['discount_num'] = $rs_vou['vou_iccid_id'];
                                        }
                                        else {
                                            //no action
                                        }
                                    }
                                    else {
                                        if(date("Y-m-d", strtotime($rs_vou['new_expiry_date'])) >= date("Y-m-d", strtotime($today))) {
                                            if($ttl_limit > $use_counter) {
                                                if($rs_vou['vou_package_ctrl'] == 'yes') {
                                                    if($vou_chk_packages_count > 0) {
                                                        $do_discount = true;

                                                        $rs_vou_type = $rs_vou['vou_discount_type'];
                                                        $rs_vou_val = $rs_vou['vou_discount_val'];
                                                    }
                                                }
                                                else {
                                                    $do_discount = true;

                                                    $rs_vou_type = $rs_vou['vou_discount_type'];
                                                    $rs_vou_val = $rs_vou['vou_discount_val'];
                                                }

                                                // $voucher_arr['discount_status'] = '1';
                                                // $voucher_arr['discount_type'] = $rs_vou['vou_discount_type'];
                                                // $voucher_arr['discount_val'] = $rs_vou['vou_discount_val'];
                                                // $voucher_arr['discount_num'] = $rs_vou['vou_iccid_id'];
                                            }
                                            else {
                                                //no action
                                            }
                                        }
                                        else {
                                            //no action
                                        }
                                    }
                                }
                                else {
                                    //no action
                                }
                            }
                        }
                        else {
                            //no action
                        }
                    }
                    else {
                        //no action
                    }
                }
                
                foreach($rs_get_price as $rs_get_priceitem) {
                    $data['pro_id'] = wc_get_product_id_by_sku($rs_get_priceitem['cm_pack_id']);
                    $data['destination'] = $rs_get_priceitem['cm_destination'];
                    $data['packname'] = $rs_get_priceitem['cm_packname'];

                    if($do_discount && !empty($rs_vou_type) && !empty($rs_vou_val)) {
                        if($rs_vou_type == 'price') {
                            $final_price = $rs_get_priceitem['cm_price'] - $rs_vou_val;

                            if($final_price < 0) {
                                $final_price = 0.00;
                            }

                            $data['price'] = get_woocommerce_currency() . number_format((float)$final_price, 2, '.', '');
                        }
                        else if($rs_vou_type == 'percent') {
                            $final_price = $rs_get_priceitem['cm_price'] - (($rs_get_priceitem['cm_price']/100)*$rs_vou_val);

                            if($final_price < 0) {
                                $final_price = 0.00;
                            }

                            $data['price'] = get_woocommerce_currency() . number_format((float)$final_price, 2, '.', '');
                        }
                        else {
                            $data['price'] = get_woocommerce_currency() . $rs_get_priceitem['cm_price'];
                        }
                    }
                    else {
                        $data['price'] = get_woocommerce_currency() . $rs_get_priceitem['cm_price'];
                    }
                    
                    //$data['price'] = wc_price($rs_get_priceitem['cm_price']);
                    //$data['desc'] = $rs_get_priceitem['cm_desc'];
                    $data['desc'] = str_replace("|br|", "<br/>", $rs_get_priceitem['cm_desc']);
                    $data['desc'] = str_replace("|textred_start|", "<span style='color:red;'>", $data['desc']);
                    $data['desc'] = str_replace("|textred_end|", "</span>", $data['desc']);
                    $data['cover'] = $rs_get_priceitem['cm_cover'];

                    $output = '<div class="infoprice">Price: ' . $data['price'];

                    if($do_discount && !empty($rs_vou_type) && !empty($rs_vou_val)) {
                        $output .= '  <span style="color:#747474;"><s>' . get_woocommerce_currency() . $rs_get_priceitem['cm_price'] . '</s></span>';
                    }

                    $output .= '</div><div class="infodesc">'.$data['desc'].'</div>';

                    $data['output'] = $output;
                }
            }
            
            $result['status'] = 'pass';
            $result['html'] = $data;
        }
        else {
            $result['status'] = 'fail';
            $result['html'] = '';
        }
        
        echo json_encode($result);
        
        die();
    }
    
    public function plancheckout() {
        if(!wp_verify_nonce($_POST['nonce'], "check_form_nonce")) {
            die();
        }
        
        global $wpdb;
        global $woocommerce;
        
        $result = array();
        $extrainfo_arr = array();
        
        $parent_pro_id = get_option('cmproductloadproduct');
        $proid = htmlentities($_POST['proid'], ENT_QUOTES);
        $esim = htmlentities($_POST['esim'], ENT_QUOTES);
        
        if(!empty($proid) && !empty($esim)) {
            $product = wc_get_product($proid);
            $prod_sku = $product->get_sku();

            $qry_proinfo = "SELECT * FROM ".$wpdb->prefix."woocommerce_cm_products WHERE cm_pack_id='".$prod_sku."'";
            $rs_get_proinfo = $wpdb->get_results($qry_proinfo, ARRAY_A);

            $extrainfo_arr['eSIM'] = $esim;
            if($rs_get_proinfo) {
                foreach($rs_get_proinfo as $rs_get_proinfoitem) {
                    $extrainfo_arr['Dest'] = $rs_get_proinfoitem['cm_destination'];
                    $extrainfo_arr['Plan'] = $rs_get_proinfoitem['cm_packname'];
                }
            }

            $woocommerce->cart->empty_cart();
            $woocommerce->cart->add_to_cart($parent_pro_id, '1', $proid, $extrainfo_arr, null);

            $result['status'] = 'pass';
            $result['html'] = '';
        }
        else {
            $result['status'] = 'fail';
            $result['html'] = '';
        }
        
        echo json_encode($result);
        
        die();
    }
    
    public function esim_status_check_test() {
        // if(!wp_verify_nonce($_POST['nonce'], "check_smc_esim_nonce")) {
        //     die();
        // }
      
        // $internal_error = false;
        // $cur_package_name = '';
        // $cur_package_style = '';
        // $cur_subscribe_key = '';
        // $cur_quote_limit = 0;
        // $cur_quote_bal = 0;
        // $cur_quote_formula = 0;
        // $data_bundle_id = '';
        // $data_mmc = '';
        // $data_createtime = '';
        // $data_endtime = '';
        // $data_todaytime = '';
        // $data_nextdaytime = '';
        // $html_table = '';
        // $result = array();
        // $result['data'] = array();
        // $all_output = array();
        
        // $result['data']['orders'] = array();
        // $result['data']['ipt_smc_curactvpac'] = '';
        // $result['data']['ipt_smc_actvtime'] = '';
        // $result['data']['ipt_smc_pacend'] = '';
        // $result['data']['ipt_smc_idreg'] = '';
        // $result['data']['ipt_smc_expiry'] = '';
        // $result['data']['ipt_smc_status'] = '';
        // $result['data']['ipt_smc_installdev'] = '';
        // $result['data']['ipt_smc_datausedtoday'] = '';
        // $result['data']['ipt_smc_ttlusedtraf'] = 0;
        // $result['data']['ipt_smc_aviopet'] = '';
        // $result['data']['ipt_smc_netapn'] = '';
        // $result['data']['quote_style'] = '';
        // $result['data']['quote_limit'] = 0;
        // $result['data']['quote_bal'] = 0;
        // $result['data']['quote_formula'] = 0;
        // $result['data']['mmc'] = '';
        
        date_default_timezone_set('UTC');
        
        //action: "chkstatusesim", esim : esim, nonce: nonce

        $action_val = '';
        $esim_val = '';

        if(!empty($_POST['ajx'])) {
            $action_val = htmlentities($_POST['ajx'], ENT_QUOTES);
        }
        
        if(!empty($_POST['esim'])) {
            $esim_val = htmlentities($_POST['esim'], ENT_QUOTES);
        }

        if(!empty($_GET['ajx'])) {
            $action_val = htmlentities($_GET['ajx'], ENT_QUOTES);
        }
        
        if(!empty($_GET['esim'])) {
            $esim_val = htmlentities($_GET['esim'], ENT_QUOTES);
        }
        
        if(!empty($esim_val)) {
            // echo 'Action - ' . $action_val . '<br/>';
            // echo 'eSIM - ' . $esim_val . '<br/>';

            
            $api_secret = get_option('chinamobile_api_appsecret');
            $api_key = get_option('chinamobile_api_appkey');

            $access_func = 'APP_getAccessToken_SBO/v1';
            $access_tokent = '';
            $access_data = array(
                "id" => $api_key, 
                "type" => "106"
            );

            $access_res = $this->china_mobile_api_call($api_secret, $api_key, $access_func, $access_tokent, $access_data);
            //if($access_res['status'] == 'success' && $access_res['data']['code'] == '0000000') {
            if($access_res['status'] == 'success') {
                //SBO_query_SIMInfo
                //SBO_queryEsimCardInfo
                //APP_getSubedUserDataBundle_SBO
                //APP_getSubscriberAllQuota_SBO_today - APP_getSubscriberAllQuota_SBO
                //APP_getSubscriberAllQuota_SBO_ttl - APP_getSubscriberAllQuota_SBO
                //SBO_query_usingTrajectories
                //APP_queryCarrier_SBO

                //SBO_query_SIMInfo

                ///////////////////////////////////////////////////////

                $siminfo_func = 'SBO_query_SIMInfo/v1';
                $pass_tokent = $access_res['data']['accessToken'];

                $siminfo_item_arr = array(
                    "imsi" => "",
                    "iccid" => $esim_val
                );

                $siminfo_data = array(
                    $siminfo_item_arr
                );
                
                $siminfo_res = $this->china_mobile_api_call($api_secret, $api_key, $siminfo_func, $pass_tokent, $siminfo_data);
                
                ///////////////////////////////////////////////////////

                $termstate_func = 'APP_HIMSI_TERMSTATE_SBO/v1';
                $termstate_data = array(
                    "accessToken" => $pass_tokent,
                    "iccid" => $esim_val
                );

                $termstate_res = $this->china_mobile_api_call($api_secret, $api_key, $termstate_func, $pass_tokent, $termstate_data);

                $data_mmc = $termstate_res['data']['mobileCountryCode'];

                //////////---------------------

                $qrycarrier_func = 'APP_queryCarrier_SBO/v1';
                $qrycarrier_data = array(
                    "language" => "2",
                    "mcc" => $data_mmc
                );

                $qrycarrier_res = $this->china_mobile_api_call($api_secret, $api_key, $qrycarrier_func, $pass_tokent, $qrycarrier_data);

                ///////////////////////////////////////////////////////

                $esimcardinfo_func = 'SBO_queryEsimCardInfo/v1';
                $esimcardinfo_data = array(
                    "iccid" => $esim_val,
                    "accessToken" => $pass_tokent
                );

                $esimcardinfo_res = $this->china_mobile_api_call($api_secret, $api_key, $esimcardinfo_func, $pass_tokent, $esimcardinfo_data);

                ///////////////////////////////////////////////////////

                $getsubdatabundle_func = 'APP_getSubedUserDataBundle_SBO/v1';
                $getsubdatabundle_data = array(
                    "accessToken" => $pass_tokent,
                    "iccid" => $esim_val,
                    'count' => 50,
                    "language" => "2" //English
                );

                $getsubdatabundle_res = $this->china_mobile_api_call($api_secret, $api_key, $getsubdatabundle_func, $pass_tokent, $getsubdatabundle_data);

                $cur_subscribe_key = '';
                $user_subscribed_arr = $getsubdatabundle_res['data']['userDataBundles'];
                for($b=0; $b<count($user_subscribed_arr); $b++) {
                    $cur_subscribe_key = $user_subscribed_arr[$b]['subscriptionKey'];

                    // $result['data']['orders'][$datesort]['bundleid'] = $user_subscribed_arr[$b]['dataBundleId'];
                    // $result['data']['orders'][$datesort]['subkey'] = $user_subscribed_arr[$b]['subscriptionKey'];
                    // $result['data']['orders'][$datesort]['package'] = $user_subscribed_arr[$b]['name'][0]['value'];
                    // $result['data']['orders'][$datesort]['createTime'] = $createTime;
                    // $result['data']['orders'][$datesort]['expireTime'] = $expireTime;
                    // $result['data']['orders'][$datesort]['endTime'] = $endTime;
                    // $result['data']['orders'][$datesort]['activeTime'] = $activeTime;
                    // $result['data']['orders'][$datesort]['status'] = $user_subscribed_arr[$b]['status'];
                }
                
                ///////////////////////////////////////////////////////

                //1836861029483047953
                $getallquotetoday_func = 'APP_getSubscriberAllQuota_SBO/v1';
                $getallquotetoday_data = array(
                    "iccid" => $esim_val,
                    "childOrderId" => $cur_subscribe_key
                );

                // $getallquotetoday_data = array(
                //     "iccid" => $esim_val,
                //     "childOrderId" => '1843490023368495857'
                // );

                $getallquotetoday_res = $this->china_mobile_api_call($api_secret, $api_key, $getallquotetoday_func, $pass_tokent, $getallquotetoday_data);
                
                echo '<pre>';
                    print_r($getsubdatabundle_data);
                    print_r($getallquotetoday_func);
                    print_r($getallquotetoday_data);
                echo '</pre>';

                echo '<pre>';
                    print_r($access_res);
                    print_r($siminfo_res);
                    print_r($esimcardinfo_res);
                    print_r($getsubdatabundle_res);
                    print_r($getallquotetoday_res);
                    print_r($termstate_res);
                    print_r($qrycarrier_res);
                echo '</pre>';

                if($siminfo_res['status'] == 'success') {
                    
                }
                else {

                }
            }
            else {

            }
            
        }
        else {

        }

        echo 'wow';
        
        // echo json_encode($result);
        
        // unset($result);
        // unset($all_output);
        
        die();
    }

    public function esim_status_check_result() {
        if(!wp_verify_nonce($_POST['nonce'], "check_smc_esim_nonce")) {
            die();
        }
      
        global $wpdb;

        $internal_error = false;
        $cur_package_name = '';
        $cur_package_style = '';
        $cur_subscribe_key = '';
        $cur_quote_limit = 0;
        $cur_quote_bal = 0;
        $cur_quote_formula = 0;
        $data_bundle_id = '';
        $data_mmc = '';
        $data_createtime = '';
        $data_endtime = '';
        $data_todaytime = '';
        $data_nextdaytime = '';
        $html_table = '';
        $result = array();
        $result['data'] = array();
        $all_output = array();
        
        $result['data']['orders'] = array();
        $result['data']['ipt_smc_curactvpac'] = '';
        $result['data']['ipt_smc_actvtime'] = '';
        $result['data']['ipt_smc_pacend'] = '';
        $result['data']['ipt_smc_idreg'] = '';
        $result['data']['ipt_smc_expiry'] = '';
        $result['data']['ipt_smc_status'] = '';
        $result['data']['ipt_smc_installdev'] = '';
        $result['data']['ipt_smc_datausedtoday'] = '';
        $result['data']['ipt_smc_ttlusedtraf'] = 0;
        $result['data']['ipt_smc_aviopet'] = '';
        $result['data']['ipt_smc_netapn'] = '';
        $result['data']['quote_style'] = '';
        $result['data']['quote_limit'] = 0;
        $result['data']['quote_bal'] = 0;
        $result['data']['quote_formula'] = 0;
        $result['data']['mmc'] = '';
        $result['data']['timezone'] = '';

        $country_timezone = 'Asia/Singapore';
        
        date_default_timezone_set('UTC');
        
        //action: "chkstatusesim", esim : esim, nonce: nonce
        $action_val = htmlentities($_POST['action'], ENT_QUOTES);
        $esim_val = htmlentities($_POST['esim'], ENT_QUOTES);
        
        if(!empty($esim_val)) {
            $api_secret = get_option('chinamobile_api_appsecret');
            $api_key = get_option('chinamobile_api_appkey');

            $access_func = 'APP_getAccessToken_SBO/v1';
            $access_tokent = '';
            $access_data = array(
                "id" => $api_key, 
                "type" => "106"
            );

            $access_res = $this->china_mobile_api_call($api_secret, $api_key, $access_func, $access_tokent, $access_data);
            //if($access_res['status'] == 'success' && $access_res['data']['code'] == '0000000') {
            if($access_res['status'] == 'success') {
                //SBO_query_SIMInfo
                //SBO_queryEsimCardInfo
                //APP_getSubedUserDataBundle_SBO
                //APP_getSubscriberAllQuota_SBO_today - APP_getSubscriberAllQuota_SBO
                //APP_getSubscriberAllQuota_SBO_ttl - APP_getSubscriberAllQuota_SBO
                //SBO_query_usingTrajectories
                //APP_queryCarrier_SBO

                //SBO_query_SIMInfo
                $siminfo_func = 'SBO_query_SIMInfo/v1';
                $pass_tokent = $access_res['data']['accessToken'];

                $siminfo_item_arr = array(
                    "imsi" => "",
                    "iccid" => $esim_val
                );

                $siminfo_data = array(
                    $siminfo_item_arr
                );
                
                $siminfo_res = $this->china_mobile_api_call($api_secret, $api_key, $siminfo_func, $pass_tokent, $siminfo_data);
                
                if($siminfo_res['status'] == 'success') {
                    if(count($siminfo_res['data']['himsis']) > 0) {
                        //SBO_query_SIMInfo Data
                        $all_output['SBO_query_SIMInfo'] = $siminfo_res;

                        //SBO_queryEsimCardInfo
                        $esimcardinfo_func = 'SBO_queryEsimCardInfo/v1';
                        $esimcardinfo_data = array(
                            "iccid" => $esim_val,
                            "accessToken" => $pass_tokent
                        );

                        $esimcardinfo_res = $this->china_mobile_api_call($api_secret, $api_key, $esimcardinfo_func, $pass_tokent, $esimcardinfo_data);

                        if($esimcardinfo_res['status'] == 'success') {
                            //SBO_queryEsimCardInfo Data
                            $all_output['SBO_queryEsimCardInfo'] = $esimcardinfo_res;

                            //SBO_query_SIMInfo =========== copy
                            if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['realRuleList'][0]['authStatus'] == '1') {
                                $result['data']['ipt_smc_idreg'] = 'To be certified';
                            }
                            else if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['realRuleList'][0]['authStatus'] == '2') {
                                $result['data']['ipt_smc_idreg'] = 'Verifying';
                            }
                            else if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['realRuleList'][0]['authStatus'] == '3') {
                                //$result['data']['ipt_smc_idreg'] = 'Certified';
                                $result['data']['ipt_smc_idreg'] = 'Approved';
                            }
                            else if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['realRuleList'][0]['authStatus'] == '4') {
                                $result['data']['ipt_smc_idreg'] = 'Authentication failed';
                            }
                            else if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['realRuleList'][0]['authStatus'] == '5') {
                                $result['data']['ipt_smc_idreg'] = 'The certificate has expired';
                            }
                            else {
                                $result['data']['ipt_smc_idreg'] = 'NA';
                            }
                            
                            ////////////need to move to timezone convertor
                            $result['data']['ipt_smc_auths'] = $all_output['SBO_query_SIMInfo']['data']['himsis'][0]['realRuleList'][0]['authStatus'];

                            ////
                            $smcexpiry = str_split($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['expireTime']);

                            $smc_expiry_date = $smcexpiry[0].$smcexpiry[1].$smcexpiry[2].$smcexpiry[3].'-'.$smcexpiry[4].$smcexpiry[5].'-'.$smcexpiry[6].$smcexpiry[7];
                            $smc_expiry_time = $smcexpiry[8].$smcexpiry[9].':'.$smcexpiry[10].$smcexpiry[11].':'.$smcexpiry[12].$smcexpiry[13];

                            $sim_expire_new_date = $smc_expiry_date . ' ' . $smc_expiry_time;

                            // date_default_timezone_set("Asia/Singapore"); // your user's timezone
                            // $sim_expire_new_date_str = $sim_expire_new_date . " UTC";
                            // $sim_expire_new_date_conv = date("Y-m-d H:i:s", strtotime($sim_expire_new_date_str));

                            // $result['data']['ipt_smc_expiry'] = $sim_expire_new_date_conv;
                            ////

                            date_default_timezone_set('UTC');

                            //SBO_queryEsimCardInfo ===========
                            $result['data']['ipt_smc_installdev'] = $all_output['SBO_queryEsimCardInfo']['data']['data']['installDevice'];

                            if($all_output['SBO_queryEsimCardInfo']['data']['data']['state'] == 'Disable') {
                                $result['data']['ipt_smc_status'] = 'eSIM Off Now';
                            }
                            else if($all_output['SBO_queryEsimCardInfo']['data']['data']['state'] == 'Enabled') {
                                $result['data']['ipt_smc_status'] = 'eSIM On Now';
                            }
                            else if($all_output['SBO_queryEsimCardInfo']['data']['data']['state'] == 'Enable') {
                                $result['data']['ipt_smc_status'] = 'eSIM On Now';
                            }
                            else if($all_output['SBO_queryEsimCardInfo']['data']['data']['state'] == '') {
                                $result['data']['ipt_smc_status'] = 'eSIM Not Install';
                            }
                            else {
                                $result['data']['ipt_smc_status'] = $all_output['SBO_queryEsimCardInfo']['data']['data']['state'];
                            }
                            
                            //APP_getSubedUserDataBundle_SBO
                            $getsubdatabundle_func = 'APP_getSubedUserDataBundle_SBO/v1';
                            $getsubdatabundle_data = array(
                                "accessToken" => $pass_tokent,
                                "iccid" => $esim_val,
                                'count' => 50,
                                "language" => "2" //English
                            );

                            $getsubdatabundle_res = $this->china_mobile_api_call($api_secret, $api_key, $getsubdatabundle_func, $pass_tokent, $getsubdatabundle_data);

                            if($getsubdatabundle_res['status'] == 'success') {
                                //APP_getSubedUserDataBundle_SBO Data
                                $all_output['APP_getSubedUserDataBundle_SBO'] = $getsubdatabundle_res;
                                // $result['APP_getSubedUserDataBundle_SBO'] = $getsubdatabundle_res;
                                
                                $extra_info_activation_time = '';
                                
                                //***********************
                                //APP_getSubedUserDataBundle_SBO ===========
                                $user_subscribed_arr = $all_output['APP_getSubedUserDataBundle_SBO']['data']['userDataBundles'];

                                //////////////////
                                $new_arr_result = array();
                                for($b=0; $b<count($user_subscribed_arr); $b++) {
                                    // undo
                                    // date_default_timezone_set('UTC');
                                    $temp_from = date("Y-m-d H:i:s", strtotime($user_subscribed_arr[$b]['createTime']));
                                    $temp_now = date("Y-m-d H:i:s");
                                    $datediff = strtotime($temp_now) - strtotime($temp_from);
                                    //$datesort = ceil($datediff/86400);
                                    $datesort = $datediff;
                                    
                                    $check_style = strtolower($user_subscribed_arr[$b]['name'][0]['value']);
                                    
                                    $new_arr_result['data']['orders'][$datesort]['datediff_ori'] = $datediff;
                                    
                                    if(substr_count($check_style, "unlimited") > 0) {
                                        $new_arr_result['data']['orders'][$datesort]['style'] = 'unlimited';
                                    }
                                    else {
                                        $new_arr_result['data']['orders'][$datesort]['style'] = 'fixed';
                                    }
                                    
                                    //////////

                                    // undo
                                    // date_default_timezone_set($result['data']['timezone']); // your user's timezone
                                    if(!empty($user_subscribed_arr[$b]['createTime'])) {
                                        $createTime_str = $user_subscribed_arr[$b]['createTime'] . " UTC";
                                        $createTime = date("Y-m-d H:i:s", strtotime($createTime_str));
                                    }
                                    else {
                                        $createTime = "";
                                    }
                                    
                                    if(!empty($user_subscribed_arr[$b]['expireTime'])) {
                                        $expireTime_str = $user_subscribed_arr[$b]['expireTime'] . " UTC";
                                        $expireTime = date("Y-m-d H:i:s", strtotime($expireTime_str));
                                    }
                                    else {
                                        $expireTime = "";
                                    }
                                    
                                    if(!empty($user_subscribed_arr[$b]['endTime'])) {
                                        $endTime_str = $user_subscribed_arr[$b]['endTime'] . " UTC";
                                        $endTime = date("Y-m-d H:i:s", strtotime($endTime_str));
                                    }
                                    else {
                                        $endTime = "";
                                    }
                                    
                                    if(!empty($user_subscribed_arr[$b]['activeTime'])) {
                                        $activeTime_str = $user_subscribed_arr[$b]['activeTime'] . " UTC";
                                        $activeTime = date("Y-m-d H:i:s", strtotime($activeTime_str));
                                    }
                                    else {
                                        $activeTime = "";
                                    }
                                    
                                    $new_arr_result['data']['orders'][$datesort]['bundleid'] = $user_subscribed_arr[$b]['dataBundleId'];
                                    $new_arr_result['data']['orders'][$datesort]['subkey'] = $user_subscribed_arr[$b]['subscriptionKey'];
                                    $new_arr_result['data']['orders'][$datesort]['package'] = $user_subscribed_arr[$b]['name'][0]['value'];
                                    $new_arr_result['data']['orders'][$datesort]['createTime'] = $createTime;
                                    $new_arr_result['data']['orders'][$datesort]['expireTime'] = $expireTime;
                                    $new_arr_result['data']['orders'][$datesort]['endTime'] = $endTime;
                                    $new_arr_result['data']['orders'][$datesort]['activeTime'] = $activeTime;
                                    $new_arr_result['data']['orders'][$datesort]['status'] = $user_subscribed_arr[$b]['status'];
                                    
                                    $new_arr_result['testtime'][] = array(
                                        "name" => $user_subscribed_arr[$b]['name'][0]['value'],
                                        "order" => $createTime,
                                        "diff" => $datediff,
                                        "index" => $datesort
                                    );
                                }

                                $result['data']['test_raw'] = $new_arr_result;
                                $result['data']['test_raw_date'] = date("Y-m-d H:i:s");

                                // undo
                                // date_default_timezone_set('UTC');
                                
                                ksort($new_arr_result['data']['orders']);
                                $ttl_data_orders = count($new_arr_result['data']['orders']);
                                if(count($new_arr_result['data']['orders']) > 0) {
                                    $active_order_index = "";
                                    $first_activate_status = false;
                                    $check_cur_active = false;
                                    $uniqe_order_keys = array_keys($new_arr_result['data']['orders']);
                                    
                                    // date_default_timezone_set("Asia/Singapore"); // your user's timezone
                                    // undo
                                    // date_default_timezone_set($result['data']['timezone']); // your user's timezone
                                    $temp_check_now = date("Y-m-d H:i:s");
                                    
                                    // undo
                                    // date_default_timezone_set('UTC');
                                    
                                    // orders loop checking
                                    for($c=0; $c<count($new_arr_result['data']['orders']); $c++) {
                                        if(($check_cur_active == false) && ($new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['status'] == "3") && (strtotime($temp_check_now) >= strtotime($new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['activeTime']) && strtotime($temp_check_now) <= strtotime($new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['expireTime']))) {
                                            $result['data']['testone1'][$c]['now'] = $temp_check_now;
                                            $result['data']['testone1'][$c]['actv'] = $new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['activeTime'];
                                            $result['data']['testone1'][$c]['expi'] = $new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['expireTime'];
                                        }
                                        else {
                                            $result['data']['testone2'][$c]['now'] = $temp_check_now;
                                            $result['data']['testone2'][$c]['actv'] = $new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['activeTime'];
                                            $result['data']['testone2'][$c]['expi'] = $new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['expireTime'];
                                        }

                                        if(($check_cur_active == false) && ($new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['status'] == "3") && (strtotime($temp_check_now) >= strtotime($new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['activeTime'])) && (strtotime($temp_check_now) <= strtotime($new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['expireTime']))) {
                                            $active_order_index = $uniqe_order_keys[$c];
                                            $check_cur_active = true;
                                            
                                            $getactivationtime_arr = explode(" ", $new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['activeTime']);
                                            $extra_info_activation_time = $getactivationtime_arr[1];

                                            $result['data']['testone']['sample1'] = 'option 1';

                                            // $result['data']['testone']['now'] = $temp_check_now;
                                            // $result['data']['testone']['active'] = $new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['activeTime'];
                                            // $result['data']['testone']['expire'] = $new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['expireTime'];
                                            // $result['data']['testone']['endtime'] = $new_arr_result['data']['orders'][$uniqe_order_keys[$c]]['endTime'];

                                            break;
                                        }
                                        else {
                                            $result['data']['testone']['sample2'] = 'option 2';
                                        }
                                    }
                                    
                                    if(!empty($active_order_index)) {
                                        $cur_package_style = $new_arr_result['data']['orders'][$active_order_index]['style'];

                                        $data_bundle_id = $new_arr_result['data']['orders'][$active_order_index]['bundleid'];
                                        $cur_subscribe_key = $new_arr_result['data']['orders'][$active_order_index]['subkey'];

                                        $result['data']['test_bundle_id'] = $data_bundle_id;
                                        $result['data']['test_subscribe_key'] = $cur_subscribe_key;

                                        // $data_bundle_id = $user_subscribed_arr[$j]['dataBundleId'];
                                        // $cur_subscribe_key = $user_subscribed_arr[$j]['subscriptionKey'];
                                    }
                                    else {
                                        $cur_package_style = "";
                                    }
                                }
                                else {
                                    $cur_package_style = "";
                                }















////////////////////

                                // for($j=0; $j<count($user_subscribed_arr); $j++) {
                                //     $data_bundle_id = $user_subscribed_arr[$j]['dataBundleId'];
                                //     $cur_subscribe_key = $user_subscribed_arr[$j]['subscriptionKey'];
                                // }

                                if(!empty($cur_subscribe_key) || !empty($data_bundle_id)) {
                                    //***********************
                                    //////////////////////////////////// Change to one call only ///////////////////////////////
                                    //APP_getSubscriberAllQuota_SBO_today - APP_getSubscriberAllQuota_SBO
                                    $getallquotetoday_func = 'APP_getSubscriberAllQuota_SBO/v1';
                                    $getallquotetoday_data = array(
                                        "iccid" => $esim_val,
                                        "childOrderId" => $cur_subscribe_key
                                    );

                                    //$data_todaytime = date("Ymd");
                                    //$data_nextdaytime = date("Ymd", time() + 86400);

                                    //$getallquotetoday_data = array(
                                    //    "iccid" => $esim_val,
                                    //    "beginTime" => date("Ymd"),
                                    //    "endTime" => date("Ymd", time() + 86400)
                                    //);

                                    $getallquotetoday_res = $this->china_mobile_api_call($api_secret, $api_key, $getallquotetoday_func, $pass_tokent, $getallquotetoday_data);

                                    if($getallquotetoday_res['status'] == 'success') {
                                        //APP_getSubscriberAllQuota_SBO_today Data - APP_getSubscriberAllQuota_SBO
                                        $all_output['APP_getSubscriberAllQuota_SBO_today'] = $getallquotetoday_res;
                                        //$result['APP_getSubscriberAllQuota_SBO_today'] = $getallquotetoday_res;
                                        //$result['APP_getSubscriberAllQuota_SBO_today_param'] = $getallquotetoday_data;

                                        //APP_getSubscriberAllQuota_SBO_ttl - APP_getSubscriberAllQuota_SBO
                                        $getallquotettl_func = 'APP_getSubscriberAllQuota_SBO/v1';
                                        $getallquotettl_data = array(
                                            "iccid" => $esim_val,
                                            "beginTime" => date("Ymd"),
                                            "endTime" => date("Ymd", time() + 86400)
                                        );

                                        $getallquotettl_res = $this->china_mobile_api_call($api_secret, $api_key, $getallquotettl_func, $pass_tokent, $getallquotettl_data);

                                        if($getallquotettl_res['status'] == 'success') {
                                            //APP_getSubscriberAllQuota_SBO_ttl Data - APP_getSubscriberAllQuota_SBO
                                            $all_output['APP_getSubscriberAllQuota_SBO_ttl'] = $getallquotettl_res;
                                            //$result['APP_getSubscriberAllQuota_SBO_ttl'] = $getallquotettl_res;
                                            //$result['APP_getSubscriberAllQuota_SBO_ttl_param'] = $getallquotettl_data;

                                            $show_notice = "0";
                                            
                                            ////////////////////
                                            //APP_getSubscriberAllQuota_SBO_today - APP_getSubscriberAllQuota_SBO ===========
                                            $ttl_data_consumption = 0.00;

                                            if($cur_package_style == 'unlimited') {
                                                //qtaconsumptionTotal
                                                $ttl_consumption_arr = $all_output['APP_getSubscriberAllQuota_SBO_ttl']['data']['historyQuota'];
                                                for($s=0; $s<count($ttl_consumption_arr); $s++) {
                                                    $ttl_data_consumption += $ttl_consumption_arr[$s]['qtaconsumption'];
                                                }

                                                $today_consumption_arr = $all_output['APP_getSubscriberAllQuota_SBO_today']['data']['historyQuota'];
                                                for($t=0; $t<count($today_consumption_arr); $t++) {
                                                    $ttl_data_consumption += $today_consumption_arr[$t]['qtaconsumption'];
                                                }
                                                
                                                $subscribe_consumption_arr = $all_output['APP_getSubscriberAllQuota_SBO_today']['data']['subscriberQuota'];
                                                
                                                if($subscribe_consumption_arr['qtavalue'] <= $subscribe_consumption_arr['qtaconsumption']) {
                                                    $cur_quote_bal = number_format(0, 2);
                                                    $show_notice = "1";
                                                }
                                                else {
                                                    $cur_quote_bal = number_format($subscribe_consumption_arr['qtabalance'], 2);
                                                }
                                                
                                                $today_data_consumption_num = number_format($subscribe_consumption_arr['qtaconsumption'], 2);
                                                //$today_data_consumption_num = number_format($subscribe_consumption_arr['qtaconsumptionTotal'], 2);
                                                $cur_quote_limit = number_format($subscribe_consumption_arr['qtavalue'], 2);

                                                $ttl_data_consumption_num = number_format($ttl_data_consumption, 2);
                                            }
                                            else {
                                                $subscribe_consumption_arr = $all_output['APP_getSubscriberAllQuota_SBO_today']['data']['subscriberQuota'];
                                                $subscribe_his_consumption_arr = $all_output['APP_getSubscriberAllQuota_SBO_today']['data']['historyQuota'];

                                                for($s=0; $s<count($subscribe_his_consumption_arr); $s++) {
                                                    $ttl_data_consumption += $subscribe_his_consumption_arr[$s]['qtaconsumption'];
                                                }

                                                $today_data_consumption_num = number_format($subscribe_his_consumption_arr[0]['qtaconsumption'], 2);
                                                //$today_data_consumption_num = number_format($subscribe_his_consumption_arr[0]['qtaconsumptionTotal'], 2);
                                                $cur_quote_bal = number_format($subscribe_consumption_arr['qtabalance'], 2);
                                                $cur_quote_limit = number_format($subscribe_consumption_arr['qtavalue'], 2);

                                                $ttl_data_consumption_num = number_format($subscribe_consumption_arr['qtaconsumption'], 2);
                                                //$ttl_data_consumption_num = number_format($ttl_data_consumption, 2);
                                            }

                                            $result['data']['ipt_smc_datausedtoday'] = $today_data_consumption_num;
                                            $result['data']['ipt_smc_ttlusedtraf'] = $ttl_data_consumption_num;
                                            $result['data']['quote_style'] = $cur_package_style;
                                            $result['data']['quote_limit'] = $cur_quote_limit;
                                            $result['data']['quote_bal'] = $cur_quote_bal;
                                            $result['data']['quote_formula'] = $cur_quote_bal;
                                            $result['data']['noticeshow'] = $show_notice;
                                            $result['data']['activationtime'] = $extra_info_activation_time;

                                            //////////////////////////////////////

                                            $termstate_func = 'APP_HIMSI_TERMSTATE_SBO/v1';
                                            $termstate_data = array(
                                                "accessToken" => $pass_tokent,
                                                "iccid" => $esim_val
                                            );

                                            $termstate_res = $this->china_mobile_api_call($api_secret, $api_key, $termstate_func, $pass_tokent, $termstate_data);
                                            if($termstate_res['status'] == 'success') {
                                                //SBO_query_usingTrajectories Data
                                                //$all_output['SBO_query_usingTrajectories'] = $usetrajectories_res;
                                                $all_output['APP_HIMSI_TERMSTATE_SBO'] = $termstate_res;

                                                $data_mmc = $all_output['APP_HIMSI_TERMSTATE_SBO']['data']['mobileCountryCode'];
                                                $result['data']['mmc'] = $all_output['APP_HIMSI_TERMSTATE_SBO']['data']['mobileCountryCode'];

                                                if(empty($all_output['APP_HIMSI_TERMSTATE_SBO']['data']['mobileCountryCode'])) {
                                                    $result['data']['last_country'] = 'Not Available';
                                                    $result['data']['timezone'] = $country_timezone;
                                                    $result['data']['ipt_smc_aviopet'] = '';
                                                    $result['data']['ipt_smc_netapn'] = '';
                                                }
                                                else {
                                                    //APP_queryCarrier_SBO
                                                    $qrycarrier_func = 'APP_queryCarrier_SBO/v1';
                                                    $qrycarrier_data = array(
                                                        "language" => "2",
                                                        "mcc" => $data_mmc
                                                    );

                                                    $qrycarrier_res = $this->china_mobile_api_call($api_secret, $api_key, $qrycarrier_func, $pass_tokent, $qrycarrier_data);

                                                    if($qrycarrier_res['status'] == 'success') {
                                                        //APP_queryCarrier_SBO Data
                                                        $all_output['APP_queryCarrier_SBO'] = $qrycarrier_res;

                                                        //APP_queryCarrier_SBO ===========
                                                        $carrier_country_name = '';
                                                        $carrier_list_arr = array();
                                                        $apn_list_arr = array();
                                                        $info_carrier_arr = $all_output['APP_queryCarrier_SBO']['data']['stateList'];

                                                        for($c=count($info_carrier_arr)-1; $c>=0; $c--) {
                                                            //$result['data']['country'] = $info_carrier_arr[$c]['country'];
                                                            //$result['data']['continent'] = $info_carrier_arr[$c]['continent'];
                                                            //$result['data']['mcc'] = $info_carrier_arr[$c]['mcc'];

                                                            $carrier_country_name = $info_carrier_arr[$c]['country'];

                                                            if(!in_array($info_carrier_arr[$c]['carrier'], $carrier_list_arr)) {
                                                                $carrier_list_arr[] = $info_carrier_arr[$c]['carrier'];
                                                            }

                                                            if(!in_array($info_carrier_arr[$c]['APN'], $apn_list_arr)) {
                                                                $apn_list_arr[] = $info_carrier_arr[$c]['APN'];
                                                            }
                                                        }

                                                        $sql_carrier_country_name = str_replace("'", "", $carrier_country_name);
                                                        $sql_carrier_country_name = str_replace(",", "", $sql_carrier_country_name);

                                                        $result['data']['last_country'] = $carrier_country_name;

                                                        /////////////////////////
                                                        // $qry_timezone = "SELECT * FROM " . $wpdb->prefix . "automatc_timezone_ctry c 
                                                        //     LEFT JOIN " . $wpdb->prefix . "automatc_timezone_states s ON(c.timez_ctry_id=s.timez_state_ctry_id) 
                                                        //     WHERE c.timez_ctry_name LIKE '%" . strtolower($carrier_country_name) . "%' AND s.timez_state_default='1' 
                                                        //     ORDER BY c.timez_ctry_name ASC LIMIT 1";
                                                        $qry_timezone = "SELECT * FROM (
                                                                (
                                                                    SELECT * FROM " . $wpdb->prefix . "automatc_timezone_ctry c
                                                                    LEFT JOIN " . $wpdb->prefix . "automatc_timezone_states s ON(c.timez_ctry_id=s.timez_state_ctry_id)
                                                                    WHERE c.timez_ctry_name='" . strtolower($sql_carrier_country_name) . "' AND s.timez_state_default='1' ORDER BY c.timez_ctry_name ASC
                                                                )
                                                                UNION
                                                                (
                                                                    SELECT * FROM " . $wpdb->prefix . "automatc_timezone_ctry c
                                                                    LEFT JOIN " . $wpdb->prefix . "automatc_timezone_states s ON(c.timez_ctry_id=s.timez_state_ctry_id)
                                                                    WHERE c.timez_ctry_name LIKE '%" . strtolower($sql_carrier_country_name) . "%' AND s.timez_state_default='1' ORDER BY c.timez_ctry_name ASC
                                                                )
                                                            ) a LIMIT 1";
                                                        $rs_timezone = $wpdb->get_row($qry_timezone, ARRAY_A);
                                                        $ttl_rs_timezone = $wpdb->num_rows;
                                                        
                                                        if($ttl_rs_timezone > 0) {
                                                            $result['data']['timezone'] = $rs_timezone['timez_state_tz'];
                                                        }
                                                        else {
                                                            $result['data']['timezone'] = $country_timezone;
                                                        }
                                                        /////////////////////////

                                                        $result['data']['ipt_smc_aviopet'] = implode(", ", $carrier_list_arr);
                                                        $result['data']['ipt_smc_netapn'] = implode(", ", $apn_list_arr);
                                                    }
                                                    else {
                                                        $internal_error = true;
                                                    }
                                                }
                                            }
                                            else {
                                                $internal_error = true;
                                            }
                                        }
                                        else {
                                            $internal_error = true;
                                        }
                                    }
                                    else {
                                        $internal_error = true;
                                    }
                                }
                                else {
                                    ////////////////////////
                                    $result['data']['ipt_smc_datausedtoday'] = "";
                                    $result['data']['ipt_smc_ttlusedtraf'] = "";
                                    $result['data']['quote_style'] = "";
                                    $result['data']['quote_limit'] = "";
                                    $result['data']['quote_bal'] = "";
                                    $result['data']['quote_formula'] = "";

                                    $result['data']['mmc'] = "";
                                    
                                    $result['data']['last_country'] = "";

                                    $result['data']['ipt_smc_aviopet'] = "";
                                    $result['data']['ipt_smc_netapn'] = "";

                                    $result['data']['timezone'] = $country_timezone;
                                }


                                // date_default_timezone_set("Asia/Singapore"); // your user's timezone
                                date_default_timezone_set($result['data']['timezone']); // your user's timezone
                                $sim_expire_new_date_str = $sim_expire_new_date . " UTC";
                                $sim_expire_new_date_conv = date("Y-m-d H:i:s", strtotime($sim_expire_new_date_str));

                                $result['data']['ipt_smc_expiry'] = $sim_expire_new_date_conv;


















                                for($b=0; $b<count($user_subscribed_arr); $b++) {
                                    //need to sort by "Order date", because "activation date" is empty if not avtivated
                                    //[createTime] => Order Date
                                    //need to get the latest status 3 1-time only, all other status 3 assign as "Used"
                                    
                                    date_default_timezone_set('UTC');
                                    $temp_from = date("Y-m-d H:i:s", strtotime($user_subscribed_arr[$b]['createTime']));
                                    $temp_now = date("Y-m-d H:i:s");
                                    $datediff = strtotime($temp_now) - strtotime($temp_from);
                                    //$datesort = ceil($datediff/86400);
                                    $datesort = $datediff;
                                    
                                    $check_style = strtolower($user_subscribed_arr[$b]['name'][0]['value']);
                                    
                                    $result['data']['orders'][$datesort]['datediff_ori'] = $datediff;
                                    
                                    if(substr_count($check_style, "unlimited") > 0) {
                                        $result['data']['orders'][$datesort]['style'] = 'unlimited';
                                    }
                                    else {
                                        $result['data']['orders'][$datesort]['style'] = 'fixed';
                                    }
                                    
                                    /////////////////==>
                                    // $result['data']['timezone']
                                    // date_default_timezone_set("Asia/Singapore"); // your user's timezone
                                    date_default_timezone_set($result['data']['timezone']); // your user's timezone
                                    if(!empty($user_subscribed_arr[$b]['createTime'])) {
                                        $createTime_str = $user_subscribed_arr[$b]['createTime'] . " UTC";
                                        $createTime = date("Y-m-d H:i:s", strtotime($createTime_str));
                                    }
                                    else {
                                        $createTime = "";
                                    }
                                    
                                    if(!empty($user_subscribed_arr[$b]['expireTime'])) {
                                        $expireTime_str = $user_subscribed_arr[$b]['expireTime'] . " UTC";
                                        $expireTime = date("Y-m-d H:i:s", strtotime($expireTime_str));
                                    }
                                    else {
                                        $expireTime = "";
                                    }
                                    
                                    if(!empty($user_subscribed_arr[$b]['endTime'])) {
                                        $endTime_str = $user_subscribed_arr[$b]['endTime'] . " UTC";
                                        $endTime = date("Y-m-d H:i:s", strtotime($endTime_str));
                                    }
                                    else {
                                        $endTime = "";
                                    }
                                    
                                    if(!empty($user_subscribed_arr[$b]['activeTime'])) {
                                        $activeTime_str = $user_subscribed_arr[$b]['activeTime'] . " UTC";
                                        $activeTime = date("Y-m-d H:i:s", strtotime($activeTime_str));
                                    }
                                    else {
                                        $activeTime = "";
                                    }
                                    
                                    $result['data']['orders'][$datesort]['bundleid'] = $user_subscribed_arr[$b]['dataBundleId'];
                                    $result['data']['orders'][$datesort]['subkey'] = $user_subscribed_arr[$b]['subscriptionKey'];
                                    $result['data']['orders'][$datesort]['package'] = $user_subscribed_arr[$b]['name'][0]['value'];
                                    $result['data']['orders'][$datesort]['createTime'] = $createTime;
                                    $result['data']['orders'][$datesort]['expireTime'] = $expireTime;
                                    $result['data']['orders'][$datesort]['endTime'] = $endTime;
                                    $result['data']['orders'][$datesort]['activeTime'] = $activeTime;
                                    $result['data']['orders'][$datesort]['status'] = $user_subscribed_arr[$b]['status'];
                                    
                                    // $result['testtime'][] = array(
                                    //     "name" => $user_subscribed_arr[$b]['name'][0]['value'],
                                    //     "order" => $createTime,
                                    //     "diff" => $datediff,
                                    //     "index" => $datesort
                                    // );
                                    
                                    /*if($user_subscribed_arr[$b]['status'] == '3') {
                                        $cur_package_name = strtolower($user_subscribed_arr[$b]['name'][0]['value']);
                                        
                                        if(substr_count($cur_package_name, "unlimited") > 0) {
                                            $cur_package_style = 'unlimited';
                                        }
                                        else {
                                            $cur_package_style = 'fixed';
                                        }
                                        
                                        $cur_quote_limit = 0;
                                        
//                                        if(substr_count($cur_package_name, "(") > 0) {
//                                            $cur_package_name_arr = explode("(", $cur_package_name);
//
//                                            if(substr_count($cur_package_name_arr[0], "unlimited") > 0) {
//                                                $cur_package_style = 'unlimited';
//                                            }
//                                            else {
//                                                $cur_package_style = 'fixed';
//                                            }
//
//                                            $cur_package_quote_arr = explode("/", $cur_package_name_arr[1]);
//
//                                            if(substr_count($cur_package_quote_arr[0], "gb") > 0) {
//                                                $cur_quote_limit = str_replace("gb", "", $cur_package_quote_arr[0]);
//                                                $cur_quote_limit = $cur_quote_limit * 1024;
//                                            }
//                                            else if(substr_count($cur_package_quote_arr[0], "mb") > 0) {
//                                                $cur_quote_limit = str_replace("mb", "", $cur_package_quote_arr[0]);
//                                            }
//                                            else {
//                                                $cur_quote_limit = 0;
//                                            }
//                                        }
//                                        else {
//                                            //Europe 30 Days 10GB Data Package
//                                            //Japan 30 Days 15GB Data Package
//                                            $cur_package_name_arr = explode("days", $cur_package_name);
//                                            
//                                            $cur_package_quote_arr = explode(" ", trim($cur_package_name_arr[1]));
//                                            
//                                            if(substr_count($cur_package_quote_arr[0], "gb") > 0) {
//                                                $cur_quote_limit = str_replace("gb", "", $cur_package_quote_arr[0]);
//                                                $cur_quote_limit = $cur_quote_limit * 1024;
//                                            }
//                                            else if(substr_count($cur_package_quote_arr[0], "mb") > 0) {
//                                                $cur_quote_limit = str_replace("mb", "", $cur_package_quote_arr[0]);
//                                            }
//                                            else {
//                                                $cur_quote_limit = 0;
//                                            }
//                                        }

                                        $result['data']['ipt_smc_curactvpac'] = $user_subscribed_arr[$b]['name'][0]['value'];
                                        $result['data']['ipt_smc_actvtime'] = $user_subscribed_arr[$b]['activeTime'];
                                        $result['data']['ipt_smc_pacend'] = $user_subscribed_arr[$b]['endTime'];

                                        $data_bundle_id = $user_subscribed_arr[$b]['dataBundleId'];
                                        $cur_subscribe_key = $user_subscribed_arr[$b]['subscriptionKey'];
                                        
                                        //$data_createtime = date("Ymd", strtotime($user_subscribed_arr[$b]['createTime']));
                                        //$data_endtime = date("Ymd", strtotime($user_subscribed_arr[$b]['endTime']));
                                        //$data_todaytime = date("Ymd");
                                        //$data_nextdaytime = date("Ymd", time() + 86400);
                                    }
                                    
                                    $result['data']['orders'][$datesort]['bundleid'] = $user_subscribed_arr[$b]['dataBundleId'];
                                    $result['data']['orders'][$datesort]['subkey'] = $user_subscribed_arr[$b]['subscriptionKey'];
                                    $result['data']['orders'][$datesort]['package'] = $user_subscribed_arr[$b]['name'][0]['value'];
                                    $result['data']['orders'][$datesort]['createtime'] = $user_subscribed_arr[$b]['createTime'];
                                    $result['data']['orders'][$datesort]['expiretime'] = $user_subscribed_arr[$b]['expireTime'];
                                    $result['data']['orders'][$datesort]['endTime'] = $user_subscribed_arr[$b]['endTime'];
                                    $result['data']['orders'][$datesort]['activeTime'] = $user_subscribed_arr[$b]['activeTime'];
                                    $result['data']['orders'][$datesort]['status_no'] = $user_subscribed_arr[$b]['status'];
                                    $result['data']['orders'][$datesort]['status'] = '';
                                    
                                    if($user_subscribed_arr[$b]['status'] == '1') {
                                        $result['data']['orders'][$datesort]['status'] = 'Not activated';
                                    }
                                    else if($user_subscribed_arr[$b]['status'] == '2') {
                                        $result['data']['orders'][$datesort]['status'] = 'Expired';
                                    }
                                    else if($user_subscribed_arr[$b]['status'] == '3') {
                                        $result['data']['orders'][$datesort]['status'] = 'Activated';
                                    }
                                    else if($user_subscribed_arr[$b]['status'] == '99') {
                                        $result['data']['orders'][$datesort]['status'] = 'Refunded';
                                    }
                                    else {
                                        $result['data']['orders'][$datesort]['status'] = 'NA';
                                    }*/
                                }
                                
                                date_default_timezone_set('UTC');
                                
                                ksort($result['data']['orders']);
                                $ttl_data_orders = count($result['data']['orders']);
                                
                                if(count($result['data']['orders']) > 0) {
                                    //re-order according status after date sorting
                                    //$result['data']['orders'][$datesort]
                                    $arr_reorder_used = array();
                                    $arr_reorder_expired = array();
                                    $arr_reorder_unuse = array();
                                    $arr_reorder_refunded = array();
                                    $arr_reorder_na = array();
                                    $arr_reorder_merge = array();
                                    $reorder_order_keys = array_keys($result['data']['orders']);

                                    for($c=0; $c<count($result['data']['orders']); $c++) {
                                        if($result['data']['orders'][$reorder_order_keys[$c]]['status'] == "1") {
                                            $arr_reorder_unuse[$reorder_order_keys[$c]] = $result['data']['orders'][$reorder_order_keys[$c]];
                                        }
                                        else if($result['data']['orders'][$reorder_order_keys[$c]]['status'] == "2") {
                                            $arr_reorder_expired[$reorder_order_keys[$c]] = $result['data']['orders'][$reorder_order_keys[$c]];
                                        }
                                        else if($result['data']['orders'][$reorder_order_keys[$c]]['status'] == "3") {
                                            $arr_reorder_used[$reorder_order_keys[$c]] = $result['data']['orders'][$reorder_order_keys[$c]];
                                        }
                                        else if($result['data']['orders'][$reorder_order_keys[$c]]['status'] == "99") {
                                            $arr_reorder_refunded[$reorder_order_keys[$c]] = $result['data']['orders'][$reorder_order_keys[$c]];
                                        }
                                        else {
                                            $arr_reorder_na[$reorder_order_keys[$c]] = $result['data']['orders'][$reorder_order_keys[$c]];
                                        }
                                    }

                                    $arr_reorder_merge = array_merge($arr_reorder_unuse, $arr_reorder_used, $arr_reorder_expired, $arr_reorder_refunded, $arr_reorder_na);
                                    $result['data']['orders'] = $arr_reorder_merge;
                                    
                                    // $result['test_reorder'] = $arr_reorder_merge;
                                }

                                if(count($result['data']['orders']) > 0) {
                                    $active_order_index = "";
                                    $first_activate_status = false;
                                    $check_cur_active = false;
                                    $uniqe_order_keys = array_keys($result['data']['orders']);
                                    
                                    // date_default_timezone_set("Asia/Singapore"); // your user's timezone
                                    date_default_timezone_set($result['data']['timezone']); // your user's timezone
                                    $temp_check_now = date("Y-m-d H:i:s");
                                    
                                    //$result['test']['now'] = $temp_check_now;
                                    
                                    // undo
                                    // date_default_timezone_set('UTC');
                                    
                                    // orders loop checking
                                    for($c=0; $c<count($result['data']['orders']); $c++) {
                                        if(($check_cur_active == false) && ($result['data']['orders'][$uniqe_order_keys[$c]]['status'] == "3") && (strtotime($temp_check_now) <= strtotime($result['data']['orders'][$uniqe_order_keys[$c]]['expireTime']))) {
                                            $active_order_index = $uniqe_order_keys[$c];
                                            $check_cur_active = true;
                                            
                                            $getactivationtime_arr = explode(" ", $result['data']['orders'][$uniqe_order_keys[$c]]['activeTime']);
                                            $extra_info_activation_time = $getactivationtime_arr[1];
                                            
                                            $result['data']['testtwo']['now'] = $temp_check_now;
                                            $result['data']['testtwo']['active'] = $result['data']['orders'][$uniqe_order_keys[$c]]['activeTime'];
                                            $result['data']['testtwo']['expire'] = $result['data']['orders'][$uniqe_order_keys[$c]]['expireTime'];
                                            $result['data']['testtwo']['endtime'] = $result['data']['orders'][$uniqe_order_keys[$c]]['endTime'];
                                            
                                            break;
                                        }
                                    }
                                    
                                    $html_table .= '<table>';
                                        $html_table .= '<tr>';
                                            $html_table .= '<td class="td_title">Package Name</td>';
                                            $html_table .= '<td class="td_title">Package Status</td>';
                                            $html_table .= '<td class="td_title">Activation Date/Time</td>';
                                            $html_table .= '<td class="td_title">End Date/Time</td>';
                                            $html_table .= '<td class="td_title">Order Date/Time</td>';
                                            $html_table .= '<td class="td_title">Expiry Date/Time</td>';
                                        $html_table .= '</tr>';

                                        for($r=0; $r<count($result['data']['orders']); $r++) {
                                            $inner_status_code = '';
                                            
                                            if(($active_order_index === $uniqe_order_keys[$r]) && ($result['data']['orders'][$uniqe_order_keys[$r]]['status'] == "3")) {
                                                if(isset($result['data']['orders'][$active_order_index])) {
                                                    $inner_status_code = "Activated";
                                                }
                                                else {
                                                    $inner_status_code = "Used";
                                                }
                                                        
                                                $first_activate_status = true;

                                                $result['data']['sampleactv_index'] = $active_order_index;
                                                $result['data']['sampleactv_key'] = $uniqe_order_keys[$r];

                                                $result['data']['ipt_smc_curactvpac'] = $result['data']['orders'][$active_order_index]['package'];
                                                $result['data']['ipt_smc_actvtime'] = $result['data']['orders'][$active_order_index]['activeTime'];
                                                $result['data']['ipt_smc_pacend'] = $result['data']['orders'][$active_order_index]['expireTime'];

                                                $data_bundle_id = $result['data']['orders'][$active_order_index]['bundleid'];
                                                $cur_subscribe_key = $result['data']['orders'][$active_order_index]['subkey'];

                                                $cur_package_style = $result['data']['orders'][$active_order_index]['style'];
                                            }
                                            else if(($active_order_index !== $uniqe_order_keys[$r]) && ($result['data']['orders'][$uniqe_order_keys[$r]]['status'] == "3")) {
                                                $inner_status_code = "Used";
                                            }
                                            else if($result['data']['orders'][$uniqe_order_keys[$r]]['status'] == "2") {
                                                $inner_status_code = "Expired";
                                            }
                                            else if($result['data']['orders'][$uniqe_order_keys[$r]]['status'] == "1") {
                                                //$inner_status_code = "Not activated";
                                                $inner_status_code = "Unuse";
                                            }
                                            else if($result['data']['orders'][$uniqe_order_keys[$r]]['status'] == "99") {
                                                $inner_status_code = "Refunded";
                                            }
                                            else {
                                                $inner_status_code = "NA";
                                            }
                                            
                                            if($r%2 == 0) {
                                                $css_cls = "td_one";
                                            }
                                            else {
                                                $css_cls = "td_two";
                                            }
                                            
                                            $html_table .= '<tr>';
                                                $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['package'].'</td>';
                                                $html_table .= '<td class="'.$css_cls.'">'.$inner_status_code.'</td>';

                                                if($result['data']['last_country'] == 'Not Available') {
                                                    $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['activeTime'].' (GMT+8)'.'</td>';
                                                    $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['expireTime'].' (GMT+8)'.'</td>';
                                                    $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['createTime'].' (GMT+8)'.'</td>';
                                                    $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['endTime'].'  (GMT+8)'.'</td>';
                                                }
                                                else if($result['data']['last_country'] == '') {
                                                    $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['activeTime'].' (GMT+8)'.'</td>';
                                                    $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['expireTime'].' (GMT+8)'.'</td>';
                                                    $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['createTime'].' (GMT+8)'.'</td>';
                                                    $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['endTime'].'  (GMT+8)'.'</td>';
                                                }
                                                else {
                                                    $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['activeTime'].' ('.$result['data']['last_country'].' Time)'.'</td>';
                                                    $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['expireTime'].' ('.$result['data']['last_country'].' Time)'.'</td>';
                                                    $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['createTime'].' ('.$result['data']['last_country'].' Time)'.'</td>';
                                                    $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['endTime'].' ('.$result['data']['last_country'].' Time)'.'</td>';
                                                }
                                            $html_table .= '</tr>';
                                        }
                                    $html_table .= '</table>';
                                    
                                    if(!$first_activate_status) {
                                        $result['data']['ipt_smc_curactvpac'] = "NIL";
                                        $result['data']['ipt_smc_actvtime'] = "";
                                        $result['data']['ipt_smc_pacend'] = "";

                                        $data_bundle_id = "";
                                        $cur_subscribe_key = "";

                                        $cur_package_style = "";
                                    }
                                    
                                    //$result['data']['ipt_smc_curactvpac'] = $result['data']['orders'][$uniqe_order_keys[0]]['package'];
                                    //$result['data']['ipt_smc_actvtime'] = $result['data']['orders'][$uniqe_order_keys[0]]['activeTime'];
                                    //$result['data']['ipt_smc_pacend'] = $result['data']['orders'][$uniqe_order_keys[0]]['expireTime'];

                                    //$data_bundle_id = $result['data']['orders'][$uniqe_order_keys[0]]['bundleid'];
                                    //$cur_subscribe_key = $result['data']['orders'][$uniqe_order_keys[0]]['subkey'];
                                    
                                    //$cur_package_style = $result['data']['orders'][$uniqe_order_keys[0]]['style'];
                                }
                                else {
                                    $result['data']['ipt_smc_curactvpac'] = "NIL";
                                    $result['data']['ipt_smc_actvtime'] = "";
                                    $result['data']['ipt_smc_pacend'] = "";

                                    $data_bundle_id = "";
                                    $cur_subscribe_key = "";
                                    
                                    $cur_package_style = "";
                                }
                            }
                            else {
                                $internal_error = true;
                            }

                            /*
                            //reverse operation
                            $smcexpiry = str_split($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['expireTime']);

                            $smc_expiry_date = $smcexpiry[0].$smcexpiry[1].$smcexpiry[2].$smcexpiry[3].'-'.$smcexpiry[4].$smcexpiry[5].'-'.$smcexpiry[6].$smcexpiry[7];
                            $smc_expiry_time = $smcexpiry[8].$smcexpiry[9].':'.$smcexpiry[10].$smcexpiry[11].':'.$smcexpiry[12].$smcexpiry[13];

                            $sim_expire_new_date = $smc_expiry_date . ' ' . $smc_expiry_time;

                            // date_default_timezone_set("Asia/Singapore"); // your user's timezone
                            date_default_timezone_set($result['data']['timezone']); // your user's timezone
                            $sim_expire_new_date_str = $sim_expire_new_date . " UTC";
                            $sim_expire_new_date_conv = date("Y-m-d H:i:s", strtotime($sim_expire_new_date_str));

                            $result['data']['ipt_smc_expiry'] = $sim_expire_new_date_conv;
                            */
                        }
                        else {
                            $internal_error = true;
                        }

                        if(!$internal_error) {
                            $result['table'] = $html_table;
                            $result['status'] = 'pass';
                            $result['html'] = '';
                            $result['msg'] = '';
                        }
                        else {
                            $result['table'] = $html_table;
                            $result['status'] = 'fail';
                            $result['html'] = '';
                            $result['msg'] = '<div class="badnews">Incomplete Checking. Please Try Again.</div>';
                        }
                    }
                    else {
                        $result['table'] = $html_table;
                        $result['status'] = 'fail';
                        $result['html'] = '';
                        $result['msg'] = '<div class="badnews">eSim ICCID Not Found.</div>';
                    }
                }
                else {
                    $result['table'] = $html_table;
                    $result['status'] = 'fail';
                    $result['html'] = '';
                    $result['msg'] = '<div class="badnews">eSim ICCID Not Found.</div>';
                }
            }
            else {
                $result['table'] = $html_table;
                $result['status'] = 'fail';
                $result['html'] = '';
                $result['msg'] = '<div class="badnews">Connection Timeout. Please Try Again.</div>';
            }
        }
        else {
            $result['table'] = $html_table;
            $result['status'] = 'fail';
            $result['html'] = '';
            $result['msg'] = '<div class="badnews">No eSIM ICCID Detected.</div>';
        }
        
        echo json_encode($result);
        
        unset($result);
        unset($all_output);
        
        die();
    }
    
    /*public function esim_status_check_result() {
        if(!wp_verify_nonce($_POST['nonce'], "check_smc_esim_nonce")) {
            die();
        }
        $internal_error = false;
        $cur_package_name = '';
        $cur_package_style = '';
        $cur_quote_limit = 0;
        $cur_quote_bal = 0;
        $cur_quote_formula = 0;
        $data_bundle_id = '';
        $data_mmc = '';
        $data_createtime = '';
        $data_endtime = '';
        $data_todaytime = '';
        $data_nextdaytime = '';
        $html_table = '';
        $result = array();
        $result['data'] = array();
        $all_output = array();
        $result['data']['orders'] = array();
        $result['data']['ipt_smc_curactvpac'] = '';
        $result['data']['ipt_smc_actvtime'] = '';
        $result['data']['ipt_smc_pacend'] = '';
        $result['data']['ipt_smc_idreg'] = '';
        $result['data']['ipt_smc_expiry'] = '';
        $result['data']['ipt_smc_status'] = '';
        $result['data']['ipt_smc_installdev'] = '';
        $result['data']['ipt_smc_datausedtoday'] = '';
        $result['data']['ipt_smc_ttlusedtraf'] = 0;
        $result['data']['ipt_smc_aviopet'] = '';
        $result['data']['ipt_smc_netapn'] = '';
        $result['data']['quote_style'] = '';
        $result['data']['quote_limit'] = 0;
        $result['data']['quote_bal'] = 0;
        $result['data']['quote_formula'] = 0;
        $result['data']['mmc'] = '';
        date_default_timezone_set('UTC');
        //action: "chkstatusesim", esim : esim, nonce: nonce
        $action_val = htmlentities($_POST['action'], ENT_QUOTES);
        $esim_val = htmlentities($_POST['esim'], ENT_QUOTES);
        if(!empty($esim_val)) {
            $api_secret = get_option('chinamobile_api_appsecret');
            $api_key = get_option('chinamobile_api_appkey');
            $access_func = 'APP_getAccessToken_SBO/v1';
            $access_tokent = '';
            $access_data = array(
                "id" => $api_key, 
                "type" => "106"
            );
            $access_res = $this->china_mobile_api_call($api_secret, $api_key, $access_func, $access_tokent, $access_data);
            //if($access_res['status'] == 'success' && $access_res['data']['code'] == '0000000') {
            if($access_res['status'] == 'success') {
                //SBO_query_SIMInfo
                //SBO_queryEsimCardInfo
                //APP_getSubedUserDataBundle_SBO
                //APP_getSubscriberAllQuota_SBO_today - APP_getSubscriberAllQuota_SBO
                //APP_getSubscriberAllQuota_SBO_ttl - APP_getSubscriberAllQuota_SBO
                //SBO_query_usingTrajectories
                //APP_queryCarrier_SBO
                //SBO_query_SIMInfo
                $siminfo_func = 'SBO_query_SIMInfo/v1';
                $pass_tokent = $access_res['data']['accessToken'];
                $siminfo_item_arr = array(
                    "imsi" => "",
                    "iccid" => $esim_val
                );
                $siminfo_data = array(
                    $siminfo_item_arr
                );
                $siminfo_res = $this->china_mobile_api_call($api_secret, $api_key, $siminfo_func, $pass_tokent, $siminfo_data);
                if($siminfo_res['status'] == 'success') {
                    if(count($siminfo_res['data']['himsis']) > 0) {
                        //SBO_query_SIMInfo Data
                        $all_output['SBO_query_SIMInfo'] = $siminfo_res;
                        //SBO_queryEsimCardInfo
                        $esimcardinfo_func = 'SBO_queryEsimCardInfo/v1';
                        $esimcardinfo_data = array(
                            "iccid" => $esim_val,
                            "accessToken" => $pass_tokent
                        );
                        $esimcardinfo_res = $this->china_mobile_api_call($api_secret, $api_key, $esimcardinfo_func, $pass_tokent, $esimcardinfo_data);
                        if($esimcardinfo_res['status'] == 'success') {
                            //SBO_queryEsimCardInfo Data
                            $all_output['SBO_queryEsimCardInfo'] = $esimcardinfo_res;
                            //APP_getSubedUserDataBundle_SBO
                            $getsubdatabundle_func = 'APP_getSubedUserDataBundle_SBO/v1';
                            $getsubdatabundle_data = array(
                                "accessToken" => $pass_tokent,
                                "iccid" => $esim_val,
                                "language" => "2" //English
                            );
                            $getsubdatabundle_res = $this->china_mobile_api_call($api_secret, $api_key, $getsubdatabundle_func, $pass_tokent, $getsubdatabundle_data);
                            if($getsubdatabundle_res['status'] == 'success') {
                                //APP_getSubedUserDataBundle_SBO Data
                                $all_output['APP_getSubedUserDataBundle_SBO'] = $getsubdatabundle_res;
                                //***********************
                                //APP_getSubedUserDataBundle_SBO ===========
                                $user_subscribed_arr = $all_output['APP_getSubedUserDataBundle_SBO']['data']['userDataBundles'];
                                for($b=0; $b<count($user_subscribed_arr); $b++) {
                                    $temp_from = date("Y-m-d", strtotime($user_subscribed_arr[$b]['createTime']));
                                    $temp_now = date("Y-m-d");
                                    $datediff = strtotime($temp_now) - strtotime($temp_from);
                                    $datesort = ceil($datediff/86400);
                                    if($user_subscribed_arr[$b]['status'] == '3') {
                                        $cur_package_name = strtolower($user_subscribed_arr[$b]['name'][0]['value']);
                                        if(substr_count($cur_package_name, "(") > 0) {
                                            $cur_package_name_arr = explode("(", $cur_package_name);
                                            if(substr_count($cur_package_name_arr[0], "unlimited") > 0) {
                                                $cur_package_style = 'unlimited';
                                            }
                                            else {
                                                $cur_package_style = 'fixed';
                                            }
                                            $cur_package_quote_arr = explode("/", $cur_package_name_arr[1]);
                                            if(substr_count($cur_package_quote_arr[0], "gb") > 0) {
                                                $cur_quote_limit = str_replace("gb", "", $cur_package_quote_arr[0]);
                                                $cur_quote_limit = $cur_quote_limit * 1024;
                                            }
                                            else if(substr_count($cur_package_quote_arr[0], "mb") > 0) {
                                                $cur_quote_limit = str_replace("mb", "", $cur_package_quote_arr[0]);
                                            }
                                            else {
                                                $cur_quote_limit = 0;
                                            }
                                        }
                                        else {
                                            //Europe 30 Days 10GB Data Package
                                            //Japan 30 Days 15GB Data Package
                                            $cur_package_name_arr = explode("days", $cur_package_name);
                                            $cur_package_quote_arr = explode(" ", trim($cur_package_name_arr[1]));
                                            if(substr_count($cur_package_quote_arr[0], "gb") > 0) {
                                                $cur_quote_limit = str_replace("gb", "", $cur_package_quote_arr[0]);
                                                $cur_quote_limit = $cur_quote_limit * 1024;
                                            }
                                            else if(substr_count($cur_package_quote_arr[0], "mb") > 0) {
                                                $cur_quote_limit = str_replace("mb", "", $cur_package_quote_arr[0]);
                                            }
                                            else {
                                                $cur_quote_limit = 0;
                                            }
                                        }
                                        $result['data']['ipt_smc_curactvpac'] = $user_subscribed_arr[$b]['name'][0]['value'];
                                        $result['data']['ipt_smc_actvtime'] = $user_subscribed_arr[$b]['activeTime'];
                                        $result['data']['ipt_smc_pacend'] = $user_subscribed_arr[$b]['endTime'];
                                        $data_bundle_id = $user_subscribed_arr[$b]['dataBundleId'];
                                        $data_createtime = date("Ymd", strtotime($user_subscribed_arr[$b]['createTime']));
                                        $data_endtime = date("Ymd", strtotime($user_subscribed_arr[$b]['endTime']));
                                        $data_todaytime = date("Ymd");
                                        $data_nextdaytime = date("Ymd", time() + 86400);
                                    }
                                    $result['data']['orders'][$datesort]['package'] = $user_subscribed_arr[$b]['name'][0]['value'];
                                    $result['data']['orders'][$datesort]['createtime'] = $user_subscribed_arr[$b]['createTime'];
                                    $result['data']['orders'][$datesort]['expiretime'] = $user_subscribed_arr[$b]['expireTime'];
                                    if($user_subscribed_arr[$b]['status'] == '1') {
                                        $result['data']['orders'][$datesort]['status'] = 'Not activated';
                                    }
                                    else if($user_subscribed_arr[$b]['status'] == '2') {
                                        $result['data']['orders'][$datesort]['status'] = 'Expired';
                                    }
                                    else if($user_subscribed_arr[$b]['status'] == '3') {
                                        $result['data']['orders'][$datesort]['status'] = 'Activated';
                                    }
                                    else if($user_subscribed_arr[$b]['status'] == '99') {
                                        $result['data']['orders'][$datesort]['status'] = 'Refunded';
                                    }
                                    else {
                                        $result['data']['orders'][$datesort]['status'] = 'NA';
                                    }
                                }
                                //***********************
                                //APP_getSubscriberAllQuota_SBO_today - APP_getSubscriberAllQuota_SBO
                                $getallquotetoday_func = 'APP_getSubscriberAllQuota_SBO/v1';
                                $getallquotetoday_data = array(
                                    "iccid" => $esim_val,
                                    "beginTime" => $data_todaytime, //APP_getSubedUserDataBundle_SBO => active package => [createTime] => 2022-12-05 02:09:15
                                    "endTime" => $data_nextdaytime //"20230603" - APP_getSubedUserDataBundle_SBO => active package => [endTime] => 2023-06-03 02:09:15
                                );
                                $getallquotetoday_res = $this->china_mobile_api_call($api_secret, $api_key, $getallquotetoday_func, $pass_tokent, $getallquotetoday_data);
                                if($getallquotetoday_res['status'] == 'success') {
                                    //APP_getSubscriberAllQuota_SBO_today Data - APP_getSubscriberAllQuota_SBO
                                    $all_output['APP_getSubscriberAllQuota_SBO_today'] = $getallquotetoday_res;
                                    //APP_getSubscriberAllQuota_SBO_ttl - APP_getSubscriberAllQuota_SBO
                                    $getallquotettl_func = 'APP_getSubscriberAllQuota_SBO/v1';
                                    $getallquotettl_data = array(
                                        "iccid" => $esim_val,
                                        "beginTime" => $data_createtime, //APP_getSubedUserDataBundle_SBO => active package => [createTime] => 2022-12-05 02:09:15
                                        "endTime" => $data_endtime //APP_getSubedUserDataBundle_SBO => active package => [endTime] => 2023-06-03 02:09:15
                                    );
                                    $getallquotettl_res = $this->china_mobile_api_call($api_secret, $api_key, $getallquotettl_func, $pass_tokent, $getallquotettl_data);
                                    if($getallquotettl_res['status'] == 'success') {
                                        //APP_getSubscriberAllQuota_SBO_ttl Data - APP_getSubscriberAllQuota_SBO
                                        $all_output['APP_getSubscriberAllQuota_SBO_ttl'] = $getallquotettl_res;
                                        //SBO_query_usingTrajectories
                                        $usetrajectories_func = 'SBO_query_usingTrajectories/v1';
                                        $usetrajectories_data = array(
                                            "iccid" => $esim_val,
                                            "packageID" => $data_bundle_id,
                                            "language" => "1"
                                        );
                                        $usetrajectories_res = $this->china_mobile_api_call($api_secret, $api_key, $usetrajectories_func, $pass_tokent, $usetrajectories_data);
                                        if($usetrajectories_res['status'] == 'success') {
                                            //SBO_query_usingTrajectories Data
                                            $all_output['SBO_query_usingTrajectories'] = $usetrajectories_res;
                                            //***********************
                                            //SBO_query_usingTrajectories ===========
                                            $user_networks_arr = $all_output['SBO_query_usingTrajectories']['data']['trajectoriesList'];
                                            for($kr=0; $kr<count($user_networks_arr); $kr++) {
                                                $data_mmc = $user_networks_arr[$kr]['mcc'];
                                            }
                                            $result['data']['mmc'] = $data_mmc;
                                            //***********************
                                            //APP_queryCarrier_SBO
                                            $qrycarrier_func = 'APP_queryCarrier_SBO/v1';
                                            $qrycarrier_data = array(
                                                "language" => "2",
                                                "mcc" => $data_mmc
                                            );
                                            $qrycarrier_res = $this->china_mobile_api_call($api_secret, $api_key, $qrycarrier_func, $pass_tokent, $qrycarrier_data);
                                            if($qrycarrier_res['status'] == 'success') {
                                                //APP_queryCarrier_SBO Data
                                                $all_output['APP_queryCarrier_SBO'] = $qrycarrier_res;
                                                //*************** Start generate output ****************
                                                //SBO_query_SIMInfo =========== copy
                                                if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['realRuleList'][0]['authStatus'] == '1') {
                                                    $result['data']['ipt_smc_idreg'] = 'To be certified';
                                                }
                                                else if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['realRuleList'][0]['authStatus'] == '2') {
                                                    $result['data']['ipt_smc_idreg'] = 'Verifying';
                                                }
                                                else if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['realRuleList'][0]['authStatus'] == '3') {
                                                    $result['data']['ipt_smc_idreg'] = 'Certified';
                                                }
                                                else if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['realRuleList'][0]['authStatus'] == '4') {
                                                    $result['data']['ipt_smc_idreg'] = 'Authentication failed';
                                                }
                                                else if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['realRuleList'][0]['authStatus'] == '5') {
                                                    $result['data']['ipt_smc_idreg'] = 'The certificate has expired';
                                                }
                                                else {
                                                    $result['data']['ipt_smc_idreg'] = 'N/A';
                                                }
                                                //$result['data']['ipt_smc_idreg'] = $all_output['SBO_query_SIMInfo']['data']['himsis'][0]['realRuleList'][0]['authStatus'];
                                                //$result['data']['ipt_smc_expiry'] = $all_output['SBO_query_SIMInfo']['data']['himsis'][0]['expireTime']; //YYYYMMDDHHMMSS
                                                $smcexpiry = str_split($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['expireTime']);
                                                $smc_expiry_date = $smcexpiry[0].$smcexpiry[1].$smcexpiry[2].$smcexpiry[3].'-'.$smcexpiry[4].$smcexpiry[5].'-'.$smcexpiry[6].$smcexpiry[7];
                                                $smc_expiry_time = $smcexpiry[8].$smcexpiry[9].':'.$smcexpiry[10].$smcexpiry[11].':'.$smcexpiry[12].$smcexpiry[13];
                                                $result['data']['ipt_smc_expiry'] = $smc_expiry_date . ' ' . $smc_expiry_time;
                                                if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['status'] == '0') {
                                                    $result['data']['ipt_smc_status'] = 'Normal';
                                                }
                                                else if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['status'] == '1') {
                                                    $result['data']['ipt_smc_status'] = 'Pause';
                                                }
                                                else if($all_output['SBO_query_SIMInfo']['data']['himsis'][0]['status'] == '3') {
                                                    $result['data']['ipt_smc_status'] = 'Log out';
                                                }
                                                else {
                                                    //$result['data']['ipt_smc_status'] = 'QC';
                                                    $result['data']['ipt_smc_status'] = '';
                                                }
                                                //SBO_queryEsimCardInfo ===========
                                                $result['data']['ipt_smc_installdev'] = $all_output['SBO_queryEsimCardInfo']['data']['data']['installDevice'];
                                                //$result['SBO_queryEsimCardInfo'] = $all_output['SBO_queryEsimCardInfo'];
                                                //APP_getSubedUserDataBundle_SBO ===========
                                                ksort($result['data']['orders']);
                                                //$html_table .= '';
                                                $ttl_data_orders = count($result['data']['orders']);
                                                if(count($result['data']['orders']) > 0) {
                                                    $html_table .= '<table>';
                                                        $html_table .= '<tr>';
                                                            $html_table .= '<td class="td_title">Package Name</td>';
                                                            $html_table .= '<td class="td_title">Package Status</td>';
                                                            $html_table .= '<td class="td_title">Order Date/Time</td>';
                                                            $html_table .= '<td class="td_title">Expiry Date/Time</td>';
                                                        $html_table .= '</tr>';
                                                        $uniqe_order_keys = array_keys($result['data']['orders']);
                                                        for($r=0; $r<count($result['data']['orders']); $r++) {
                                                            if($r%2 == 0) {
                                                                $css_cls = "td_one";
                                                            }
                                                            else {
                                                                $css_cls = "td_two";
                                                            }
                                                            $html_table .= '<tr>';
                                                                $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['package'].'</td>';
                                                                $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['status'].'</td>';
                                                                $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['createtime'].'</td>';
                                                                $html_table .= '<td class="'.$css_cls.'">'.$result['data']['orders'][$uniqe_order_keys[$r]]['expiretime'].'</td>';
                                                            $html_table .= '</tr>';
                                                        }
                                                    $html_table .= '</table>';
                                                }
                                                //APP_getSubscriberAllQuota_SBO_today - APP_getSubscriberAllQuota_SBO ===========
                                                $today_data_consumption = 0.00;
                                                $today_consumption_arr = $all_output['APP_getSubscriberAllQuota_SBO_today']['data']['historyQuota'];
                                                for($t=0; $t<count($today_consumption_arr); $t++) {
                                                    $today_data_consumption += $today_consumption_arr[$t]['qtaconsumption'];
                                                }
                                                $today_data_consumption_num = number_format($today_data_consumption, 2);
                                                $result['data']['ipt_smc_datausedtoday'] = $today_data_consumption_num;
                                                //APP_getSubscriberAllQuota_SBO_ttl - APP_getSubscriberAllQuota_SBO ===========
                                                $ttl_data_consumption = 0.00;
                                                $ttl_consumption_arr = $all_output['APP_getSubscriberAllQuota_SBO_ttl']['data']['historyQuota'];
                                                for($s=0; $s<count($ttl_consumption_arr); $s++) {
                                                    $ttl_data_consumption += $ttl_consumption_arr[$s]['qtaconsumption'];
                                                }
                                                $ttl_data_consumption_num = number_format($ttl_data_consumption, 2);
                                                $result['data']['ipt_smc_ttlusedtraf'] = $ttl_data_consumption_num;
                                                $cur_quote_bal = $cur_quote_limit - $ttl_data_consumption_num;
                                                if($cur_package_style == 'unlimited') {
                                                    $cur_quote_formula = $cur_quote_limit - $today_data_consumption_num;
                                                }
                                                else {
                                                    $cur_quote_formula = $cur_quote_limit - $ttl_data_consumption_num;
                                                }
                                                $result['data']['quote_style'] = $cur_package_style;
                                                $result['data']['quote_limit'] = $cur_quote_limit;
                                                $result['data']['quote_bal'] = $cur_quote_bal;
                                                $result['data']['quote_formula'] = $cur_quote_formula;
                                                //APP_queryCarrier_SBO ===========
                                                $carrier_list_arr = array();
                                                $apn_list_arr = array();
                                                $info_carrier_arr = $all_output['APP_queryCarrier_SBO']['data']['stateList'];
                                                for($c=0; $c<count($info_carrier_arr); $c++) {
                                                    //$result['data']['country'] = $info_carrier_arr[$c]['country'];
                                                    //$result['data']['continent'] = $info_carrier_arr[$c]['continent'];
                                                    //$result['data']['mcc'] = $info_carrier_arr[$c]['mcc'];
                                                    if(!in_array($info_carrier_arr[$c]['carrier'], $carrier_list_arr)) {
                                                        $carrier_list_arr[] = $info_carrier_arr[$c]['carrier'];
                                                    }
                                                    if(!in_array($info_carrier_arr[$c]['APN'], $apn_list_arr)) {
                                                        $apn_list_arr[] = $info_carrier_arr[$c]['APN'];
                                                    }
                                                }
                                                $result['data']['ipt_smc_aviopet'] = implode(", ", $carrier_list_arr);
                                                $result['data']['ipt_smc_netapn'] = implode(", ", $apn_list_arr);
                                            }
                                            else {
                                                $internal_error = true;
                                            }
                                        }
                                        else {
                                            $internal_error = true;
                                        }
                                    }
                                    else {
                                        $internal_error = true;
                                    }
                                }
                                else {
                                    $internal_error = true;
                                }
                            }
                            else {
                                $internal_error = true;
                            }
                        }
                        else {
                            $internal_error = true;
                        }
                        if(!$internal_error) {
                            $result['table'] = $html_table;
                            $result['status'] = 'pass';
                            $result['html'] = '';
                            $result['msg'] = '';
                        }
                        else {
                            $result['table'] = $html_table;
                            $result['status'] = 'fail';
                            $result['html'] = '';
                            $result['msg'] = '<div class="badnews">Incomplete Checking. Please Try Again.</div>';
                        }
                    }
                    else {
                        $result['table'] = $html_table;
                        $result['status'] = 'fail';
                        $result['html'] = '';
                        $result['msg'] = '<div class="badnews">eSim ICCID Not Found.</div>';
                    }
                }
                else {
                    $result['table'] = $html_table;
                    $result['status'] = 'fail';
                    $result['html'] = '';
                    $result['msg'] = '<div class="badnews">eSim ICCID Not Found.</div>';
                }
            }
            else {
                $result['table'] = $html_table;
                $result['status'] = 'fail';
                $result['html'] = '';
                $result['msg'] = '<div class="badnews">Connection Timeout. Please Try Again.</div>';
            }
        }
        else {
            $result['table'] = $html_table;
            $result['status'] = 'fail';
            $result['html'] = '';
            $result['msg'] = '<div class="badnews">No eSIM ICCID Detected.</div>';
        }
        echo json_encode($result);
        unset($result);
        unset($all_output);
        die();
    }*/

    public function china_mobile_esim_status_check() {
        $loading_gif =  plugin_dir_url( __FILE__ ) . 'images/loading_progress.gif';
        ?>
        <div class="smcheckform">
            <div class="span_smcheck_msg"></div>
            <div class="smc_left_panel">
                <div class="smcboxseven smcspace smcdiv">
                    <div class="smclbl">Enter eSIM ICCID <span class="load_smc_esim"><img class="loadgif" src="<?php echo $loading_gif; ?>"/> Retrieving eSIM info...</span></div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_esim input-text" name="val_smc_esim" value=""/><br/>
                        <a href="#model_smc_esim" class="highlinelink" rel="modal:open">Where to find my eSIM ICCID?</a>
                    </div>
                </div>
                <div class="smcboxthree smcspace">
                    <?php
                    $chk_smc_esim_nonce = wp_create_nonce( 'check_smc_esim_nonce' );
                    ?>
                    <input type="hidden" class="chksmcesimnonce" value="<?php echo $chk_smc_esim_nonce; ?>"/>
                    <button type="button" name="val_smc_chk_esim" class="btn_esim_iccid chk_smc_esim button alt" style="">Check</button>
                </div>
                <div class="smcclear"></div>
                <div class="smcboxfiveleft smcdiv">
                    <div class="smclbl">eSIM status</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_status input-text" name="val_smc_status" value=""/>
                    </div>
                </div>
                <div class="smcboxfiveright smcdiv">
                    <div class="smclbl">eSIM Expiry Date/Time <a class="tooltip_main1" href="#" title="eSIM can be reuse till this date/time.">(?)</a></div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_expiry input-text" name="val_smc_expiry" value=""/>
                    </div>
                </div>
                <div class="smcclear"></div>
                <div class="smcdiv smcspace">
                    <div class="smclbl">Installation Device</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_installdev input-text" name="val_smc_installdev" value=""/>
                    </div>
                </div>
                <div class="smcclear"></div>
                <div class="smcdiv smcspace">
                    <div class="smclbl">Real Name Registration (Hong Kong & Taiwan visitors only)</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_idreg input-text" name="val_smc_idreg" value=""/>
                        <a class="highlinelink registerlink registerlinkhide" target="_blank" href="https://global.cmlink.com/store/realname?LT=en">Register here</a>
                    </div>
                </div>
                <div style="margin-top:20px;margin-bottom:20px;">
                    <a href="#model_smc_allorders" class="highlinelink btnhighlinelink button" style="" rel="modal:open">Order History</a>
                    <?php
                    //<a href="#model_smc_allorders" class="highlinelink" rel="modal:open">Click here to see your recent orders</a>
                    ?>
                </div>
                <div id="model_smc_esim" class="modal">
                    <p>
                        <h4>How to check eSIM ICCID</h4>
                        (8985234202xxxxxxxxxx)<br/><br/>
                        <b>iPhone:</b><br/>
                        <ol>
                            <li>Go to Settings > Mobile Data or Cellular Data > eSIM > Turn ON</li>
                            <li>Go to Settings > General > About</li>
                            <li>Scroll down until you see eSIM ICCID</li>
                            <li>Turn OFF eSIM</li>
                        </ol>
                        <b>Android Phones:</b><br/>
                        <ol>
                            <li>Go to Phone Settings page where it shows all SIM cards</li>
                            <li>Open eSIM information</li>
                        </ol>
                    </p>
                </div>
                <div id="model_smc_allorders" class="modal">
                    <p>
                        <h4>Recent Orders</h4>
                        <div class="allordershtml" style="overflow:auto;"></div>
                    </p>
                </div>
            </div>
            <div class="smc_right_panel">
                <div class="smcdiv smcspace">
                    <div class="smclbl">Current Activated Package</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_curactvpac input-text" name="val_smc_curactvpac" value=""/>
                    </div>
                </div>
                <div class="smcboxfiveleft smcdiv">
                    <div class="smclbl">Package Start Date/Time</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_actvtime input-text" name="val_smc_actvtime" value=""/>
                    </div>
                </div>
                <div class="smcboxfiveright smcdiv">
                    <div class="smclbl">Package End Date/Time</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_pacend input-text" name="val_smc_pacend" value=""/>
                    </div>
                </div>

                <?php
                // <div class="smcboxfiveleft smcdiv smcdailydiv">
                //     <div class="smclbl smcdailylbl">Data Used For Current 24-hours Cycle (MB)</div>
                //     <div class="div_smc_esim">
                //         <input type="text" class="ipt_smc_datausedtoday input-text" name="val_smc_datausedtoday" value=""/>
                //     </div>
                //     <span class="smcdailynotice noticestyle noticehide">
                //         You have exceeded the high-speed threshold for the current cycle. Speed will be slow until the cycle resets at <span class="smcdailynoticetime"></span> GMT+8
                //     </span>
                // </div>

                // <div class="smcboxfiveright smcdiv smctotaldiv">
                //     <div class="smclbl">Total Used Traffic (MB)</div>
                //     <div class="div_smc_esim">
                //         <input type="text" class="ipt_smc_ttlusedtraf input-text" name="val_smc_ttlusedtraf" value=""/>
                //     </div>
                // </div>
                ?>

                <div class="smcdiv smcspace smcdailydiv">
                    <div class="smclbl smcdailylbl">Data Used For Current 24-hours Cycle (MB)</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_datausedtoday input-text" name="val_smc_datausedtoday" value=""/>
                    </div>
                    <span class="smcdailynotice noticestyle noticehide">
                    Usage exceeded the high-speed threshold for the current 24hrs cycle. 
                    Data speed will slow to 384kbps until the cycle resets at <span class="smcdailynoticetime"></span>
                    </span>
                </div>

                <div class="smcdiv smcspace smctotaldiv">
                    <div class="smclbl">Total Used Traffic (MB)</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_ttlusedtraf input-text" name="val_smc_ttlusedtraf" value=""/>
                    </div>
                </div>

                <div class="smcboxfiveleft smcdiv">
                    <div class="smclbl">High Speed Data Limit (MB)</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_highspddatalmt input-text" name="val_smc_highspddatalmt" value=""/>
                    </div>
                </div>
                <div class="smcboxfiveright smcdiv">
                    <div class="smclbl">High Speed Data Balance (MB)</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_highspddatabal input-text" name="val_smc_highspddatabal" value=""/>
                    </div>
                </div>
                <div class="smcdiv smcspace">
                    <div class="smclbl">Available Operator</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_aviopet input-text" name="val_smc_aviopet" value=""/>
                    </div>
                </div>
                <div class="smcboxfiveleft smcdiv">
                    <div class="smclbl">Last Known Location</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_lastknowloc input-text" name="val_smc_lastknowloc" value=""/>
                    </div>
                </div>
                <div class="smcboxfiveright smcdiv">
                    <div class="smclbl">APN (Access Point Names)</div>
                    <div class="div_smc_esim">
                        <input type="text" class="ipt_smc_netapn input-text" name="val_smc_netapn" value=""/>
                    </div>
                </div>
            </div>
            <div class="smc_clear_panel">&nbsp;</div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />

        <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
        <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
        <script>
            jQuery(document).ready(function() {
                jQuery(".tooltip_main1").click(function(e) {
                    e.preventDefault();
                });

                jQuery(".tooltip_main1").tooltip({
                    position: {
                        my: "center bottom", // the "anchor point" in the tooltip element
                        at: "center top", // the position of that anchor point relative to selected element
                    }
                });  

                jQuery(".btn_esim_iccid").click( function(e) {
                    e.preventDefault();

                    jQuery(".load_smc_esim").show();
                    jQuery(".span_smcheck_msg").html("");
                    jQuery(".allordershtml").html("");
                    jQuery(".ipt_smc_status").val("");
                    jQuery(".ipt_smc_expiry").val("");
                    jQuery(".ipt_smc_installdev").val("");
                    jQuery(".ipt_smc_idreg").val("");
                    jQuery(".ipt_smc_curactvpac").val("");
                    jQuery(".ipt_smc_actvtime").val("");
                    jQuery(".ipt_smc_pacend").val("");
                    jQuery(".ipt_smc_datausedtoday").val("");
                    jQuery(".ipt_smc_ttlusedtraf").val("");
                    jQuery(".ipt_smc_highspddatalmt").val("");
                    jQuery(".ipt_smc_highspddatabal").val("");
                    jQuery(".ipt_smc_aviopet").val("");
                    jQuery(".ipt_smc_netapn").val("");
                    jQuery(".ipt_smc_lastknowloc").val("");
                    jQuery(".smcdailynotice").addClass("noticehide");
                    jQuery(".registerlink").addClass("registerlinkhide");

                    // jQuery(".smcdailydiv").addClass("smcboxfiveleft");
                    // jQuery(".smcdailydiv").removeClass("smcspace");
                    jQuery(".smctotaldiv").show();
                    // jQuery(".smcdailylbl").html("Data Used For The Day (MB)");

                    var esim = jQuery(".ipt_smc_esim").val();
                    var nonce = jQuery(".chksmcesimnonce").val();

                    if(esim == "") {
                        alert("Please kindly enter your eSIM ICCID.");
                        jQuery(".load_smc_esim").hide();
                    }
                    else {
                        jQuery.ajax({
                            type : "post",
                            url : "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                            data : {action: "chkstatusesim", esim : esim, nonce: nonce},
                            success: function(response) {
                                var json = jQuery.parseJSON(response);
                                jQuery(".ipt_smc_status").val(json.data.ipt_smc_status);
                                jQuery(".ipt_smc_installdev").val(json.data.ipt_smc_installdev);
                                jQuery(".ipt_smc_idreg").val(json.data.ipt_smc_idreg);
                                // jQuery(".ipt_smc_curactvpac").val(json.data.ipt_smc_curactvpac);

                                if(json.data.ipt_smc_curactvpac == null) {
                                    jQuery(".ipt_smc_curactvpac").val("");
                                }
                                else if(json.data.ipt_smc_curactvpac == "NIL") {
                                    jQuery(".ipt_smc_curactvpac").val("");
                                }
                                else {
                                    jQuery(".ipt_smc_curactvpac").val(json.data.ipt_smc_curactvpac);
                                }

                                jQuery(".ipt_smc_ttlusedtraf").val(json.data.ipt_smc_ttlusedtraf);
                                jQuery(".ipt_smc_highspddatalmt").val(json.data.quote_limit);
                                jQuery(".ipt_smc_highspddatabal").val(json.data.quote_formula);
                                jQuery(".ipt_smc_aviopet").val(json.data.ipt_smc_aviopet);
                                jQuery(".ipt_smc_netapn").val(json.data.ipt_smc_netapn);
                                jQuery(".ipt_smc_lastknowloc").val(json.data.last_country);

                                if(json.data.last_country == 'Not Available') {
                                    jQuery(".ipt_smc_expiry").val(json.data.ipt_smc_expiry + " (GMT+8)");
                                    jQuery(".ipt_smc_actvtime").val(json.data.ipt_smc_actvtime + " (GMT+8)");
                                    jQuery(".ipt_smc_pacend").val(json.data.ipt_smc_pacend + " (GMT+8)");
                                }
                                else {
                                    if(json.data.ipt_smc_actvtime == null) {
                                        jQuery(".ipt_smc_expiry").val("");
                                        jQuery(".ipt_smc_actvtime").val("");
                                        jQuery(".ipt_smc_pacend").val("");
                                    }
                                    else if(json.data.ipt_smc_actvtime == "") {
                                        jQuery(".ipt_smc_expiry").val("");
                                        jQuery(".ipt_smc_actvtime").val("");
                                        jQuery(".ipt_smc_pacend").val("");
                                    }
                                    else {
                                        jQuery(".ipt_smc_expiry").val(json.data.ipt_smc_expiry + " (" + json.data.last_country + " Time)");
                                        jQuery(".ipt_smc_actvtime").val(json.data.ipt_smc_actvtime + " (" + json.data.last_country + " Time)");
                                        jQuery(".ipt_smc_pacend").val(json.data.ipt_smc_pacend + " (" + json.data.last_country + " Time)");
                                    }
                                }

                                var reset_time_val = '';
                                if(json.data.ipt_smc_actvtime != "") {
                                    if(json.data.ipt_smc_actvtime != null) {
                                        var reset_time = json.data.ipt_smc_actvtime.split(" ");
                                        reset_time_val = reset_time[1];
                                    }
                                }
                                
                                //if(json.data.mmc == "454") {
                                //    jQuery(".registerlink").removeClass("registerlinkhide");
                                //    jQuery(".ipt_smc_idreg").val("Registration required before you can use mobile data");
                                //}
                                //if(json.data.mmc == "466") {
                                //    jQuery(".registerlink").removeClass("registerlinkhide");
                                //    jQuery(".ipt_smc_idreg").val("Registration required before you can use mobile data");
                                //}

                                
                                // jQuery(".smcdailynoticetime").html(json.data.activationtime + " (" + json.data.last_country + " Time)");
                                jQuery(".smcdailynoticetime").html(reset_time_val + " (" + json.data.last_country + " Time)");
                                
                                if(json.data.noticeshow == "1") {
                                    jQuery(".smcdailynotice").removeClass("noticehide");
                                }
                                else {
                                    jQuery(".smcdailynotice").addClass("noticehide");
                                }

                                if(json.data.ipt_smc_idreg == "To be certified") {
                                    jQuery(".registerlink").removeClass("registerlinkhide");
                                    jQuery(".ipt_smc_idreg").val("Registration required before you can use mobile data");
                                }

                                if(json.data.quote_style == "unlimited") {
                                    jQuery(".ipt_smc_datausedtoday").val(json.data.ipt_smc_datausedtoday);
                                    // jQuery(".smcdailydiv").removeClass("smcboxfiveleft");
                                    // jQuery(".smcdailydiv").addClass("smcspace");
                                    // jQuery(".smcdailylbl").html("High Speed Data Used for Current 24hours Cycle (MB)");
                                    jQuery(".smctotaldiv").hide();
                                    jQuery(".smcdailydiv").show();
                                    console.log("option 1");
                                }
                                else {
                                    jQuery(".ipt_smc_datausedtoday").val(json.data.ipt_smc_datausedtoday);
                                    // jQuery(".smcdailydiv").addClass("smcboxfiveleft");
                                    // jQuery(".smcdailydiv").removeClass("smcspace");
                                    // jQuery(".smcdailylbl").html("Data Used For The Day (MB)");
                                    jQuery(".smctotaldiv").show();
                                    jQuery(".smcdailydiv").hide();
                                    console.log("option 2");
                                }

                                jQuery(".allordershtml").html(json.table);

                                if(json.status == "pass") {
                                    jQuery(".load_smc_esim").hide();
                                }
                                else {
                                    jQuery(".span_smcheck_msg").html(json.msg);
                                    jQuery(".load_smc_esim").hide();
                                }
                            }
                        });
                    }
                });
            });
        </script>
        <style>
            .ui-tooltip, .arrow:after {
                background: #000;
            }
            .ui-tooltip {
                /*
                padding: 10px 20px;
                border-radius: 20px;
                font: bold 14px "Helvetica Neue", Sans-Serif;
                text-transform: uppercase;
                box-shadow: 0 0 7px black;
                */
                font-size: 13px;
                padding:5px 15px;
                color: #fff;
                box-shadow: none !important;
                border: none !important;
            }
            @media (min-width: 1025px) {
                .smcheckform .smc_left_panel {
                    width:50%;
                    padding:0px 20px;
                    float:left;
                }
                .smcheckform .smc_right_panel {
                    width:50%;
                    padding:0px 20px;
                    float:left;
                }
                .smcheckform .smc_clear_panel {
                    clear: both;
                }
                .smcheckform .smcboxseven {
                    float:left;
                    width:70%;
                }
                .smcheckform .smcboxthree {
                    float:left;
                    width:30%;
                    padding-top:28px;
                }
                .smcheckform .smcboxfiveleft {
                    float:left;
                    width:50%;
                    padding:0px 20px 10px 0px;
                }
                .smcheckform .smcboxfiveright {
                    float:left;
                    width:50%;
                    padding:0px 0px 10px 20px;
                }
            }
            @media (min-width: 768px) and (max-width: 1024px) {
                .smcheckform .smc_left_panel {
                    width:100%;
                    padding:10px 20px;
                    float:left;
                }
                .smcheckform .smc_right_panel {
                    width:100%;
                    padding:10px 20px;
                    float:left;
                    border-left:none;
                }
                .smcheckform .smc_clear_panel {
                    clear: both;
                }
                .smcheckform .smcboxseven {
                    float:left;
                    width:70%;
                }
                .smcheckform .smcboxthree {
                    float:left;
                    width:30%;
                    padding-top:28px;
                }
                .smcheckform .smcboxfiveleft {
                    float:left;
                    width:50%;
                    padding:0px 20px 10px 0px;
                }
                .smcheckform .smcboxfiveright {
                    float:left;
                    width:50%;
                    padding:0px 0px 10px 20px;
                }
            }
            @media (max-width: 767px) {
                .smcheckform .smc_left_panel {
                    width:100%;
                    padding:10px 20px;
                    float:left;
                }
                .smcheckform .smc_right_panel {
                    width:100%;
                    padding:10px 20px;
                    float:left;
                    border-left:none;
                }
                .smcheckform .smc_clear_panel {
                    clear: both;
                }
                .smcheckform .smcboxseven {
                    float:left;
                    width:70%;
                }
                .smcheckform .smcboxthree {
                    float:left;
                    width:30%;
                    padding-top:25px;
                }
                .smcheckform .smcboxfiveleft {
                    float:left;
                    width:100%;
                    padding:0px 0px 10px 0px;
                }
                .smcheckform .smcboxfiveright {
                    float:left;
                    width:100%;
                    padding:0px 0px 10px 0px;
                }
            }
            .load_smc_esim {
                display:none;
            }
            .registerlinkhide {
                display:none;
            }
            .noticehide {
                display:none;
            }
            .noticestyle {
                color:#cf0a13;
            }
            .smcheckform .smcspace {
                padding-bottom: 20px;
            }
            .smcheckform .smcclear {
                clear:both;
            }
            .smcheckform .highlinelink {
                color:#7dbae6;
                text-decoration: underline;
            }
            .smcheckform .loadgif {
                width:12px;
                margin-top:-2px;
                margin-left:5px;
            }
            .smcheckform .input-text {
                width: 100%;
            }
            .smcheckform .btn_esim_iccid {
                margin-left:10px;
                font-family: Montserrat;
                border-radius: 25px;
                box-shadow: 5px 5px 25px 0px rgba(0,0,0,0.25);
                background: linear-gradient(#7775a9, #4e4d67) !important;
                /*background:#7e7d9c;*/
            }
            .smcheckform .btn_esim_iccid:hover {
                background: linear-gradient(#54536c, #302f44) !important;
            }
            .btnhighlinelink {
                /*margin-left:10px;*/
                font-family: Montserrat;
                text-decoration:none !important;
                color:#fff !important;
                padding:14px 40px !important;
                border-radius: 25px !important;
                box-shadow: 5px 5px 25px 0px rgba(0,0,0,0.25) !important;
                background: linear-gradient(#7775a9, #4e4d67) !important;
                /*background:#7e7d9c;*/
            }
            .btnhighlinelink:hover {
                background: linear-gradient(#54536c, #302f44) !important;
            }
            .smcheckform .goodnews {
                background: #edfff8;
                border:1px solid #dbf4ea;
                padding:20px 20px;
                margin-bottom:10px;
            }
            .smcheckform .badnews {
                background: #ffeded;
                border:1px solid #f4dbdb;
                padding:20px 20px;
                margin-bottom:10px;
            }
            #model_smc_allorders .td_title {
                background: #f2f9f6;font-weight: bold;
            }
            #model_smc_allorders .td_one {
                background: #fff;
            }
            #model_smc_allorders .td_two {
                background: #f2f9f6;
            }
        </style>
        <?php
    }
    
    //shortcode display
    public function main_shortcode_output() {
        $loading_gif =  plugin_dir_url( __FILE__ ) . 'images/loading_progress.gif';
        //require_once '/path/to/stripe-php/init.php';
        ?>
        <div class="topupform">
            <div class="span_topup_msg"></div>
            <div class="tpfdiv span_esim">
                <div class="tpflbl lbl_esim">Enter eSIM ICCID <img class="loadgif load_esim" src="<?php echo $loading_gif; ?>"/></div>
                <div class="div_esim">
                    <input type="text" class="ipt_esim input-text" name="val_esim" value=""/><br/>
                    <a href="#model_esim" class="highlinelink" rel="modal:open">Where to get your eSIM ICCID</a>
                </div>
            </div>
            <div class="tpfdiv span_vouchercode">
                <div class="tpflbl lbl_vouchercode">Enter Voucher Code (If you have one)</div>
                <div class="div_vouchercode">
                    <input type="text" class="ipt_vouchercode input-text" name="val_vouchercode" value=""/>
                    <input type="hidden" class="res_vou_num input-text" name="res_vou_num" value=""/>
                    <input type="hidden" class="res_vou_status input-text" name="res_vou_status" value=""/>
                    <input type="hidden" class="res_vou_type input-text" name="res_vou_type" value=""/>
                    <input type="hidden" class="res_vou_val input-text" name="res_vou_val" value=""/>
                </div>
            </div>
            <div id="model_esim" class="modal">
                <p>
                    <h4>How to check eSIM ICCID</h4>
                    (8985234202xxxxxxxxxx)<br/><br/>
                    <b>iPhone:</b><br/>
                    <ol>
                        <li>Go to Settings > Mobile Data or Cellular Data > eSIM > Turn ON</li>
                        <li>Go to Settings > General > About</li>
                        <li>Scroll down until you see eSIM ICCID</li>
                        <li>Turn OFF eSIM</li>
                    </ol>
                    <b>Android Phones:</b><br/>
                    <ol>
                        <li>Go to Phone Settings page where it shows all SIM cards</li>
                        <li>Open eSIM information</li>
                    </ol>
                </p>
            </div>
            <?php
            $chk_esim_nonce = wp_create_nonce( 'check_esim_nonce' );
            ?>
            <input type="hidden" class="chkesimnonce" value="<?php echo $chk_esim_nonce; ?>"/>
            <button type="button" name="val_chk_esim" class="btn_esim chk_esim button alt" style="font-family: Montserrat;">Next</button>

            <div class="tpfdiv span_vouchermsg"></div>

            <div class="tpfdiv span_region">
                <div class="tpflbl lbl_region">Select Region <img class="loadgif load_region" src="<?php echo $loading_gif; ?>"/></div>
                <div class="tpfinput div_region">
                    <select class="ipt_region input-text" name="val_region">
                    </select>
                </div>
            </div>
            <?php
            $chk_dest_nonce = wp_create_nonce( 'check_dest_nonce' );
            ?>
            <input type="hidden" class="chkdestnonce" value="<?php echo $chk_dest_nonce; ?>"/>
            <div class="tpfdiv span_destination">
                <div class="tpflbl lbl_destination">Select Destination <img class="loadgif load_destination" src="<?php echo $loading_gif; ?>"/></div>
                <div class="tpfinput div_destination">
                    <select class="ipt_destination input-text" name="val_destination">
                    </select><br/>
                    <a href="#model_destination" class="destmodellink highlinelink" rel="modal:open">Click here to see covered countries</a>
                </div>
            </div>
            <div id="model_destination" class="modal">
                <p class="modeldestcontent"></p>
            </div>
            <?php
            $chk_plan_nonce = wp_create_nonce( 'check_plan_nonce' );
            ?>
            <input type="hidden" class="chkplannonce" value="<?php echo $chk_plan_nonce; ?>"/>
            <div class="tpfdiv span_dataplan">
                <div class="tpflbl lbl_dataplan">Select Data Plans <img class="loadgif load_dataplan" src="<?php echo $loading_gif; ?>"/></div>
                <div class="tpfinput div_dataplan">
                    <select class="ipt_dataplan input-text" name="val_dataplan">
                    </select>
                    <div class="price_dataplan"></div>
                </div>
            </div>
            <?php
            $chk_pricing_nonce = wp_create_nonce( 'check_price_nonce' );
            ?>
            <input type="hidden" class="chkpricenonce" value="<?php echo $chk_pricing_nonce; ?>"/>
            <div class="tpfdiv span_chkemail">
                <div class="tpflbl lbl_chkemail">Enter email</div>
                <div class="tpfinput div_chkemail">
                    <input type="text" class="ipt_chkemail input-text" name="val_chkemail" value=""/>
                </div>
            </div>
            <?php
            $form_nonce = wp_create_nonce( 'check_form_nonce' );
            ?>
            <input type="hidden" name="formnonce" class="formnonce" value="<?php echo $form_nonce; ?>"/>
            <input type="hidden" name="submission" value="complete_order"/>
            <input type="hidden" name="proid" class="filterproid" value=""/>
            <button type="button" name="val_paystripe" class="btn_paystripe button alt" style="font-family: Montserrat;">Make Payment</button>
            <img class="loadgif load_paystripe" src="<?php echo $loading_gif; ?>"/>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
        <script>
            jQuery(document).ready(function() {
                jQuery(".btn_esim").click( function(e) {
                    e.preventDefault();

                    jQuery(".span_topup_msg").html("");
                    jQuery(".span_region").hide();
                    jQuery(".span_destination").hide();
                    jQuery(".span_dataplan").hide();
                    jQuery(".span_chkemail").hide();
                    jQuery(".btn_paystripe").hide();
                    jQuery(".filterproid").val("");
                    jQuery(".price_dataplan").html("");
                    jQuery(".modeldestcontent").html("");

                    //voucher code
                    jQuery(".res_vou_num").val("");
                    jQuery(".res_vou_status").val("");
                    jQuery(".res_vou_type").val("");
                    jQuery(".res_vou_val").val("");
                    jQuery(".span_vouchermsg").html("");
                    jQuery(".span_vouchermsg").hide();
                    
                    var esim = jQuery.trim(jQuery(".ipt_esim").val());
                    var nonce = jQuery(".chkesimnonce").val();
                    var voucher = jQuery.trim(jQuery(".ipt_vouchercode").val());

                    if(esim != "") {
                        jQuery(".load_esim").show();

                        jQuery.ajax({
                            type : "post",
                            url : "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                            data : {action: "chkesim", esim : esim, nonce: nonce, voucher: voucher},
                            success: function(response) {
                                var json = jQuery.parseJSON(response);

                                if(json.status == "pass") {
                                    jQuery(".ipt_region").html(json.html);
                                    jQuery(".span_region").show();
                                    jQuery(".load_esim").hide();

                                    //voucher code
                                    jQuery(".res_vou_num").val(json.vou.discount_num);
                                    jQuery(".res_vou_status").val(json.vou.discount_status);
                                    jQuery(".res_vou_type").val(json.vou.discount_type);
                                    jQuery(".res_vou_val").val(json.vou.discount_val);

                                    if(voucher != "" && json.vou.discount_status == "1") {
                                        // console.log("show success voucher");
                                        jQuery(".span_vouchermsg").html("Voucher code successfully applied.");
                                        jQuery(".span_vouchermsg").show();
                                    }
                                    else if(voucher != "" && json.vou.discount_status == "2") {
                                        // console.log("show error voucher");
                                        jQuery(".span_vouchermsg").html("Invalid voucher code. Voucher code failed to apply. You may continue without voucher code. Thank you.");
                                        jQuery(".span_vouchermsg").show();
                                    }
                                }
                                else {
                                    jQuery(".span_topup_msg").html(json.result);
                                    jQuery(".load_esim").hide();

                                    //voucher code
                                    jQuery(".res_vou_status").val(json.vou.discount_status);
                                }
                            },
                            error: function (request, status, error) {
                                jQuery(".span_topup_msg").html("Request timeout. Please Try Search Again. Thank You.");
                                jQuery(".load_esim").hide();

                                //alert(request.responseText);
                                //location.reload()
                            }
                        });
                    }
                    else {
                        alert("Please key-in your eSim number. Thank you.");
                    }
                });

                jQuery(".ipt_region").change( function(e) {
                    e.preventDefault();

                    jQuery(".load_region").show();
                    jQuery(".span_destination").hide();
                    jQuery(".span_dataplan").hide();
                    jQuery(".span_chkemail").hide();
                    jQuery(".btn_paystripe").hide();
                    jQuery(".filterproid").val("");
                    jQuery(".price_dataplan").html("");

                    var regval = jQuery(this).val();
                    var nonce = jQuery(".chkdestnonce").val();

                    jQuery.ajax({
                        type : "post",
                        url : "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                        data : {action: "chkdest", regval : regval, nonce: nonce},
                        success: function(response) {
                            var json = jQuery.parseJSON(response);

                            if(json.status == "pass") {
                                jQuery(".ipt_destination").html(json.html);
                                jQuery(".modeldestcontent").html(json.cover);
                                jQuery(".destmodellink").hide();
                                jQuery(".span_destination").show();
                                jQuery(".load_region").hide();
                            }
                            else {
                                //alert("We could not find any result.");
                                jQuery(".span_destination").hide();
                                jQuery(".load_region").hide();
                            }
                        }
                    });
                });

                jQuery(".ipt_destination").change( function(e) {
                    e.preventDefault();
                    jQuery(".load_destination").show();
                    jQuery(".span_dataplan").hide();
                    jQuery(".span_chkemail").hide();
                    jQuery(".btn_paystripe").hide();
                    jQuery(".filterproid").val("");
                    jQuery(".price_dataplan").html("");

                    var destval = jQuery(this).val();
                    var nonce = jQuery(".chkplannonce").val();

                    if(destval == "") {
                        jQuery(".destmodellink").hide();
                        jQuery(".hidesupportinfoblock").hide();
                    }
                    else {
                        jQuery(".destmodellink").show();
                        jQuery(".hidesupportinfoblock").hide();

                        var newinfoblockcls = "." + destval + "_infoblock";
                        jQuery(newinfoblockcls).show();
                    }

                    jQuery.ajax({
                        type : "post",
                        url : "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                        data : {action: "chkplan", destval : destval, nonce: nonce},
                        success: function(response) {
                            var json = jQuery.parseJSON(response);

                            if(json.status == "pass") {
                                jQuery(".ipt_dataplan").html(json.html);
                                jQuery(".span_dataplan").show();
                                jQuery(".load_destination").hide();
                            }
                            else {
                                //alert("We could not find any result.");
                                jQuery(".span_dataplan").hide();
                                jQuery(".load_destination").hide();
                            }
                        }
                    });
                });

                jQuery(".ipt_dataplan").change( function(e) {
                    e.preventDefault();

                    jQuery(".load_dataplan").show();
                    jQuery(".span_chkemail").hide();
                    jQuery(".btn_paystripe").hide();
                    jQuery(".filterproid").val("");
                    jQuery(".price_dataplan").html("");

                    //Voucher code
                    var vou_code = jQuery(".ipt_vouchercode").val();
                    var vou_num = jQuery(".res_vou_num").val();
                    var vou_status = jQuery(".res_vou_status").val();
                    var vou_type = jQuery(".res_vou_type").val();
                    var vou_val = jQuery(".res_vou_val").val();
                    var esim = jQuery(".ipt_esim").val();

                    var planval = jQuery(this).val();
                    var nonce = jQuery(".chkpricenonce").val();

                    jQuery.ajax({
                        type : "post",
                        url : "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                        data : {action: "chkprice", planval : planval, nonce: nonce, vou_code: vou_code, vou_num: vou_num, vou_status: vou_status, vou_type: vou_type, vou_val: vou_val, esim: esim},
                        success: function(response) {
                            var json = jQuery.parseJSON(response);

                            if(json.status == "pass") {
                                jQuery(".price_dataplan").html(json.html.output);
                                jQuery(".filterproid").val(json.html.pro_id);
                                jQuery(".btn_paystripe").show();
                                jQuery(".span_chkemail").show();
                                jQuery(".load_dataplan").hide();
                            }
                            else {
                                jQuery(".load_dataplan").hide();
                                //alert("We could not find any result.");
                                //jQuery(".span_dataplan").hide();
                            }
                        }
                    });
                });

                jQuery(".btn_paystripe").click( function(e) {
                    e.preventDefault();

                    var proid = jQuery(".filterproid").val();
                    var esim = jQuery(".ipt_esim").val();
                    var chkemail = jQuery(".ipt_chkemail").val();
                    var nonce = jQuery(".formnonce").val();
                    var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

                    //Voucher code
                    var vou_code = jQuery(".ipt_vouchercode").val();
                    var vou_num = jQuery(".res_vou_num").val();
                    var vou_status = jQuery(".res_vou_status").val();
                    var vou_type = jQuery(".res_vou_type").val();
                    var vou_val = jQuery(".res_vou_val").val();

                    if(chkemail === "") {
                        alert("Please Enter Your Email Address.");
                    }
                    else {
                        if(!regex.test(chkemail)) {
                            alert("Invalid Email Address.");
                        }
                        else {
                            jQuery(".load_paystripe").show();
                            jQuery.ajax({
                                type : "post",
                                url : "<?php echo admin_url( 'admin-ajax.php' ); ?>",
                                data : {action: "chkoutpln", proid : proid, esim: esim, chkemail: chkemail, nonce: nonce, vou_code:vou_code, vou_num:vou_num, vou_status:vou_status, vou_type:vou_type, vou_val:vou_val},
                                success: function(response) {
                                    var json = jQuery.parseJSON(response);

                                    if(json.status == "pass") {
                                        window.location = json.url;
                                        //window.location = "<?php echo wc_get_checkout_url(); ?>";
                                        //jQuery(".price_dataplan").html(json.html.output);
                                        //jQuery(".filterproid").val(json.html.pro_id);
                                        //jQuery(".btn_paystripe").show();
                                        //jQuery(".load_dataplan").hide();
                                    }
                                    else {
                                        //jQuery(".load_dataplan").hide();
                                        //alert("We could not find any result.");
                                        //jQuery(".span_dataplan").hide();
                                    }
                                }
                            });
                        }
                    }
                });
            });
        </script>
        <style>
            .topupform .highlinelink {
                color:#7dbae6;
                text-decoration: underline;
            }
            .topupform .loadgif {
                width:12px;
                margin-top:-2px;
                margin-left:5px;
            }
            .topupform .goodnews {
                background: #edfff8;
                border:1px solid #dbf4ea;
                padding:20px 20px;
                margin-bottom:10px;
            }
            .topupform .badnews {
                background: #ffeded;
                border:1px solid #f4dbdb;
                padding:20px 20px;
                margin-bottom:10px;
            }
            .topupform .tpfdiv {
                margin-bottom:20px;
            }
            .topupform .btn_esim {
                margin-bottom:20px;
            }
            .topupform input, .topupform select {
                width:100%;
            }
            .span_vouchermsg {
                display:none;
                color:red;
            }
            .span_region, .span_destination, .span_dataplan, .span_chkemail, .btn_paystripe {
                display:none;
            }
            .load_esim, .load_region, .load_destination, .load_dataplan, .load_paystripe {
                display:none;
            }
            .hidesupportinfoblock {
                display:none;
            }
            .topupform .infoprice {
                margin-top: 10px;
                font-weight: bold;
                font-size: 19px;
            }
            .topupform .woocommerce-Price-amount, .topupform .woocommerce-Price-currencySymbol {
                font-size: 19px !important;
            }
            .topupform .infodesc {
                margin-top:5px;
            }
        </style>
        <?php
    }
    
    //https://support.huaweicloud.com/intl/en-us/devg-msgsms/sms_04_0003.html
    function buildWsseHeader(string $appKey, string $appSecret){
        $now = date('Y-m-d\TH:i:s\Z'); //Created
        $nonce = uniqid(); //Nonce
        $base64 = base64_encode(hash('sha256', ($nonce . $now . $appSecret))); //PasswordDigest
        return sprintf("UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"",
        $appKey, $base64, $nonce, $now);
    }
}

/*
//include shortcodes
include(plugin_dir_path(__FILE__) . 'inc/wp_location_shortcode.php');

//include widgets
include(plugin_dir_path(__FILE__) . 'inc/wp_location_widget.php');
*/

if(class_exists('wpcmproductload')) {
    $wpcmproductload = new wpcmproductload();
    //$wpcmproductload->initiate();
}
