<?php
/*
Plugin Name: Bonvoi
Plugin URI:  https://bonvoi.me
Description: Bonvoi Plugin
Version:     1.0.0
Author:      Jay
Author URI:  https://bonvoi.me
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/

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

class wpautomationbonvoi {
    // private $globalvar = array();

    public function __construct() {
        // $this->load_settings();
        $this->init();

        // add_action('init', array($this, 'check_and_purge_cloudflare_cache'), 1);

        //API - http://localhost:8039/bonvoi/wp-admin/admin-ajax.php?action=bv_orders
        add_action("wp_ajax_bv_orders", array($this, 'wpautomationbonvoi_bv_daily_reporting_api'));
        add_action("wp_ajax_nopriv_bv_orders", array($this, 'wpautomationbonvoi_bv_daily_reporting_api'));

        //API - http://localhost:8039/bonvoi/wp-admin/admin-ajax.php?action=bv_daily_report
        add_action("wp_ajax_bv_daily_report", array($this, 'wpautomationbonvoi_bv_daily_reporting_email'));
        add_action("wp_ajax_nopriv_bv_daily_report", array($this, 'wpautomationbonvoi_bv_daily_reporting_email'));

        // add_action("wp_ajax_internal_purge_cloudflare_cache", array($this, 'internal_purge_cloudflare_cache'));
        // add_action("wp_ajax_nopriv_internal_purge_cloudflare_cache", array($this, 'internal_purge_cloudflare_cache'));

        // add_action("wp_ajax_generate_chkregion", array($this, 'generate_chkregion'));
        // add_action("wp_ajax_nopriv_generate_chkregion", array($this, 'generate_chkregion'));

        // add_action("wp_ajax_generate_chkdest", array($this, 'generate_chkdest'));
        // add_action("wp_ajax_nopriv_generate_chkdest", array($this, 'generate_chkdest'));

        // add_action("wp_ajax_generate_chkplan", array($this, 'generate_chkplan'));
        // add_action("wp_ajax_nopriv_generate_chkplan", array($this, 'generate_chkplan'));

        // add_action("wp_ajax_generate_chkprice", array($this, 'generate_chkprice'));
        // add_action("wp_ajax_nopriv_generate_chkprice", array($this, 'generate_chkprice'));

        // add_action("wp_ajax_generate_chkesim", array($this, 'generate_chkesim'));
        // add_action("wp_ajax_nopriv_generate_chkesim", array($this, 'generate_chkesim'));

        // add_action("wp_ajax_generate_chkoutpln", array($this, 'save_complete_form'));
        // add_action("wp_ajax_nopriv_generate_chkoutpln", array($this, 'save_complete_form'));

        // add_action("wp_ajax_esim_stripe_success", array($this, 'stripe_success_ope'));
        // add_action("wp_ajax_nopriv_esim_stripe_success", array($this, 'stripe_success_ope'));

        // add_action("wp_ajax_new_esim_stripe_success", array($this, 'stripe_success_ope_v2'));
        // add_action("wp_ajax_nopriv_new_esim_stripe_success", array($this, 'stripe_success_ope_v2'));

        // add_action("wp_ajax_cronjob_stripe_success_ope_process", array($this, 'cronjob_stripe_success_ope_process'));
        // add_action("wp_ajax_nopriv_cronjob_stripe_success_ope_process", array($this, 'cronjob_stripe_success_ope_process'));

        // add_action("wp_ajax_cronjob_rerun_process_orders", array($this, 'cronjob_rerun_process_orders'));
        // add_action("wp_ajax_nopriv_cronjob_rerun_process_orders", array($this, 'cronjob_rerun_process_orders'));

        // add_action("wp_ajax_cronjob_rerun_process_orders_db", array($this, 'cronjob_rerun_process_orders_db'));
        // add_action("wp_ajax_nopriv_cronjob_rerun_process_orders_db", array($this, 'cronjob_rerun_process_orders_db'));

        // add_action("wp_ajax_test_apple_link", array($this, 'test_apple_link'));
        // add_action("wp_ajax_nopriv_test_apple_link", array($this, 'test_apple_link'));

        // //form save
        // add_action('admin_post_wpautomationesim_settings_update_nonce', array($this, 'settings_configuration_update'));
    }

    public function init() {
        add_action('admin_menu', array($this, 'bonvoi_add_menu_page'), 20); //admin menu

        //All forms submission
        add_action('admin_post_wpautomationbonvoi_settings_update_nonce', array($this, 'wpautomationbonvoi_settings_configuration_update'));

        //Staff
        add_action('admin_post_wpautomationbonvoi_bv_new_retail_staff_nonce', array($this, 'wpautomationbonvoi_bv_new_retail_staff_form'));
        add_action('admin_post_nopriv_wpautomationbonvoi_bv_new_retail_staff_nonce', array($this, 'wpautomationbonvoi_bv_new_retail_staff_form'));

        add_action('admin_post_wpautomationbonvoi_bv_update_retail_staff_nonce', array($this, 'wpautomationbonvoi_bv_update_retail_staff_form'));
        add_action('admin_post_wpautomationbonvoi_bv_delete_retail_staff_nonce', array($this, 'wpautomationbonvoi_bv_delete_retail_staff_form'));

        //Shop
        add_action('admin_post_wpautomationbonvoi_bv_new_retail_shop_nonce', array($this, 'wpautomationbonvoi_bv_new_retail_shops_form'));
        add_action('admin_post_wpautomationbonvoi_bv_update_retail_shop_nonce', array($this, 'wpautomationbonvoi_bv_update_retail_shops_form'));
        add_action('admin_post_wpautomationbonvoi_bv_delete_retail_shop_nonce', array($this, 'wpautomationbonvoi_bv_delete_retail_shops_form'));

        //Report
        add_action('admin_post_wpautomationbonvoi_custom_reporting_nonce', array($this, 'wpautomationbonvoi_bv_custom_reporting_form'));
        add_action('admin_post_nopriv_wpautomationbonvoi_custom_reporting_nonce', array($this, 'wpautomationbonvoi_bv_custom_reporting_form'));

        // add_action('admin_post_wpcompleteautomatc_shopee_sync_pro_delete_nonce', 'shopee_sync_pro_delete');
        // add_action('admin_post_wpcompleteautomatc_template_new_nonce', 'templates_content_new');
        // add_action('admin_post_wpcompleteautomatc_template_update_nonce', 'templates_content_update');
        // add_action('admin_post_wpcompleteautomatc_template_delete_nonce', 'templates_content_delete');

        // add_action("admin_post_wpcompleteautomatc_template_chat_new_nonce", array($this, 'templates_chat_content_new'));
        // add_action("admin_post_wpcompleteautomatc_template_chat_update_nonce", array($this, 'templates_chat_content_update'));
        // add_action("admin_post_wpcompleteautomatc_template_chat_delete_nonce", array($this, 'templates_chat_content_delete'));

        // add_action("admin_post_wpcompleteautomatc_template_rule_new_nonce", array($this, 'templates_rule_content_new'));
        // add_action("admin_post_wpcompleteautomatc_template_rule_update_nonce", array($this, 'templates_rule_content_update'));
        // add_action("admin_post_wpcompleteautomatc_template_rule_delete_nonce", array($this, 'templates_rule_content_delete'));

        // add_action('admin_post_wpcompleteautomatc_settings_update_nonce', 'settings_configuration_update');
        // add_action('admin_post_wpcompleteautomatc_klook_nbuilder_update_nonce', 'klook_nbuilder_setting_update');
        // add_action('admin_post_wpcompleteautomatc_shopee_order_cancel_nonce', 'shopee_order_cancel_automation');
        
        // add_action('admin_post_wpcompleteautomatc_klook_nbuilder_translate_new_nonce', 'klook_nbuilder_translate_new');
        // add_action('admin_post_wpcompleteautomatc_klook_nbuilder_translate_update_nonce', 'klook_nbuilder_translate_update');
        // add_action('admin_post_wpcompleteautomatc_klook_nbuilder_translate_delete_nonce', 'klook_nbuilder_translate_delete');

        //nonce - check_form_nonce
        // add_action('admin_post_check_form_nonce', 'submit_save');

        //run all shortcodes
        add_action('init', array($this, 'bonvoi_register_main_shortcodes')); //shortcodes

        //non-login require AJAX
        // add_action("wp_ajax_nopriv_ajaxautomationklookordersrerunfunc", array($this, 'ajax_automation_klook_orders_rerun'));

        //login require AJAX
        // add_action("wp_ajax_ajaxautomationklookordersrerunfunc", array($this, 'ajax_automation_klook_orders_rerun'));
    }

    public function bonvoi_add_menu_page() {
        // add_menu_page('Automation Settings', 'Automation Settings', 'manage_options', 'wpautomationesim', array($this, 'submenu_wpautomationesim_settings_callback'));

        add_menu_page('Sales Report', 'Bonvoi Sales Report', 'manage_options', 'wpautomationbonvoi', array($this, 'submenu_wpautomationbonvoi_orders_callback'));
        
        add_submenu_page('wpautomationbonvoi', 'Retail Shops', 'Retail Shops', 'manage_options', 'wpautomationbonvoi_retail_shops', array($this, 'submenu_wpautomationbonvoi_retail_shops_callback'));

        add_submenu_page('wpautomationbonvoi', 'Retail Stuff', 'Retail Staff', 'manage_options', 'wpautomationbonvoi_retail_staff', array($this, 'submenu_wpautomationbonvoi_retail_staff_callback'));

        add_submenu_page('wpautomationbonvoi', 'Settings', 'Settings', 'manage_options', 'wpautomationbonvoi_settings', array($this, 'submenu_wpautomationbonvoi_settings_callback'));

        // add_submenu_page('wpautomationbonvoi', 'Shortcodes', 'Shortcodes', 'manage_options', 'wpautomationbonvoi_shortcodes', array($this, 'submenu_wpautomationbonvoi_shortcodes_callback'));
    }

    // function submenu_order_syn_tab_callback() {
    //     // $num = '1';
    //     // $process = '';
    //     // $redirectstatus = '';
    //     // $redirectmsg = '';

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

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

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

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

    //     echo 'Hello...';
    // }

    //http://localhost:8039/bonvoi/wp-admin/admin-ajax.php?action=bv_orders&username=test_user&password=test_password&from_date=2025-11-24&to_date=2025-11-25
    function wpautomationbonvoi_bv_daily_reporting_api() {
        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        $username = '';
        $password = '';
        $from_date = '';
        $to_date = '';
        $retail_shop = '';
        $all_orders = array();

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

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

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

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

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

        if(!empty($username) && !empty($password) && !empty($from_date) && !empty($to_date)) {
            if($username == 'test_user' && $password == 'test_password') {
                if(empty($retail_shop)) {
                    $qry_orders = "SELECT * FROM ".$wpdb->prefix."autoesim_order WHERE DATE(auesim_cdate)>='".$from_date."' AND DATE(auesim_cdate)<='".$to_date."'";
                }
                else {
                    $qry_orders = "SELECT * FROM ".$wpdb->prefix."autoesim_order WHERE DATE(auesim_cdate)>='".$from_date."' AND DATE(auesim_cdate)<='".$to_date."' AND auesim_shop_id='".$retail_shop."'";
                }

                $rs_orders = $wpdb->get_results($qry_orders, ARRAY_A);

                // website orderID
                // Newtechlife orderID (api from newtechlife portal)
                // Order Type (New or Topup)
                // Date/Time
                // Customer email
                // eSIM ICCID
                // Destination 
                // Data plan
                // SKU
                // Price
                // Shop ID
                // Staff ID

                // auesim_id, auesim_order_sn, auesim_cdate, auesim_email, auesim_buyer_username, auesim_ttl_price, auesim_item_type,
                // auesim_item_sku, auesim_item_supplier, auesim_item_convert_status, auesim_item_agree_convert,
                // auesim_item_agree_convert_datetime, auesim_status, auesim_qty, auesim_package_id, auesim_region,
                // auesim_destination, auesim_plan, auesim_esim_opt, auesim_esim_iccid, auesim_discount_status, auesim_discount_type,
                // auesim_discount_price, auesim_voucher, auesim_stripe_id, auesim_stripe_cdate, auesim_stripe_data, auesim_stripe_status,
                // auesim_stripe_desc, auesim_stripe_event, auesim_stripe_orderid, auesim_cm_order_id, auesim_gdrive_name, auesim_gdrive_id,
                // auesim_posttoserver_status, auesim_posttoserver_datetime, auesim_currency, auesim_voucher_value,
                // auesim_private_key, auesim_posttoserver_last_process_dtime, auesim_posttoserver_process_count, auesim_shop_id,
                // auesim_shop_name, auesim_staff_id, auesim_staff_name;

                if($rs_orders) {
                    foreach($rs_orders as $rs_order) {
                        $row = array(
                            'order_sn' => $rs_order['auesim_order_sn'],
                            'newtechlife_order_sn' => $rs_order['auesim_cm_order_id'],
                            'order_type' => $rs_order['auesim_item_type'],
                            'cdate' => $rs_order['auesim_cdate'],
                            'customer_email' => $rs_order['auesim_email'],
                            'esim_iccid' => $rs_order['auesim_esim_iccid'],
                            'destination' => $rs_order['auesim_destination'],
                            'data_plan' => $rs_order['auesim_plan'],
                            'sku' => $rs_order['auesim_package_id'],
                            'ttl_price' => $rs_order['auesim_ttl_price'],
                            'shop_id' => $rs_order['auesim_shop_id'],
                            'shop_name' => $rs_order['auesim_shop_name'],
                            'staff_id' => $rs_order['auesim_staff_id'],
                            'staff_name' => $rs_order['auesim_staff_name']
                        );
                        
                        $all_orders['data'][] = $row;
                    }

                    $all_orders['status'] = 'success';
                    $all_orders['msg'] = '';
                }
                else {
                    $all_orders['status'] = 'success';
                    $all_orders['msg'] = 'No order found';
                    $all_orders['data'] = array();
                }
            }
            else {
                $all_orders['status'] = 'failed';
                $all_orders['msg'] = 'Invalid access';
                $all_orders['data'] = array();
            }
        }
        else {
            $all_orders['status'] = 'failed';
            $all_orders['msg'] = 'Invalid parameters';
            $all_orders['data'] = array();
        }

        echo json_encode($all_orders);
        exit;
    }

    //http://localhost:8039/bonvoi/wp-admin/admin-ajax.php?action=bv_daily_report
    function wpautomationbonvoi_bv_daily_reporting_email() {
        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        require plugin_dir_path( __FILE__ ) . 'PHPMailer/src/Exception.php';
        require plugin_dir_path( __FILE__ ) . 'PHPMailer/src/PHPMailer.php';
        require plugin_dir_path( __FILE__ ) . 'PHPMailer/src/SMTP.php';

        ///////////////// End SMTP Settings ///////////////////////
        $setting_arr = array();
        $return_arr = array();

        $def_host = '';
        $def_username = '';
        $def_password = '';
        $def_secure = '';
        $def_port = '';

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

        // date/time will according to Apache (not db data/time)
        // cronjob every 1hr for this script
        // data records time range is cut_off + cycle_hr - date("Y-m-d H:i:s") - date("Y-m-d H:i:s", strtotime("+1 hour"));

        // SELECT * FROM wp_bonvoi_email_cronjob WHERE bv_ec_start_range <= '2025-12-01 22:00:00' AND bv_ec_end_range > '2025-12-01 22:00:00'
        // $current_date_time = date("Y-m-d H:i:s");

        $qry_cronjob_settings = "SELECT * FROM " . $wpdb->prefix . "bonvoi_settings 
            WHERE bv_setting_name IN(
                'sales_report_cutoff_hr', 'sales_report_cutoff_min', 'sales_report_cutoff_cycle_hr', 
                'sales_report_email_to', 'sales_report_email_cc', 
                'smtp_host', 'smtp_username', 'smtp_password', 'smtp_secure', 'smtp_port')";
        $rs_cronjob_settings = $wpdb->get_results($qry_cronjob_settings, ARRAY_A);
    
        if($rs_cronjob_settings) {
            foreach($rs_cronjob_settings as $rs_cronjob_setting) {
                $setting_arr[$rs_cronjob_setting['bv_setting_name']] = $rs_cronjob_setting['bv_setting_val'];
            }
        }

        ///////////////// Settings ///////////////////////
        $sales_report_cutoff_hr = $setting_arr['sales_report_cutoff_hr']; // 1AM is primary cutoff
        $sales_report_cutoff_cycle_hr = $setting_arr['sales_report_cutoff_cycle_hr']; // $valid_cycles = array(1, 2, 3, 4, 6, 8, 12, 24);

        ///////////////// Check if current hour matches the cycle ///////////////////////
        $current_hour = (int) date("G"); // 0-23 format
        
        // Calculate if current hour is a valid execution hour
        // Valid hours from cutoff_hr=1, cycle=3: 1, 4, 7, 10, 13, 16, 19, 22
        $hour_diff = ($current_hour - $sales_report_cutoff_hr + 24) % 24;
        $is_valid_hour = ($hour_diff % $sales_report_cutoff_cycle_hr) === 0;

        if(!$is_valid_hour) {
            // Not the right hour, exit
            // echo "Current hour ({$current_hour}) is not a valid execution hour. Skipping.";
            exit;
        }

        ///////////////// Calculate date range ///////////////////////
        $end_date_time = date("Y-m-d H:00:00"); // Current hour
        $start_date_time = date("Y-m-d H:00:00", strtotime("-{$sales_report_cutoff_cycle_hr} hours"));

        ///////////////// Check if this range already processed ///////////////////////
        $qry_chk_existing = "SELECT * FROM " . $wpdb->prefix . "bonvoi_email_cronjob 
            WHERE bv_ec_start_range='".$start_date_time."' AND bv_ec_end_range='".$end_date_time."'";
        $rs_chk_existing = $wpdb->get_row($qry_chk_existing, ARRAY_A);
        $count_chk_existing = $wpdb->num_rows;

        if($count_chk_existing > 0) {
            // no action
        }
        else {
            $to = explode(",", trim($setting_arr['sales_report_email_to'])); // array('liebewine@gmail.com');
            
            $bcc = array();
            if(!empty(trim($setting_arr['sales_report_email_cc']))) {
                $bcc = explode(",", trim($setting_arr['sales_report_email_cc'])); // array();
            }
            
            // $attachment = array();

            $def_host = $setting_arr['smtp_host']; // 'mail.acbwebstudio.com';
            $def_username = $setting_arr['smtp_username']; // 'tester@acbwebstudio.com';
            $def_password = $setting_arr['smtp_password']; // 'u7TCTt39bbpeowAY';
            $def_secure = $setting_arr['smtp_secure']; // 'tls';
            $def_port = $setting_arr['smtp_port']; // '587';

            $email = new \PHPMailer\PHPMailer\PHPMailer(true);  // Use FULL class name with backslash
            // $email = new PHPMailer();

            try {
                $email->CharSet = "UTF-8";
                $email->isSMTP();
                $email->SMTPAuth = true;
                $email->SMTPAutoTLS = true;
                $email->SMTPDebug = 2;

                //New Setting Block
                $email->Host = $def_host;
                $email->Username = $def_username;
                $email->Password = $def_password;
                $email->SMTPSecure = $def_secure;
                $email->Port = $def_port;

                $email->SetFrom('esim@bonvoi.me', 'Bonvoi.me'); //Name is optional

                $subject = 'Daily Sales Report - ' . date('Y-m-d');

                $msg = '<h1>Daily Sales Report - '.date('Y-m-d').'</h1>';
                $msg .= '<p>This is automatic generated email.</p>';

                $email->IsHTML(true);
                $email->Subject = $subject;
                $email->Body = html_entity_decode($msg);

                if(count($bcc) > 0) {
                    for($b=0; $b<count($bcc); $b++) {
                        $email->AddBCC($bcc[$b]);
                    }
                }
            
                for($i=0; $i<count($to); $i++) {
                    $email->AddAddress($to[$i]);
                }

                ///////////////// Generate CSV from Database ///////////////////////
                $csv_content = '';
                
                $qry_orders = "SELECT * FROM ".$wpdb->prefix."autoesim_order 
                    WHERE auesim_cdate >= '".$start_date_time."' AND auesim_cdate < '".$end_date_time."' 
                    ORDER BY auesim_cdate ASC";
                // $qry_orders = "SELECT * FROM ".$wpdb->prefix."autoesim_order";
                
                $rs_orders = $wpdb->get_results($qry_orders, ARRAY_A);

                if($rs_orders) {
                    // Add CSV headers (column names)
                    $header_row = array(
                        'Website Order ID',
                        'Newtechlife Order ID',
                        'Order Type',
                        'Date/Time',
                        'Customer email',
                        'eSIM ICCID',
                        'Destination',
                        'Data plan',
                        'SKU',
                        'Price',
                        'Shop ID',
                        'Shop Name',
                        'Staff ID',
                        'Staff Name'
                    );

                    $csv_content .= implode(',', $header_row) . "\r\n";

                    foreach($rs_orders as $rs_order) {
                        $row = array(
                            $rs_order['auesim_order_sn'],
                            $rs_order['auesim_cm_order_id'],
                            $rs_order['auesim_item_type'],
                            $rs_order['auesim_cdate'],
                            $rs_order['auesim_email'],
                            $rs_order['auesim_esim_iccid'],
                            $rs_order['auesim_destination'],
                            $rs_order['auesim_plan'],
                            $rs_order['auesim_package_id'],
                            $rs_order['auesim_ttl_price'],
                            $rs_order['auesim_shop_id'],
                            $rs_order['auesim_shop_name'],
                            $rs_order['auesim_staff_id'],
                            $rs_order['auesim_staff_name']
                        );
                        
                        $csv_content .= implode(',', $row) . "\r\n";
                    }
                }

                // Attach CSV from string (no file needed)
                $filename = 'daily_sales_report_' . date('Y-m-d') . '.csv';
                $email->addStringAttachment($csv_content, $filename, 'base64', 'text/csv');
                
                $email->send();

                // Log
                $wpdb->insert($wpdb->prefix . "bonvoi_email_cronjob", 
                    array(
                        'bv_ec_datetime' => date("Y-m-d H:i:s"),
                        'bv_ec_remarks' => 'Completed',
                        'bv_ec_start_range' => $start_date_time,
                        'bv_ec_end_range' => $end_date_time,
                        'bv_ec_range_intval' => $sales_report_cutoff_cycle_hr
                    )
                );

                $return_arr['status'] = true;
                $return_arr['msg'] = $email->ErrorInfo;
            }
            catch (\Exception $e) {
                $return_arr['status'] = false;
                $return_arr['msg'] = $email->ErrorInfo;
            }
        }

        exit;
    }

    function wpautomationbonvoi_bv_custom_reporting_form() {
        global $wpdb;
        
        $nonce = sanitize_text_field($_POST['formnonce']);
        $action = sanitize_text_field($_POST['action']);

        $source_interface = '';
        if(!empty($_POST['source_interface'])) {
            $source_interface = htmlspecialchars($_POST['source_interface'], ENT_QUOTES);
        }
        
        if (!isset($nonce) || !wp_verify_nonce($nonce, $action)) {
            // print 'Sorry, your nonce did not verify.';

            if(empty($source_interface)) {
                $callback_status = "failed";
                $callback_msg = "Error. Not Able To Process. Please Try Again. Thanks";
                $callback_msg = urlencode($callback_msg);

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

                $redirect_to = admin_url('admin.php?page=wpautomationbonvoi' . $callback_param);
            }
            else {
                $_SESSION['bonvoi_retail_msg']['status'] = 'failed';
                $_SESSION['bonvoi_retail_msg']['msg'] = 'Error. Not Able To Process. Please Try Again. Thanks';

                $qry_config_setting = "SELECT bv_setting_val FROM " . $wpdb->prefix . "bonvoi_settings 
                    WHERE bv_setting_name IN('retail_page_id')";
                $rs_config_setting = $wpdb->get_row($qry_config_setting, ARRAY_A);
                
                $page_id = intval($rs_config_setting['bv_setting_val']);
                $page_url = get_permalink($page_id);

                // $redirect_to = home_url('/staff');
                $redirect_to = $page_url . '?process=reporting';
            }
            
            wp_safe_redirect($redirect_to);

            exit;
        }

        //if (!current_user_can('manage_options')) {
        //    print 'You can\'t manage options';
        //    exit;
        //}

        $retail_shop = '';
        $from_date = '';
        $to_date = '';

        if(!empty($_POST['retail_shop'])) {
            $retail_shop = htmlentities($_POST['retail_shop'], ENT_QUOTES);
        }

        if(!empty($_POST['from_date'])) {
            $from_date = htmlentities($_POST['from_date'], ENT_QUOTES);
        }

        if(!empty($_POST['to_date'])) {
            $to_date = htmlentities($_POST['to_date'], ENT_QUOTES);
        }

        if(!empty($from_date) && !empty($to_date)) {
            if(empty($retail_shop)) {
                $qry_orders = "SELECT * FROM ".$wpdb->prefix."autoesim_order WHERE DATE(auesim_cdate)>='".$from_date."' AND DATE(auesim_cdate)<='".$to_date."'";
            }
            else {
                $qry_orders = "SELECT * FROM ".$wpdb->prefix."autoesim_order WHERE DATE(auesim_cdate)>='".$from_date."' AND DATE(auesim_cdate)<='".$to_date."' AND auesim_shop_id='".$retail_shop."'";
            }

            $rs_orders = $wpdb->get_results($qry_orders, ARRAY_A);

            if($rs_orders) {
                // Set CSV headers
                $filename = 'orders_report_' . $from_date . '_to_' . $to_date . '__' . date('Y-m-d_H-i-s') . '.csv';
                
                header('Content-Type: text/csv; charset=utf-8');
                header('Content-Disposition: attachment; filename="' . $filename . '"');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Expires: 0');

                $output = fopen('php://output', 'w');

                $headers = array(
                    'Website Order ID',
                    'Newtechlife Order ID',
                    'Order Type',
                    'Date/Time',
                    'Customer email',
                    'eSIM ICCID',
                    'Destination',
                    'Data plan',
                    'SKU',
                    'Price',
                    'Shop ID',
                    'Shop Name',
                    'Staff ID',
                    'Staff Name'
                );

                fputcsv($output, $headers);

                foreach($rs_orders as $rs_order) {
                    $row = array(
                        $rs_order['auesim_order_sn'],
                        $rs_order['auesim_cm_order_id'],
                        $rs_order['auesim_item_type'],
                        $rs_order['auesim_cdate'],
                        $rs_order['auesim_email'],
                        $rs_order['auesim_esim_iccid'],
                        $rs_order['auesim_destination'],
                        $rs_order['auesim_plan'],
                        $rs_order['auesim_package_id'],
                        $rs_order['auesim_ttl_price'],
                        $rs_order['auesim_shop_id'],
                        $rs_order['auesim_shop_name'],
                        $rs_order['auesim_staff_id'],
                        $rs_order['auesim_staff_name']
                    );
                    
                    // Write row to CSV
                    fputcsv($output, $row);
                }

                exit;
            }
            else {
                if(empty($source_interface)) {
                    $callback_status = "failed";
                    $callback_msg = "No Order Found. Thanks";
                    $callback_msg = urlencode($callback_msg);

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

                    // $redirect_to = admin_url('admin.php?page=wpautomationbonvoi' . $callback_param);
                }
                else {
                    $_SESSION['bonvoi_retail_msg']['status'] = 'failed';
                    $_SESSION['bonvoi_retail_msg']['msg'] = 'No Order Found. Thanks';
                }
            }
        }
        else {
            if(empty($source_interface)) {
                $callback_status = "failed";
                $callback_msg = "Error. No Date Detected. Please Try Again. Thanks";
                $callback_msg = urlencode($callback_msg);

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

                // $redirect_to = admin_url('admin.php?page=wpautomationbonvoi' . $callback_param);
            }
            else {
                $_SESSION['bonvoi_retail_msg']['status'] = 'failed';
                $_SESSION['bonvoi_retail_msg']['msg'] = 'Error. No Date Detected. Please Try Again. Thanks';
            }
        }

        if(empty($source_interface)) {
            $redirect_to = admin_url('admin.php?page=wpautomationbonvoi' . $callback_param);
        }
        else {
            $qry_config_setting = "SELECT bv_setting_val FROM " . $wpdb->prefix . "bonvoi_settings 
                WHERE bv_setting_name IN('retail_page_id')";
            $rs_config_setting = $wpdb->get_row($qry_config_setting, ARRAY_A);
            
            $page_id = intval($rs_config_setting['bv_setting_val']);
            $page_url = get_permalink($page_id);

            // $redirect_to = home_url('/staff');
            $redirect_to = $page_url . '?process=reporting';
        }

        wp_safe_redirect($redirect_to);
        exit;
    }

    function submenu_wpautomationbonvoi_retail_shops_callback() {
        global $wpdb;

        $num = '1';
        $process = '';
        $redirectstatus = '';
        $redirectmsg = '';

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

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

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

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

        if($process === 'edit_template') {
            global $wpdb;
            date_default_timezone_set("Asia/Singapore");

            if(!empty($_GET['id'])) {
                $get_id = (int)htmlentities($_GET['id'], ENT_QUOTES);

                require_once plugin_dir_path( __FILE__ ) . 'view/bonvoi_shop_edit_template.php';
            }
            else {
                // Show default template instead
                require_once plugin_dir_path( __FILE__ ) . 'view/bonvoi_shop_default_template.php';
                
                // $callback_status = 'failed';
                // $callback_msg = 'Unable To Detect The Staff ID. Please Try Again. Thank You.';
                // $callback_msg = urlencode($callback_msg);

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

                // $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_staff' . $callback_param);
                // wp_safe_redirect($redirect_to);
                // exit;
            }
        }
        else if($process === 'new_template') {
            global $wpdb;
            date_default_timezone_set("Asia/Singapore");

            require_once plugin_dir_path( __FILE__ ) . 'view/bonvoi_shop_new_template.php';
        }
        else {
            global $wpdb;
            date_default_timezone_set("Asia/Singapore");

            require_once plugin_dir_path( __FILE__ ) . 'view/bonvoi_shop_default_template.php';
        }
    }

    function wpautomationbonvoi_bv_new_retail_shops_form() {
        global $wpdb;
        
        $nonce = sanitize_text_field($_POST['formnonce']);
        $action = sanitize_text_field($_POST['action']);

        if (!isset($nonce) || !wp_verify_nonce($nonce, $action)) {
            // print 'Sorry, your nonce did not verify.';

            $callback_status = "failed";
            $callback_msg = "Error. Not Able To Process. Please Try Again. Thanks";
            $callback_msg = urlencode($callback_msg);

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

            $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_shops' . $callback_param);
            wp_safe_redirect($redirect_to);

            exit;
        }

        //if (!current_user_can('manage_options')) {
        //    print 'You can\'t manage options';
        //    exit;
        //}

        if(count($_POST['field']) > 0) {
            // echo '<pre>';
            // print_r($_POST['field']);
            // echo '</pre>';

            // Array
            // (
            //     [bv_shop_name] => 2
            //     [bv_shop_email] => 1
            //     [bv_shop_phone] => ABC123
            // )

            $bv_shop_name = htmlspecialchars($_POST['field']['bv_shop_name'], ENT_QUOTES);
            $bv_shop_email = htmlspecialchars($_POST['field']['bv_shop_email'], ENT_QUOTES);
            $bv_shop_phone = htmlspecialchars($_POST['field']['bv_shop_phone'], ENT_QUOTES);
            
            if(empty($bv_shop_name)) {
                $callback_status = "failed";
                $callback_msg = "Not Able To Detect The Parameters. Please Try Again. Thanks";
                $callback_msg = urlencode($callback_msg);

                $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
            }
            else {
                $qry_chk_existing = "SELECT COUNT(bv_shop_id) AS ttl_records FROM " . $wpdb->prefix . "bonvoi_shops 
                    WHERE bv_shop_name='" . $bv_shop_name . "'";
                $rs_chk_existing = $wpdb->get_row($qry_chk_existing, ARRAY_A);

                $ttl_records = (int)$rs_chk_existing['ttl_records'];

                if($ttl_records > 0) {
                    $callback_status = "failed";
                    $callback_msg = "Retail Shop Existed. Please Try Again. Thanks";
                    $callback_msg = urlencode($callback_msg);

                    $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
                }
                else {
                    $wpdb->insert($wpdb->prefix . "bonvoi_shops", 
                        array(
                            'bv_shop_name' => $bv_shop_name,
                            'bv_shop_email' => $bv_shop_email,
                            'bv_shop_phone' => $bv_shop_phone
                        )
                    );

                    $callback_status = "success";
                    $callback_msg = "Registration Completed.";
                    $callback_msg = urlencode($callback_msg);

                    $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
                }
            }
        }
        else {
            $callback_status = "failed";
            $callback_msg = "Not Able To Detect The Parameters. Please Try Again. Thanks";
            $callback_msg = urlencode($callback_msg);

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

        $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_shops' . $callback_param);
        wp_safe_redirect($redirect_to);
        exit;
    }

    function wpautomationbonvoi_bv_update_retail_shops_form() {
        global $wpdb;
        
        $nonce = sanitize_text_field($_POST['formnonce']);
        $action = sanitize_text_field($_POST['action']);

        if (!isset($nonce) || !wp_verify_nonce($nonce, $action)) {
            // print 'Sorry, your nonce did not verify.';

            $callback_status = "failed";
            $callback_msg = "Error. Not Able To Process. Please Try Again. Thanks";
            $callback_msg = urlencode($callback_msg);

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

            $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_shops' . $callback_param);
            wp_safe_redirect($redirect_to);

            exit;
        }

        //if (!current_user_can('manage_options')) {
        //    print 'You can\'t manage options';
        //    exit;
        //}

        if(count($_POST['field']) > 0) {
            // echo '<pre>';
            // print_r($_POST['field']);
            // echo '</pre>';

            // Array
            // (
            //     [bv_shop_name] => 2
            //     [bv_shop_email] => 1
            //     [bv_shop_phone] => ABC123
            // )

            // bv_shop_id
            // bv_shop_name
            // bv_shop_email
            // bv_shop_phone

            $bv_shop_id = htmlspecialchars($_POST['field']['bv_shop_id'], ENT_QUOTES);
            $bv_shop_name = htmlspecialchars($_POST['field']['bv_shop_name'], ENT_QUOTES);
            $bv_shop_email = htmlspecialchars($_POST['field']['bv_shop_email'], ENT_QUOTES);
            $bv_shop_phone = htmlspecialchars($_POST['field']['bv_shop_phone'], ENT_QUOTES);
            
            if(empty($bv_shop_id)) {
                $callback_status = "failed";
                $callback_msg = "Not Able To Detect The Parameters. Please Try Again. Thanks";
                $callback_msg = urlencode($callback_msg);

                $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
            }
            else {
                $qry_chk_existing = "SELECT COUNT(bv_shop_id) AS ttl_records FROM " . $wpdb->prefix . "bonvoi_shops 
                    WHERE bv_shop_id='" . $bv_shop_id . "'";
                $rs_chk_existing = $wpdb->get_row($qry_chk_existing, ARRAY_A);

                $ttl_records = (int)$rs_chk_existing['ttl_records'];

                if($ttl_records > 0) {
                    $wpdb->update(
                        $wpdb->prefix."bonvoi_shops", 
                        array(
                            'bv_shop_name' => $bv_shop_name,
                            'bv_shop_email' => $bv_shop_email,
                            'bv_shop_phone' => $bv_shop_phone
                        ),
                        array('bv_shop_id' => $bv_shop_id)
                    );

                    $callback_status = "success";
                    $callback_msg = "Retail Shop Updated.";
                    $callback_msg = urlencode($callback_msg);

                    $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
                }
                else {
                    $callback_status = "failed";
                    $callback_msg = "Retail Shop Not Existed. Please Try Again. Thanks";
                    $callback_msg = urlencode($callback_msg);

                    $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
                }
            }
        }
        else {
            $callback_status = "failed";
            $callback_msg = "Not Able To Detect The Parameters. Please Try Again. Thanks";
            $callback_msg = urlencode($callback_msg);

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

        $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_shops' . $callback_param);
        wp_safe_redirect($redirect_to);
        exit;
    }
    
    function wpautomationbonvoi_bv_delete_retail_shops_form() {
        global $wpdb;
        
        $nonce = sanitize_text_field($_POST['formnonce']);
        $action = sanitize_text_field($_POST['action']);

        if (!isset($nonce) || !wp_verify_nonce($nonce, $action)) {
            // print 'Sorry, your nonce did not verify.';

            $callback_status = "failed";
            $callback_msg = "Error. Not Able To Process. Please Try Again. Thanks";
            $callback_msg = urlencode($callback_msg);

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

            $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_shops' . $callback_param);
            wp_safe_redirect($redirect_to);

            exit;
        }

        //if (!current_user_can('manage_options')) {
        //    print 'You can\'t manage options';
        //    exit;
        //}

        // echo '<pre>';
        // print_r($_POST);
        // echo '</pre>';

        if(!empty($_POST['del_ids'])) {
            // echo '<pre>';
            // print_r($_POST['field']);
            // echo '</pre>';

            // Array
            // (
            //     [action] => wpautomationbonvoi_bv_delete_retail_staff_nonce
            //     [formnonce] => c1ebbf3486
            //     [del_ids] => 18
            // )

            $del_ids = htmlspecialchars($_POST['del_ids'], ENT_QUOTES);
            
            $wpdb->delete(
                $wpdb->prefix . "bonvoi_shops", 
                array('bv_shop_id' => $del_ids)
            );

            $callback_status = "success";
            $callback_msg = "Delete Completed.";
            $callback_msg = urlencode($callback_msg);

            $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
        }
        else {
            $callback_status = "failed";
            $callback_msg = "Not Able To Detect The Parameters. Please Try Again. Thanks";
            $callback_msg = urlencode($callback_msg);

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

        $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_shops' . $callback_param);
        wp_safe_redirect($redirect_to);
        exit;
    }

    function submenu_wpautomationbonvoi_retail_staff_callback() {
        global $wpdb;

        $num = '1';
        $process = '';
        $redirectstatus = '';
        $redirectmsg = '';

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

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

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

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

        // Check for stored admin notices
        // $stored_notice = get_transient('staff_admin_notice_' . get_current_user_id());
        // if ($stored_notice) {
        //     delete_transient('staff_admin_notice_' . get_current_user_id());
        //     echo '<div class="notice notice-' . esc_attr($stored_notice['type']) . ' is-dismissible">';
        //     echo '<p>' . esc_html($stored_notice['message']) . '</p>';
        //     echo '</div>';
        // }
        
        if($process === 'edit_template') {
            global $wpdb;
            date_default_timezone_set("Asia/Singapore");

            if(!empty($_GET['id'])) {
                $get_id = (int)htmlentities($_GET['id'], ENT_QUOTES);

                require_once plugin_dir_path( __FILE__ ) . 'view/bonvoi_staff_edit_template.php';
            }
            else {
                // Show default template instead
                require_once plugin_dir_path( __FILE__ ) . 'view/bonvoi_staff_default_template.php';
                
                // $callback_status = 'failed';
                // $callback_msg = 'Unable To Detect The Staff ID. Please Try Again. Thank You.';
                // $callback_msg = urlencode($callback_msg);

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

                // $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_staff' . $callback_param);
                // wp_safe_redirect($redirect_to);
                // exit;
            }
        }
        else if($process === 'new_template') {
            global $wpdb;
            date_default_timezone_set("Asia/Singapore");

            require_once plugin_dir_path( __FILE__ ) . 'view/bonvoi_staff_new_template.php';
        }
        else {
            global $wpdb;
            date_default_timezone_set("Asia/Singapore");

            require_once plugin_dir_path( __FILE__ ) . 'view/bonvoi_staff_default_template.php';
        }
    }

    function wpautomationbonvoi_bv_new_retail_staff_form() {
        global $wpdb;
        
        $nonce = sanitize_text_field($_POST['formnonce']);
        $action = sanitize_text_field($_POST['action']);

        $source_interface = '';
        if(!empty($_POST['source_interface'])) {
            $source_interface = htmlspecialchars($_POST['source_interface'], ENT_QUOTES);
        }
        
        if (!isset($nonce) || !wp_verify_nonce($nonce, $action)) {
            // print 'Sorry, your nonce did not verify.';

            if(empty($source_interface)) {
                $callback_status = "failed";
                $callback_msg = "Error. Not Able To Process. Please Try Again. Thanks";
                $callback_msg = urlencode($callback_msg);

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

                $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_staff' . $callback_param);
            }
            else {
                $_SESSION['bonvoi_retail_msg']['status'] = 'failed';
                $_SESSION['bonvoi_retail_msg']['msg'] = 'Error. Not Able To Process. Please Try Again. Thanks';

                $qry_config_setting = "SELECT bv_setting_val FROM " . $wpdb->prefix . "bonvoi_settings 
                    WHERE bv_setting_name IN('retail_page_id')";
                $rs_config_setting = $wpdb->get_row($qry_config_setting, ARRAY_A);
                
                $page_id = intval($rs_config_setting['bv_setting_val']);
                $page_url = get_permalink($page_id);

                // $redirect_to = home_url('/staff');
                $redirect_to = $page_url . '?process=registration';
            }
            
            wp_safe_redirect($redirect_to);

            exit;
        }

        //if (!current_user_can('manage_options')) {
        //    print 'You can\'t manage options';
        //    exit;
        //}

        if(count($_POST['field']) > 0) {
            // echo '<pre>';
            // print_r($_POST['field']);
            // echo '</pre>';

            // Array
            // (
            //     [allstaff_shop_id] => 2
            //     [allstaff_role_id] => 1
            //     [allstaff_code] => ABC123
            //     [front_passwd] => 123456
            //     [allstaff_name] => Test 1
            //     [allstaff_email] => test1@gmail.com
            //     [allstaff_phone] => 123456
            // )

            $allstaff_shop_id = htmlspecialchars($_POST['field']['allstaff_shop_id'], ENT_QUOTES);
            $allstaff_role_id = htmlspecialchars($_POST['field']['allstaff_role_id'], ENT_QUOTES);
            $allstaff_code = htmlspecialchars($_POST['field']['allstaff_code'], ENT_QUOTES);
            $front_passwd = htmlspecialchars($_POST['field']['front_passwd'], ENT_QUOTES);
            $allstaff_name = htmlspecialchars($_POST['field']['allstaff_name'], ENT_QUOTES);
            $allstaff_email = htmlspecialchars($_POST['field']['allstaff_email'], ENT_QUOTES);
            $allstaff_phone = htmlspecialchars($_POST['field']['allstaff_phone'], ENT_QUOTES);

            if(empty($allstaff_shop_id) || empty($allstaff_role_id) || empty($allstaff_code) || empty($front_passwd) || empty($allstaff_name)) {
                if(empty($source_interface)) {
                    $callback_status = "failed";
                    $callback_msg = "Not Able To Detect The Parameters. Please Try Again. Thanks";
                    $callback_msg = urlencode($callback_msg);

                    $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
                }
                else {
                    $_SESSION['bonvoi_retail_msg']['status'] = 'failed';
                    $_SESSION['bonvoi_retail_msg']['msg'] = 'Not Able To Detect The Parameters. Please Try Again. Thanks';
                }
            }
            else {
                $qry_chk_existing = "SELECT COUNT(bv_allstaff_id) AS ttl_records FROM " . $wpdb->prefix . "bonvoi_allstaff 
                    WHERE bv_allstaff_code='" . $allstaff_code . "'";
                $rs_chk_existing = $wpdb->get_row($qry_chk_existing, ARRAY_A);

                $ttl_records = (int)$rs_chk_existing['ttl_records'];

                if($ttl_records > 0) {
                    if(empty($source_interface)) {
                        $callback_status = "failed";
                        $callback_msg = "Staff Code Existed. Please Try Again. Thanks";
                        $callback_msg = urlencode($callback_msg);

                        $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
                    }
                    else {
                        $_SESSION['bonvoi_retail_msg']['status'] = 'failed';
                        $_SESSION['bonvoi_retail_msg']['msg'] = 'Staff Code Existed. Please Try Again. Thanks';
                    }
                }
                else {
                    // $hash_passwd = password_hash($front_passwd, PASSWORD_DEFAULT);
                    $hash_passwd = md5($front_passwd);

                    $wpdb->insert($wpdb->prefix . "bonvoi_allstaff", 
                        array(
                            'bv_allstaff_shop_id' => $allstaff_shop_id,
                            'bv_allstaff_name' => $allstaff_name,
                            'bv_allstaff_email' => $allstaff_email,
                            'bv_allstaff_phone' => $allstaff_phone,
                            'bv_allstaff_active' => '1',
                            'bv_allstaff_cdate' => date("Y-m-d H:i:s"),
                            'bv_allstaff_mdate' => date("Y-m-d H:i:s"),
                            'bv_allstaff_passwd' => $hash_passwd,
                            'bv_allstaff_code' => $allstaff_code,
                            'bv_allstaff_role_id' => $allstaff_role_id
                        )
                    );

                    if(empty($source_interface)) {
                        $callback_status = "success";
                        $callback_msg = "Registration Completed.";
                        $callback_msg = urlencode($callback_msg);

                        $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
                    }
                    else {
                        $_SESSION['bonvoi_retail_msg']['status'] = 'success';
                        $_SESSION['bonvoi_retail_msg']['msg'] = 'Registration Completed.';
                    }
                }
            }
        }
        else {
            if(empty($source_interface)) {
                $callback_status = "failed";
                $callback_msg = "Not Able To Detect The Parameters. Please Try Again. Thanks";
                $callback_msg = urlencode($callback_msg);

                $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
            }
            else {
                $_SESSION['bonvoi_retail_msg']['status'] = 'failed';
                $_SESSION['bonvoi_retail_msg']['msg'] = 'Not Able To Detect The Parameters. Please Try Again. Thanks';
            }
        }

        if(empty($source_interface)) {
            $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_staff' . $callback_param);
        }
        else {
            $qry_config_setting = "SELECT bv_setting_val FROM " . $wpdb->prefix . "bonvoi_settings 
                WHERE bv_setting_name IN('retail_page_id')";
            $rs_config_setting = $wpdb->get_row($qry_config_setting, ARRAY_A);
            
            $page_id = intval($rs_config_setting['bv_setting_val']);
            $page_url = get_permalink($page_id);

            $redirect_to = $page_url . '?process=registration';
        }

        wp_safe_redirect($redirect_to);
        exit;
    }

    function wpautomationbonvoi_bv_update_retail_staff_form() {
        global $wpdb;
        
        $nonce = sanitize_text_field($_POST['formnonce']);
        $action = sanitize_text_field($_POST['action']);

        if (!isset($nonce) || !wp_verify_nonce($nonce, $action)) {
            // print 'Sorry, your nonce did not verify.';

            $callback_status = "failed";
            $callback_msg = "Error. Not Able To Process. Please Try Again. Thanks";
            $callback_msg = urlencode($callback_msg);

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

            $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_staff' . $callback_param);
            wp_safe_redirect($redirect_to);

            exit;
        }

        //if (!current_user_can('manage_options')) {
        //    print 'You can\'t manage options';
        //    exit;
        //}

        if(count($_POST['field']) > 0) {
            // echo '<pre>';
            // print_r($_POST['field']);
            // echo '</pre>';

            // Array
            // (
            //     [allstaff_id] => 2
            //     [allstaff_shop_id] => 2
            //     [allstaff_role_id] => 2
            //     [allstaff_code] => a2
            //     [front_passwd] => 123456
            //     [allstaff_name] => B
            //     [allstaff_email] => 1@test.com
            //     [allstaff_phone] => 1
            //     [allstaff_active] => 1
            // )

            $allstaff_id = htmlspecialchars($_POST['field']['allstaff_id'], ENT_QUOTES);
            $allstaff_shop_id = htmlspecialchars($_POST['field']['allstaff_shop_id'], ENT_QUOTES);
            $allstaff_role_id = htmlspecialchars($_POST['field']['allstaff_role_id'], ENT_QUOTES);
            $allstaff_code = htmlspecialchars($_POST['field']['allstaff_code'], ENT_QUOTES);
            $front_passwd = htmlspecialchars($_POST['field']['front_passwd'], ENT_QUOTES);
            $allstaff_name = htmlspecialchars($_POST['field']['allstaff_name'], ENT_QUOTES);
            $allstaff_email = htmlspecialchars($_POST['field']['allstaff_email'], ENT_QUOTES);
            $allstaff_phone = htmlspecialchars($_POST['field']['allstaff_phone'], ENT_QUOTES);
            $allstaff_active = htmlspecialchars($_POST['field']['allstaff_active'], ENT_QUOTES);
            
            if(empty($allstaff_shop_id) || empty($allstaff_role_id) || empty($allstaff_code) || empty($allstaff_id) || empty($allstaff_name)) {
                $callback_status = "failed";
                $callback_msg = "Not Able To Detect The Parameters. Please Try Again. Thanks";
                $callback_msg = urlencode($callback_msg);

                $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
            }
            else {
                $qry_chk_existing = "SELECT COUNT(bv_allstaff_id) AS ttl_records FROM " . $wpdb->prefix . "bonvoi_allstaff 
                    WHERE bv_allstaff_id='" . $allstaff_id . "'";
                $rs_chk_existing = $wpdb->get_row($qry_chk_existing, ARRAY_A);

                $ttl_records = (int)$rs_chk_existing['ttl_records'];

                if($ttl_records > 0) {
                    if(empty($allstaff_active)) {
                        $allstaff_active_val = '0';
                    }
                    else {
                        $allstaff_active_val = '1';
                    }

                    if(!empty($front_passwd)) {
                        // $hash_passwd = password_hash($front_passwd, PASSWORD_DEFAULT);
                        $hash_passwd = md5($front_passwd);

                        $wpdb->update(
                            $wpdb->prefix."bonvoi_allstaff", 
                            array(
                                'bv_allstaff_shop_id' => $allstaff_shop_id,
                                'bv_allstaff_name' => $allstaff_name,
                                'bv_allstaff_email' => $allstaff_email,
                                'bv_allstaff_phone' => $allstaff_phone,
                                'bv_allstaff_active' => $allstaff_active_val,
                                'bv_allstaff_mdate' => date("Y-m-d H:i:s"),
                                'bv_allstaff_passwd' => $hash_passwd,
                                'bv_allstaff_code' => $allstaff_code,
                                'bv_allstaff_role_id' => $allstaff_role_id
                            ),
                            array('bv_allstaff_id' => $allstaff_id)
                        );
                    }
                    else {
                        $wpdb->update(
                            $wpdb->prefix."bonvoi_allstaff", 
                            array(
                                'bv_allstaff_shop_id' => $allstaff_shop_id,
                                'bv_allstaff_name' => $allstaff_name,
                                'bv_allstaff_email' => $allstaff_email,
                                'bv_allstaff_phone' => $allstaff_phone,
                                'bv_allstaff_active' => $allstaff_active_val,
                                'bv_allstaff_mdate' => date("Y-m-d H:i:s"),
                                'bv_allstaff_code' => $allstaff_code,
                                'bv_allstaff_role_id' => $allstaff_role_id
                            ),
                            array('bv_allstaff_id' => $allstaff_id)
                        );
                    }
                    
                    $callback_status = "success";
                    $callback_msg = "Staff Info Updated.";
                    $callback_msg = urlencode($callback_msg);

                    $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
                }
                else {
                    $callback_status = "failed";
                    $callback_msg = "Staff Code Not Existed. Please Try Again. Thanks";
                    $callback_msg = urlencode($callback_msg);

                    $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
                }
            }
        }
        else {
            $callback_status = "failed";
            $callback_msg = "Not Able To Detect The Parameters. Please Try Again. Thanks";
            $callback_msg = urlencode($callback_msg);

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

        $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_staff' . $callback_param);
        wp_safe_redirect($redirect_to);
        exit;
    }
    
    function wpautomationbonvoi_bv_delete_retail_staff_form() {
        global $wpdb;
        
        $nonce = sanitize_text_field($_POST['formnonce']);
        $action = sanitize_text_field($_POST['action']);

        if (!isset($nonce) || !wp_verify_nonce($nonce, $action)) {
            // print 'Sorry, your nonce did not verify.';

            $callback_status = "failed";
            $callback_msg = "Error. Not Able To Process. Please Try Again. Thanks";
            $callback_msg = urlencode($callback_msg);

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

            $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_staff' . $callback_param);
            wp_safe_redirect($redirect_to);

            exit;
        }

        //if (!current_user_can('manage_options')) {
        //    print 'You can\'t manage options';
        //    exit;
        //}

        // echo '<pre>';
        // print_r($_POST);
        // echo '</pre>';

        if(!empty($_POST['del_ids'])) {
            // echo '<pre>';
            // print_r($_POST['field']);
            // echo '</pre>';

            // Array
            // (
            //     [action] => wpautomationbonvoi_bv_delete_retail_staff_nonce
            //     [formnonce] => c1ebbf3486
            //     [del_ids] => 18
            // )

            $del_ids = htmlspecialchars($_POST['del_ids'], ENT_QUOTES);
            
            $wpdb->delete(
                $wpdb->prefix . "bonvoi_allstaff", 
                array('bv_allstaff_id' => $del_ids)
            );

            $callback_status = "success";
            $callback_msg = "Delete Completed.";
            $callback_msg = urlencode($callback_msg);

            $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
        }
        else {
            $callback_status = "failed";
            $callback_msg = "Not Able To Detect The Parameters. Please Try Again. Thanks";
            $callback_msg = urlencode($callback_msg);

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

        $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_retail_staff' . $callback_param);
        wp_safe_redirect($redirect_to);
        exit;
    }

    function submenu_wpautomationbonvoi_settings_callback() {
        global $wpdb;

        $num = '1';
        $process = '';
        $redirectstatus = '';
        $redirectmsg = '';

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

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

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

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

        if($process === 'inner_templates') {
            // global $wpdb;
            // date_default_timezone_set("Asia/Singapore");

            // if(!empty($_GET['id'])) {
            //     $get_tempt_id = (int)htmlentities($_GET['id'], ENT_QUOTES);

            //     require_once plugin_dir_path( __FILE__ ) . 'views/templates_tab_inner_contnet.php';
            // }
            // else {
            //     $callback_status = 'failed';
            //     $callback_msg = 'Unable To Detect The Template ID. Please Try Again. Thank You.';
            //     $callback_msg = urlencode($callback_msg);
            //     $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;

            //     $redirect_to = admin_url('admin.php?page=wpcompleteautomatc_email_templates' . $callback_param);
            //     wp_safe_redirect($redirect_to);
            //     exit;
            // }
        }
        else {
            global $wpdb;
            date_default_timezone_set("Asia/Singapore");

            require_once plugin_dir_path( __FILE__ ) . 'view/bonvoi_settings.php';
        }
    }

    function wpautomationbonvoi_settings_configuration_update() {
        global $wpdb;
        
        $nonce = sanitize_text_field($_POST['formnonce']);
        $action = sanitize_text_field($_POST['action']);

        if (!isset($nonce) || !wp_verify_nonce($nonce, $action)) {
            // print 'Sorry, your nonce did not verify.';

            $callback_status = "failed";
            $callback_msg = "Error. Not Able To Process. Please Try Again. Thanks";
            $callback_msg = urlencode($callback_msg);

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

            $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_settings' . $callback_param);
            wp_safe_redirect($redirect_to);

            exit;
        }

        //if (!current_user_can('manage_options')) {
        //    print 'You can\'t manage options';
        //    exit;
        //}

        if(count($_POST['field']) > 0) {
            $all_keys = array_keys($_POST['field']);
            for($f=0; $f<count($_POST['field']); $f++) {
                $field_key = htmlspecialchars($all_keys[$f], ENT_QUOTES);
                $field_val = htmlspecialchars($_POST['field'][$all_keys[$f]], ENT_QUOTES);

                $wpdb->update(
                    $wpdb->prefix."bonvoi_settings", 
                    array('bv_setting_val' => $field_val), 
                    array('bv_setting_name' => $field_key)
                );
            }

            $callback_status = "success";
            $callback_msg = "Setting Updated.";
            $callback_msg = urlencode($callback_msg);

            $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;
        }
        else {
            $callback_status = "failed";
            $callback_msg = "Not Able To Detect The Settings. Please Try Again. Thanks";
            $callback_msg = urlencode($callback_msg);

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

        $redirect_to = admin_url('admin.php?page=wpautomationbonvoi_settings' . $callback_param);
        wp_safe_redirect($redirect_to);
        exit;
    }

    // function submenu_wpautomationbonvoi_shortcodes_callback() {
    //     global $wpdb;

    //     $num = '1';
    //     $process = '';
    //     $redirectstatus = '';
    //     $redirectmsg = '';

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

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

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

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

    //     if($process === 'inner_templates') {
    //         // global $wpdb;
    //         // date_default_timezone_set("Asia/Singapore");

    //         // if(!empty($_GET['id'])) {
    //         //     $get_tempt_id = (int)htmlentities($_GET['id'], ENT_QUOTES);

    //         //     require_once plugin_dir_path( __FILE__ ) . 'views/templates_tab_inner_contnet.php';
    //         // }
    //         // else {
    //         //     $callback_status = 'failed';
    //         //     $callback_msg = 'Unable To Detect The Template ID. Please Try Again. Thank You.';
    //         //     $callback_msg = urlencode($callback_msg);
    //         //     $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;

    //         //     $redirect_to = admin_url('admin.php?page=wpcompleteautomatc_email_templates' . $callback_param);
    //         //     wp_safe_redirect($redirect_to);
    //         //     exit;
    //         // }
    //     }
    //     else {
    //         global $wpdb;
    //         date_default_timezone_set("Asia/Singapore");

    //         // require_once plugin_dir_path( __FILE__ ) . 'view/wpautomationesim_shortcodes.php';
    //         echo 'wow 2';
    //     }
    // }

    function submenu_wpautomationbonvoi_orders_callback() {
        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        $num = '1';
        $process = '';
        $redirectstatus = '';
        $redirectmsg = '';

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

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

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

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

        if(!empty($_GET['filter_orders'])) {
            $filter_orders = htmlentities($_GET['filter_orders'], ENT_QUOTES);
        }
        else {
            $filter_orders = "";
        }

        if($process === 'inner_templates') {
            // global $wpdb;
            // date_default_timezone_set("Asia/Singapore");

            // if(!empty($_GET['id'])) {
            //     $get_tempt_id = (int)htmlentities($_GET['id'], ENT_QUOTES);

            //     require_once plugin_dir_path( __FILE__ ) . 'views/templates_tab_inner_contnet.php';
            // }
            // else {
            //     $callback_status = 'failed';
            //     $callback_msg = 'Unable To Detect The Template ID. Please Try Again. Thank You.';
            //     $callback_msg = urlencode($callback_msg);
            //     $callback_param = "&redirectstatus=" . $callback_status . "&redirectmsg=" . $callback_msg;

            //     $redirect_to = admin_url('admin.php?page=wpcompleteautomatc_email_templates' . $callback_param);
            //     wp_safe_redirect($redirect_to);
            //     exit;
            // }
        }
        else {
            require_once plugin_dir_path( __FILE__ ) . 'view/bonvoi_reporting.php';
        }
    }

    //Register all shortcodes here...
    public function bonvoi_register_main_shortcodes(){
        // add_shortcode('main_wpautomationesim_form', array($this, 'main_wpautomationesim_form_output'));
        // add_shortcode('order_cancel_wpautomationesim', array($this, 'order_cancel_wpautomationesim_output'));
        // add_shortcode('order_success_wpautomationesim', array($this, 'order_success_wpautomationesim_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'));
    }

    //shortcode display
    // public function main_wpautomationesim_form_output() {
        // global $wpdb;

        // $param_pre = '';
        // $param_pde = '';
        // $param_pda = '';
        // $param_pdp = '';
        // $param_peo = '';
        // $param_pvc = '';

        // if(!empty($_GET['pre'])) {
        //     $param_pre = htmlentities($_GET['pre'], ENT_QUOTES);
        // }

        // if(!empty($_GET['pde'])) {
        //     $param_pde = htmlentities($_GET['pde'], ENT_QUOTES);
        // }

        // if(!empty($_GET['pda'])) {
        //     $param_pda = htmlentities($_GET['pda'], ENT_QUOTES);
        // }

        // if(!empty($_GET['pdp'])) {
        //     $param_pdp = htmlentities($_GET['pdp'], ENT_QUOTES);
        // }

        // if(!empty($_GET['peo'])) {
        //     $param_peo = htmlentities($_GET['peo'], ENT_QUOTES);
        // }

        // if(!empty($_GET['pvc'])) {
        //     $param_pvc = htmlentities($_GET['pvc'], ENT_QUOTES);
        // }

        // ob_start();

        // $loading_gif =  plugin_dir_url( __FILE__ ) . 'images/loading_progress.gif';
        // $img_deative_arrow =  plugin_dir_url( __FILE__ ) . 'images/fake_select_icon_deactive.png';
        // $img_ative_arrow =  plugin_dir_url( __FILE__ ) . 'images/fake_select_icon_active.png';
        
        // // include_once("view/main_wpautomationesim_form.php");
        // require "view/main_wpautomationesim_form.php";

        // return ob_get_clean();
    // }

    // function order_cancel_wpautomationesim_output() {
    //     //http://localhost:8039/szoove/order-cancelled/?action=transaction&orderid=SZV20250617CVJ63JZI0E&status=failed&trans=m1g36w34q5rzlt02c7gs

    //     $result = array();

    //     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 = htmlentities($_GET['orderid'], ENT_QUOTES);
    //         $status_val = htmlentities($_GET['status'], ENT_QUOTES);
    //         $trans_val = htmlentities($_GET['trans'], ENT_QUOTES);

    //         global $wpdb;
    //         date_default_timezone_set("Asia/Singapore");

    //         $qry_order = "SELECT * FROM " . $wpdb->prefix . "autoesim_order WHERE auesim_order_sn='".$orderid_val."' AND auesim_private_key='".$trans_val."'";
    //         $rs_order = $wpdb->get_row($qry_order, ARRAY_A);
    //         $rs_order_count = $wpdb->num_rows;

    //         if($rs_order_count > 0) {
    //             $wpdb->update(
    //                 $wpdb->prefix."autoesim_order", 
    //                 array('auesim_status' => 'Cancelled', 'auesim_private_key' => ''), 
    //                 array('auesim_id' => $rs_order['auesim_id'])
    //             );
    //         }
    //     }
    // }

    /*
    function check_and_purge_cloudflare_cache() {
        // Check if nocache parameter exists
        if (!isset($_GET['nocache']) || empty($_GET['nocache']) || !isset($_GET['purge_key']) || empty($_GET['purge_key'])) {
            return;
        }

        if (!wp_verify_nonce($_GET['purge_key'], 'purge_cache')) {
            return;
        }

        global $wpdb;
        date_default_timezone_set("Asia/Singapore");
        
        // Your Cloudflare credentials
        $zone_id = ''; // Found in Cloudflare dashboard
        $api_token = ''; // Create at Cloudflare -> My Profile -> API Tokens
        
        $qry_settings = "SELECT * FROM " . $wpdb->prefix . "autoesim_settings WHERE autoesim_opt IN('cloudflare_zone_id', 'cloudflare_api_token')";
        // $rs_settings = $wpdb->get_row($qry_settings, ARRAY_A);
        $rs_settings = $wpdb->get_results($qry_settings, ARRAY_A);
        // $rs_settings_count = $wpdb->num_rows;

        if($rs_settings) {
            foreach($rs_settings as $rs_setting) {
                if($rs_setting['autoesim_opt'] == 'cloudflare_zone_id') {
                    $zone_id = $rs_setting['autoesim_val'];
                }

                if($rs_setting['autoesim_opt'] == 'cloudflare_api_token') {
                    $api_token = $rs_setting['autoesim_val'];
                }
            }
        }

        if(!empty($zone_id) && !empty($api_token)) {
            // Prevent multiple purges - check if we already purged recently
            $last_purge = get_transient('cloudflare_last_purge');
            if ($last_purge && (time() - $last_purge) < 300) { // 5 minutes
                return;
            }
            
            // Purge everything
            $data = array('purge_everything' => true);
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/{$zone_id}/purge_cache");
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Authorization: Bearer ' . $api_token,
                'Content-Type: application/json'
            ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Add timeout
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            // Log the purge
            if ($http_code == 200) {
                set_transient('cloudflare_last_purge', time(), 300);
                
                //wp_autoesim_cloudflare
                //cf_id, cf_func, cf_datetime, cf_status_code, cf_status_logs

                $wpdb->insert($wpdb->prefix . "autoesim_cloudflare", 
                    array(
                        'cf_func' => 'check_and_purge_cloudflare_cache',
                        'cf_datetime' => date("Y-m-d H:i:s"),
                        'cf_status_code' => '200',
                        'cf_status_logs' => 'Success'
                    )
                );
                
                // Optional: Add admin notice
                // set_transient('cloudflare_purge_notice', 'Cache cleared successfully', 5);
                
                // Log to file
                // error_log(sprintf(
                //     "[%s] Cache purged via nocache parameter - IP: %s\n",
                //     date('Y-m-d H:i:s'),
                //     $_SERVER['REMOTE_ADDR']
                // ), 3, WP_CONTENT_DIR . '/cloudflare-purge.log');
            }
            else {
                $wpdb->insert($wpdb->prefix . "autoesim_cloudflare", 
                    array(
                        'cf_func' => 'check_and_purge_cloudflare_cache',
                        'cf_datetime' => date("Y-m-d H:i:s"),
                        'cf_status_code' => $http_code,
                        'cf_status_logs' => 'Failed'
                    )
                );
            }
            
            // Optional: Remove nocache parameter from URL
            // if ($http_code == 200) {
            //     add_action('wp_loaded', function() {
            //         if (!is_admin()) {
            //             wp_redirect(remove_query_arg('nocache'));
            //             exit;
            //         }
            //     });
            // }
        }
        else {
            // $zone_id = $rs_settings['autoesim_val'];
            // }

            // if($rs_settings['autoesim_opt'] == 'cloudflare_api_token') {
            //     $api_token = $rs_settings['autoesim_val'];

            $wpdb->insert($wpdb->prefix . "autoesim_cloudflare", 
                array(
                    'cf_func' => 'check_and_purge_cloudflare_cache',
                    'cf_datetime' => date("Y-m-d H:i:s"),
                    'cf_status_code' => '400',
                    'cf_status_logs' => 'Failed - No Zone id or API token - Zone: ' . $zone_id . ', Token:' . $api_token
                )
            );
        }
    }

    //https://szoove.com/wp-admin/admin-ajax.php?action=internal_purge_cloudflare_cache
    function internal_purge_cloudflare_cache() {
        global $wpdb;
        date_default_timezone_set("Asia/Singapore");
        
        // Your Cloudflare credentials
        $zone_id = ''; // Found in Cloudflare dashboard
        $api_token = ''; // Create at Cloudflare -> My Profile -> API Tokens
        
        $qry_settings = "SELECT * FROM " . $wpdb->prefix . "autoesim_settings WHERE autoesim_opt IN('cloudflare_zone_id', 'cloudflare_api_token')";
        // $rs_settings = $wpdb->get_row($qry_settings, ARRAY_A);
        $rs_settings = $wpdb->get_results($qry_settings, ARRAY_A);
        // $rs_settings_count = $wpdb->num_rows;

        if($rs_settings) {
            foreach($rs_settings as $rs_setting) {
                if($rs_setting['autoesim_opt'] == 'cloudflare_zone_id') {
                    $zone_id = $rs_setting['autoesim_val'];
                }

                if($rs_setting['autoesim_opt'] == 'cloudflare_api_token') {
                    $api_token = $rs_setting['autoesim_val'];
                }
            }
        }

        if(!empty($zone_id) && !empty($api_token)) {
            // Prevent multiple purges - check if we already purged recently
            // $last_purge = get_transient('cloudflare_last_purge');
            // if ($last_purge && (time() - $last_purge) < 300) { // 5 minutes
            //     return;
            // }
            
            // Purge everything
            $data = array('purge_everything' => true);
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/{$zone_id}/purge_cache");
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Authorization: Bearer ' . $api_token,
                'Content-Type: application/json'
            ));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Add timeout
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            // Log the purge
            if ($http_code == 200) {
                // set_transient('cloudflare_last_purge', time(), 300);
                
                //wp_autoesim_cloudflare
                //cf_id, cf_func, cf_datetime, cf_status_code, cf_status_logs

                $wpdb->insert($wpdb->prefix . "autoesim_cloudflare", 
                    array(
                        'cf_func' => 'internal_purge_cloudflare_cache',
                        'cf_datetime' => date("Y-m-d H:i:s"),
                        'cf_status_code' => '200',
                        'cf_status_logs' => 'Success'
                    )
                );
                
                // Optional: Add admin notice
                // set_transient('cloudflare_purge_notice', 'Cache cleared successfully', 5);
                
                // Log to file
                // error_log(sprintf(
                //     "[%s] Cache purged via nocache parameter - IP: %s\n",
                //     date('Y-m-d H:i:s'),
                //     $_SERVER['REMOTE_ADDR']
                // ), 3, WP_CONTENT_DIR . '/cloudflare-purge.log');
            }
            else {
                $wpdb->insert($wpdb->prefix . "autoesim_cloudflare", 
                    array(
                        'cf_func' => 'internal_purge_cloudflare_cache',
                        'cf_datetime' => date("Y-m-d H:i:s"),
                        'cf_status_code' => $http_code,
                        'cf_status_logs' => 'Failed'
                    )
                );
            }
            
            // Optional: Remove nocache parameter from URL
            // if ($http_code == 200) {
            //     add_action('wp_loaded', function() {
            //         if (!is_admin()) {
            //             wp_redirect(remove_query_arg('nocache'));
            //             exit;
            //         }
            //     });
            // }
        }
        else {
            $wpdb->insert($wpdb->prefix . "autoesim_cloudflare", 
                array(
                    'cf_func' => 'internal_purge_cloudflare_cache',
                    'cf_datetime' => date("Y-m-d H:i:s"),
                    'cf_status_code' => '400',
                    'cf_status_logs' => 'Failed - No Zone id or API token'
                )
            );
        }

        die();
    }

    function generate_chkregion() {
        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        $html_region = array();

        // $domain = 'http://localhost/brightline_v5';
        $domain = '';

        $qry_domain = "SELECT * FROM " . $wpdb->prefix . "autoesim_settings WHERE autoesim_opt='remote_server_domain'";
        $rs_domain = $wpdb->get_row($qry_domain, ARRAY_A);
        $rs_domain_count = $wpdb->num_rows;

        if($rs_domain_count > 0) {
            $domain = $rs_domain['autoesim_val'];
        }

        if(!empty($domain)) {
            $url = $domain . '/wp-admin/admin-ajax.php?action=remoteapi_chkregion';

            $api_data = array();

            $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
            }
            else {
                if($result_arr['status'] == 'success') {
                    $html_region['html'] = $result_arr['respond'];
                    $html_region['json'] = $result_arr['json'];
                }
                else {
                    $html_region['html'] = '';
                    $html_region['json'] = '';
                }
            }
        }

        return $html_region;
    }

    function generate_parameters($settings_param_arr = array(), $options_param_arr = array()) {
        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        $return_param = array();

        // $domain = 'http://localhost/brightline_v5';
        $domain = '';

        $qry_domain = "SELECT * FROM " . $wpdb->prefix . "autoesim_settings WHERE autoesim_opt='remote_server_domain'";
        $rs_domain = $wpdb->get_row($qry_domain, ARRAY_A);
        $rs_domain_count = $wpdb->num_rows;

        if($rs_domain_count > 0) {
            $domain = $rs_domain['autoesim_val'];
        }

        if(!empty($domain)) {
            $url = $domain . '/wp-admin/admin-ajax.php?action=remoteapi_settings';

            // $settings_param_arr = array(
            //     'chinamobile_topup_new_esim_price'
            // );
            // $options_param_arr = array();

            $api_data = array(
                'settings_param' => $settings_param_arr,
                'options_param' => $options_param_arr
            );

            $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
            }
            else {
                if($result_arr['status'] == 'success') {
                    $return_param = $result_arr['respond'];
                }
                else {

                }
            }
        }

        return $return_param;
    }

    function generate_chkdest($param_regval = '') {
        // Add cache prevention headers at the very beginning
        header('Cache-Control: no-cache, no-store, must-revalidate');
        header('Pragma: no-cache');
        header('Expires: 0');

        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        $return_type = '';
        $regval = '';

        if(!empty($param_regval)) {
            $regval = htmlentities($param_regval, ENT_QUOTES);

            $return_type = 'array';
        }

        if(!empty($_POST['regval'])) {
            $regval = htmlentities($_POST['regval'], ENT_QUOTES);

            $return_type = 'json';
        }

        if($return_type == 'json') {
            if(!wp_verify_nonce($_POST['nonce'], "check_dest_nonce")) {
                die();
            }
        }
        
        // $regval = htmlentities($_POST['regval'], ENT_QUOTES);
        $return = array();
        $select_html = '';
        $cover = '';
        
        if(!empty($regval)) {
            // $domain = 'http://localhost/brightline_v5';
            $domain = '';

            $qry_domain = "SELECT * FROM " . $wpdb->prefix . "autoesim_settings WHERE autoesim_opt='remote_server_domain'";
            $rs_domain = $wpdb->get_row($qry_domain, ARRAY_A);
            $rs_domain_count = $wpdb->num_rows;

            if($rs_domain_count > 0) {
                $domain = $rs_domain['autoesim_val'];
            }

            if(!empty($domain)) {
                $url = $domain . '/wp-admin/admin-ajax.php?action=remoteapi_chkdest';

                $api_data = array(
                    'regval' => $regval
                );

                $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
                    $return['status'] = 'fail';
                    $return['html'] = '';
                    $return['json'] = '';
                    $return['cover'] = '';
                }
                else {
                    if($result_arr['status'] == 'pass') {
                        $return['status'] = 'pass';
                        $return['html'] = $result_arr['html'];
                        $return['json'] = $result_arr['json'];
                        $return['cover'] = $result_arr['cover'];
                    }
                    else {
                        $return['status'] = 'fail';
                        $return['html'] = '';
                        $return['json'] = '';
                        $return['cover'] = '';
                    }
                }
            }
            else {
                $return['status'] = 'fail';
                $return['html'] = '';
                $return['json'] = '';
                $return['cover'] = '';
            }
        }
        else {
            $return['status'] = 'fail';
            $return['html'] = '';
            $return['json'] = '';
            $return['cover'] = '';
        }

        if($return_type == 'array') {
            return $return;
        }
        else {
            echo json_encode($return);
            die();
        }
    }

    function generate_chkplan_old() {
        if(!wp_verify_nonce($_POST['nonce'], "check_plan_nonce")) {
            die();
        }
        
        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        $destval = htmlentities($_POST['destval'], ENT_QUOTES);

        $return = array();
        $select_html = '';
        $cover = '';
        
        if(!empty($destval)) {
            // $domain = 'http://localhost/brightline_v5';
            $domain = '';

            $qry_domain = "SELECT * FROM " . $wpdb->prefix . "autoesim_settings WHERE autoesim_opt='remote_server_domain'";
            $rs_domain = $wpdb->get_row($qry_domain, ARRAY_A);
            $rs_domain_count = $wpdb->num_rows;

            if($rs_domain_count > 0) {
                $domain = $rs_domain['autoesim_val'];
            }

            if(!empty($domain)) {
                $url = $domain . '/wp-admin/admin-ajax.php?action=remoteapi_chkplan';

                $api_data = array(
                    'destval' => $destval
                );

                $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
                    $return['status'] = 'fail';
                    $return['html'] = '';
                    $return['json'] = '';
                    $return['day_json'] = '';
                }
                else {
                    if($result_arr['status'] == 'pass') {
                        $return['status'] = 'pass';
                        $return['html'] = $result_arr['html'];
                        $return['json'] = $result_arr['json'];
                        $return['day_json'] = $result_arr['day_json'];
                    }
                    else {
                        $return['status'] = 'fail';
                        $return['html'] = '';
                        $return['json'] = '';
                        $return['day_json'] = '';
                    }
                }
            }
            else {
                $return['status'] = 'fail';
                $return['html'] = '';
                $return['json'] = '';
                $return['day_json'] = '';
            }
        }
        else {
            $return['status'] = 'fail';
            $return['html'] = '';
            $return['json'] = '';
            $return['day_json'] = '';
        }

        echo json_encode($return);
        
        die();
    }

    function generate_chkplan($param_destval = '') {
        // Add cache prevention headers at the very beginning
        header('Cache-Control: no-cache, no-store, must-revalidate');
        header('Pragma: no-cache');
        header('Expires: 0');

        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        $return_type = '';
        $destval = '';

        if(!empty($param_destval)) {
            $destval = htmlentities($param_destval, ENT_QUOTES);

            $return_type = 'array';
        }

        if(!empty($_POST['destval'])) {
            $destval = htmlentities($_POST['destval'], ENT_QUOTES);

            $return_type = 'json';
        }

        if($return_type == 'json') {
            if(!wp_verify_nonce($_POST['nonce'], "check_plan_nonce")) {
                die();
            }
        }

        // $destval = htmlentities($_POST['destval'], ENT_QUOTES);

        $return = array();
        $select_html = '';
        $cover = '';
        
        if(!empty($destval)) {
            // $domain = 'http://localhost/brightline_v5';
            $domain = '';

            $qry_domain = "SELECT * FROM " . $wpdb->prefix . "autoesim_settings WHERE autoesim_opt='remote_server_domain'";
            $rs_domain = $wpdb->get_row($qry_domain, ARRAY_A);
            $rs_domain_count = $wpdb->num_rows;

            if($rs_domain_count > 0) {
                $domain = $rs_domain['autoesim_val'];
            }

            if(!empty($domain)) {
                $url = $domain . '/wp-admin/admin-ajax.php?action=remoteapi_chkplan';

                $api_data = array(
                    'destval' => $destval
                );

                $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
                    $return['status'] = 'fail';
                    $return['html'] = '';
                    $return['json'] = '';
                    $return['day_json'] = '';
                }
                else {
                    if($result_arr['status'] == 'pass') {
                        $return['status'] = 'pass';
                        $return['html'] = $result_arr['html'];
                        $return['json'] = $result_arr['json'];
                        $return['day_json'] = $result_arr['day_json'];
                    }
                    else {
                        $return['status'] = 'fail';
                        $return['html'] = '';
                        $return['json'] = '';
                        $return['day_json'] = '';
                    }
                }
            }
            else {
                $return['status'] = 'fail';
                $return['html'] = '';
                $return['json'] = '';
                $return['day_json'] = '';
            }
        }
        else {
            $return['status'] = 'fail';
            $return['html'] = '';
            $return['json'] = '';
            $return['day_json'] = '';
        }

        if($return_type == 'array') {
            return $return;
        }
        else {
            echo json_encode($return);
            die();
        }
    }

    function generate_chkprice() {
        if(!wp_verify_nonce($_POST['nonce'], "check_price_nonce")) {
            die();
        }

        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

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

        $return = array();

        $esim = '';
        $vou_code = '';
        $vou_num = '';
        $vou_status = '';
        $vou_type = '';
        $vou_val = '';
        $planval = '';
        $card_opt = '';

        if(!empty($_POST['esim'])) {
            $esim = htmlentities($_POST['esim'], ENT_QUOTES);
        }
        
        if(!empty($_POST['vou_code'])) {
            $vou_code = htmlentities($_POST['vou_code'], ENT_QUOTES);
        }
        
        if(!empty($_POST['vou_num'])) {
            $vou_num = (int)htmlentities($_POST['vou_num'], ENT_QUOTES);
        }
        
        if(!empty($_POST['vou_status'])) {
            $vou_status = htmlentities($_POST['vou_status'], ENT_QUOTES);
        }
        
        if(!empty($_POST['vou_type'])) {
            $vou_type = htmlentities($_POST['vou_type'], ENT_QUOTES);
        }

        if(!empty($_POST['vou_val'])) {
            $vou_val = htmlentities($_POST['vou_val'], ENT_QUOTES);
        }

        if(!empty($_POST['planval'])) {
            $planval = htmlentities($_POST['planval'], ENT_QUOTES);
        }
        
        if(!empty($_POST['card_opt'])) {
            $card_opt = htmlentities($_POST['card_opt'], ENT_QUOTES);
        }

        if(!empty($planval)) {
            // $domain = 'http://localhost/brightline_v5';
            $domain = '';

            $qry_domain = "SELECT * FROM " . $wpdb->prefix . "autoesim_settings WHERE autoesim_opt='remote_server_domain'";
            $rs_domain = $wpdb->get_row($qry_domain, ARRAY_A);
            $rs_domain_count = $wpdb->num_rows;

            if($rs_domain_count > 0) {
                $domain = $rs_domain['autoesim_val'];
            }

            if(!empty($domain)) {
                $url = $domain . '/wp-admin/admin-ajax.php?action=remoteapi_chkprice';

                $api_data = array(
                    'esim' => $esim,
                    'vou_code' => $vou_num,
                    'vou_status' => $vou_status,
                    'vou_type' => $vou_type,
                    'vou_val' => $vou_val,
                    'planval' => $planval,
                    'card_opt' => $card_opt
                );

                $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
                    $return['status'] = 'fail';
                    $return['html'] = '';
                }
                else {
                    if($result_arr['status'] == 'pass') {
                        $return['status'] = 'pass';
                        $return['html'] = $result_arr['html'];

                    }
                    else {
                        $return['status'] = 'fail';
                        $return['html'] = '';
                    }
                }
            }
            else {
                $return['status'] = 'fail';
                $return['html'] = '';
            }
        }
        else {
            $return['status'] = 'fail';
            $return['html'] = '';
        }

        echo json_encode($return);
        
        die();
    }

    function generate_chkesim($param_esim = '', $param_voucher = '', $param_card_opt = '', $param_planval = '', $param_proid = '', $param_esim_convert = '') {
        $return_type = '';

        $esim = '';
        $voucher = '';
        $card_opt = '';
        $planval = '';
        $proid = '';
        $esim_convert = '';

        //Function Call
        if(!empty($param_esim)) {
            $return_type = 'array';

            $esim = $param_esim;
        }

        if(!empty($param_voucher)) {
            $return_type = 'array';

            $voucher = $param_voucher;
        }

        if(!empty($param_card_opt)) {
            $return_type = 'array';

            $card_opt = $param_card_opt;
        }

        if(!empty($param_planval)) {
            $return_type = 'array';

            $planval = $param_planval;
        }

        if(!empty($param_proid)) {
            $return_type = 'array';

            $proid = $param_proid;
        }

        if(!empty($param_esim_convert)) {
            $return_type = 'array';

            $esim_convert = $param_esim_convert;
        }

        //POST Filter
        if(!empty($_POST['p_esim'])) {
            $return_type = 'json';

            $esim = htmlentities($_POST['p_esim'], ENT_QUOTES);
        }
        
        if(!empty($_POST['p_voucher'])) {
            $return_type = 'json';

            $voucher = trim(htmlentities($_POST['p_voucher'], ENT_QUOTES));
        }
        
        if(!empty($_POST['p_card_opt'])) {
            $return_type = 'json';

            $card_opt = htmlentities($_POST['p_card_opt'], ENT_QUOTES);
        }

        if(!empty($_POST['p_planval'])) {
            $return_type = 'json';

            $planval = htmlentities($_POST['p_planval'], ENT_QUOTES);
        }

        if(!empty($_POST['p_proid'])) {
            $return_type = 'json';

            $proid = htmlentities($_POST['p_proid'], ENT_QUOTES);
        }

        if(!empty($_POST['p_esim_convert'])) {
            $return_type = 'json';

            $esim_convert = htmlentities($_POST['p_esim_convert'], ENT_QUOTES);
        }

        if($return_type == 'json') {
            // Add cache prevention headers at the very beginning
            header('Cache-Control: no-cache, no-store, must-revalidate');
            header('Pragma: no-cache');
            header('Expires: 0');
            
            if(!wp_verify_nonce($_POST['nonce'], "check_esim_nonce")) {
                die();
            }
        }

        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        $result = array();
        $voucher_arr = array();
        $post_supplier_name = '';
        $supplier_error = false;
        $convert_arr = array();

        if(empty($esim_convert)) {
            $esim_convert = 'No';
        }

        if(!empty($planval)) {
            // $domain = 'http://localhost/brightline_v5';
            $domain = '';

            $qry_domain = "SELECT * FROM " . $wpdb->prefix . "autoesim_settings WHERE autoesim_opt='remote_server_domain'";
            $rs_domain = $wpdb->get_row($qry_domain, ARRAY_A);
            $rs_domain_count = $wpdb->num_rows;

            if($rs_domain_count > 0) {
                $domain = $rs_domain['autoesim_val'];
            }

            if(!empty($domain)) {
                $url = $domain . '/wp-admin/admin-ajax.php?action=remoteapi_chkesim';

                $api_data = array(
                    'esim' => $esim,
                    'voucher' => $voucher,
                    'card_opt' => $card_opt,
                    'planval' => $planval,
                    'proid' => $proid,
                    'esim_convert' => $esim_convert
                );

                $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
                    $return['status'] = 'fail';
                    $return['html'] = '';
                    $return['result'] = '<div class="badnews">Error, please refresh the page and try again. Thank you.</div>';
                    $return['vou'] = $voucher_arr;
                    $return['convert'] = $convert_arr;
                }
                else {
                    $return = $result_arr;
                }
            }
            else {
                $return['status'] = 'fail';
                $return['html'] = '';
                $return['result'] = '<div class="badnews">Error, please refresh the page and try again. Thank you.</div>';
                $return['vou'] = $voucher_arr;
                $return['convert'] = $convert_arr;
            }
        }
        else {
            $return['status'] = 'fail';
            $return['html'] = '';
            $return['result'] = '<div class="badnews">Error, please refresh the page and try again. Thank you.</div>';
            $return['vou'] = $voucher_arr;
            $return['convert'] = $convert_arr;
        }

        // echo json_encode($return);
        
        // die();

        if($return_type == 'array') {
            return $return;
        }
        else {
            echo json_encode($return);
            die();
        }
    }

    function generate_planinfo($param_planval = '') {
        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        $return_type = '';
        $return = array();

        $planval = '';

        //Function Call
        if(!empty($param_planval)) {
            $return_type = 'array';

            $planval = $param_planval;
        }

        //POST Filter
        if(!empty($_POST['planvalue'])) {
            $return_type = 'json';

            $planval = htmlentities($_POST['planvalue'], ENT_QUOTES);
        }
        
        // if($return_type == 'json') {
        //     if(!wp_verify_nonce($_POST['nonce'], "check_esim_nonce")) {
        //         die();
        //     }
        // }

        $result = array();

        if(!empty($planval)) {
            // $domain = 'http://localhost/brightline_v5';
            $domain = '';

            $qry_domain = "SELECT * FROM " . $wpdb->prefix . "autoesim_settings WHERE autoesim_opt='remote_server_domain'";
            $rs_domain = $wpdb->get_row($qry_domain, ARRAY_A);
            $rs_domain_count = $wpdb->num_rows;

            if($rs_domain_count > 0) {
                $domain = $rs_domain['autoesim_val'];
            }

            if(!empty($domain)) {
                $url = $domain . '/wp-admin/admin-ajax.php?action=remoteapi_get_planinfo';

                $api_data = array(
                    'planval' => $planval
                );

                $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
                    $return['status'] = 'failed';
                    $return['respond'] = '';
                }
                else {
                    $return = $result_arr;
                }
            }
            else {
                $return['status'] = 'failed';
                $return['respond'] = '';
            }
        }
        else {
            $return['status'] = 'failed';
            $return['respond'] = '';
        }

        if($return_type == 'array') {
            return $return;
        }
        else {
            echo json_encode($return);
            die();
        }
    }

    function save_complete_form() {
        // Add cache prevention headers at the very beginning
        header('Cache-Control: no-cache, no-store, must-revalidate');
        header('Pragma: no-cache');
        header('Expires: 0');
        
        if(!wp_verify_nonce($_POST['nonce'], "check_form_nonce")) {
            die();
        }

        global $wpdb;
        $result = array();

        date_default_timezone_set("Asia/Singapore");

        $proid = '';
        $esim = '';
        $chkemail = '';
        $vou_code = '';
        $vou_num = '';
        $vou_status = '';
        $vou_type = '';
        $vou_val = '';
        $card_opt = '';
        $esim_convert = '';
        $agree_convert = '';
        $planval = '';
        
        if(!empty($_POST['planval'])) {
            $planval = htmlentities($_POST['planval'], ENT_QUOTES);
        }

        if(!empty($_POST['proid'])) {
            $proid = htmlentities($_POST['proid'], ENT_QUOTES);
        }

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

        if(!empty($_POST['chkemail'])) {
            $chkemail = htmlentities($_POST['chkemail'], ENT_QUOTES);
        }
        
        if(!empty($_POST['vou_code'])) {
            $vou_code = trim(htmlentities($_POST['vou_code'], ENT_QUOTES));
        }
        
        if(!empty($_POST['vou_num'])) {
            $vou_num = htmlentities($_POST['vou_num'], ENT_QUOTES);
        }

        if(!empty($_POST['vou_status'])) {
            $vou_status = htmlentities($_POST['vou_status'], ENT_QUOTES);
        }

        if(!empty($_POST['vou_type'])) {
            $vou_type = htmlentities($_POST['vou_type'], ENT_QUOTES);
        }

        if(!empty($_POST['vou_val'])) {
            $vou_val = htmlentities($_POST['vou_val'], ENT_QUOTES);
        }

        if(!empty($_POST['card_opt'])) {
            $card_opt = htmlentities($_POST['card_opt'], ENT_QUOTES);
        }

        if(!empty($_POST['esim_convert'])) {
            $esim_convert = htmlentities($_POST['esim_convert'], ENT_QUOTES); // No | Yes
        }

        if(!empty($_POST['agree_convert'])) {
            $agree_convert = htmlentities($_POST['agree_convert'], ENT_QUOTES); // Accepted | Declined
        }
        
        if(!empty($card_opt)) {
            require_once plugin_dir_path( __FILE__ ) . 'stripe' . DIRECTORY_SEPARATOR . 'init.php';


            $final_price_return = $this->generate_chkesim($esim, $vou_code, $card_opt, $planval, $proid, $esim_convert);
            $planinfo_return = $this->generate_planinfo($planval);

            $stripe_api_key = '';
            $stripe_success_url = '';
            $stripe_failed_url = '';
            $default_order_prefix = '';

            $qry_stripeinfos = "SELECT * FROM ".$wpdb->prefix."autoesim_settings WHERE autoesim_opt 
                IN('stripe_api_key', 'stripe_success_url', 'stripe_failed_url', 'order_prefix')";
            $rs_stripeinfos = $wpdb->get_results($qry_stripeinfos, ARRAY_A);

            if($rs_stripeinfos) {
                foreach($rs_stripeinfos as $rs_stripeinfo) {
                    if($rs_stripeinfo['autoesim_opt'] == 'stripe_api_key') {
                        $stripe_api_key = $rs_stripeinfo['autoesim_val'];
                    }

                    if($rs_stripeinfo['autoesim_opt'] == 'stripe_success_url') {
                        $stripe_success_url = $rs_stripeinfo['autoesim_val'];
                    }

                    if($rs_stripeinfo['autoesim_opt'] == 'stripe_failed_url') {
                        $stripe_failed_url = $rs_stripeinfo['autoesim_val'];
                    }

                    if($rs_stripeinfo['autoesim_opt'] == 'order_prefix') {
                        $default_order_prefix = $rs_stripeinfo['autoesim_val'];
                    }
                }
            }

            if(empty($default_order_prefix)) {
                $default_order_prefix = 'SZV';
            }

            $order_cur = 'SGD';
            $order_ttl = 0;
            $order_discount = 0;

            if($final_price_return['status'] == 'pass') {
                $order_cur = $final_price_return['order_cur'];
                $order_ttl = $final_price_return['order_ttl'];
                $order_discount = $final_price_return['order_discount'];
            }

            $order_region = '';
            $order_destination = '';
            $order_packname = '';

            if($planinfo_return['status'] == 'success') {
                // $planinfo_return['respond']['cm_pack_id'];
                // $planinfo_return['respond']['cm_price'];
                // $planinfo_return['respond']['cm_desc'];
                // $planinfo_return['respond']['cm_cover'];
                // $planinfo_return['respond']['cm_destination_val'];
                // $planinfo_return['respond']['cm_region_val'];
                // $planinfo_return['respond']['cm_uniq_supplier'];
                // $planinfo_return['respond']['cm_uniq_sku'];

                $order_region = $planinfo_return['respond']['cm_region'];
                $order_destination = $planinfo_return['respond']['cm_destination'];
                $order_packname = $planinfo_return['respond']['cm_packname'];
            }

            $agree_datetime = '';

            if(empty($esim_convert)) {
                $esim_convert = 'No';
            }

            if($esim_convert == 'Yes') {
                $agree_datetime = date("Y-m-d H:i:s");
            }

            $username_arr = explode("@", $chkemail);
            $username = $username_arr[0];
            
            //SZV20241234567890
            $order_sn = $default_order_prefix . date("ymd") . strtoupper($this->generateRandomString(6));
            
            $order_sn_status = false;
            while(!$order_sn_status) {
                $qry_chk_sn = "SELECT COUNT(*) AS ttl_record FROM ".$wpdb->prefix."autoesim_order WHERE auesim_order_sn='".$order_sn."'";
                $rs_chk_sn = $wpdb->get_row($qry_chk_sn, ARRAY_A);

                if($rs_chk_sn['setting_val'] > 0) {
                    $order_sn = $default_order_prefix . date("ymd") . strtoupper($this->generateRandomString(6));
                }
                else {
                    // $order_sn_status = true;
                    break;
                }
            }

            $order_privatekey = $this->generateRandomString(20);

            // auesim_id, auesim_order_sn, auesim_cdate, auesim_email, auesim_buyer_username, auesim_ttl_price, auesim_item_type, auesim_item_sku, auesim_item_supplier, auesim_item_convert_status, auesim_item_agree_convert, auesim_item_agree_convert_datetime, auesim_status, auesim_qty, auesim_package_id, auesim_region, auesim_destination, auesim_plan, auesim_esim_opt, auesim_esim_iccid, auesim_discount_status, auesim_discount_type, auesim_discount_price, auesim_voucher, auesim_stripe_id, auesim_stripe_cdate, auesim_stripe_data, auesim_stripe_status, auesim_stripe_desc, auesim_stripe_event, auesim_stripe_orderid, auesim_cm_order_id, auesim_gdrive_name, auesim_gdrive_id, auesim_posttoserver_status, auesim_posttoserver_datetime, auesim_currency, auesim_voucher_value, auesim_private_key

            //existing_card | new_card
            if($card_opt == 'new_card') {
                $order_type = 'new_esim';
                $esim = '';
            }
            else {
                $order_type = 'topup';
            }

            if($esim_convert == 'Yes') {
                $esim = '';
            }

            $wpdb->insert($wpdb->prefix . "autoesim_order", 
                array(
                    'auesim_order_sn' => $order_sn,
                    'auesim_cdate' => date("Y-m-d H:i:s"),
                    'auesim_email' => $chkemail,
                    'auesim_buyer_username' => $username,
                    'auesim_ttl_price' => $order_ttl,
                    'auesim_item_type' => $order_type,
                    'auesim_item_sku' => '',
                    'auesim_item_supplier' => '',
                    'auesim_item_convert_status' => $esim_convert,
                    'auesim_item_agree_convert' => $agree_convert,
                    'auesim_item_agree_convert_datetime' => $agree_datetime,
                    'auesim_status' => 'Pending',
                    'auesim_qty' => '1',
                    'auesim_package_id' => $planval,
                    'auesim_region' => $order_region,
                    'auesim_destination' => $order_destination,
                    'auesim_plan' => $order_packname,
                    'auesim_esim_opt' => $card_opt,
                    'auesim_esim_iccid' => $esim,
                    'auesim_discount_status' => $vou_status,
                    'auesim_discount_type' => $vou_type,
                    'auesim_discount_price' => $order_discount,
                    'auesim_voucher' => $vou_code,
                    'auesim_voucher_value' => $vou_val,
                    'auesim_currency' => $order_cur,
                    'auesim_private_key' => $order_privatekey,
                    'auesim_posttoserver_status' => 'No' // No | Pending | Process | Done
                )
            );

            // increase the voucher - vou_used_ttl_checkout count


            \Stripe\Stripe::setApiKey($stripe_api_key);

            // $api_callbackone = get_option('chinamobile_api_callbackone');
            // $api_callbacktwo = get_option('chinamobile_api_callbacktwo');
            
            $success_url = $stripe_success_url . "?action=transaction&orderid=" . $order_sn . "&status=success&trans=" . $order_privatekey;
            $fail_url = $stripe_failed_url . "?action=transaction&orderid=" . $order_sn . "&status=failed&trans=" . $order_privatekey;
            
            if($card_opt == 'new_card') {
                $stripe_item_name = $order_destination . ' - ' .  $order_packname;
            }
            else {
                $stripe_item_name = $order_destination . ' - ' .  $order_packname . ' - ' . $esim;
            }

            $stripe_total = $order_ttl * 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_sn],
                "success_url" => $success_url,
                "cancel_url" => $fail_url,
                "locale" => "auto",
                "line_items" => [
                    [
                        "quantity" => 1,
                        "price_data" => [
                            "currency" => $order_cur,
                            "unit_amount" => $stripe_total,
                            "product_data" => [
                                "name" => $stripe_item_name
                            ]
                        ]
                    ]       
                ],
                "client_reference_id" => $order_sn
            ]);
            
            //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;
        }
        else {
            $result['status'] = 'failed';
            $result['url'] = '';
        }
        
        echo json_encode($result);
        
        die();
    }

    function stripe_success_ope() {
        // https://brightline.com.sg/wp-admin/admin-ajax.php?action=esim_stripe_success

        require_once plugin_dir_path( __FILE__ ) . 'stripe' . DIRECTORY_SEPARATOR . 'init.php';
        // require_once plugin_dir_path( __FILE__ ) . 'stripe-php/init.php';

        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        // $esim = htmlentities($_POST['esim'], ENT_QUOTES);
        // $voucher = trim(htmlentities($_POST['voucher'], ENT_QUOTES));
        // $card_opt = htmlentities($_POST['card_opt'], ENT_QUOTES);
        
        $stripe_api_key = '';
        $stripe_success_url = '';
        $stripe_failed_url = '';
        $stripe_webhook_key = '';
        $qry_stripeinfos = "SELECT * FROM ".$wpdb->prefix."autoesim_settings WHERE autoesim_opt IN('stripe_api_key', 'stripe_success_url', 'stripe_failed_url', 'stripe_webhook_key')";
        $rs_stripeinfos = $wpdb->get_results($qry_stripeinfos, ARRAY_A);

        if($rs_stripeinfos) {
            foreach($rs_stripeinfos as $rs_stripeinfo) {
                if($rs_stripeinfo['autoesim_opt'] == 'stripe_api_key') {
                    $stripe_api_key = $rs_stripeinfo['autoesim_val'];
                }

                if($rs_stripeinfo['autoesim_opt'] == 'stripe_success_url') {
                    $stripe_success_url = $rs_stripeinfo['autoesim_val'];
                }

                if($rs_stripeinfo['autoesim_opt'] == 'stripe_failed_url') {
                    $stripe_failed_url = $rs_stripeinfo['autoesim_val'];
                }

                if($rs_stripeinfo['autoesim_opt'] == 'stripe_webhook_key') {
                    $stripe_webhook_key = $rs_stripeinfo['autoesim_val'];
                }
            }
        }
        
        \Stripe\Stripe::setApiKey($stripe_api_key);

        // If you are testing your webhook locally with the Stripe CLI you
        // can find the endpoint's secret by running `stripe listen`
        // Otherwise, find your endpoint's secret in your webhook settings in the Developer Dashboard
        // $endpoint_secret = 'whsec_f58aec977075e83f6061a279988bb7432abb6644abb497b1e86c1b41df23561a';
        // $endpoint_secret = 'whsec_B1ICnVNVvikVKWNGav1SCMnmTxW40jjF';
        $endpoint_secret = $stripe_webhook_key;

        $payload = @file_get_contents('php://input');
        $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
        $event = null;

        try {
            $event = \Stripe\Webhook::constructEvent(
                $payload, $sig_header, $endpoint_secret
            );
        } catch(\UnexpectedValueException $e) {
            // Invalid payload
            http_response_code(400);
            // echo json_encode(['Error parsing payload: ' => $e->getMessage()]);
            exit();
        } catch(\Stripe\Exception\SignatureVerificationException $e) {
            // Invalid signature
            http_response_code(400);
            // echo json_encode(['Error verifying webhook signature: ' => $e->getMessage()]);
            exit();
        }

        // Handle the event
        switch ($event->type) {
            case 'payment_intent.succeeded':
                // $event->data->object->description = "Order ID:44421";

                // detect it is order from topup
                if(strpos($event->data->object->description, "Order ID:") !== false) {
                    $sub_orderid = trim(str_replace("Order ID:", "", $event->data->object->description));
                    
                    //order sn checking to prevent duplicate records.
                    $qry_chk_dup = "SELECT *, DATE_FORMAT(auesim_cdate, '%Y-%m-%d') AS create_date FROM " . $wpdb->prefix . "autoesim_order WHERE auesim_order_sn='" . $sub_orderid . "' AND auesim_status='Pending'";
                    $rs_chk_dup = $wpdb->get_row($qry_chk_dup, ARRAY_A);
                    $rs_chk_dup_count = $wpdb->num_rows;

                    if($rs_chk_dup_count > 0) {
                        //just skip, because already have the record in db
                    }
                    else {
                        // $rs_chk_dup['auesim_id'];

                        $param_str = json_encode($event);

                        $wpdb->update(
                            $wpdb->prefix."autoesim_order", 
                            array(
                                'auesim_status' => 'Paid',
                                'auesim_stripe_id' => $event->id,
                                'auesim_stripe_cdate' => date("Y-m-d H:i:s"),
                                'auesim_stripe_data' => $param_str,
                                'auesim_stripe_status' => $event->data->object->status,
                                'auesim_stripe_desc' => $event->data->object->description,
                                'auesim_stripe_event' => $event->type,
                                'auesim_stripe_orderid' => $sub_orderid
                            ), 
                            array('auesim_id' => $rs_chk_dup['auesim_id'])
                        );
                        
                        $web_orders_arr = array(
                            'order_sn' => $rs_chk_dup['auesim_order_sn'],
                            'order_buyer_id' => '', //not woocommerce
                            'order_buyer_username' => $rs_chk_dup['auesim_buyer_username'],
                            'order_create_time' => $rs_chk_dup['create_date'],
                            'order_msg_to_seller' => '',
                            'order_shopee_status' => 'Pending',
                            'order_cdate' => date("Y-m-d H:i:s"),
                            'order_mdate' => date("Y-m-d H:i:s"),
                            'order_extract_emails' => $rs_chk_dup['auesim_email'],
                            'order_process_status' => 'Sync Process', //Use 1. Sync Process, 2. No Line Detected, 3. Pending, 4. Picked Up, 5. Completed
                            'order_active' => '1',
                            'order_currency' => $rs_chk_dup['auesim_currency'],
                            'order_total_amount' => $rs_chk_dup['auesim_ttl_price'],
                            'order_buyer_name' => $rs_chk_dup['auesim_buyer_username'],
                            'order_buyer_email' => $rs_chk_dup['auesim_email'],
                            'order_buyer_phone_number' => '',
                            'order_rerun_status' => 'new'
                        );

                        $web_order_items = array(
                            'item_item_id' => '',
                            'item_item_name' => $rs_chk_dup['auesim_destination'],
                            'item_item_sku' => $rs_chk_dup['auesim_package_id'],
                            'item_model_id' => '',
                            'item_model_name' => $rs_chk_dup['auesim_plan'],
                            'item_model_sku' => '',
                            'item_qty' => $rs_chk_dup['auesim_qty'],
                            'item_order_item_id' => '',
                            'item_status' => 'Pending',
                            'item_mdate' => date("Y-m-d H:i:s"),
                            'item_package_id' => $rs_chk_dup['auesim_package_id'],
                            'item_type' => $rs_chk_dup['auesim_item_type'],
                            'item_iccid_info' => $rs_chk_dup['auesim_esim_iccid'],
                            'item_convert_status' => $rs_chk_dup['auesim_item_convert_status'],
                            'auesim_esim_opt' => $rs_chk_dup['auesim_esim_opt'],
                            'auesim_item_agree_convert' => $rs_chk_dup['auesim_item_agree_convert'],
                            'auesim_item_agree_convert_datetime' => $rs_chk_dup['auesim_item_agree_convert_datetime']
                        );

                        $res = $this->private_cm_order_completion($sub_orderid, 'success');
                        
                        // send to brightline.com.sg automation db
                        // $domain = 'http://localhost/brightline_v5';
                        $domain = '';

                        $qry_domain = "SELECT * FROM " . $wpdb->prefix . "autoesim_settings WHERE autoesim_opt='remote_server_domain'";
                        $rs_domain = $wpdb->get_row($qry_domain, ARRAY_A);
                        $rs_domain_count = $wpdb->num_rows;

                        if($rs_domain_count > 0) {
                            $domain = $rs_domain['autoesim_val'];
                        }

                        if(!empty($domain)) {
                            $url = $domain . '/wp-admin/admin-ajax.php?action=remoteapi_stripe_success_ope';

                            $api_data = array(
                                'order' => $web_orders_arr,
                                'order_item' => $web_order_items
                            );

                            $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
                                $return['status'] = 'failed';
                                $return['respond'] = '';
                            }
                            else {
                                $return = $result_arr;

                                if($return['status'] == 'success') {
                                    $wpdb->update(
                                        $wpdb->prefix."autoesim_order", 
                                        array(
                                            'auesim_status' => 'Completed',
                                            'auesim_item_supplier' => $return['respond']['auesim_item_supplier'],
                                            'auesim_cm_order_id' => $return['respond']['auesim_cm_order_id'],
                                            'auesim_gdrive_name' => $return['respond']['auesim_gdrive_name'],
                                            'auesim_gdrive_id' => $return['respond']['auesim_gdrive_id'],
                                            'auesim_posttoserver_status' => 'Done',
                                            'auesim_posttoserver_datetime' => date("Y-m-d H:i:s")
                                        ), 
                                        array('auesim_id' => $rs_chk_dup['auesim_id'])
                                    );
                                }
                            }
                        }
                        else {
                            $return['status'] = 'failed';
                            $return['respond'] = '';
                        }
                    }
                }

                break;
            default:
                // echo 'Received unknown event type ' . $event->type;
        }

        http_response_code(200);
        die();
    }

    function stripe_success_ope_v2() {
        // http://localhost:8039/szoove/wp-admin/admin-ajax.php?action=new_esim_stripe_success
        // https://szoove.com/wp-admin/admin-ajax.php?action=new_esim_stripe_success

        require_once plugin_dir_path( __FILE__ ) . 'stripe' . DIRECTORY_SEPARATOR . 'init.php';
        // require_once plugin_dir_path( __FILE__ ) . 'stripe-php/init.php';

        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        // $esim = htmlentities($_POST['esim'], ENT_QUOTES);
        // $voucher = trim(htmlentities($_POST['voucher'], ENT_QUOTES));
        // $card_opt = htmlentities($_POST['card_opt'], ENT_QUOTES);
        
        $stripe_api_key = '';
        $stripe_success_url = '';
        $stripe_failed_url = '';
        $stripe_webhook_key = '';
        $default_order_prefix = '';

        $domain = '';

        $qry_stripeinfos = "SELECT * FROM ".$wpdb->prefix."autoesim_settings WHERE autoesim_opt 
            IN('stripe_api_key', 'stripe_success_url', 'stripe_failed_url', 'stripe_webhook_key', 'order_prefix', 'remote_server_domain')";
        $rs_stripeinfos = $wpdb->get_results($qry_stripeinfos, ARRAY_A);

        if($rs_stripeinfos) {
            foreach($rs_stripeinfos as $rs_stripeinfo) {
                if($rs_stripeinfo['autoesim_opt'] == 'stripe_api_key') {
                    $stripe_api_key = $rs_stripeinfo['autoesim_val'];
                }

                if($rs_stripeinfo['autoesim_opt'] == 'stripe_success_url') {
                    $stripe_success_url = $rs_stripeinfo['autoesim_val'];
                }

                if($rs_stripeinfo['autoesim_opt'] == 'stripe_failed_url') {
                    $stripe_failed_url = $rs_stripeinfo['autoesim_val'];
                }

                if($rs_stripeinfo['autoesim_opt'] == 'stripe_webhook_key') {
                    $stripe_webhook_key = $rs_stripeinfo['autoesim_val'];
                }

                if($rs_stripeinfo['autoesim_opt'] == 'order_prefix') {
                    $default_order_prefix = $rs_stripeinfo['autoesim_val'];
                }

                if($rs_stripeinfo['autoesim_opt'] == 'remote_server_domain') {
                    $domain = $rs_stripeinfo['autoesim_val'];
                }
            }
        }
        
        if(empty($default_order_prefix)) {
            $default_order_prefix = 'SZV';
        }

        \Stripe\Stripe::setApiKey($stripe_api_key);

        // If you are testing your webhook locally with the Stripe CLI you
        // can find the endpoint's secret by running `stripe listen`
        // Otherwise, find your endpoint's secret in your webhook settings in the Developer Dashboard
        // $endpoint_secret = 'whsec_f58aec977075e83f6061a279988bb7432abb6644abb497b1e86c1b41df23561a';
        // $endpoint_secret = 'whsec_B1ICnVNVvikVKWNGav1SCMnmTxW40jjF';
        $endpoint_secret = $stripe_webhook_key;

        $payload = @file_get_contents('php://input');
        $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
        $event = null;

        try {
            $event = \Stripe\Webhook::constructEvent(
                $payload, $sig_header, $endpoint_secret
            );
        } catch(\UnexpectedValueException $e) {
            // Invalid payload
            http_response_code(400);
            // echo json_encode(['Error parsing payload: ' => $e->getMessage()]);
            exit();
        } catch(\Stripe\Exception\SignatureVerificationException $e) {
            // Invalid signature
            http_response_code(400);
            // echo json_encode(['Error verifying webhook signature: ' => $e->getMessage()]);
            exit();
        }

        // Handle the event
        switch ($event->type) {
            case 'payment_intent.succeeded':
                // $event->data->object->description = "Order ID:44421";

                // $param_str1 = json_encode($event);
                // $sub_orderid1 = trim(str_replace("Order ID:", "", $event->data->object->description));
                // $order_prefix_chk1 = substr($sub_orderid1, 0, 3);

                // $wpdb->insert($wpdb->prefix . "automatc_stripe", 
                //     array(
                //         'stripe_id' => $event->id,
                //         'stripe_cdate' => date("Y-m-d H:i:s"),
                //         'stripe_data' => $order_prefix_chk1,
                //         'stripe_status' => $event->data->object->status,
                //         'stripe_desc' => $event->data->object->description,
                //         'stripe_event' => $event->type,
                //         'stripe_orderid' => $sub_orderid1,
                //         'stripe_cronjob' => $default_order_prefix
                //     )
                // );
                
                // detect it is order from topup
                if(strpos($event->data->object->description, "Order ID:") !== false) {
                    $sub_orderid = trim(str_replace("Order ID:", "", $event->data->object->description));
                    
                    $order_prefix_chk = substr($sub_orderid, 0, 3);

                    if($order_prefix_chk == $default_order_prefix) {
                        //verified order

                        //order sn checking to prevent duplicate records.
                        // auesim_status => Pending | Paid | Sync | Completed
                        // $qry_chk_dup = "SELECT *, DATE_FORMAT(auesim_cdate, '%Y-%m-%d') AS create_date FROM " . $wpdb->prefix . "autoesim_order WHERE auesim_order_sn='" . $sub_orderid . "' AND auesim_status='Pending'";
                        $qry_chk_dup = "SELECT *, DATE_FORMAT(auesim_cdate, '%Y-%m-%d') AS create_date FROM " . $wpdb->prefix . "autoesim_order WHERE auesim_order_sn='" . $sub_orderid . "' AND auesim_status='Pending'";
                        $rs_chk_dup = $wpdb->get_row($qry_chk_dup, ARRAY_A);
                        $rs_chk_dup_count = $wpdb->num_rows;

                        if($rs_chk_dup_count == 0) {
                            //just skip, because already have the record in db
                        }
                        else {
                            // $rs_chk_dup['auesim_id'];

                            $param_str = json_encode($event);

                            $wpdb->update(
                                $wpdb->prefix."autoesim_order", 
                                array(
                                    'auesim_status' => 'Paid',
                                    'auesim_stripe_id' => $event->id,
                                    'auesim_stripe_cdate' => date("Y-m-d H:i:s"),
                                    'auesim_stripe_data' => $param_str,
                                    'auesim_stripe_status' => $event->data->object->status,
                                    'auesim_stripe_desc' => $event->data->object->description,
                                    'auesim_stripe_event' => $event->type,
                                    'auesim_stripe_orderid' => $sub_orderid,
                                    'auesim_posttoserver_status' => 'Pending'  // No | Pending | Process | Done
                                ), 
                                array('auesim_id' => $rs_chk_dup['auesim_id'])
                            );
                            
                            // $web_orders_arr = array(
                            //     'order_sn' => $rs_chk_dup['auesim_order_sn'],
                            //     'order_buyer_id' => '', //not woocommerce
                            //     'order_buyer_username' => $rs_chk_dup['auesim_buyer_username'],
                            //     'order_create_time' => $rs_chk_dup['create_date'],
                            //     'order_msg_to_seller' => '',
                            //     'order_shopee_status' => 'Pending',
                            //     'order_cdate' => date("Y-m-d H:i:s"),
                            //     'order_mdate' => date("Y-m-d H:i:s"),
                            //     'order_extract_emails' => $rs_chk_dup['auesim_email'],
                            //     'order_process_status' => 'Sync Process', //Use 1. Sync Process, 2. No Line Detected, 3. Pending, 4. Picked Up, 5. Completed
                            //     'order_active' => '1',
                            //     'order_currency' => $rs_chk_dup['auesim_currency'],
                            //     'order_total_amount' => $rs_chk_dup['auesim_ttl_price'],
                            //     'order_buyer_name' => $rs_chk_dup['auesim_buyer_username'],
                            //     'order_buyer_email' => $rs_chk_dup['auesim_email'],
                            //     'order_buyer_phone_number' => '',
                            //     'order_rerun_status' => 'new'
                            // );

                            // $web_order_items = array(
                            //     'item_item_id' => '',
                            //     'item_item_name' => $rs_chk_dup['auesim_destination'],
                            //     'item_item_sku' => $rs_chk_dup['auesim_package_id'],
                            //     'item_model_id' => '',
                            //     'item_model_name' => $rs_chk_dup['auesim_plan'],
                            //     'item_model_sku' => '',
                            //     'item_qty' => $rs_chk_dup['auesim_qty'],
                            //     'item_order_item_id' => '',
                            //     'item_status' => 'Pending',
                            //     'item_mdate' => date("Y-m-d H:i:s"),
                            //     'item_package_id' => $rs_chk_dup['auesim_package_id'],
                            //     'item_type' => $rs_chk_dup['auesim_item_type'],
                            //     'item_iccid_info' => $rs_chk_dup['auesim_esim_iccid'],
                            //     'item_convert_status' => $rs_chk_dup['auesim_item_convert_status'],
                            //     'auesim_esim_opt' => $rs_chk_dup['auesim_esim_opt'],
                            //     'auesim_item_agree_convert' => $rs_chk_dup['auesim_item_agree_convert'],
                            //     'auesim_item_agree_convert_datetime' => $rs_chk_dup['auesim_item_agree_convert_datetime']
                            // );

                            // $res = $this->private_cm_order_completion($sub_orderid, 'success');
                            
                            // send to brightline.com.sg automation db
                            // $domain = 'http://localhost/brightline_v5';
                            
                            // if(!empty($domain)) {
                            //     $url = $domain . '/wp-admin/admin-ajax.php?action=remoteapi_stripe_success_ope';

                            //     $api_data = array(
                            //         'order' => $web_orders_arr,
                            //         'order_item' => $web_order_items
                            //     );

                            //     $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 - ***** need to do error handling properly
                            //         $return['status'] = 'failed';
                            //         $return['respond'] = '';
                            //     }
                            //     else {
                            //         $return = $result_arr;

                            //         if($return['status'] == 'success') {
                            //             $wpdb->update(
                            //                 $wpdb->prefix."autoesim_order", 
                            //                 array(
                            //                     'auesim_status' => 'Completed',
                            //                     'auesim_item_supplier' => $return['respond']['auesim_item_supplier'],
                            //                     'auesim_cm_order_id' => $return['respond']['auesim_cm_order_id'],
                            //                     'auesim_gdrive_name' => $return['respond']['auesim_gdrive_name'],
                            //                     'auesim_gdrive_id' => $return['respond']['auesim_gdrive_id'],
                            //                     'auesim_posttoserver_status' => 'Done',
                            //                     'auesim_posttoserver_datetime' => date("Y-m-d H:i:s")
                            //                 ), 
                            //                 array('auesim_id' => $rs_chk_dup['auesim_id'])
                            //             );
                            //         }
                            //     }
                            // }
                            // else {
                            //     $return['status'] = 'failed';
                            //     $return['respond'] = '';
                            // }
                        }
                    }
                    else {
                        //not verify order
                    }
                }

                break;
            default:
                // echo 'Received unknown event type ' . $event->type;
        }

        http_response_code(200);
        die();
    }

    public function cronjob_stripe_success_ope_process() {
        // http://localhost:8039/szoove/wp-admin/admin-ajax.php?action=cronjob_stripe_success_ope_process
        // https://szoove.com/wp-admin/admin-ajax.php?action=cronjob_stripe_success_ope_process

        global $wpdb;
        date_default_timezone_set("Asia/Singapore");
        $return = array();

        // $esim = htmlentities($_POST['esim'], ENT_QUOTES);
        // $voucher = trim(htmlentities($_POST['voucher'], ENT_QUOTES));
        // $card_opt = htmlentities($_POST['card_opt'], ENT_QUOTES);
        
        // auesim_posttoserver_status => No | Pending | Process | Done
        $qry_chk_dup = "SELECT *, DATE_FORMAT(auesim_cdate, '%Y-%m-%d') AS create_date FROM " . $wpdb->prefix . "autoesim_order WHERE auesim_posttoserver_status='Pending' ORDER BY auesim_cdate ASC LIMIT 1";
        $rs_chk_dup = $wpdb->get_row($qry_chk_dup, ARRAY_A);
        $rs_chk_dup_count = $wpdb->num_rows;

        if($rs_chk_dup_count > 0) {
            // Start Process
            // auesim_id, auesim_order_sn, auesim_cdate, auesim_email, auesim_buyer_username, auesim_ttl_price, auesim_item_type, auesim_item_sku,
            // auesim_item_supplier, auesim_item_convert_status, auesim_item_agree_convert, auesim_item_agree_convert_datetime, auesim_status,
            // auesim_qty, auesim_package_id, auesim_region, auesim_destination, auesim_plan, auesim_esim_opt, auesim_esim_iccid, auesim_discount_status,
            // auesim_discount_type, auesim_discount_price, auesim_voucher, auesim_stripe_id, auesim_stripe_cdate, auesim_stripe_data, auesim_stripe_status,
            // auesim_stripe_desc, auesim_stripe_event, auesim_stripe_orderid, auesim_cm_order_id, auesim_gdrive_name, auesim_gdrive_id,
            // auesim_posttoserver_status, auesim_posttoserver_datetime, auesim_currency, auesim_voucher_value, auesim_private_key;
            
            //Avoid duplication
            $wpdb->update(
                $wpdb->prefix."autoesim_order", 
                array(
                    'auesim_posttoserver_status' => 'Process', // No | Pending | Process | Done
                    'auesim_posttoserver_last_process_dtime' => date("Y-m-d H:i:s"),
                    'auesim_posttoserver_process_count' => '1'
                ), 
                array('auesim_id' => $rs_chk_dup['auesim_id'])
            );

            $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
                array(
                    'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
                    'logs_order_action' => 'Start first process',
                    'logs_param' => 'cronjob_stripe_success_ope_process - Status change to Process',
                    'logs_cdate' => date("Y-m-d H:i:s")
                )
            );

            // Settings
            $default_order_prefix = '';
            $domain = '';

            $qry_stripeinfos = "SELECT * FROM ".$wpdb->prefix."autoesim_settings WHERE autoesim_opt 
                IN('order_prefix', 'remote_server_domain')";
            $rs_stripeinfos = $wpdb->get_results($qry_stripeinfos, ARRAY_A);

            if($rs_stripeinfos) {
                foreach($rs_stripeinfos as $rs_stripeinfo) {
                    if($rs_stripeinfo['autoesim_opt'] == 'order_prefix') {
                        $default_order_prefix = $rs_stripeinfo['autoesim_val'];
                    }

                    if($rs_stripeinfo['autoesim_opt'] == 'remote_server_domain') {
                        $domain = $rs_stripeinfo['autoesim_val'];
                    }
                }
            }
            
            if(empty($default_order_prefix)) {
                $default_order_prefix = 'SZV';
            }
            
            $web_orders_arr = array(
                'order_sn' => $rs_chk_dup['auesim_order_sn'],
                'order_buyer_id' => '', //not woocommerce
                'order_buyer_username' => $rs_chk_dup['auesim_buyer_username'],
                'order_create_time' => $rs_chk_dup['create_date'],
                'order_msg_to_seller' => '',
                'order_shopee_status' => 'Pending',
                'order_cdate' => date("Y-m-d H:i:s"),
                'order_mdate' => date("Y-m-d H:i:s"),
                'order_extract_emails' => $rs_chk_dup['auesim_email'],
                'order_process_status' => 'Sync Process', //Use 1. Sync Process, 2. No Line Detected, 3. Pending, 4. Picked Up, 5. Completed
                'order_active' => '1',
                'order_currency' => $rs_chk_dup['auesim_currency'],
                'order_total_amount' => $rs_chk_dup['auesim_ttl_price'],
                'order_buyer_name' => $rs_chk_dup['auesim_buyer_username'],
                'order_buyer_email' => $rs_chk_dup['auesim_email'],
                'order_buyer_phone_number' => '',
                'order_rerun_status' => 'new',
                'auesim_voucher' => $rs_chk_dup['auesim_voucher']
            );

            $web_order_items = array(
                'item_item_id' => '',
                'item_item_name' => $rs_chk_dup['auesim_destination'],
                'item_item_sku' => $rs_chk_dup['auesim_package_id'],
                'item_model_id' => '',
                'item_model_name' => $rs_chk_dup['auesim_plan'],
                'item_model_sku' => '',
                'item_qty' => $rs_chk_dup['auesim_qty'],
                'item_order_item_id' => '',
                'item_status' => 'Pending',
                'item_mdate' => date("Y-m-d H:i:s"),
                'item_package_id' => $rs_chk_dup['auesim_package_id'],
                'item_type' => $rs_chk_dup['auesim_item_type'],
                'item_iccid_info' => $rs_chk_dup['auesim_esim_iccid'],
                'item_convert_status' => $rs_chk_dup['auesim_item_convert_status'],
                'auesim_esim_opt' => $rs_chk_dup['auesim_esim_opt'],
                'auesim_item_agree_convert' => $rs_chk_dup['auesim_item_agree_convert'],
                'auesim_item_agree_convert_datetime' => $rs_chk_dup['auesim_item_agree_convert_datetime']
            );

            // $res = $this->private_cm_order_completion($sub_orderid, 'success');
            
            // send to brightline.com.sg automation db
            if(!empty($domain)) {
                $url = $domain . '/wp-admin/admin-ajax.php?action=remoteapi_stripe_success_ope';

                $api_data = array(
                    'order' => $web_orders_arr,
                    'order_item' => $web_order_items
                );

                $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);

                // echo '<pre>';
                // print_r($result);
                // echo '</pre>';

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

                curl_close($ch);

                if($http_code != 200) {
                    //error
                    $return['status'] = 'failed';
                    $return['respond'] = '';

                    $wpdb->update(
                        $wpdb->prefix."autoesim_order", 
                        array(
                            'auesim_posttoserver_status' => 'Rerun', // No | Pending | Process | Done
                            'auesim_posttoserver_last_process_dtime' => date("Y-m-d H:i:s"),
                            'auesim_posttoserver_process_count' => '1'
                        ), 
                        array('auesim_id' => $rs_chk_dup['auesim_id'])
                    );

                    $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
                        array(
                            'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
                            'logs_order_action' => 'HTTP Code is not 200',
                            'logs_param' => 'cronjob_stripe_success_ope_process - Status change to Rurun',
                            'logs_cdate' => date("Y-m-d H:i:s")
                        )
                    );
                }
                else {
                    $return = $result_arr;

                    if($return['status'] == 'success') {
                        $wpdb->update(
                            $wpdb->prefix."autoesim_order", 
                            array(
                                'auesim_status' => 'Completed',
                                'auesim_item_supplier' => $return['respond']['auesim_item_supplier'],
                                'auesim_cm_order_id' => $return['respond']['auesim_cm_order_id'],
                                'auesim_gdrive_name' => $return['respond']['auesim_gdrive_name'],
                                'auesim_gdrive_id' => $return['respond']['auesim_gdrive_id'],
                                'auesim_posttoserver_status' => 'Done',
                                'auesim_posttoserver_datetime' => date("Y-m-d H:i:s")
                            ), 
                            array('auesim_id' => $rs_chk_dup['auesim_id'])
                        );

                        $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
                            array(
                                'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
                                'logs_order_action' => 'Order run completed',
                                'logs_param' => 'cronjob_stripe_success_ope_process - Status change to Done',
                                'logs_cdate' => date("Y-m-d H:i:s")
                            )
                        );
                    }
                    else {
                        $wpdb->update(
                            $wpdb->prefix."autoesim_order", 
                            array(
                                'auesim_posttoserver_status' => 'Rerun', // No | Pending | Process | Done
                                'auesim_posttoserver_last_process_dtime' => date("Y-m-d H:i:s"),
                                'auesim_posttoserver_process_count' => '1'
                            ), 
                            array('auesim_id' => $rs_chk_dup['auesim_id'])
                        );

                        $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
                            array(
                                'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
                                'logs_order_action' => 'HTTP Code is not 200',
                                'logs_param' => 'cronjob_stripe_success_ope_process - Status change to Rurun',
                                'logs_cdate' => date("Y-m-d H:i:s")
                            )
                        );
                    }
                }
            }
            else {
                $return['status'] = 'failed';
                $return['respond'] = '';

                $wpdb->update(
                    $wpdb->prefix."autoesim_order", 
                    array(
                        'auesim_posttoserver_status' => 'Rerun', // No | Pending | Process | Done
                        'auesim_posttoserver_last_process_dtime' => date("Y-m-d H:i:s"),
                        'auesim_posttoserver_process_count' => '1'
                    ), 
                    array('auesim_id' => $rs_chk_dup['auesim_id'])
                );

                $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
                    array(
                        'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
                        'logs_order_action' => 'Cannot found remote server domain',
                        'logs_param' => 'cronjob_stripe_success_ope_process - Status change to Rurun',
                        'logs_cdate' => date("Y-m-d H:i:s")
                    )
                );
            }
        }

        die();
    }

    public function cronjob_rerun_process_orders_db() {
        // http://localhost:8039/szoove/wp-admin/admin-ajax.php?action=cronjob_rerun_process_orders_db
        // https://szoove.com/wp-admin/admin-ajax.php?action=cronjob_rerun_process_orders_db

        global $wpdb;
        date_default_timezone_set("Asia/Singapore");
        $return = array();
        $admin_email = 'no';
        $failed_operation = false;

        $brightline_prefix = 'sp6yz_';
        $cur_dtime = date("Y-m-d H:i:s");

        //so, it is search for records that is 3min or more then 3min
        // $qry_chk_dup = "SELECT *, DATE_FORMAT(auesim_cdate, '%Y-%m-%d') AS create_date FROM " . $wpdb->prefix . "autoesim_order 
        // WHERE auesim_posttoserver_status='Process' AND TIMESTAMPDIFF(MINUTE, auesim_cdate, '" . $cur_dtime . "') >= 3 
        // ORDER BY auesim_cdate ASC LIMIT 1";
        // $qry_chk_dup = "SELECT *, DATE_FORMAT(auesim_cdate, '%Y-%m-%d') AS create_date FROM " . $wpdb->prefix . "autoesim_order 
        // WHERE auesim_posttoserver_status='Rerun' ORDER BY auesim_cdate ASC LIMIT 1";
        $qry_chk_dup = "SELECT *, DATE_FORMAT(auesim_cdate, '%Y-%m-%d') AS create_date FROM " . $wpdb->prefix . "autoesim_order 
        WHERE auesim_posttoserver_status='Rerun' ORDER BY auesim_cdate ASC";

        $rs_chk_dups = $wpdb->get_results($qry_chk_dup, ARRAY_A);
        // $rs_chk_dup_count = $wpdb->num_rows;

        if($rs_chk_dups && count($rs_chk_dups) > 0) {
            /////////////////////////////////////////////
            //Brightline database connection
            $settings_arr = array();

            $qry_brightdbinfos = "SELECT * FROM ".$wpdb->prefix."autoesim_settings WHERE autoesim_opt 
                IN('brightline_db_host', 'brightline_db_user', 'brightline_db_passwd', 'brightline_db_name', 'brightline_db_prefix')";
            $rs_brightdbinfos = $wpdb->get_results($qry_brightdbinfos, ARRAY_A);

            if($rs_brightdbinfos) {
                foreach($rs_brightdbinfos as $rs_brightdbinfo) {
                    if($rs_brightdbinfo['autoesim_opt'] == 'brightline_db_passwd') {
                        $settings_arr[$rs_brightdbinfo['autoesim_opt']] = substr($rs_brightdbinfo['autoesim_val'], 0, -1);
                    }
                    else if($rs_brightdbinfo['autoesim_opt'] == 'brightline_db_prefix') {
                        $settings_arr[$rs_brightdbinfo['autoesim_opt']] = $rs_brightdbinfo['autoesim_val'];

                        $brightline_prefix = $rs_brightdbinfo['autoesim_val'];
                    }
                    else {
                        $settings_arr[$rs_brightdbinfo['autoesim_opt']] = $rs_brightdbinfo['autoesim_val'];
                    }
                }
            }
            
            // Create a new database connection for the brightline database
            $brightline_db = new wpdb(
                $settings_arr['brightline_db_user'], 
                $settings_arr['brightline_db_passwd'], 
                $settings_arr['brightline_db_name'], 
                $settings_arr['brightline_db_host']
            );

            // Check for connection errors
            if (!empty($brightline_db->error)) {
                // error_log('Database connection failed: ' . $brightline_db->error);
                // return;

                $failed_operation = true;

                $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
                    array(
                        'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
                        'logs_order_action' => 'Cannot Connecto To Brightline DB',
                        'logs_param' => 'Database connection failed: ' . $brightline_db->error,
                        'logs_cdate' => date("Y-m-d H:i:s")
                    )
                );
            }
            /////////////////////////////////////////////

            if(!$failed_operation) {
                foreach($rs_chk_dups as $rs_chk_dup) {
                    //$rs_chk_dup['auesim_order_sn']

                    $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
                        array(
                            'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
                            'logs_order_action' => 'Order Found - ' . $rs_chk_dup['auesim_order_sn'],
                            'logs_param' => '',
                            'logs_cdate' => date("Y-m-d H:i:s")
                        )
                    );
                    
                    $order_arr = array(
                        'order_sn' => $rs_chk_dup['auesim_order_sn'],
                        'order_buyer_id' => '', //not woocommerce
                        'order_buyer_username' => $rs_chk_dup['auesim_buyer_username'],
                        'order_create_time' => $rs_chk_dup['create_date'],
                        'order_msg_to_seller' => '',
                        'order_shopee_status' => 'Pending',
                        'order_cdate' => date("Y-m-d H:i:s"),
                        'order_mdate' => date("Y-m-d H:i:s"),
                        'order_extract_emails' => $rs_chk_dup['auesim_email'],
                        'order_process_status' => 'Sync Process', //Use 1. Sync Process, 2. No Line Detected, 3. Pending, 4. Picked Up, 5. Completed
                        'order_active' => '1',
                        'order_currency' => $rs_chk_dup['auesim_currency'],
                        'order_total_amount' => $rs_chk_dup['auesim_ttl_price'],
                        'order_buyer_name' => $rs_chk_dup['auesim_buyer_username'],
                        'order_buyer_email' => $rs_chk_dup['auesim_email'],
                        'order_buyer_phone_number' => '',
                        'order_rerun_status' => 'new',
                        'auesim_voucher' => $rs_chk_dup['auesim_voucher']
                    );

                    $order_item_arr = array(
                        'item_item_id' => '',
                        'item_item_name' => $rs_chk_dup['auesim_destination'],
                        'item_item_sku' => $rs_chk_dup['auesim_package_id'],
                        'item_model_id' => '',
                        'item_model_name' => $rs_chk_dup['auesim_plan'],
                        'item_model_sku' => '',
                        'item_qty' => $rs_chk_dup['auesim_qty'],
                        'item_order_item_id' => '',
                        'item_status' => 'Pending',
                        'item_mdate' => date("Y-m-d H:i:s"),
                        'item_package_id' => $rs_chk_dup['auesim_package_id'],
                        'item_type' => $rs_chk_dup['auesim_item_type'],
                        'item_iccid_info' => $rs_chk_dup['auesim_esim_iccid'],
                        'item_convert_status' => $rs_chk_dup['auesim_item_convert_status'],
                        'auesim_esim_opt' => $rs_chk_dup['auesim_esim_opt'],
                        'auesim_item_agree_convert' => $rs_chk_dup['auesim_item_agree_convert'],
                        'auesim_item_agree_convert_datetime' => $rs_chk_dup['auesim_item_agree_convert_datetime']
                    );

                    $run_main_process = false;
                    $order_pre_check = '';
                    $order_sn = $order_arr['order_sn'];

                    $order_chk = "SELECT * FROM " . $brightline_prefix . "automatc_web_orders WHERE order_sn='" . $order_sn . "'";
                    $rs_order_chk = $brightline_db->get_row($order_chk, ARRAY_A);
                    $rs_order_chk_count = $brightline_db->num_rows;

                    if($rs_order_chk_count > 0) {
                        // echo 'Get order record<br/>';

                        $lastid = $rs_order_chk['order_id'];

                        // Check the new_esim/topup process already completed or not to run the action
                        if($rs_order_chk['order_process_status'] == 'Completed') {
                            // Done order, just send the signal back to szoove server to update
                            $run_main_process = false;
                            $order_pre_check = 'Completed';

                            $brightline_db->insert($brightline_prefix."automatc_web_ord_szoove_logs", 
                            array(
                                'logs_order_sn' => $order_sn,
                                'logs_order_action' => 'Order Run Completed But Not Update Szoove',
                                'logs_param' => 'Order Run Completed But Not Update Szoove - ' . $order_sn,
                                'logs_cdate' => date("Y-m-d H:i:s")
                                )
                            );

                            $qry_refresh = "SELECT * FROM " . $brightline_prefix . "automatc_web_orders w 
                                LEFT JOIN " . $brightline_prefix . "automatc_web_order_items i ON(w.order_id=i.item_order_id) 
                                WHERE w.order_sn='" . $order_sn . "';";
                            $rs_refresh = $brightline_db->get_results($qry_refresh, ARRAY_A);

                            $auesim_item_supplier = '';
                            $auesim_cm_order_id = '';
                            $auesim_gdrive_name = '';
                            $auesim_gdrive_id = '';

                            if($rs_refresh) {
                                foreach($rs_refresh as $rs_refresh_item) {
                                    $auesim_item_supplier = $rs_refresh_item['item_main_supplier'];
                                    $auesim_cm_order_id = $rs_refresh_item['item_cm_order_id'];
                                    $auesim_gdrive_name = $rs_refresh_item['item_gdrive_name'];
                                    $auesim_gdrive_id = $rs_refresh_item['item_gdrive_id'];
                                }
                            }
                            
                            $return['status'] = 'success';
                            $return['respond']['auesim_item_supplier'] = $auesim_item_supplier;
                            $return['respond']['auesim_cm_order_id'] = $auesim_cm_order_id;
                            $return['respond']['auesim_gdrive_name'] = $auesim_gdrive_name;
                            $return['respond']['auesim_gdrive_id'] = $auesim_gdrive_id;

                            $wpdb->update(
                                $wpdb->prefix."autoesim_order", 
                                array(
                                    'auesim_status' => 'Completed',
                                    'auesim_item_supplier' => $return['respond']['auesim_item_supplier'],
                                    'auesim_cm_order_id' => $return['respond']['auesim_cm_order_id'],
                                    'auesim_gdrive_name' => $return['respond']['auesim_gdrive_name'],
                                    'auesim_gdrive_id' => $return['respond']['auesim_gdrive_id'],
                                    'auesim_posttoserver_status' => 'Done',
                                    'auesim_posttoserver_datetime' => date("Y-m-d H:i:s")
                                ), 
                                array('auesim_id' => $rs_chk_dup['auesim_id'])
                            );

                            $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
                            array(
                                    'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
                                    'logs_order_action' => 'Send API Request Success - Status was Success',
                                    'logs_param' => 'Change Order Status From Rerun to Done - ' . json_encode($return),
                                    'logs_cdate' => date("Y-m-d H:i:s")
                                )
                            );
                        }
                        else {
                            $run_main_process = true;

                            $wpdb->update(
                                $wpdb->prefix."autoesim_order", 
                                array(
                                    'auesim_posttoserver_status' => 'Sync', // From 'Rerun' to 'Sync'
                                    'auesim_posttoserver_last_process_dtime' => date("Y-m-d H:i:s")
                                ), 
                                array('auesim_id' => $rs_chk_dup['auesim_id'])
                            );

                            // Update Brightline Order table to make the order rerun again
                            $upt_order_sync_status = $brightline_db->update(
                                $brightline_prefix . "automatc_web_orders", 
                                array(
                                    'order_process_status' => 'Pending',
                                    'order_rerun_status' => 'rerun'
                                ), 
                                array('order_id' => $lastid)
                            );
                            
                            $brightline_db->insert($brightline_prefix."automatc_web_ord_szoove_logs", 
                                array(
                                    'logs_order_sn' => $order_sn,
                                    'logs_order_action' => 'Order Rerun Detected',
                                    'logs_param' => 'Update Brightline Order Process Status To Pending - ' . $brightline_prefix . 'automatc_web_orders',
                                    'logs_cdate' => date("Y-m-d H:i:s")
                                )
                            );
                        }
                    }
                    else {
                        $run_main_process = true;

                        // echo 'Insert order record<br/>';

                        $brightline_db->insert($brightline_prefix."automatc_web_ord_szoove_logs", 
                        array(
                            'logs_order_sn' => $order_sn,
                            'logs_order_action' => 'New Order Rerun Insert',
                            'logs_param' => 'New Rerun Order Insert To DB',
                            'logs_cdate' => date("Y-m-d H:i:s")
                            )
                        );
                        
                        // insert new record
                        // $wpdb->show_errors();
                        $order_table = $brightline_prefix . "automatc_web_orders";
                        $res = $brightline_db->insert($order_table, 
                            array(
                                'order_sn' => $order_sn,
                                'order_buyer_id' => $order_arr['order_buyer_id'],
                                'order_buyer_username' => $order_arr['order_buyer_username'],
                                'order_create_time' => $order_arr['order_create_time'],
                                'order_msg_to_seller' => $order_arr['order_msg_to_seller'],
                                'order_shopee_status' => $order_arr['order_shopee_status'],
                                'order_cdate' => $order_arr['order_cdate'],
                                'order_mdate' => $order_arr['order_mdate'],
                                'order_extract_emails' => $order_arr['order_extract_emails'], //'order_extract_emails' => 'kelvin@brightline.com.sg',
                                'order_process_status' => $order_arr['order_process_status'], //Use 1. Sync Process, 2. No Line Detected, 3. Pending, 4. Picked Up, 5. Completed
                                'order_active' => $order_arr['order_active'],
                                'order_currency' => $order_arr['order_currency'],
                                'order_total_amount' => $order_arr['order_total_amount'],
                                'order_buyer_name' => $order_arr['order_buyer_name'],
                                'order_buyer_email' => $order_arr['order_buyer_email'],
                                'order_buyer_phone_number' => $order_arr['order_buyer_phone_number'],
                                'order_rerun_status' => $order_arr['order_rerun_status']
                            )
                        );
                        // echo '<pre>';
                        // print_r($wpdb->print_error());
                        // echo '</pre>';

                        if($res === FALSE) {
                            $run_main_process = false;

                            // $return_arr['status'] = 'failed';
                            // $return_arr['respond'] = '';

                            $brightline_db->insert($brightline_prefix."automatc_web_ord_szoove_logs", 
                            array(
                                'logs_order_sn' => $order_sn,
                                'logs_order_action' => 'New Order Failed To Insert',
                                'logs_param' => 'New Rerun Order Cannot Insert To DB',
                                'logs_cdate' => date("Y-m-d H:i:s")
                                )
                            );
                            
                            // //Update record
                            if(empty($rs_chk_dup['auesim_posttoserver_process_count'])) {
                                $new_ttl = 1;
                            }
                            else {
                                $new_ttl = (int)$rs_chk_dup['auesim_posttoserver_process_count'] + 1;
                            }
                            
                            $wpdb->update(
                                $wpdb->prefix."autoesim_order", 
                                array(
                                    'auesim_posttoserver_status' => 'Rerun', // From 'Process' to 'Rerun'
                                    'auesim_posttoserver_last_process_dtime' => date("Y-m-d H:i:s"),
                                    'auesim_posttoserver_process_count' => $new_ttl
                                ), 
                                array('auesim_id' => $rs_chk_dup['auesim_id'])
                            );
                            
                            $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
                            array(
                                    'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
                                    'logs_order_action' => 'Send API Request Success - Status was Failed',
                                    'logs_param' => 'Change Order Status To Rerun',
                                    'logs_cdate' => date("Y-m-d H:i:s")
                                )
                            );
                        }
                        else {
                            $lastid = $brightline_db->insert_id;
                    
                            $all_qty_check = 0;
                            
                            // $wpdb->show_errors();
                            $order_item_table = $brightline_prefix . "automatc_web_order_items";
                            $res_child = $brightline_db->insert($order_item_table, 
                                array(
                                    'item_order_id' => $lastid, 
                                    'item_item_id' => $order_item_arr['item_item_id'], 
                                    'item_item_name' => $order_item_arr['item_item_name'], 
                                    'item_item_sku' => $order_item_arr['item_item_sku'], 
                                    'item_model_id' => $order_item_arr['item_model_id'], 
                                    'item_model_name' => $order_item_arr['item_model_name'], 
                                    'item_model_sku' => $order_item_arr['item_model_sku'], 
                                    'item_qty' => $order_item_arr['item_qty'], 
                                    'item_order_item_id' => $order_item_arr['item_order_item_id'], 
                                    'item_status' => $order_item_arr['item_status'], 
                                    'item_mdate' => $order_item_arr['item_mdate'],
                                    'item_package_id' => $order_item_arr['item_package_id'],
                                    'item_type' => $order_item_arr['item_type'],
                                    'item_iccid_info' => $order_item_arr['item_iccid_info'],
                                    'item_convert_status' => $order_item_arr['item_convert_status'],
                                    'auesim_esim_opt' => $order_item_arr['auesim_esim_opt'],
                                    'auesim_item_agree_convert' => $order_item_arr['auesim_item_agree_convert'],
                                    'auesim_item_agree_convert_datetime' => $order_item_arr['auesim_item_agree_convert_datetime']
                                )
                            );

                            if($res_child === FALSE) {
                                $run_main_process = false;

                                // $return_arr['status'] = 'failed';
                                // $return_arr['respond'] = '';

                                // //Update record
                                if(empty($rs_chk_dup['auesim_posttoserver_process_count'])) {
                                    $new_ttl = 1;
                                }
                                else {
                                    $new_ttl = (int)$rs_chk_dup['auesim_posttoserver_process_count'] + 1;
                                }
                                
                                $wpdb->update(
                                    $wpdb->prefix."autoesim_order", 
                                    array(
                                        'auesim_posttoserver_status' => 'Rerun', // From 'Process' to 'Rerun'
                                        'auesim_posttoserver_last_process_dtime' => date("Y-m-d H:i:s"),
                                        'auesim_posttoserver_process_count' => $new_ttl
                                    ), 
                                    array('auesim_id' => $rs_chk_dup['auesim_id'])
                                );

                                $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
                                array(
                                        'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
                                        'logs_order_action' => 'Insert Order Item Failed',
                                        'logs_param' => 'Change Order Status To Rerun',
                                        'logs_cdate' => date("Y-m-d H:i:s")
                                    )
                                );
                                
                                // delete the order header
                                //$order_table = $wpdb->prefix . "automatc_web_orders";
                                $brightline_db->delete($brightline_prefix . "automatc_web_orders", array('order_id' => $lastid));

                                $brightline_db->insert($brightline_prefix . "automatc_web_ord_szoove_logs", 
                                array(
                                    'logs_order_sn' => $order_sn,
                                    'logs_order_action' => 'New Order Item Failed To Insert',
                                    'logs_param' => 'New Rerun Order Item Cannot Insert To DB - Deleted Order Header Record',
                                    'logs_cdate' => date("Y-m-d H:i:s")
                                    )
                                );
                            }
                            else {
                                $run_main_process = true;

                                // echo '<pre>';
                                // print_r($wpdb->print_error());
                                // echo '</pre>';

                                //update new status code here to prevent error....
                                //'order_process_status' => 'Pending', //Use 1. Sync Process, 2. No Line Detected, 3. Pending, 4. Picked Up, 5. Completed
                                //$lastid
                                $upt_order_sync_status = $brightline_db->update(
                                    $brightline_prefix."automatc_web_orders", 
                                    array('order_process_status' => 'Pending'), 
                                    array('order_id' => $lastid)
                                );

                                $wpdb->update(
                                    $wpdb->prefix."autoesim_order", 
                                    array(
                                        'auesim_posttoserver_status' => 'Sync', // From 'Rerun' to 'Sync'
                                        'auesim_posttoserver_last_process_dtime' => date("Y-m-d H:i:s")
                                    ), 
                                    array('auesim_id' => $rs_chk_dup['auesim_id'])
                                );

                                $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
                                array(
                                        'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
                                        'logs_order_action' => 'Insert Order Success',
                                        'logs_param' => 'Change Order Status To Sync',
                                        'logs_cdate' => date("Y-m-d H:i:s")
                                    )
                                );
                               
                                if(!empty($vou_code)) {
                                    $vou_chk = "SELECT * FROM " . $brightline_prefix . "automatc_vouchers WHERE vou_code='".$vou_code."' AND vou_active='1' LIMIT 1";
                                    $rs_vou_chk = $brightline_db->get_row($vou_chk, ARRAY_A);
                                    $rs_vou_chk_count = $brightline_db->num_rows;

                                    if($rs_vou_chk_count > 0) {
                                        $new_ttl_count = (int)$rs_vou_chk['vou_used_ttl_checkout'] + 1;

                                        $brightline_db->update(
                                            $brightline_prefix."automatc_vouchers", 
                                            array('vou_used_ttl_checkout' => $new_ttl_count), 
                                            array('vou_id' => $rs_vou_chk['vou_id'])
                                        );
                                    }
                                }

                                $brightline_db->insert($brightline_prefix."automatc_web_ord_szoove_logs", 
                                array(
                                    'logs_order_sn' => $order_sn,
                                    'logs_order_action' => 'New Order Item Successfully Insert To DB',
                                    'logs_param' => 'New Rerun Order Item Successfully Insert To DB - Change The Process Status To Pending',
                                    'logs_cdate' => date("Y-m-d H:i:s")
                                    )
                                );

                                $brightline_db->insert($brightline_prefix."automatc_web_ordlogs", 
                                array(
                                        'logs_order_id' => $lastid, 
                                        'logs_param' => $order_sn, 
                                        'logs_cdate' => date("Y-m-d H:i:s"), 
                                        'logs_order_sn' => $order_sn, 
                                        'logs_order_action' => 'Rerun - Auto Order Syn - Unlock Order Status.', 
                                        'logs_order_status' => 'Success'
                                    )
                                );
                            }
                        }
                    }
                }
            }
        }

        die();
    }

    public function cronjob_rerun_process_orders() {
        // http://localhost:8039/szoove/wp-admin/admin-ajax.php?action=cronjob_rerun_process_orders
        // https://szoove.com/wp-admin/admin-ajax.php?action=cronjob_rerun_process_orders

        // global $wpdb;
        // date_default_timezone_set("Asia/Singapore");
        // $return = array();
        // $admin_email = 'no';

        // // echo '999<br/>';

        // // $esim = htmlentities($_POST['esim'], ENT_QUOTES);
        // // $voucher = trim(htmlentities($_POST['voucher'], ENT_QUOTES));
        // // $card_opt = htmlentities($_POST['card_opt'], ENT_QUOTES);
        
        // // auesim_posttoserver_status => No | Pending | Process | Done
        // // $qry_chk_dup = "SELECT *, DATE_FORMAT(auesim_cdate, '%Y-%m-%d') AS create_date FROM " . $wpdb->prefix . "autoesim_order WHERE auesim_posttoserver_status='Pending' ORDER BY auesim_cdate ASC LIMIT 1";
        // // $qry_chk_dup = "SELECT *, DATE_FORMAT(auesim_cdate, '%Y-%m-%d') AS create_date FROM " . $wpdb->prefix . "autoesim_order 
        // // WHERE auesim_posttoserver_status='Process' ORDER BY auesim_cdate ASC LIMIT 1";
        // // $qry_chk_dup = "SELECT *, DATE_FORMAT(auesim_cdate, '%Y-%m-%d') AS create_date FROM wp_autoesim_order 
        // // WHERE auesim_posttoserver_status='Process' AND TIMESTAMPDIFF(MINUTE, auesim_cdate, '2025-09-04 11:49:06') > 2";

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

        // // echo $cur_dtime . '<br>';

        // //so, it is search for records that is 3min or more then 3min
        // $qry_chk_dup = "SELECT *, DATE_FORMAT(auesim_cdate, '%Y-%m-%d') AS create_date FROM " . $wpdb->prefix . "autoesim_order 
        // WHERE auesim_posttoserver_status='Process' AND TIMESTAMPDIFF(MINUTE, auesim_cdate, '" . $cur_dtime . "') >= 3 
        // ORDER BY auesim_cdate ASC LIMIT 1";

        // // echo $qry_chk_dup . '<br>';

        // $rs_chk_dup = $wpdb->get_row($qry_chk_dup, ARRAY_A);
        // $rs_chk_dup_count = $wpdb->num_rows;

        // if($rs_chk_dup_count > 0) {
        //     // Start Process
        //     // auesim_id, auesim_order_sn, auesim_cdate, auesim_email, auesim_buyer_username, auesim_ttl_price, auesim_item_type, auesim_item_sku,
        //     // auesim_item_supplier, auesim_item_convert_status, auesim_item_agree_convert, auesim_item_agree_convert_datetime, auesim_status,
        //     // auesim_qty, auesim_package_id, auesim_region, auesim_destination, auesim_plan, auesim_esim_opt, auesim_esim_iccid, auesim_discount_status,
        //     // auesim_discount_type, auesim_discount_price, auesim_voucher, auesim_stripe_id, auesim_stripe_cdate, auesim_stripe_data, auesim_stripe_status,
        //     // auesim_stripe_desc, auesim_stripe_event, auesim_stripe_orderid, auesim_cm_order_id, auesim_gdrive_name, auesim_gdrive_id,
        //     // auesim_posttoserver_status, auesim_posttoserver_datetime, auesim_currency, auesim_voucher_value, auesim_private_key;
            
        //     $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
        //     array(
        //             'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
        //             'logs_order_action' => 'Order Found - ' . $rs_chk_dup['auesim_order_sn'],
        //             'logs_param' => 'SQL Fileter Datetime - ' . $cur_dtime,
        //             'logs_cdate' => date("Y-m-d H:i:s")
        //         )
        //     );
            
        //     //Update record
        //     if(empty($rs_chk_dup['auesim_posttoserver_process_count'])) {
        //         $new_ttl = 1;
        //     }
        //     else {
        //         $new_ttl = (int)$rs_chk_dup['auesim_posttoserver_process_count'] + 1;
        //     }

        //     // send email to admin - 99
        //     if($new_ttl > 3) {
        //         $admin_email = 'yes';
        //     }

        //     // 'auesim_posttoserver_status' => 'Process', // No | Pending | Process | Done
        //     $wpdb->update(
        //         $wpdb->prefix."autoesim_order", 
        //         array(
        //             'auesim_posttoserver_last_process_dtime' => date("Y-m-d H:i:s"),
        //             'auesim_posttoserver_process_count' => $new_ttl,
        //             'auesim_posttoserver_status' => 'Rerun' // From 'Process' to 'Rerun'
        //         ), 
        //         array('auesim_id' => $rs_chk_dup['auesim_id'])
        //     );

        //     $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
        //     array(
        //             'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
        //             'logs_order_action' => 'Change Order Status - ' . $rs_chk_dup['auesim_order_sn'],
        //             'logs_param' => 'Post to server status - From Process to Rerun',
        //             'logs_cdate' => date("Y-m-d H:i:s")
        //         )
        //     );

        //     $web_orders_arr = array(
        //         'order_sn' => $rs_chk_dup['auesim_order_sn'],
        //         'order_buyer_id' => '', //not woocommerce
        //         'order_buyer_username' => $rs_chk_dup['auesim_buyer_username'],
        //         'order_create_time' => $rs_chk_dup['create_date'],
        //         'order_msg_to_seller' => '',
        //         'order_shopee_status' => 'Pending',
        //         'order_cdate' => date("Y-m-d H:i:s"),
        //         'order_mdate' => date("Y-m-d H:i:s"),
        //         'order_extract_emails' => $rs_chk_dup['auesim_email'],
        //         'order_process_status' => 'Sync Process', //Use 1. Sync Process, 2. No Line Detected, 3. Pending, 4. Picked Up, 5. Completed
        //         'order_active' => '1',
        //         'order_currency' => $rs_chk_dup['auesim_currency'],
        //         'order_total_amount' => $rs_chk_dup['auesim_ttl_price'],
        //         'order_buyer_name' => $rs_chk_dup['auesim_buyer_username'],
        //         'order_buyer_email' => $rs_chk_dup['auesim_email'],
        //         'order_buyer_phone_number' => '',
        //         'order_rerun_status' => 'new',
        //         'auesim_voucher' => $rs_chk_dup['auesim_voucher']
        //     );

        //     $web_order_items = array(
        //         'item_item_id' => '',
        //         'item_item_name' => $rs_chk_dup['auesim_destination'],
        //         'item_item_sku' => $rs_chk_dup['auesim_package_id'],
        //         'item_model_id' => '',
        //         'item_model_name' => $rs_chk_dup['auesim_plan'],
        //         'item_model_sku' => '',
        //         'item_qty' => $rs_chk_dup['auesim_qty'],
        //         'item_order_item_id' => '',
        //         'item_status' => 'Pending',
        //         'item_mdate' => date("Y-m-d H:i:s"),
        //         'item_package_id' => $rs_chk_dup['auesim_package_id'],
        //         'item_type' => $rs_chk_dup['auesim_item_type'],
        //         'item_iccid_info' => $rs_chk_dup['auesim_esim_iccid'],
        //         'item_convert_status' => $rs_chk_dup['auesim_item_convert_status'],
        //         'auesim_esim_opt' => $rs_chk_dup['auesim_esim_opt'],
        //         'auesim_item_agree_convert' => $rs_chk_dup['auesim_item_agree_convert'],
        //         'auesim_item_agree_convert_datetime' => $rs_chk_dup['auesim_item_agree_convert_datetime']
        //     );

        //     $qry_brightdbinfos = "SELECT * FROM ".$wpdb->prefix."autoesim_settings WHERE autoesim_opt 
        //         IN('remote_server_domain')";
        //     $rs_brightdbinfos = $wpdb->get_results($qry_brightdbinfos, ARRAY_A);

        //     if($rs_brightdbinfos) {
        //         foreach($rs_brightdbinfos as $rs_brightdbinfo) {
        //             if($rs_brightdbinfo['autoesim_opt'] == 'remote_server_domain') {
        //                 $domain = $rs_brightdbinfo['autoesim_val'];
        //             }
        //         }
        //     }

        //     // send to brightline.com.sg automation db
        //     if(!empty($domain)) {
        //         $url = $domain . '/wp-admin/admin-ajax.php?action=remoteapi_rerun_process_ope';

        //         $api_data = array(
        //             'order' => $web_orders_arr,
        //             'order_item' => $web_order_items,
        //             'admin_email' => $admin_email
        //         );

        //         $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
        //         array(
        //                 'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
        //                 'logs_order_action' => 'Send API Request to Brightline Server',
        //                 'logs_param' => $url . ' - ' . json_encode($api_data),
        //                 'logs_cdate' => 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);

        //         // echo '<pre>';
        //         // print_r($result);
        //         // echo '</pre>';

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

        //         curl_close($ch);

        //         if($http_code != 200) {
        //             //error
        //             $return['status'] = 'failed';
        //             $return['respond'] = '';

        //             $wpdb->update(
        //                 $wpdb->prefix."autoesim_order", 
        //                 array(
        //                     'auesim_posttoserver_status' => 'Process' // From 'Process' to 'Rerun'
        //                 ), 
        //                 array('auesim_id' => $rs_chk_dup['auesim_id'])
        //             );
                    
        //             $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
        //             array(
        //                     'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
        //                     'logs_order_action' => 'Send API Request Failed',
        //                     'logs_param' => 'Change Order Status From Rerun to Process - HTTP Code 200',
        //                     'logs_cdate' => date("Y-m-d H:i:s")
        //                 )
        //             );
        //         }
        //         else {
        //             $return = $result_arr;

        //             // $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
        //             // array(
        //             //         'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
        //             //         'logs_order_action' => 'Send API Request Success',
        //             //         'logs_param' => json_encode($return),
        //             //         'logs_cdate' => date("Y-m-d H:i:s")
        //             //     )
        //             // );

        //             if($return['status'] == 'success') {
        //                 $wpdb->update(
        //                     $wpdb->prefix."autoesim_order", 
        //                     array(
        //                         'auesim_status' => 'Completed',
        //                         'auesim_item_supplier' => $return['respond']['auesim_item_supplier'],
        //                         'auesim_cm_order_id' => $return['respond']['auesim_cm_order_id'],
        //                         'auesim_gdrive_name' => $return['respond']['auesim_gdrive_name'],
        //                         'auesim_gdrive_id' => $return['respond']['auesim_gdrive_id'],
        //                         'auesim_posttoserver_status' => 'Done',
        //                         'auesim_posttoserver_datetime' => date("Y-m-d H:i:s")
        //                     ), 
        //                     array('auesim_id' => $rs_chk_dup['auesim_id'])
        //                 );

        //                 $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
        //                 array(
        //                         'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
        //                         'logs_order_action' => 'Send API Request Success - Status was Success',
        //                         'logs_param' => 'Change Order Status From Rerun to Done - ' . json_encode($return),
        //                         'logs_cdate' => date("Y-m-d H:i:s")
        //                     )
        //                 );
        //             }
        //             else {
        //                 // Reverse back to status "Process"

        //                 $wpdb->update(
        //                     $wpdb->prefix."autoesim_order", 
        //                     array(
        //                         'auesim_posttoserver_status' => 'Process' // From 'Process' to 'Rerun'
        //                     ), 
        //                     array('auesim_id' => $rs_chk_dup['auesim_id'])
        //                 );
                        
        //                 $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
        //                 array(
        //                         'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
        //                         'logs_order_action' => 'Send API Request Success - Status was Failed',
        //                         'logs_param' => 'Change Order Status From Rerun to Process - ' . json_encode($return),
        //                         'logs_cdate' => date("Y-m-d H:i:s")
        //                     )
        //                 );
        //             }
        //         }
        //     }
        //     else {
        //         $return['status'] = 'failed';
        //         $return['respond'] = '';

        //         $wpdb->update(
        //             $wpdb->prefix."autoesim_order", 
        //             array(
        //                 'auesim_posttoserver_status' => 'Process' // From 'Process' to 'Rerun'
        //             ), 
        //             array('auesim_id' => $rs_chk_dup['auesim_id'])
        //         );
                
        //         $wpdb->insert($wpdb->prefix."autoesim_order_cronlogs", 
        //         array(
        //                 'logs_order_sn' => $rs_chk_dup['auesim_order_sn'],
        //                 'logs_order_action' => 'Cannot Send API Request to Brightline Server',
        //                 'logs_param' => 'No Remote Server Domain Found',
        //                 'logs_cdate' => date("Y-m-d H:i:s")
        //             )
        //         );
        //     }
        // }
        // die();
    }
    */

    /*public function stripe_success_ope_process_copy() {
        // https://brightline.com.sg/wp-admin/admin-ajax.php?action=webstripesuccess

        global $wpdb;
        date_default_timezone_set("Asia/Singapore");

        //check pending orders
        //stripe_cronjob - Pending | Process | Completed
        $qry_pending = "SELECT * FROM " . $wpdb->prefix . "automatc_stripe WHERE stripe_cronjob='Pending' ORDER BY stripe_cdate ASC LIMIT 1";
        $rs_pending = $wpdb->get_row($qry_pending, ARRAY_A);
        $rs_pending_count = $wpdb->num_rows;

        if($rs_pending_count > 0) {
            //run the process
            //id, stripe_id, stripe_cdate, stripe_data, stripe_status, stripe_desc, stripe_event, stripe_orderid, stripe_cronjob
            $sub_orderid = $rs_pending['stripe_orderid'];
            $stripe_order_status = $rs_pending['stripe_cronjob'];
            $stripe_main_id = $rs_pending['id'];

            $upt_order_sync_status = $wpdb->update(
                $wpdb->prefix."automatc_stripe", 
                array('stripe_cronjob' => 'Process'), 
                array('id' => $stripe_main_id)
            );
            
            $wpdb->insert($wpdb->prefix."automatc_web_ordlogs", 
            array(
                    'logs_order_id' => $sub_orderid, 
                    'logs_param' => $sub_orderid, 
                    'logs_cdate' => date("Y-m-d H:i:s"), 
                    'logs_order_sn' => $sub_orderid, 
                    'logs_order_action' => 'Start Topup Process', 
                    'logs_order_status' => 'Success'
                )
            );
            
            $res = $this->private_cm_order_completion($sub_orderid, 'success');

            $upt_order_sync_status = $wpdb->update(
                $wpdb->prefix."automatc_stripe", 
                array('stripe_cronjob' => 'Completed'), 
                array('id' => $stripe_main_id)
            );
            
            $wpdb->insert($wpdb->prefix."automatc_web_ordlogs", 
            array(
                    'logs_order_id' => $sub_orderid, 
                    'logs_param' => $sub_orderid, 
                    'logs_cdate' => date("Y-m-d H:i:s"), 
                    'logs_order_sn' => $sub_orderid, 
                    'logs_order_action' => 'End Topup Process', 
                    'logs_order_status' => 'Success'
                )
            );
        }

        die();
    }

    function complete_form() {
        if(!wp_verify_nonce($_POST['nonce'], "check_form_nonce")) {
            die();
        }
        
        //if(!empty($_POST['proid']) && !empty($_POST['esim'])) {
        if(!empty($_POST['proid']) && !empty($_POST['card_opt'])) {
            require_once plugin_dir_path( __FILE__ ) . 'stripe' . DIRECTORY_SEPARATOR . 'init.php';
            
            date_default_timezone_set("Asia/Singapore");

            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);
            $card_opt = htmlentities($_POST['card_opt'], ENT_QUOTES);

            $esim_convert = htmlentities($_POST['esim_convert'], ENT_QUOTES); // No | Yes
            $agree_convert = htmlentities($_POST['agree_convert'], ENT_QUOTES); // Accepted | Declined
            $agree_datetime = '';
            
            $do_discount = false;
            $rs_vou_iccid_type = '';
            $rs_vou_type = '';
            $rs_vou_val = '';
            $rs_vou_code = '';

            //automatic_pro_relation

            if(empty($esim_convert)) {
                $esim_convert = 'No';
            }

            if($esim_convert == 'Yes') {
                $agree_datetime = date("Y-m-d H:i:s");
            }

            $new_esim_price = '0';
            $qry_esim_price = "SELECT * FROM " . $wpdb->prefix . "automatc_settings WHERE setting_opt='chinamobile_topup_new_esim_price'";
            $rs_esim_price = $wpdb->get_row($qry_esim_price, ARRAY_A);
            $rs_esim_price_count = $wpdb->num_rows;

            if($rs_esim_price_count > 0) {
                $new_esim_price = $rs_esim_price['setting_val'];
            }
            
            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($card_opt == "existing_card") {
                    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
                    }
                }
                else {
                    //new card
                    if(!empty($vou_code)) {
                        $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') {
                                if($rs_vou_filter['vou_expiry_type'] == 'opendate') {
                                    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)
                                        // ); 
                                    }
                                }
                                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($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)
                                            // ); 
                                        }
                                    }
                                    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');

            //chinamobile_api_newcard

            //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;
                    }

                    if($card_opt == "new_card") {
                        $final_price += $new_esim_price;
                    }

                    $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;
                    }

                    if($card_opt == "new_card") {
                        $final_price += $new_esim_price;
                    }

                    $final_price = number_format((float)$final_price, 2, '.', '');
                }
                else {
                    if($card_opt == "new_card") {
                        $final_price += $new_esim_price;
                    }

                    $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 ) );

                // existing_card
                // new_card

                $card_text = ucfirst(str_replace("_", " ", $card_opt));

                $args = array( 
                    'variation' => array(
                        'eSim Option' => $card_text,
                        '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,
                        'eSim Convert' => $esim_convert,
                        'Agree Convert' => $agree_convert,
                        'Agree Datetime' => $agree_datetime
                    ),
                    '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 {
                $product_obj = get_product( $proid );
                $sale_price = $product_obj->get_price();

                if($card_opt == "new_card") {
                    $final_price = $sale_price + $new_esim_price;
                }
                else {
                    $final_price = $sale_price;
                }

                $card_text = ucfirst(str_replace("_", " ", $card_opt));

                $args = array( 
                    'variation' => array(
                        'eSim Option' => $card_text,
                        'eSim' => $esim, 
                        'Destination Name' => $rs_dest_val, 
                        'Plan' => $rs_pack_val,
                        'Email' => $emailaddr,
                        'SKU' => $prod_sku,
                        'eSim Convert' => $esim_convert,
                        'Agree Convert' => $agree_convert,
                        'Agree Datetime' => $agree_datetime
                    ),
                    'totals' => array(
                        'subtotal' => $sale_price,
                        'total' => $final_price
                    )
                ); 

                $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);
            update_post_meta($order->id, '_order_info_cm_card_opt', $card_opt);

            update_post_meta($order->id, '_order_info_cm_esim_convert', $esim_convert);
            update_post_meta($order->id, '_order_info_cm_agree_convert', $agree_convert);
            update_post_meta($order->id, '_order_info_cm_agree_datetime', $agree_datetime);

            //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_dest_val . ' - ' .  $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();
        }
    }

    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;
    }*/
}

if (class_exists('wpautomationbonvoi')) {
    $wpautomationbonvoi = new wpautomationbonvoi();
    // $wpautomationbonvoi->init();
}
