<?php
$param_pre = 'zoner'; // pre-select the zone for all cases
$html_region = $this->bonvoi_retail_generate_chkregion();

//generate destination list if region provided
if(!empty($param_pre)) {
    $html_dest = $this->bonvoi_retail_generate_chkdest($param_pre);
}

//generate plans options if destination provided
if(!empty($param_pde)) {
    $html_plans = $this->bonvoi_retail_generate_chkplan($param_pde);
}

$settings_param_arr = array('bonvoi_topup_new_esim_price');
$options_param_arr = array();
$return_params = $this->bonvoi_retail_generate_parameters($settings_param_arr, $options_param_arr);

$new_esim_price = '';

if(!empty($return_params['bonvoi_topup_new_esim_price'])) {
    $new_esim_price = $return_params['bonvoi_topup_new_esim_price'];
}

// echo '<pre>';
// print_r($html_region);
// print_r($html_dest);
//print_r($html_plans);
// echo '</pre>';
?>

<?php
// $_SESSION['bonvoi_retail_msg']['status'] = 'success';
// $_SESSION['bonvoi_retail_msg']['msg'] = 'Login Successfully.';

if(!empty($_SESSION['bonvoi_retail_msg']['status'])) {
    if($_SESSION['bonvoi_retail_msg']['status'] == "success") {
        echo '<div class="wpcompleteautomatc_msgbox_success">';
            echo $_SESSION['bonvoi_retail_msg']['msg'];
        echo '</div>';
    }
    else if ($_SESSION['bonvoi_retail_msg']['status'] == "failed") {
        echo '<div class="wpcompleteautomatc_msgbox_error">';
            echo $_SESSION['bonvoi_retail_msg']['msg'];
        echo '</div>';
    }

    unset($_SESSION['bonvoi_retail_msg']);
}
?>
<style>
@media (min-width: 1025px) {
    .wpcompleteautomatc_msgbox_success {
        padding:20px 20px;
        margin-bottom:10px;
    }

    .wpcompleteautomatc_msgbox_error {
        padding:20px 20px;
        margin-bottom:10px;
    }
}

@media (min-width: 768px) and (max-width: 1024px) {
    .wpcompleteautomatc_msgbox_success {
        padding:10px 10px;
        margin-bottom:10px;
    }

    .wpcompleteautomatc_msgbox_error {
        padding:10px 10px;
        margin-bottom:10px;
    }
}

@media (max-width: 767px) {
    .wpcompleteautomatc_msgbox_success {
        padding:10px 10px;
        margin-bottom:10px;
    }

    .wpcompleteautomatc_msgbox_error {
        padding:10px 10px;
        margin-bottom:10px;
    }
}

.wpcompleteautomatc_msgbox_success {
    background:#f4fff2;
    border:1px solid #dbe8cf;
}

.wpcompleteautomatc_msgbox_error {
    background:#fff2f2;
    border:1px solid #f4dbdb;
}
</style>

<div class="topupform">
    <div class="tpfdiv span_staff_id">
        Info:
        <?php
        if(!empty($_SESSION['bonvoi_retail_auth'])) {
            echo $_SESSION['bonvoi_retail_auth']['staff_name'] . ' (' . $_SESSION['bonvoi_retail_auth']['shop_name'] . ')';

            echo '&nbsp;&nbsp;|&nbsp;&nbsp;<a href="'.$page_url . '?process=logout'.'">Logout</a>';
        }

        if($_SESSION['bonvoi_retail_auth']['role'] == 'Retail Supervisor') {
            echo '<br/>';
            
            echo '<a href="'.$page_url .'">eSIM Plans</a>';
            echo '&nbsp;&nbsp;|&nbsp;&nbsp;';
            echo '<a href="'.$page_url . '?process=registration'.'">Registration</a>';
            echo '&nbsp;&nbsp;|&nbsp;&nbsp;';
            echo '<a href="'.$page_url . '?process=reporting'.'">Reporting</a>';
        }
        ?>
    </div>
    <div class="tpfdiv span_region" style="display:none;">
        <?php /*
        <div class="tpflbl lbl_region" style="font-weight:bold;color:#4a86e8;">Select Region <img class="loadgif load_region" src="<?php echo $loading_gif; ?>"/></div>
        */ ?>
        <div class="tpfinput div_region">
            <select class="ipt_region input-text selectstyle" name="val_region">
            <?php
            if(!empty($param_pre)) {
                echo '<option value="">Select Region</option>';

                for($r=0; $r<count($html_region['json']); $r++) {
                    $reg_selected = '';
                    if($param_pre == $html_region['json'][$r]['val']) {
                        $reg_selected = ' selected="selected"';
                    }

                    echo '<option'.$reg_selected.' value="'.$html_region['json'][$r]['val'].'">'.$html_region['json'][$r]['text'].'</option>';
                }
            }
            else {
                // echo '<select class="ipt_region input-text selectstyle" name="val_region">';
                    echo $html_region['html'];
                // echo '</select>';
            }
            ?>
            </select>
        </div>
    </div>

    <?php
    $chk_dest_nonce = wp_create_nonce( 'check_dest_nonce' );
    ?>
    <input type="hidden" class="chkdestnonce" value="<?php echo $chk_dest_nonce; ?>"/>
    <div class="tpfdiv span_destination">
        <?php /*
        <div class="tpflbl lbl_destination" style="font-weight:bold;color:#4a86e8;color:">Select Destination <img class="loadgif load_destination" src="<?php echo $loading_gif; ?>"/></div>
        */ ?>
        <div class="tpfinput div_destination">
            <select class="ipt_destination input-text selectstyle" name="val_destination" id="destid">
                <?php
                if(!empty($param_pre)) {
                    echo '<option value="">Select Destination</option>';

                    for($r=0; $r<count($html_dest['json']); $r++) {
                        $dest_selected = '';
                        if($param_pde == $html_dest['json'][$r]['val']) {
                            $dest_selected = ' selected="selected"';
                        }

                        echo '<option'.$dest_selected.' value="'.$html_dest['json'][$r]['val'].'">'.$html_dest['json'][$r]['text'].'</option>';
                    }
                }
                else {
                    echo '<option value="">Select Destination</option>';
                }
                ?>
            </select><br/>
            <style>
                #destid {
                    /* color: #666666 !important; */
                    color: #c9c9c9;
                }
                #destid.has-value {
                    color: #666666 !important; /* Color when option is selected */
                }
                .fake_select {
                    width:100%;
                    text-align:left;
                    border-width: 1px;
                    border-style: solid;
                    border-color: #f8dbbd;
                    border-radius: 4px;
                    cursor: default;
                    padding:13px 20px 10px 20px;
                    background:#fff;
                    font-weight: 400;
                    font-size: 1rem;
                    line-height: 1.4em;
                    text-transform: none;
                    letter-spacing: 0px;
                    background:url("<?php echo $img_deative_arrow; ?>") no-repeat 99.5% 50%;
                    /* color: #666666 !important; */
                    color: #c9c9c9 !important;
                }
                .fake_select:hover, .fake_select:active, .fake_select:focus {
                    border-width: 1px;
                    border-style: solid;
                    border-color: #f8dbbd;
                    border-radius: 4px;
                    cursor: default;
                    padding:13px 20px 10px 20px;
                    background:#fff;
                    color:#666666;
                    font-weight: 400;
                    font-size: 1rem;
                    line-height: 1.4em;
                    text-transform: none;
                    letter-spacing: 0px;
                    background:url("<?php echo $img_deative_arrow; ?>") no-repeat 99.5% 50%;
                }
                .fake_select.has-value {
                    color: #666666 !important; /* Color when option is selected */
                    background:url("<?php echo $img_ative_arrow; ?>") no-repeat 99.5% 50%;
                }
                .fake_select.has-value:hover, .fake_select.has-value:active, .fake_select.has-value:focus {
                    border-width: 1px;
                    border-style: solid;
                    border-color: #f8dbbd;
                    border-radius: 4px;
                    cursor: default;
                    padding:13px 20px 10px 20px;
                    background:#fff;
                    color:#666666;
                    font-weight: 400;
                    font-size: 1rem;
                    line-height: 1.4em;
                    text-transform: none;
                    letter-spacing: 0px;
                    background:url("<?php echo $img_ative_arrow; ?>") no-repeat 99.5% 50%;
                }
                .fake_select.selected {
                    background: #f8dbbd;
                }
                
                @media (max-width: 544px) {
                    /*body, button, input, select, textarea, .ast-button, .ast-custom-button {
                        font-size: 16px;
                        font-size: 0.84210526315789rem;
                    }*/

                    .fake_select {
                        font-size: 0.84210526315789rem;
                    }
                    .fake_select:hover, .fake_select:active, .fake_select:focus {
                        font-size: 0.84210526315789rem;
                    }
                    .fake_select.has-value {
                        font-size: 0.84210526315789rem;
                    }
                    .fake_select.has-value:hover, .fake_select.has-value:active, .fake_select.has-value:focus {
                        font-size: 0.84210526315789rem;
                    }
                }
            </style>
            <a href="#model_destination" class="destmodellink highlinelink" rel="modal:open">Click here to see covered countries</a>
            <img class="loadgif load_region" src="<?php echo $loading_gif; ?>"/>
            <img class="loadgif load_destination" src="<?php echo $loading_gif; ?>"/>
        </div>
    </div>
    <div id="model_destination" class="modal">
        <p class="modeldestcontent">
            <?php
            if(!empty($param_pde)) {
                echo $html_dest['cover'];
            }
            ?>
        </p>
    </div>

    <script>
        jQuery(document).ready(function() {
            //un-grey destination selection
            jQuery("#destid").addClass('has-value');
        });
    </script>

    <div class="tpfdiv span_plans">
        <?php /*
        <div class="tpflbl lbl_destination" style="font-weight:bold;color:#4a86e8;color:">Select Destination <img class="loadgif load_destination" src="<?php echo $loading_gif; ?>"/></div>
        */ ?>
        <div class="tpfinput div_plans">
            <button class="fake_select esim_plans_btn">Select eSIM Data Plan</button>
        </div>
    </div>

    <?php
    if(!empty($param_pde)) {
        ?>
        <script>
            jQuery(document).ready(function() {
                var newinfoblockcls = ".<?php echo $param_pde; ?>_infoblock";
                jQuery(newinfoblockcls).show();

                jQuery(".generate_chkplan_json").val(JSON.stringify(<?php echo json_encode($html_plans['json']); ?>)); // original style
                jQuery(".generate_chkplan_day_json").val(JSON.stringify(<?php echo json_encode($html_plans['day_json']); ?>)); //day style
                
                var primary_count = 0;
                var second_count = 0;
                var primary_val = '';
                var second_val = '';

                var json_val = jQuery(".generate_chkplan_day_json").val();
                var loop_variations = jQuery.parseJSON(json_val);

                var html_one = '';
                html_one += '<div class="swatch-container div_pactype_container">';

                jQuery.each( loop_variations, function( key_one, value_one ) {
                    if(primary_count == 0) {
                        primary_val = key_one;

                        // console.log( "selected: " + key_one );
                    }

                    html_one += '<span class="div_pactype_item swatch';

                    if(primary_count == 0) {
                        //temporary stop it to test...
                        // html_one += ' selected"';
                        html_one += '"';
                    }
                    else {
                        //temporary stop it to test...
                        html_one += '"';
                    }
                    
                    if(key_one > 1) {
                        $show_day_word = ' Days';
                    }
                    else {
                        $show_day_word = ' Day';
                    }

                    html_one += ' datavalue="'+key_one+'">' + key_one + $show_day_word + '</span>';

                    // console.log( key_one );

                    primary_count++;
                });

                html_one += '</div>';
                jQuery(".div_pactype").html(html_one);

                // primary_val = "7";
                var arr_unlimited_items = [];
                var arr_fixed_items = [];

                <?php /*
                var html_three = '';
                html_three += '<div class="swatch-container div_dataplansel_container">';

                jQuery.each( loop_variations, function( key_one, value_one ) {
                    // console.log( key_one );

                    jQuery.each( value_one, function( key_two, value_two ) {
                        var compare_base = parseInt(primary_val);
                        var compare_loop = parseInt(key_one);

                        // var unlimited_list = '';
                        // var fixed_list = '';

                        if(compare_base <= compare_loop) {
                            // console.log( compare_base + " - " + compare_loop );
                            // console.log( key_two );

                            jQuery.each( value_two, function( key_three, value_three ) {
                                // console.log( key_three );
                                // console.log( value_four );

                                var quote_selected = "";
                                var packid_selected = "";
                                var output_selected = "";
                                var days_selected = "";
                                var type_selected = "";
                                var selection_text = "";

                                jQuery.each( value_three, function( key_four, value_four ) {
                                    // console.log( key_four + ": " + value_four );

                                    if(key_four == "pro_id") {
                                        packid_selected = value_four;
                                    }

                                    if(key_four == "output") {
                                        output_selected = value_four;
                                    }

                                    if(key_four == "quote") {
                                        quote_selected = value_four;
                                    }

                                    if(key_four == "period") {
                                        days_selected = value_four;
                                    }

                                    if(key_four == "type") {
                                        type_selected = value_four;

                                        if(value_four == "Unlimited") {
                                            // "1GB Daily Unlimited";
                                            selection_text = quote_selected + " Daily " + value_four;
                                        }
                                        else {
                                            // "5GB, up to 10 Days";
                                            selection_text = quote_selected + " for " + days_selected;
                                        }
                                    }
                                });

                                if(compare_base <= compare_loop) {
                                    if(type_selected == "Unlimited") {
                                        if(compare_base == compare_loop) {
                                            // unlimited_list += '<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>';

                                            arr_unlimited_items.push('<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>');
                                        }
                                    }
                                    else if(type_selected == "Fixed") {
                                        if(compare_base <= compare_loop) {
                                            // fixed_list += '<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>';

                                            arr_fixed_items.push('<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>');
                                        }
                                    }
                                }
                            });

                            // html_three += unlimited_list;
                            // html_three += fixed_list;
                        }
                    });
                });

                // console.log(arr_unlimited_items);
                // console.log(arr_fixed_items);

                if(arr_unlimited_items.length > 0) {
                    html_three += arr_unlimited_items.join('');
                    html_three += '<div style="clear:both;width:100%;"></div>';
                }
                
                html_three += arr_fixed_items.join('');

                html_three += '</div>';
                jQuery(".div_dataplansel").html(html_three);
                */ ?>

                jQuery(".div_days").html("");

                product_days_variations()

                jQuery(".span_pactype").show();
                // jQuery(".span_days").show();
                // jQuery(".span_dataplansel").show();

                //active destination and esim plan
                jQuery("#destid").addClass('has-value');
                jQuery(".esim_plans_btn").addClass('has-value');

                <?php
                if(!empty($param_pda)) {
                    ?>
                    //temporary stop it to test...
                    jQuery('.div_pactype_item[datavalue="<?php echo $param_pda; ?>"]').trigger('click');
                    <?php
                }

                if(!empty($param_pdp)) {
                    ?>
                    //temporary stop it to test...
                    jQuery('.div_dataplansel_item[datavalue="<?php echo $param_pdp; ?>"]').trigger('click');
                    <?php
                }
                ?>
            });
        </script>
        <?php
    }
    ?>
    
    <?php
    // $html_plans['json'];
    // $html_plans['day_json'];
    ?>
    <input type="hidden" value="" class="generate_chkplan_json"/>
    <input type="hidden" value="" class="generate_chkplan_day_json"/>

    <style>
        .esim_plans_area_hide {
            display:none;
        }

        .esim_plans_area {
            width:100%;
            text-align:left;
            border-width: 1px;
            border-style: solid;
            border-color: #f8dbbd;
            border-radius: 4px;
            cursor: default;
            padding:13px 20px 10px 20px;
            background:#fff;
            margin-top:-15px;
            margin-bottom: 20px;

            /* Alternative animation without max-height */
            opacity: 0;
            transform: scaleY(0) translateY(-20px);
            transform-origin: top;
            transition: transform 0.3s ease-out,
                        opacity 0.3s ease-out,
                        margin-top 0.3s ease-out;
            margin-top: 0;
            height: auto;
        }

        /* Active state - showing */
        .esim_plans_area.active {
            opacity: 1;
            transform: scaleY(1) translateY(0);
            margin-top: -15px;
        }
    </style>

    <div class="esim_plans_area esim_plans_area_hide">
        <div class="tpflbl" style="font-weight:bold;color:#4a86e8;margin-bottom:10px;margin-top:5px;">Select eSIM Data Plan</div>
        
        <div class="tpfdiv span_pactype">
            <div class="tpflbl_sub" style="">Days Required:</div>
            <div class="tpfinput div_pactype">
                <?php
                // <div class="swatch-container div_pactype_container">
                //     <span class="div_pactype_item swatch selected" data-value="red">Fixed Data</span>
                //     <span class="div_pactype_item swatch" data-value="blue">Unlimited Data</span>
                // </div>
                ?>
            </div>
        </div>

        <div class="tpfdiv span_days">
            <div class="tpflbl_sub">Days Required:</div>
            <div class="tpfinput div_days">
                <?php
                // <div class="swatch-container div_days_container">
                //     <span class="div_days_item swatch selected" data-value="red">7 Days</span>
                //     <span class="div_days_item swatch" data-value="blue">8 Days</span>
                //     <span class="div_days_item swatch" data-value="green">9 Days</span>
                // </div>
                ?>
            </div>
        </div>

        <div class="tpfdiv span_dataplansel">
            <div class="tpflbl_sub" style="">Data Plan:</div>
            <div class="tpfinput div_dataplansel">
                <?php
                // <div class="swatch-container div_dataplansel_container">
                //     <span class="div_dataplansel_item swatch selected" data-value="red">1GB</span>
                //     <span class="div_dataplansel_item swatch" data-value="green">2GB</span>
                //     <span class="div_dataplansel_item swatch" data-value="blue">500MB</span>
                // </div>
                ?>
            </div>
            <input type="hidden" class="ipt_dataplan" name="val_dataplan" value=""/>
            <div class="price_dataplan"></div>
        </div>
    </div>

    <div class="tpfdiv span_first_ttl_cost card_opt_display">
        <div class="tpflbl" style="font-weight:bold;color:#4a86e8;color:">
            Total Cost: <span class="span_first_ttl_cost_text"></span>
        </div>
    </div>

    <style>
        .span_pactype, .span_days, .span_dataplansel {
            display:none;
        }
        
        .swatch-container {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            gap: 10px 5px;
        }
        .swatch {
            border-width: 1px;
            border-style: solid;
            border-color: #f8dbbd;
            border-radius: 4px;
            cursor: pointer;
            padding:7px 10px;
        }
        .swatch.selected {
            background: #f8dbbd;
        }
        .txtstyle {
            border: 1px solid #f8dbbd !important;
            border-radius: 4px !important;
            background:#fff !important;
            padding:10px 18px !important;
        }
        .selectstyle {
            border: 1px solid #f8dbbd !important;
            border-radius: 4px !important;
            background:#fff !important;
            padding:15px 18px !important;
        }
        .finalprice {
            font-weight:bold;
            color:#4a86e8;
        }
        .shareable_link {
            background:#f4f4f4;
            border:1px solid #f1f1f1;
            padding:6px 10px;
            font-size:14px;
            border-radius:50px;
            cursor: pointer;
        }
        .shareable_link_msg {
            background:#f4f4f4;
            border:1px solid #f1f1f1;
            padding:6px 10px;
            font-size:14px;
            border-radius:50px;
            margin-left:10px;
        }
        .shareable_link_msg_hide {
            display:none;
        }
    </style>
    
    <?php
    $chk_plan_nonce = wp_create_nonce( 'check_plan_nonce' );
    ?>
    <input type="hidden" class="chkplannonce" value="<?php echo $chk_plan_nonce; ?>"/>
    <?php
    /*
    <div class="tpfdiv span_dataplan">
        <div class="tpflbl lbl_dataplan">Select Data Plans <img class="loadgif load_dataplan" src="<?php echo $loading_gif; ?>"/></div>
        <div class="tpfinput div_dataplan">
            <select class="ipt_dataplan input-text" name="val_dataplan">
            </select>
            <div class="price_dataplan"></div>
        </div>
    </div>
    */
    ?>
    <?php
    $chk_pricing_nonce = wp_create_nonce( 'check_price_nonce' );
    ?>
    <input type="hidden" class="chkpricenonce" value="<?php echo $chk_pricing_nonce; ?>"/>

    <style>
        .infonextlink {
            /*border-width: 1px;
            border-style: solid;
            border-color: #f8dbbd;
            border-radius: 4px;
            cursor: pointer;
            padding:7px 10px;
            background: #f8dbbd;*/
        }
        .swatch_infosec_extra {
            align-items: center;
            height: auto;
            padding: 30px 0px 25px 0px;
        }
        .swatch_infosec_left {
            width: calc(65% - 5px); /* Use calc to account for the gap */
        }
        .swatch_infosec_right {
            width: calc(35% - 5px); /* Use calc to account for the gap */
            margin-left:5px;
            text-align: right;
        }
        .swatch_esim_left {
            width: calc(50% - 5px); /* Use calc to account for the gap */
            color:red !important;
        }
        .swatch_esim_right {
            width: calc(50% - 5px); /* Use calc to account for the gap */
            margin-left:5px;
        }
        .swatch_esim {
            text-align:left;
            border-width: 1px;
            border-style: solid;
            border-color: #f8dbbd;
            border-radius: 4px;
            cursor: default;
            padding:13px 20px 10px 20px;
            background:#fff;
            color:#666666;
            font-weight: 400;
            font-size: 1rem;
            line-height: 1.2em;
            text-transform: none;
            letter-spacing: 0px;
            /* color: #666666 !important; */
            color: #c9c9c9 !important;
        }
        .swatch_esim:hover, .swatch_esim:active, .swatch_esim:focus {
            border-width: 1px;
            border-style: solid;
            border-color: #f8dbbd;
            border-radius: 4px;
            cursor: default;
            padding:13px 20px 10px 20px;
            background:#fff;
            color:#666666;
            font-weight: 400;
            font-size: 1rem;
            line-height: 1.2em;
            text-transform: none;
            letter-spacing: 0px;
        }
        .swatch_esim.has-value {
            color: #666666 !important; /* Color when option is selected */
        }
        .swatch_esim_selected, .swatch_esim_selected:hover, .swatch_esim_selected:active, .swatch_esim_selected:focus {
            background: #f8dbbd;
        }

        @media (max-width: 544px) {
            /*body, button, input, select, textarea, .ast-button, .ast-custom-button {
                font-size: 16px;
                font-size: 0.84210526315789rem;
            }*/

            .swatch_esim {
                font-size: 0.84210526315789rem;
            }
            .swatch_esim:hover, .swatch_esim:active, .swatch_esim:focus {
                font-size: 0.84210526315789rem;
            }
            .swatch_esim.has-value {
                font-size: 0.84210526315789rem;
            }
            .swatch_esim_selected, .swatch_esim_selected:hover, .swatch_esim_selected:active, .swatch_esim_selected:focus {
                font-size: 0.84210526315789rem;
            }

            .swatch_infosec_left {
                width: calc(55% - 5px); /* Use calc to account for the gap */
            }
            .swatch_infosec_right {
                width: calc(45% - 5px); /* Use calc to account for the gap */
            }
        }
    </style>


    <div class="span_topup_msg"></div>
    <div class="tpfdiv">
        <div class="tpflbl" style="font-weight:bold;color:#4a86e8;">eSIM Option</div>
        <div class="div_opts">
            <div class="swatch-container" style="display:none;">
                <button class="swatch_esim swatch_esim_left new_esim_option">
                    New eSIM
                    <?php
                    if(!empty($new_esim_price)) {
                       echo ' (+SGD' . $new_esim_price . ')';
                    }
                    ?>
                </button>
                <button class="swatch_esim swatch_esim_right existing_esim_option">Top-up Existing eSIM</button>
            </div>
            <div class="new_esim_option_msg card_opt_display" style="margin-top:10px;">eSIM will be emailed to you.</div>

            <div class="default_radio_section card_opt_display">
                <div style="float:left;margin-right:20px;" class="div_chkbox_exist">
                    <input style="float:left;width:16px;margin-top:7px;margin-right:4px;" type="radio" id="chkbox_id_exist" class="chkbox_opts" name="chkbox_vals" value="existing_card"/>
                    <label for="chkbox_id_exist" style="float:left;">
                        Existing eSIM
                    </label>
                </div>
                
                <div style="float:left;" class="div_chkbox_new">
                    <input style="float:left;width:16px;margin-top:7px;margin-right:4px;" type="radio" id="chkbox_id_new" class="chkbox_opts" name="chkbox_vals" value="new_card"/>
                    <label for="chkbox_id_new"  style="float:left;">
                        New eSIM
                        <?php
                        if(!empty($new_esim_price)) {
                            echo ' (+SGD' . $new_esim_price . ')';
                        }
                        ?>
                    </label>
                </div>

                <div style="float:left;margin-left:20px;" class="div_chkbox_convert_new card_text_hide1">
                    <input style="float:left;width:16px;margin-top:7px;margin-right:4px;" type="radio" id="chkbox_id_convert_new" class="chkbox_opts" name="chkbox_vals" value="existing_card"/>
                    <label for="chkbox_id_convert_new"  style="float:left;">
                        New eSIM (Free)
                    </label>
                </div>
            </div>
            
            <input type="hidden" class="new_esim_unit_price" value="<?php echo $new_esim_price; ?>"/>
            <input type="hidden" class="esim_package_unit_price" value=""/>
            <input type="hidden" class="esim_package_num_price" value=""/>
        </div>
        <div style="clear:both;"></div>
    </div>
    <div class="tpfdiv span_esim card_opt_display">
        <div class="tpflbl lbl_esim">
            <span class="esim_main_lbl" style="margin-right:10px;font-weight:bold;color:#4a86e8;">Enter eSIM ICCID</span>
            <span class="esim_secd_lbl card_opt_display" style="margin-right:10px;font-weight:bold;color:#4a86e8;">New eSIM ICCID Will Be Emailed To You After Payment</span> <?php /*<img class="loadgif load_esim" src="<?php echo $loading_gif; ?>"/>*/ ?>
        </div>
        <div class="div_esim">
            <input type="text" class="ipt_esim input-text txtstyle" name="val_esim" value=""/><br/>
            <a href="#model_esim" class="highlinelink" rel="modal:open">Where to get your eSIM ICCID</a>
        </div>
    </div>
    <div class="tpfdiv span_vouchercode">
        <div class="tpflbl lbl_vouchercode" style="font-weight:bold;color:#4a86e8;">Enter Voucher Code (If you have one)</div>
        <div class="div_vouchercode">
            <input type="text" class="ipt_vouchercode input-text txtstyle" name="val_vouchercode" value="<?php if(!empty($param_pvc)) { echo $param_pvc; } ?>"/>
            <input type="hidden" class="res_vou_num input-text" name="res_vou_num" value=""/>
            <input type="hidden" class="res_vou_status input-text" name="res_vou_status" value=""/>
            <input type="hidden" class="res_vou_type input-text" name="res_vou_type" value=""/>
            <input type="hidden" class="res_vou_val input-text" name="res_vou_val" value=""/>
        </div>
    </div>
    <div id="model_esim" class="modal">
        <p>
            <h4>How to check eSIM ICCID</h4>
            (8985234202xxxxxxxxxx)<br/><br/>
            <b>iPhone:</b><br/>
            <ol>
                <li>Go to Settings > Mobile Data or Cellular Data > eSIM > Turn ON</li>
                <li>Go to Settings > General > About</li>
                <li>Scroll down until you see eSIM ICCID</li>
                <li>Turn OFF eSIM</li>
            </ol>
            <b>Android Phones:</b><br/>
            <ol>
                <li>Go to Phone Settings page where it shows all SIM cards</li>
                <li>Open eSIM information</li>
            </ol>
        </p>
    </div>

    <div class="tpfdiv span_shareable">
        <div class="tpflbl lbl_shareable">
            <span class="shareable_main_lbl shareable_link">Click to copy & share your product selection link</span>
            <span class="shareable_link_msg shareable_link_msg_hide">URL Copied</span>
        </div>
    </div>

    <?php
    $chk_esim_nonce = wp_create_nonce( 'check_esim_nonce' );
    ?>
    <input type="hidden" class="chkesimnonce" value="<?php echo $chk_esim_nonce; ?>"/>
    <button type="button" name="val_chk_esim" class="btn_esim chk_esim button alt" style="font-family: Montserrat;">Next</button>

    <img class="loadgif load_esim" src="<?php echo $loading_gif; ?>"/>

    <input type="hidden" name="ipt_esim_convert" class="ipt_esim_convert" value=""/>
    <input type="hidden" name="ipt_agree_convert" class="ipt_agree_convert" value=""/>

    <input type="hidden" class="ipt_region_fail" value="0"/>
    <input type="hidden" class="ipt_destination_fail" value="0"/>

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

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

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

    <?php
    /*
    <div class="tpfdiv span_region">
        <div class="tpflbl lbl_region">Select Region <img class="loadgif load_region" src="<?php echo $loading_gif; ?>"/></div>
        <div class="tpfinput div_region">
            <select class="ipt_region input-text" name="val_region">
            </select>
        </div>
    </div>
    <?php
    $chk_dest_nonce = wp_create_nonce( 'check_dest_nonce' );
    ?>
    <input type="hidden" class="chkdestnonce" value="<?php echo $chk_dest_nonce; ?>"/>
    <div class="tpfdiv span_destination">
        <div class="tpflbl lbl_destination">Select Destination <img class="loadgif load_destination" src="<?php echo $loading_gif; ?>"/></div>
        <div class="tpfinput div_destination">
            <select class="ipt_destination input-text" name="val_destination">
            </select><br/>
            <a href="#model_destination" class="destmodellink highlinelink" rel="modal:open">Click here to see covered countries</a>
        </div>
    </div>
    <div id="model_destination" class="modal">
        <p class="modeldestcontent"></p>
    </div>
    <?php
    $chk_plan_nonce = wp_create_nonce( 'check_plan_nonce' );
    ?>
    <input type="hidden" class="chkplannonce" value="<?php echo $chk_plan_nonce; ?>"/>
    <div class="tpfdiv span_dataplan">
        <div class="tpflbl lbl_dataplan">Select Data Plans <img class="loadgif load_dataplan" src="<?php echo $loading_gif; ?>"/></div>
        <div class="tpfinput div_dataplan">
            <select class="ipt_dataplan input-text" name="val_dataplan">
            </select>
            <div class="price_dataplan"></div>
        </div>
    </div>
    <?php
    $chk_pricing_nonce = wp_create_nonce( 'check_price_nonce' );
    ?>
    <input type="hidden" class="chkpricenonce" value="<?php echo $chk_pricing_nonce; ?>"/>
    */
    ?>

    <div class="tpfdiv span_chkemail">
        <div class="tpflbl lbl_chkemail" style="font-weight:bold;color:#4a86e8;">Enter email</div>
        <div class="tpfinput div_chkemail">
            <input type="text" class="ipt_chkemail input-text txtstyle" name="val_chkemail" value=""/>
        </div>
    </div>

    <?php
    $form_nonce = wp_create_nonce( 'check_form_nonce' );
    ?>
    <input type="hidden" name="formnonce" class="formnonce" value="<?php echo $form_nonce; ?>"/>

    <?php
    $form_cf_nonce = wp_create_nonce( 'purge_cache' );
    ?>
    <input type="hidden" class="form_cf_nonce" value="<?php echo $form_cf_nonce; ?>"/>

    <input type="hidden" class="" name="submission" value="complete_order"/>
    <input type="hidden" name="proid" class="filterproid" value=""/>
    <button type="button" name="val_paystripe" class="btn_paystripe button alt" style="font-family: Montserrat;">Make Payment</button>
    <img class="loadgif load_paystripe" src="<?php echo $loading_gif; ?>"/>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css" />
<script>
    function agreement_btns() {
        jQuery(".val_chk_agr_accept").click(function(e) {
            e.preventDefault();

            /////
            jQuery('#chkbox_id_exist').prop('checked', false); //uncheck checkbox
            jQuery('#chkbox_id_convert_new').prop('checked', true); //check checkbox

            // reset the esim option selection
            jQuery(".new_esim_option").removeClass("swatch_esim_selected");
            jQuery(".existing_esim_option").removeClass("swatch_esim_selected");

            // esim option - new esim selected and change text
            jQuery(".new_esim_option").addClass("swatch_esim_selected");
            jQuery(".new_esim_option").text("New eSIM (Free)");

            jQuery(".new_esim_option_msg").removeClass("card_opt_display");

            jQuery(".esim_main_lbl").addClass("card_opt_display");
            jQuery(".esim_secd_lbl").addClass("card_opt_display");
            jQuery(".ipt_esim").addClass("card_opt_display");
            jQuery(".span_esim").addClass("card_opt_display");
            
            // jQuery(".new_esim_option").text("");
            /////

            // jQuery(".div_chkbox_new").addClass("card_text_hide");
            // jQuery(".div_chkbox_convert_new").removeClass("card_text_hide");

            // jQuery(".div_chkbox_new").addClass("card_text_hide");
            // jQuery(".div_chkbox_convert_new").removedClass("card_text_hide");

            // jQuery(".esim_main_lbl").addClass("card_opt_display");
            // jQuery(".esim_secd_lbl").removeClass("card_opt_display");

            jQuery(".ipt_esim").val("Install new eSIM to use mobile data");
            jQuery(".ipt_esim").attr("readonly", "readonly");

            jQuery(".ipt_agree_convert").val("Accepted");

            jQuery(".span_agreementmsg").html("");
            jQuery(".span_agreementmsg").hide();

            jQuery(".btn_paystripe").show();
            jQuery(".span_chkemail").show();
        });

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

            // jQuery(".newcard_default_text").removeClass("card_text_hide");
            // jQuery(".newcard_free_text").addClass("card_text_hide");

            jQuery(".ipt_agree_convert").val("Declined");

            jQuery(".span_agreementmsg").html("");
            jQuery(".span_agreementmsg").hide();

            jQuery(".btn_paystripe").hide();
            jQuery(".span_chkemail").hide();

            alert("Please provide another eSIM ICCID. Thank you.");
        });
    }

    /*
    // original clicks
    function product_variations() {
        jQuery(".div_pactype_item").click(function() {
            jQuery(".price_dataplan").html("");
            jQuery(".ipt_dataplan").val("");

            jQuery(".btn_paystripe").hide();
            jQuery(".span_chkemail").hide();
            jQuery(".span_showttl").html("");

            var primary_count = 0;
            var second_count = 0;
            var primary_val = jQuery(this).attr("datavalue");
            var second_val = '';

            var json_val = jQuery(".generate_chkplan_json").val();
            var loop_variations = jQuery.parseJSON(json_val);

            var html_one = '';
            html_one += '<div class="swatch-container div_pactype_container">';

            jQuery.each( loop_variations, function( key_one, value_one ) {
                html_one += '<span class="div_pactype_item swatch';

                if(primary_val == key_one) {
                    html_one += ' selected"';
                }
                else {
                    html_one += '"';
                }
                
                html_one += ' datavalue="'+key_one+'">' + key_one + ' Data</span>';

                // console.log( key_one );
            });

            html_one += '</div>';
            jQuery(".div_pactype").html(html_one);

            var html_two = '';
            html_two += '<div class="swatch-container div_days_container">';

            jQuery.each( loop_variations, function( key_one, value_one ) {
                if(key_one == primary_val) {
                    jQuery.each( value_one, function( key_two, value_two ) {
                        if(second_count == 0) {
                            second_val = key_two;

                            // console.log( "selected: " + key_two );
                        }

                        html_two += '<span class="div_days_item swatch';

                        if(second_count == 0) {
                            html_two += ' selected"';
                        }
                        else {
                            html_two += '"';
                        }
                        
                        html_two += ' datavalue="'+key_two+'">' + key_two + '</span>';
                        
                        // console.log( key_two );

                        second_count++;
                    });
                }
            });
            
            html_two += '</div>';
            jQuery(".div_days").html(html_two);

            var html_three = '';
            html_three += '<div class="swatch-container div_dataplansel_container">';

            jQuery.each( loop_variations, function( key_one, value_one ) {
                jQuery.each( value_one, function( key_two, value_two ) {
                    if(key_one == primary_val && key_two == second_val) {
                        // console.log( key_one );
                        // console.log( key_two );

                        jQuery.each( value_two, function( key_three, value_three ) {
                            // console.log( key_three );

                            var quote_selected = "";
                            var packid_selected = "";
                            var output_selected = "";

                            jQuery.each( value_three, function( key_four, value_four ) {
                                // console.log( key_four + ": " + value_four );

                                if(key_four == "pro_id") {
                                    packid_selected = value_four;
                                }

                                if(key_four == "output") {
                                    output_selected = value_four;
                                }

                                if(key_four == "quote") {
                                    quote_selected = value_four;
                                }
                            });

                            html_three += '<span class="div_dataplansel_item swatch" dataid="' + quote_selected + '" datavalue="'+packid_selected+'">' + quote_selected + '</span>';
                        });
                    }
                });
            });

            html_three += '</div>';
            jQuery(".div_dataplansel").html(html_three);

            product_variations();
        });

        jQuery(".div_days_item").click(function() {
            jQuery(".price_dataplan").html("");
            jQuery(".ipt_dataplan").val("");

            jQuery(".btn_paystripe").hide();
            jQuery(".span_chkemail").hide();
            jQuery(".span_showttl").html("");

            var primary_count = 0;
            var second_count = 0;
            var primary_val = '';
            var second_val = '';

            var json_val = jQuery(".generate_chkplan_json").val();
            var loop_variations = jQuery.parseJSON(json_val);
            
            jQuery(".div_pactype_item").each(function() {
                if(jQuery(this).hasClass("selected")) {
                    primary_val = jQuery(this).attr("datavalue");
                }
            });

            second_val = jQuery(this).attr("datavalue");

            var html_three = '';
            html_three += '<div class="swatch-container div_dataplansel_container">';

            jQuery.each( loop_variations, function( key_one, value_one ) {
                jQuery.each( value_one, function( key_two, value_two ) {
                    if(key_one == primary_val && key_two == second_val) {
                        // console.log( key_one );
                        // console.log( key_two );

                        jQuery.each( value_two, function( key_three, value_three ) {
                            // console.log( key_three );

                            var quote_selected = "";
                            var packid_selected = "";
                            var output_selected = "";

                            jQuery.each( value_three, function( key_four, value_four ) {
                                // console.log( key_four + ": " + value_four );

                                if(key_four == "pro_id") {
                                    packid_selected = value_four;
                                }

                                if(key_four == "output") {
                                    output_selected = value_four;
                                }

                                if(key_four == "quote") {
                                    quote_selected = value_four;
                                }
                            });

                            html_three += '<span class="div_dataplansel_item swatch" dataid="' + quote_selected + '" datavalue="'+packid_selected+'">' + quote_selected + '</span>';
                        });
                    }
                });
            });

            html_three += '</div>';
            jQuery(".div_dataplansel").html(html_three);

            jQuery(".div_days_item").each(function() {
                if(second_val == jQuery(this).attr("datavalue")) {
                    jQuery(this).addClass("selected");
                }
                else {
                    jQuery(this).removeClass("selected");
                }
            });

            product_variations();
        });

        jQuery(".div_dataplansel_item").click(function() {
            jQuery(".btn_paystripe").hide();
            jQuery(".span_chkemail").hide();
            jQuery(".span_showttl").html("");

            var primary_val = '';
            var second_val = '';
            var third_val = jQuery(this).attr("dataid");
            var third_pacid_val = jQuery(this).attr("datavalue");
            
            jQuery(".div_pactype_item").each(function() {
                if(jQuery(this).hasClass("selected")) {
                    primary_val = jQuery(this).attr("datavalue");
                }
            });

            jQuery(".div_days_item").each(function() {
                if(jQuery(this).hasClass("selected")) {
                    second_val = jQuery(this).attr("datavalue");
                }
            });

            jQuery(".div_dataplansel_item").each(function() {
                if(third_val == jQuery(this).attr("dataid")) {
                    jQuery(this).addClass("selected");
                }
                else {
                    jQuery(this).removeClass("selected");
                }
            });

            var json_val = jQuery(".generate_chkplan_json").val();
            var loop_variations = jQuery.parseJSON(json_val);

            jQuery.each( loop_variations, function( key_one, value_one ) {
                jQuery.each( value_one, function( key_two, value_two ) {
                    if(key_one == primary_val && key_two == second_val) {
                        jQuery.each( value_two, function( key_three, value_three ) {
                            var quote_selected = "";
                            var packid_selected = "";
                            var output_selected = "";
                            
                            jQuery.each( value_three, function( key_four, value_four ) {
                                // console.log( key_four + ": " + value_four );

                                if(key_four == "pro_id") {
                                    packid_selected = value_four;
                                }

                                if(key_four == "output") {
                                    output_selected = value_four;
                                }

                                if(key_four == "quote") {
                                    quote_selected = value_four;
                                }
                            });

                            if(third_val == quote_selected) {
                                jQuery(".ipt_dataplan").val(third_pacid_val);
                                jQuery(".price_dataplan").html(output_selected);
                            }
                        });
                    }
                });
            });
        });
    }
    */

    function product_days_variations() {
        jQuery(".div_pactype_item").click(function() {
            jQuery(".price_dataplan").html("");
            jQuery(".ipt_dataplan").val("");

            jQuery(".btn_paystripe").hide();
            jQuery(".span_chkemail").hide();
            jQuery(".span_showttl").html("");

            //reset radio option////
            jQuery(".esim_plans_btn").text("Select eSIM Data Plan");

            jQuery(".new_esim_option_msg").addClass("card_opt_display");
            jQuery(".span_esim").addClass("card_opt_display");
            jQuery(".new_esim_option").removeClass("swatch_esim_selected");
            jQuery(".existing_esim_option").removeClass("swatch_esim_selected");

            /////
            ////grey selection
            jQuery(".new_esim_option").removeClass('has-value');
            jQuery(".existing_esim_option").removeClass('has-value');


            jQuery('#chkbox_id_new').prop('checked', false); //check checkbox
            jQuery('#chkbox_id_exist').prop('checked', false); //uncheck checkbox
            jQuery('#chkbox_id_convert_new').prop('checked', false); //check checkbox

            // reset new esim button text
            var button_text = jQuery(".new_esim_option").text().toLowerCase();
            var has_free = button_text.includes("free");
            
            if(has_free) {
                // reset new esim button
                var raw_price_new_esim = jQuery(".new_esim_unit_price").val();
                var new_btn_text = "New eSIM (+SGD" + raw_price_new_esim + ")";

                jQuery(".new_esim_option").text(new_btn_text);
            }
            /////

            // cal total reset
            jQuery(".span_first_ttl_cost").addClass("card_opt_display");
            jQuery(".esim_package_unit_price").val("");
            jQuery(".esim_package_num_price").val("");

            // jQuery('#chkbox_id_convert_new').prop('checked', false); //uncheck checkbox
            // jQuery('#chkbox_id_exist').prop('checked', true); //check checkbox

            // jQuery(".div_chkbox_new").removeClass("card_text_hide");
            // jQuery(".div_chkbox_convert_new").addClass("card_text_hide");

            jQuery(".esim_main_lbl").removeClass("card_opt_display");
            jQuery(".esim_secd_lbl").addClass("card_opt_display");
            jQuery(".ipt_esim").val("");
            jQuery(".ipt_esim").removeAttr("readonly");
            ///////

            var primary_count = 0;
            var second_count = 0;
            var primary_val = jQuery.trim(jQuery(this).attr("datavalue"));
            var second_val = '';

            // alert(primary_val);

            var json_val = jQuery(".generate_chkplan_day_json").val();
            var loop_variations = jQuery.parseJSON(json_val);

            var html_one = '';
            html_one += '<div class="swatch-container div_pactype_container">';

            jQuery.each( loop_variations, function( key_one, value_one ) {
                html_one += '<span class="div_pactype_item swatch';

                if(primary_val == key_one) {
                    html_one += ' selected"';
                }
                else {
                    html_one += '"';
                }
                
                if(key_one > 1) {
                    $show_day_word = ' Days';
                }
                else {
                    $show_day_word = ' Day';
                }

                html_one += ' datavalue="'+key_one+'">' + key_one + $show_day_word + '</span>';

                // console.log( key_one );

                primary_count++;
            });

            html_one += '</div>';
            jQuery(".div_pactype").html(html_one);

            // primary_val = "7";
            var arr_unlimited_items = [];
            var arr_fixed_items = [];

            var html_three = '';
            html_three += '<div class="swatch-container div_dataplansel_container">';

            jQuery.each( loop_variations, function( key_one, value_one ) {
                // console.log( key_one );

                jQuery.each( value_one, function( key_two, value_two ) {
                    var compare_base = parseInt(primary_val);
                    var compare_loop = parseInt(key_one);

                    // var unlimited_list = '';
                    // var fixed_list = '';

                    if(compare_base <= compare_loop) {
                        // console.log( compare_base + " - " + compare_loop );
                        // console.log( key_two );

                        jQuery.each( value_two, function( key_three, value_three ) {
                            // console.log( key_three );
                            // console.log( value_four );

                            var quote_selected = "";
                            var packid_selected = "";
                            var output_selected = "";
                            var days_selected = "";
                            var type_selected = "";
                            var selection_text = "";

                            jQuery.each( value_three, function( key_four, value_four ) {
                                // console.log( key_four + ": " + value_four );

                                if(key_four == "pro_id") {
                                    packid_selected = value_four;
                                }

                                if(key_four == "output") {
                                    output_selected = value_four;
                                }

                                if(key_four == "quote") {
                                    quote_selected = value_four;
                                }

                                if(key_four == "period") {
                                    days_selected = value_four;
                                }

                                if(key_four == "type") {
                                    type_selected = value_four;

                                    if(value_four == "Unlimited") {
                                        // "1GB Daily Unlimited";
                                        selection_text = quote_selected + " Daily " + value_four;
                                    }
                                    else {
                                        // "5GB, up to 10 Days";
                                        selection_text = quote_selected + " for " + days_selected;
                                    }
                                }
                            });

                            if(compare_base <= compare_loop) {
                                if(type_selected == "Unlimited") {
                                    if(compare_base == compare_loop) {
                                        // unlimited_list += '<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>';

                                        arr_unlimited_items.push('<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>');
                                    }
                                }
                                else if(type_selected == "Fixed") {
                                    if(compare_base <= compare_loop) {
                                        // fixed_list += '<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>';

                                        arr_fixed_items.push('<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>');
                                    }
                                }
                            }
                        });

                        // html_three += unlimited_list;
                        // html_three += fixed_list;
                    }
                });
            });

            // console.log(arr_unlimited_items);
            // console.log(arr_fixed_items);

            if(arr_unlimited_items.length > 0) {
                html_three += arr_unlimited_items.join('');
                html_three += '<div style="clear:both;width:100%;"></div>';
            }
            
            html_three += arr_fixed_items.join('');

            html_three += '</div>';
            jQuery(".div_dataplansel").html(html_three);

            jQuery(".div_days").html("");

            jQuery(".span_pactype").show();
            // jQuery(".span_days").show();
            jQuery(".span_dataplansel").show();

            product_days_variations();
        });

        jQuery(".div_dataplansel_item").click(function() {
            jQuery(".btn_paystripe").hide();
            jQuery(".span_chkemail").hide();
            jQuery(".span_showttl").html("");

            //reset radio option////
            /////
            //un-grey selection
            jQuery(".new_esim_option").addClass('has-value');
            jQuery(".existing_esim_option").addClass('has-value');

            jQuery(".new_esim_option_msg").addClass("card_opt_display");
            jQuery(".span_esim").addClass("card_opt_display");
            jQuery(".new_esim_option").removeClass("swatch_esim_selected");
            jQuery(".existing_esim_option").removeClass("swatch_esim_selected");

            jQuery('#chkbox_id_new').prop('checked', false); //check checkbox
            jQuery('#chkbox_id_exist').prop('checked', false); //uncheck checkbox
            jQuery('#chkbox_id_convert_new').prop('checked', false); //check checkbox

            // reset new esim button text
            var button_text = jQuery(".new_esim_option").text().toLowerCase();
            var has_free = button_text.includes("free");
            
            if(has_free) {
                // reset new esim button
                var raw_price_new_esim = jQuery(".new_esim_unit_price").val();
                var new_btn_text = "New eSIM (+SGD" + raw_price_new_esim + ")";

                jQuery(".new_esim_option").text(new_btn_text);
            }
            
            // cal total cost
            jQuery(".span_first_ttl_cost").removeClass("card_opt_display");

            /////
            // jQuery('#chkbox_id_convert_new').prop('checked', false); //uncheck checkbox
            // jQuery('#chkbox_id_exist').prop('checked', true); //check checkbox

            // jQuery(".div_chkbox_new").removeClass("card_text_hide");
            // jQuery(".div_chkbox_convert_new").addClass("card_text_hide");

            jQuery(".esim_main_lbl").removeClass("card_opt_display");
            jQuery(".esim_secd_lbl").addClass("card_opt_display");
            jQuery(".ipt_esim").val("");
            jQuery(".ipt_esim").removeAttr("readonly");
            ///////

            var primary_val = '';
            // var second_val = '';
            var third_val = jQuery(this).attr("dataid");
            var third_pacid_val = jQuery(this).attr("datavalue");
            
            // jQuery(".div_pactype_item").each(function() {
            //     if(jQuery(this).hasClass("selected")) {
            //         primary_val = jQuery(this).attr("datavalue");
            //     }
            // });

            // jQuery(".div_days_item").each(function() {
            //     if(jQuery(this).hasClass("selected")) {
            //         second_val = jQuery(this).attr("datavalue");
            //     }
            // });

            jQuery(".div_dataplansel_item").each(function() {
                if(third_pacid_val == jQuery(this).attr("datavalue")) {
                    jQuery(this).addClass("selected");
                }
                else {
                    jQuery(this).removeClass("selected");
                }
            });

            var json_val = jQuery(".generate_chkplan_day_json").val();
            var loop_variations = jQuery.parseJSON(json_val);

            // console.log(third_val);
            // console.log(third_pacid_val);
            // console.log(json_val);

            var arr_unlimited_items = [];
            var arr_fixed_items = [];

            var html_three = '';
            html_three += '<div class="swatch-container div_dataplansel_container">';

            var selected_plan_name = "";
            var selected_raw_price_num = "";
            var selected_raw_price_unit = "";

            jQuery.each( loop_variations, function( key_one, value_one ) {
                // console.log(value_one);

                jQuery.each( value_one, function( key_two, value_two ) {
                    jQuery.each( value_two, function( key_three, value_three ) {
                        // console.log( key_three + ": " + value_three );

                        var quote_selected = "";
                        var packid_selected = "";
                        var output_selected = "";
                        var days_selected = "";
                        var packname_selected = "";
                        var raw_price_num = "";
                        var raw_price_unit = "";

                        jQuery.each( value_three, function( key_four, value_four ) {
                            // console.log( key_four + ": " + value_four );

                            if(key_four == "pro_id") {
                                packid_selected = value_four;
                            }

                            if(key_four == "output") {
                                output_selected = value_four;
                            }

                            if(key_four == "quote") {
                                quote_selected = value_four;
                            }

                            if(key_four == "period") {
                                days_selected = value_four;
                            }

                            if(key_four == "packname") {
                                packname_selected = value_four;
                            }

                            if(key_four == "price_num") {
                                raw_price_num = value_four;
                            }

                            if(key_four == "price_unit") {
                                raw_price_unit = value_four;
                            }

                            // if(third_pacid_val == packid_selected) {
                            //     console.log( key_four + ": " + value_four );
                            // }
                        });

                        if(third_pacid_val == packid_selected) {
                            jQuery(".ipt_dataplan").val(third_pacid_val);
                            jQuery(".price_dataplan").html(output_selected);

                            selected_plan_name = packname_selected;
                            selected_raw_price_num = raw_price_num;
                            selected_raw_price_unit = raw_price_unit;
                        }
                    });
                });
            });

            jQuery(".esim_plans_btn").text(selected_plan_name);
            jQuery(".esim_package_unit_price").val(selected_raw_price_unit);
            jQuery(".esim_package_num_price").val(selected_raw_price_num);

            var new_ttl = selected_raw_price_unit + selected_raw_price_num;
            jQuery(".span_first_ttl_cost_text").html(new_ttl);

            // console.log(selected_plan_name);

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

                jQuery(".esim_plans_area").removeClass("active");
                        
                // Wait for animation to complete before hiding
                setTimeout(function() {
                    jQuery(".esim_plans_area").addClass("esim_plans_area_hide");
                }, 200); // Match this with your CSS transition duration
            });

            // auto click the "new esim" option
            jQuery('.new_esim_option').trigger('click');
        });
    }

    // Most reliable cross-browser/device solution
    function copyURLToClipboard(url) {
        // Try modern API first
        if(navigator.clipboard && window.isSecureContext) {
            return navigator.clipboard.writeText(url);
        }
        
        // Fallback that works everywhere
        var textarea = document.createElement('textarea');
        textarea.value = url;
        textarea.setAttribute('readonly', '');
        textarea.style.position = 'absolute';
        textarea.style.left = '-9999px';
        
        document.body.appendChild(textarea);
        
        // iOS specific selection
        if(/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
            var range = document.createRange();
            range.selectNodeContents(textarea);
            var selection = window.getSelection();
            selection.removeAllRanges();
            selection.addRange(range);
            textarea.setSelectionRange(0, 999999);
        }
        else {
            textarea.select();
        }
        
        var success = false;
        try {
            success = document.execCommand('copy');
        } catch (err) {
            console.error('Copy failed:', err);
        }
        
        document.body.removeChild(textarea);
        return Promise.resolve(success);
    }

    jQuery(document).ready(function() {
        jQuery(".shareable_link").click(function(e) {
            e.preventDefault();

            var link = '';
            var link_param = '';

            var current_domain = window.location.origin;
            
            link += current_domain + "/?";

            var region_opt = jQuery(".ipt_region").val();
            if(region_opt != "") {
                if(link_param.length > 0) {
                    link_param += "&";
                }

                link_param += "pre=" + region_opt;
            }

            var dest_opt = jQuery(".ipt_destination").val();
            if(dest_opt != "") {
                if(link_param.length > 0) {
                    link_param += "&";
                }

                link_param += "pde=" + dest_opt;
            }

            var days_opt = jQuery('.div_pactype_item.selected').attr('datavalue');
            if(days_opt !== undefined) {
                if(link_param.length > 0) {
                    link_param += "&";
                }

                link_param += "pda=" + days_opt;
            }

            var plans_opt = jQuery('.div_dataplansel_item.selected').attr('datavalue');
            if(plans_opt !== undefined) {
                if(link_param.length > 0) {
                    link_param += "&";
                }

                link_param += "pdp=" + plans_opt;
            }

            var esim_opt_val = jQuery('.chkbox_opts:checked').val();
            if(esim_opt_val !== undefined) {
                if(link_param.length > 0) {
                    link_param += "&";
                }

                link_param += "peo=" + esim_opt_val;
            }

            // if(jQuery('.chkbox_opts:checked').val() == "new_card") {
            //     if(link_param.length > 0) {
            //         link_param += "&";
            //     }

            //     link_param += "peo=new_card";
            // }

            var vc_opt = jQuery.trim(jQuery(".ipt_vouchercode").val());
            if(vc_opt != "") {
                if(link_param.length > 0) {
                    link_param += "&";
                }

                link_param += "pvc=" + vc_opt;
            }

            link += link_param;
            link += "#buy-now";

            copyURLToClipboard(link).then(function() {
                // alert('URL copied!');
                jQuery('.shareable_link_msg')
                .stop(true, true) // Stop any current animations
                .removeClass('shareable_link_msg_hide')
                .fadeIn(300)
                .delay(3000)
                .fadeOut(300, function() {
                    jQuery(this).addClass('shareable_link_msg_hide');
                });
            });
        });

        jQuery(".new_esim_option").click(function(e) {
            var button_text = jQuery(this).text().toLowerCase();
            var has_free = button_text.includes("free");
            
            if(has_free) {
                // no action needed
                // alert("no action");
            }
            else {
                if(jQuery(".swatch_esim").hasClass("has-value")) {
                    jQuery('#chkbox_id_new').prop('checked', true); //check checkbox

                    jQuery(".existing_esim_option").removeClass("swatch_esim_selected");
                    jQuery(".new_esim_option").addClass("swatch_esim_selected");

                    jQuery(".new_esim_option_msg").removeClass("card_opt_display");

                    ///radio
                    jQuery(".esim_main_lbl").addClass("card_opt_display");
                    jQuery(".esim_secd_lbl").addClass("card_opt_display");
                    jQuery(".ipt_esim").addClass("card_opt_display");
                    jQuery(".ipt_esim").val("Install new eSIM to use mobile data");
                    jQuery(".ipt_esim").attr("readonly", "readonly");
                    jQuery(".span_esim").addClass("card_opt_display");

                    //cal total cost
                    var raw_price_new_esim = jQuery(".new_esim_unit_price").val();
                    var raw_price_unit = jQuery(".esim_package_unit_price").val();
                    var raw_price_num = jQuery(".esim_package_num_price").val();

                    var new_ttl_cal = parseFloat(raw_price_new_esim) + parseFloat(raw_price_num);
                    var display_new_ttl = raw_price_unit + new_ttl_cal.toFixed(2);

                    jQuery(".span_first_ttl_cost_text").html(display_new_ttl);
                }
                else {
                    alert("Please select your eSIM data plan. Thank you.");
                }
            }
        });

        jQuery(".existing_esim_option").click(function(e) {
            if(jQuery(".swatch_esim").hasClass("has-value")) {
                var button_text = jQuery(".new_esim_option").text().toLowerCase();
                var has_free = button_text.includes("free");
                
                if(has_free) {
                    // reset new esim button
                    var raw_price_new_esim = jQuery(".new_esim_unit_price").val();
                    var new_btn_text = "New eSIM (+SGD" + raw_price_new_esim + ")";

                    jQuery(".new_esim_option").text(new_btn_text);
                }
                
                jQuery('#chkbox_id_exist').prop('checked', true); //check checkbox

                jQuery(".new_esim_option").removeClass("swatch_esim_selected");
                jQuery(".existing_esim_option").addClass("swatch_esim_selected");

                jQuery(".new_esim_option_msg").addClass("card_opt_display");

                ///radio
                jQuery(".esim_main_lbl").removeClass("card_opt_display");
                jQuery(".esim_secd_lbl").addClass("card_opt_display");
                jQuery(".ipt_esim").removeClass("card_opt_display");
                jQuery(".ipt_esim").val("");
                jQuery(".ipt_esim").removeAttr("readonly");
                jQuery(".span_esim").removeClass("card_opt_display");

                //cal total cost
                var raw_price_new_esim = jQuery(".new_esim_unit_price").val();
                var raw_price_unit = jQuery(".esim_package_unit_price").val();
                var raw_price_num = jQuery(".esim_package_num_price").val();

                var display_new_ttl = raw_price_unit + raw_price_num;

                jQuery(".span_first_ttl_cost_text").html(display_new_ttl);
            }
            else {
                alert("Please select your eSIM data plan. Thank you.");
            }

            // var cur_price = jQuery(".new_esim_unit_price").val();
            // cur_price = "New eSIM (+SGD" + cur_price + ")";

            // jQuery(".new_esim_option").text(cur_price);
        });
        
        jQuery(".ipt_region").change(function(e) {
            e.preventDefault();

            jQuery(".load_region").show();
            jQuery(".span_chkemail").hide();
            jQuery(".btn_paystripe").hide();
            jQuery(".filterproid").val("");

            jQuery(".span_showttl").html("");

            // jQuery(".ipt_dataplan").html("");
            jQuery(".ipt_dataplan").val("");
            
            jQuery(".price_dataplan").html("");

            jQuery(".span_pactype").hide();
            jQuery(".span_days").hide();
            jQuery(".span_dataplansel").hide();

            //reset radio option////
            jQuery(".esim_plans_btn").text("Select eSIM Data Plan");
            ////grey selection
            jQuery(".new_esim_option").removeClass('has-value');
            jQuery(".existing_esim_option").removeClass('has-value');

            jQuery(".new_esim_option_msg").addClass("card_opt_display");
            jQuery(".span_esim").addClass("card_opt_display");
            jQuery(".new_esim_option").removeClass("swatch_esim_selected");
            jQuery(".existing_esim_option").removeClass("swatch_esim_selected");

            jQuery('#chkbox_id_new').prop('checked', false); //check checkbox
            jQuery('#chkbox_id_exist').prop('checked', false); //uncheck checkbox
            jQuery('#chkbox_id_convert_new').prop('checked', false); //check checkbox

            // reset new esim button text
            var button_text = jQuery(".new_esim_option").text().toLowerCase();
            var has_free = button_text.includes("free");
            
            if(has_free) {
                // reset new esim button
                var raw_price_new_esim = jQuery(".new_esim_unit_price").val();
                var new_btn_text = "New eSIM (+SGD" + raw_price_new_esim + ")";

                jQuery(".new_esim_option").text(new_btn_text);
            }
            /////

            // cal total reset
            jQuery(".span_first_ttl_cost").addClass("card_opt_display");
            jQuery(".esim_package_unit_price").val("");
            jQuery(".esim_package_num_price").val("");

            // jQuery(".div_chkbox_new").removeClass("card_text_hide");
            // jQuery(".div_chkbox_convert_new").addClass("card_text_hide");

            jQuery(".esim_main_lbl").removeClass("card_opt_display");
            jQuery(".esim_secd_lbl").addClass("card_opt_display");
            jQuery(".ipt_esim").val("");
            jQuery(".ipt_esim").removeAttr("readonly");
            ///////

            //// reset the Select eSIM Data Plan
            if(jQuery(".esim_plans_area").hasClass("esim_plans_area_hide")) {
                //grey selection
                jQuery(".esim_plans_btn").removeClass('has-value');
            }
            else {
                jQuery(".esim_plans_area").removeClass("active");
                
                // Wait for animation to complete before hiding
                setTimeout(function() {
                    jQuery(".esim_plans_area").addClass("esim_plans_area_hide");
                }, 200); // Match this with your CSS transition duration

                //grey selection
                jQuery(".esim_plans_btn").removeClass('has-value');
            }
            ////

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

            if(regval == "") {
                // grey out all select and back to default
                var default_destination = '<option value="">Select Destination</option>';

                jQuery(".ipt_destination").html(default_destination);
                jQuery(".modeldestcontent").html("");

                //grey destination selection
                jQuery("#destid").removeClass('has-value');
                // jQuery("#destid").css('color', '#c9c9c9 !important'); // Gray color for placeholder

                jQuery(".load_region").hide();
            }
            else {
                //un-grey destination selection
                jQuery("#destid").addClass('has-value');
                // jQuery("#destid").css('color', '#666666 !important'); // Gray color for placeholder

                jQuery.ajax({
                    type : "post",
                    url : "<?php echo admin_url( 'admin-ajax.php' ); ?>?t=" + Date.now(),
                    data : {action: "bonvoi_retail_generate_chkdest", regval : regval, nonce: nonce, cache_buster: Date.now()},
                    success: function(response) {
                        // Check for empty response
                        if(!response || response.trim() === '') {
                            console.error("Empty response detected, redirecting with nocache...");
                            
                            alert("Server busy, please click OK for webpage to refresh. Then try again after refreshed");

                            // Redirect with nocache parameter
                            window.location.href = window.location.pathname + '?nocache=' + Date.now() + '&purge_key=' + cf_nonce;
                            return;
                        }
                        
                        var json = jQuery.parseJSON(response);

                        if(json.status == "pass") {
                            console.log("status passed...");

                            jQuery(".ipt_destination").html(json.html);
                            jQuery(".modeldestcontent").html(json.cover);
                            jQuery(".load_region").hide();
                        }
                        else {
                            // jQuery(".load_region").hide();
                            //retry
                            console.log("status failed...");

                            jQuery.ajax({
                                type : "post",
                                url : "<?php echo admin_url( 'admin-ajax.php' ); ?>?t=" + Date.now(),
                                data : {action: "bonvoi_retail_generate_chkdest", regval : regval, nonce: nonce, cache_buster: Date.now()},
                                success: function(response) {
                                    // Check for empty response
                                    if(!response || response.trim() === '') {
                                        console.error("Empty response detected, redirecting with nocache...");
                                        
                                        alert("Server busy, please click OK for webpage to refresh. Then try again after refreshed");

                                        // Redirect with nocache parameter
                                        window.location.href = window.location.pathname + '?nocache=' + Date.now() + '&purge_key=' + cf_nonce;
                                        return;
                                    }
                                    
                                    var json = jQuery.parseJSON(response);

                                    if(json.status == "pass") {
                                        jQuery(".ipt_destination").html(json.html);
                                        jQuery(".modeldestcontent").html(json.cover);
                                        jQuery(".load_region").hide();
                                    }
                                    else {
                                        jQuery(".load_region").hide();

                                        alert("Loading error... Page reload and try agian! Thank you.");
                                        location.reload();
                                    }
                                }
                            });

                            console.log("status failed end...");
                        }
                    },
                    error: function(jq_xhr, text_status, error_thrown) {
                        // ipt_region This function will run if the AJAX request fails.
                        // ipt_region_fail
                        // ipt_destination_fail
                        // console.log("error block: start");

                        var ipt_region_fail = jQuery(".ipt_region_fail").val();
                        var rerun = "no";

                        if(ipt_region_fail == "0") {
                            jQuery(".ipt_region_fail").val("1");
                            rerun = "yes";
                        }

                        if(rerun == "yes") {
                            // console.log("error block: ajax request...");

                            jQuery.ajax({
                                type : "post",
                                url : "<?php echo admin_url( 'admin-ajax.php' ); ?>?t=" + Date.now(),
                                data : {action: "bonvoi_retail_generate_chkdest", regval : regval, nonce: nonce, cache_buster: Date.now()},
                                success: function(response) {
                                    // Check for empty response
                                    if(!response || response.trim() === '') {
                                        console.error("Empty response detected, redirecting with nocache...");
                                        
                                        alert("Server busy, please click OK for webpage to refresh. Then try again after refreshed");

                                        // Redirect with nocache parameter
                                        window.location.href = window.location.pathname + '?nocache=' + Date.now() + '&purge_key=' + cf_nonce;
                                        return;
                                    }
                                    
                                    var json = jQuery.parseJSON(response);

                                    if(json.status == "pass") {
                                        jQuery(".ipt_destination").html(json.html);
                                        jQuery(".modeldestcontent").html(json.cover);
                                        jQuery(".load_region").hide();
                                    }
                                    else {
                                        jQuery(".load_region").hide();

                                        alert("Loading error... Page reload and try agian! Thank you.");
                                        location.reload();
                                    }
                                }
                            });
                        }
                        else {
                            // console.log("error block: reloading...");

                            jQuery(".load_region").hide();

                            alert("Loading error... Page reload and try agian! Thank you.");
                            location.reload();
                        }
                        
                        // console.log("error block: end");

                        // // Hide the loading indicator
                        // jQuery(".load_region").hide();

                        // // Log the detailed error to the console for debugging
                        // console.error("AJAX Error: " + text_status + " - " + error_thrown);

                        // // Show a more user-friendly error message
                        // alert("An error occurred while trying to connect to the server. Please check your internet connection and try again.");
                    }
                });
            }
        });

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

            if(jQuery(".esim_plans_btn").hasClass("has-value")) {
                if(jQuery(".esim_plans_area").hasClass("esim_plans_area_hide")) {
                    jQuery(".esim_plans_area").removeClass("esim_plans_area_hide");
                    
                    // Force browser to recognize the display change before animation
                    setTimeout(function() {
                        jQuery(".esim_plans_area").addClass("active");
                    }, 10); // Small delay to ensure display:block is applied
                }
                else {
                    jQuery(".esim_plans_area").removeClass("active");
                    
                    // Wait for animation to complete before hiding
                    setTimeout(function() {
                        jQuery(".esim_plans_area").addClass("esim_plans_area_hide");
                    }, 200); // Match this with your CSS transition duration
                }

                // reset new esim button text
                // var button_text = jQuery(".new_esim_option").text().toLowerCase();
                // var has_free = button_text.includes("free");
                
                // if(has_free) {
                //     // reset new esim button
                //     var raw_price_new_esim = jQuery(".new_esim_unit_price").val();
                //     var new_btn_text = "New eSIM (+SGD" + raw_price_new_esim + ")";

                //     jQuery(".new_esim_option").text(new_btn_text);
                // }
            }
            else {
                alert("Please select your destination. Thank you.");
            }
        });

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

            jQuery(".span_showttl").html("");

            jQuery(".ipt_dataplan").val("");

            jQuery(".span_pactype").hide();
            jQuery(".span_days").hide();
            jQuery(".span_dataplansel").hide();

            //reset radio option////
            jQuery(".esim_plans_btn").text("Select eSIM Data Plan");
            ////grey selection
            jQuery(".new_esim_option").removeClass('has-value');
            jQuery(".existing_esim_option").removeClass('has-value');

            jQuery(".new_esim_option_msg").addClass("card_opt_display");
            jQuery(".span_esim").addClass("card_opt_display");
            jQuery(".new_esim_option").removeClass("swatch_esim_selected");
            jQuery(".existing_esim_option").removeClass("swatch_esim_selected");

            jQuery('#chkbox_id_new').prop('checked', false); //check checkbox
            jQuery('#chkbox_id_exist').prop('checked', false); //uncheck checkbox
            jQuery('#chkbox_id_convert_new').prop('checked', false); //check checkbox

            // reset new esim button text
            var button_text = jQuery(".new_esim_option").text().toLowerCase();
            var has_free = button_text.includes("free");
            
            if(has_free) {
                // reset new esim button
                var raw_price_new_esim = jQuery(".new_esim_unit_price").val();
                var new_btn_text = "New eSIM (+SGD" + raw_price_new_esim + ")";

                jQuery(".new_esim_option").text(new_btn_text);
            }

            // cal total reset
            jQuery(".span_first_ttl_cost").addClass("card_opt_display");
            jQuery(".esim_package_unit_price").val("");
            jQuery(".esim_package_num_price").val("");

            /////
            // jQuery('#chkbox_id_convert_new').prop('checked', false); //uncheck checkbox
            // jQuery('#chkbox_id_exist').prop('checked', true); //check checkbox

            // jQuery(".div_chkbox_new").removeClass("card_text_hide");
            // jQuery(".div_chkbox_convert_new").addClass("card_text_hide");

            jQuery(".esim_main_lbl").removeClass("card_opt_display");
            jQuery(".esim_secd_lbl").addClass("card_opt_display");
            jQuery(".ipt_esim").val("");
            jQuery(".ipt_esim").removeAttr("readonly");
            ///////

            //// reset the Select eSIM Data Plan
            if(jQuery(".esim_plans_area").hasClass("esim_plans_area_hide")) {
                //nothing happen
            }
            else {
                jQuery(".esim_plans_area").removeClass("active");
                
                // Wait for animation to complete before hiding
                setTimeout(function() {
                    jQuery(".esim_plans_area").addClass("esim_plans_area_hide");
                }, 200); // Match this with your CSS transition duration
            }
            ////

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

            if(destval == "") {
                jQuery(".hidesupportinfoblock").hide();

                jQuery(".load_destination").hide();

                //grey selection
                jQuery(".esim_plans_btn").removeClass('has-value');
            }
            else {
                //un-grey selection
                jQuery(".esim_plans_btn").addClass('has-value');

                jQuery(".hidesupportinfoblock").hide();

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

                jQuery.ajax({
                    type : "post",
                    url : "<?php echo admin_url( 'admin-ajax.php' ); ?>?t=" + Date.now(),
                    data : {action: "bonvoi_retail_generate_chkplan", destval : destval, nonce: nonce, cache_buster: Date.now()},
                    success: function(response) {
                        // Check for empty response
                        if(!response || response.trim() === '') {
                            console.error("Empty response detected, redirecting with nocache...");
                            
                            alert("Server busy, please click OK for webpage to refresh. Then try again after refreshed");

                            // Redirect with nocache parameter
                            window.location.href = window.location.pathname + '?nocache=' + Date.now() + '&purge_key=' + cf_nonce;
                            return;
                        }

                        var json = jQuery.parseJSON(response);

                        if(json.status == "pass") {
                            // jQuery(".ipt_dataplan").html(json.html);

                            jQuery(".load_destination").hide();
                            jQuery(".generate_chkplan_json").val(JSON.stringify(json.json)); // original style
                            jQuery(".generate_chkplan_day_json").val(JSON.stringify(json.day_json)); //day style
                            
                            var primary_count = 0;
                            var second_count = 0;
                            var primary_val = '';
                            var second_val = '';

                            var json_val = jQuery(".generate_chkplan_day_json").val();
                            var loop_variations = jQuery.parseJSON(json_val);

                            var html_one = '';
                            html_one += '<div class="swatch-container div_pactype_container">';

                            jQuery.each( loop_variations, function( key_one, value_one ) {
                                if(primary_count == 0) {
                                    primary_val = key_one;

                                    // console.log( "selected: " + key_one );
                                }

                                html_one += '<span class="div_pactype_item swatch';

                                if(primary_count == 0) {
                                    // html_one += ' selected"'; //no default selection needed
                                    html_one += '"';
                                }
                                else {
                                    html_one += '"';
                                }
                                
                                if(key_one > 1) {
                                    $show_day_word = ' Days';
                                }
                                else {
                                    $show_day_word = ' Day';
                                }

                                html_one += ' datavalue="'+key_one+'">' + key_one + $show_day_word + '</span>';

                                // console.log( key_one );

                                primary_count++;
                            });

                            html_one += '</div>';
                            jQuery(".div_pactype").html(html_one);

                            <?php
                            /*
                            // primary_val = "7";
                            var arr_unlimited_items = [];
                            var arr_fixed_items = [];

                            var html_three = '';
                            html_three += '<div class="swatch-container div_dataplansel_container">';

                            jQuery.each( loop_variations, function( key_one, value_one ) {
                                // console.log( key_one );

                                jQuery.each( value_one, function( key_two, value_two ) {
                                    var compare_base = parseInt(primary_val);
                                    var compare_loop = parseInt(key_one);

                                    // var unlimited_list = '';
                                    // var fixed_list = '';

                                    if(compare_base <= compare_loop) {
                                        // console.log( compare_base + " - " + compare_loop );
                                        // console.log( key_two );

                                        jQuery.each( value_two, function( key_three, value_three ) {
                                            // console.log( key_three );
                                            // console.log( value_four );

                                            var quote_selected = "";
                                            var packid_selected = "";
                                            var output_selected = "";
                                            var days_selected = "";
                                            var type_selected = "";
                                            var selection_text = "";

                                            jQuery.each( value_three, function( key_four, value_four ) {
                                                // console.log( key_four + ": " + value_four );

                                                if(key_four == "pro_id") {
                                                    packid_selected = value_four;
                                                }

                                                if(key_four == "output") {
                                                    output_selected = value_four;
                                                }

                                                if(key_four == "quote") {
                                                    quote_selected = value_four;
                                                }

                                                if(key_four == "period") {
                                                    days_selected = value_four;
                                                }

                                                if(key_four == "type") {
                                                    type_selected = value_four;

                                                    if(value_four == "Unlimited") {
                                                        // "1GB Daily Unlimited";
                                                        selection_text = quote_selected + " Daily " + value_four;
                                                    }
                                                    else {
                                                        // "5GB, up to 10 Days";
                                                        selection_text = quote_selected + " for " + days_selected;
                                                    }
                                                }
                                            });

                                            if(compare_base <= compare_loop) {
                                                if(type_selected == "Unlimited") {
                                                    if(compare_base == compare_loop) {
                                                        // unlimited_list += '<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>';

                                                        arr_unlimited_items.push('<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>');
                                                    }
                                                }
                                                else if(type_selected == "Fixed") {
                                                    if(compare_base <= compare_loop) {
                                                        // fixed_list += '<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>';

                                                        arr_fixed_items.push('<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>');
                                                    }
                                                }
                                            }
                                        });

                                        // html_three += unlimited_list;
                                        // html_three += fixed_list;
                                    }
                                });
                            });

                            // console.log(arr_unlimited_items);
                            // console.log(arr_fixed_items);

                            if(arr_unlimited_items.length > 0) {
                                html_three += arr_unlimited_items.join('');
                                html_three += '<div style="clear:both;width:100%;"></div>';
                            }
                            
                            html_three += arr_fixed_items.join('');

                            html_three += '</div>';
                            jQuery(".div_dataplansel").html(html_three);
                            */ ?>

                            jQuery(".div_days").html("");

                            product_days_variations();

                            jQuery(".span_pactype").show();
                            // jQuery(".span_days").show();
                            // jQuery(".span_dataplansel").show();

                            /*
                            // original style
                            var primary_count = 0;
                            var second_count = 0;
                            var primary_val = '';
                            var second_val = '';

                            var json_val = jQuery(".generate_chkplan_json").val();
                            var loop_variations = jQuery.parseJSON(json_val);

                            var html_one = '';
                            html_one += '<div class="swatch-container div_pactype_container">';

                            jQuery.each( loop_variations, function( key_one, value_one ) {
                                if(primary_count == 0) {
                                    primary_val = key_one;

                                    // console.log( "selected: " + key_one );
                                }

                                
                                html_one += '<span class="div_pactype_item swatch';

                                if(primary_count == 0) {
                                    html_one += ' selected"';
                                }
                                else {
                                    html_one += '"';
                                }
                                
                                html_one += ' datavalue="'+key_one+'">' + key_one + ' Data</span>';

                                // console.log( key_one );

                                primary_count++;
                            });

                            html_one += '</div>';
                            jQuery(".div_pactype").html(html_one);

                            var html_two = '';
                            html_two += '<div class="swatch-container div_days_container">';

                            jQuery.each( loop_variations, function( key_one, value_one ) {
                                if(key_one == primary_val) {
                                    jQuery.each( value_one, function( key_two, value_two ) {
                                        if(second_count == 0) {
                                            second_val = key_two;

                                            // console.log( "selected: " + key_two );
                                        }

                                        html_two += '<span class="div_days_item swatch';

                                        if(second_count == 0) {
                                            html_two += ' selected"';
                                        }
                                        else {
                                            html_two += '"';
                                        }
                                        
                                        html_two += ' datavalue="'+key_two+'">' + key_two + '</span>';
                                        
                                        // console.log( key_two );

                                        second_count++;
                                    });
                                }
                            });
                            
                            html_two += '</div>';
                            jQuery(".div_days").html(html_two);

                            var html_three = '';
                            html_three += '<div class="swatch-container div_dataplansel_container">';

                            jQuery.each( loop_variations, function( key_one, value_one ) {
                                jQuery.each( value_one, function( key_two, value_two ) {
                                    if(key_one == primary_val && key_two == second_val) {
                                        // console.log( key_one );
                                        // console.log( key_two );

                                        jQuery.each( value_two, function( key_three, value_three ) {
                                            // console.log( key_three );

                                            var quote_selected = "";
                                            var packid_selected = "";
                                            var output_selected = "";

                                            jQuery.each( value_three, function( key_four, value_four ) {
                                                // console.log( key_four + ": " + value_four );

                                                if(key_four == "pro_id") {
                                                    packid_selected = value_four;
                                                }

                                                if(key_four == "output") {
                                                    output_selected = value_four;
                                                }

                                                if(key_four == "quote") {
                                                    quote_selected = value_four;
                                                }
                                            });

                                            html_three += '<span class="div_dataplansel_item swatch" dataid="' + quote_selected + '" datavalue="'+packid_selected+'">' + quote_selected + '</span>';
                                        });
                                    }
                                });
                            });

                            html_three += '</div>';
                            jQuery(".div_dataplansel").html(html_three);

                            product_variations();

                            jQuery(".span_pactype").show();
                            jQuery(".span_days").show();
                            jQuery(".span_dataplansel").show();
                            */
                        }
                        else {
                            // jQuery(".load_destination").hide();
                            // retry
                            jQuery.ajax({
                                type : "post",
                                url : "<?php echo admin_url( 'admin-ajax.php' ); ?>?t=" + Date.now(),
                                data : {action: "bonvoi_retail_generate_chkplan", destval : destval, nonce: nonce, cache_buster: Date.now()},
                                success: function(response) {
                                    // Check for empty response
                                    if(!response || response.trim() === '') {
                                        console.error("Empty response detected, redirecting with nocache...");
                                        
                                        alert("Server busy, please click OK for webpage to refresh. Then try again after refreshed");

                                        // Redirect with nocache parameter
                                        window.location.href = window.location.pathname + '?nocache=' + Date.now() + '&purge_key=' + cf_nonce;
                                        return;
                                    }
                                    
                                    var json = jQuery.parseJSON(response);

                                    if(json.status == "pass") {
                                        // jQuery(".ipt_dataplan").html(json.html);

                                        jQuery(".load_destination").hide();
                                        jQuery(".generate_chkplan_json").val(JSON.stringify(json.json)); // original style
                                        jQuery(".generate_chkplan_day_json").val(JSON.stringify(json.day_json)); //day style
                                        
                                        var primary_count = 0;
                                        var second_count = 0;
                                        var primary_val = '';
                                        var second_val = '';

                                        var json_val = jQuery(".generate_chkplan_day_json").val();
                                        var loop_variations = jQuery.parseJSON(json_val);

                                        var html_one = '';
                                        html_one += '<div class="swatch-container div_pactype_container">';

                                        jQuery.each( loop_variations, function( key_one, value_one ) {
                                            if(primary_count == 0) {
                                                primary_val = key_one;

                                                // console.log( "selected: " + key_one );
                                            }

                                            html_one += '<span class="div_pactype_item swatch';

                                            if(primary_count == 0) {
                                                html_one += ' selected"';
                                            }
                                            else {
                                                html_one += '"';
                                            }
                                            
                                            if(key_one > 1) {
                                                $show_day_word = ' Days';
                                            }
                                            else {
                                                $show_day_word = ' Day';
                                            }

                                            html_one += ' datavalue="'+key_one+'">' + key_one + $show_day_word + '</span>';

                                            // console.log( key_one );

                                            primary_count++;
                                        });

                                        html_one += '</div>';
                                        jQuery(".div_pactype").html(html_one);

                                        // primary_val = "7";
                                        var arr_unlimited_items = [];
                                        var arr_fixed_items = [];

                                        var html_three = '';
                                        html_three += '<div class="swatch-container div_dataplansel_container">';

                                        jQuery.each( loop_variations, function( key_one, value_one ) {
                                            // console.log( key_one );

                                            jQuery.each( value_one, function( key_two, value_two ) {
                                                var compare_base = parseInt(primary_val);
                                                var compare_loop = parseInt(key_one);

                                                // var unlimited_list = '';
                                                // var fixed_list = '';

                                                if(compare_base <= compare_loop) {
                                                    // console.log( compare_base + " - " + compare_loop );
                                                    // console.log( key_two );

                                                    jQuery.each( value_two, function( key_three, value_three ) {
                                                        // console.log( key_three );
                                                        // console.log( value_four );

                                                        var quote_selected = "";
                                                        var packid_selected = "";
                                                        var output_selected = "";
                                                        var days_selected = "";
                                                        var type_selected = "";
                                                        var selection_text = "";

                                                        jQuery.each( value_three, function( key_four, value_four ) {
                                                            // console.log( key_four + ": " + value_four );

                                                            if(key_four == "pro_id") {
                                                                packid_selected = value_four;
                                                            }

                                                            if(key_four == "output") {
                                                                output_selected = value_four;
                                                            }

                                                            if(key_four == "quote") {
                                                                quote_selected = value_four;
                                                            }

                                                            if(key_four == "period") {
                                                                days_selected = value_four;
                                                            }

                                                            if(key_four == "type") {
                                                                type_selected = value_four;

                                                                if(value_four == "Unlimited") {
                                                                    // "1GB Daily Unlimited";
                                                                    selection_text = quote_selected + " Daily " + value_four;
                                                                }
                                                                else {
                                                                    // "5GB, up to 10 Days";
                                                                    selection_text = quote_selected + " for " + days_selected;
                                                                }
                                                            }
                                                        });

                                                        if(compare_base <= compare_loop) {
                                                            if(type_selected == "Unlimited") {
                                                                if(compare_base == compare_loop) {
                                                                    // unlimited_list += '<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>';

                                                                    arr_unlimited_items.push('<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>');
                                                                }
                                                            }
                                                            else if(type_selected == "Fixed") {
                                                                if(compare_base <= compare_loop) {
                                                                    // fixed_list += '<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>';

                                                                    arr_fixed_items.push('<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>');
                                                                }
                                                            }
                                                        }
                                                    });

                                                    // html_three += unlimited_list;
                                                    // html_three += fixed_list;
                                                }
                                            });
                                        });

                                        // console.log(arr_unlimited_items);
                                        // console.log(arr_fixed_items);

                                        if(arr_unlimited_items.length > 0) {
                                            html_three += arr_unlimited_items.join('');
                                            html_three += '<div style="clear:both;width:100%;"></div>';
                                        }
                                        
                                        html_three += arr_fixed_items.join('');

                                        html_three += '</div>';
                                        jQuery(".div_dataplansel").html(html_three);

                                        jQuery(".div_days").html("");

                                        product_days_variations()

                                        jQuery(".span_pactype").show();
                                        // jQuery(".span_days").show();
                                        jQuery(".span_dataplansel").show();
                                    }
                                    else {
                                        jQuery(".load_destination").hide();

                                        alert("Loading error... Page reload and try agian! Thank you.");
                                        location.reload();
                                    }
                                }
                            });
                        }
                    },
                    error: function(jq_xhr, text_status, error_thrown) {
                        // ipt_destination This function will run if the AJAX request fails.
                        // ipt_region_fail
                        // ipt_destination_fail
                        // console.log("error block 2: start");

                        var ipt_destination_fail = jQuery(".ipt_destination_fail").val();
                        var rerun = "no";

                        if(ipt_destination_fail == "0") {
                            jQuery(".ipt_destination_fail").val("1");
                            rerun = "yes";
                        }

                        if(rerun == "yes") {
                            // console.log("error block 2: ajax requesting...");

                            jQuery.ajax({
                                type : "post",
                                url : "<?php echo admin_url( 'admin-ajax.php' ); ?>?t=" + Date.now(),
                                data : {action: "bonvoi_retail_generate_chkplan", destval : destval, nonce: nonce, cache_buster: Date.now()},
                                success: function(response) {
                                    // Check for empty response
                                    if(!response || response.trim() === '') {
                                        console.error("Empty response detected, redirecting with nocache...");
                                        
                                        alert("Server busy, please click OK for webpage to refresh. Then try again after refreshed");

                                        // Redirect with nocache parameter
                                        window.location.href = window.location.pathname + '?nocache=' + Date.now() + '&purge_key=' + cf_nonce;
                                        return;
                                    }
                                    
                                    var json = jQuery.parseJSON(response);

                                    if(json.status == "pass") {
                                        // jQuery(".ipt_dataplan").html(json.html);

                                        jQuery(".load_destination").hide();
                                        jQuery(".generate_chkplan_json").val(JSON.stringify(json.json)); // original style
                                        jQuery(".generate_chkplan_day_json").val(JSON.stringify(json.day_json)); //day style
                                        
                                        var primary_count = 0;
                                        var second_count = 0;
                                        var primary_val = '';
                                        var second_val = '';

                                        var json_val = jQuery(".generate_chkplan_day_json").val();
                                        var loop_variations = jQuery.parseJSON(json_val);

                                        var html_one = '';
                                        html_one += '<div class="swatch-container div_pactype_container">';

                                        jQuery.each( loop_variations, function( key_one, value_one ) {
                                            if(primary_count == 0) {
                                                primary_val = key_one;

                                                // console.log( "selected: " + key_one );
                                            }

                                            html_one += '<span class="div_pactype_item swatch';

                                            if(primary_count == 0) {
                                                html_one += ' selected"';
                                            }
                                            else {
                                                html_one += '"';
                                            }
                                            
                                            if(key_one > 1) {
                                                $show_day_word = ' Days';
                                            }
                                            else {
                                                $show_day_word = ' Day';
                                            }

                                            html_one += ' datavalue="'+key_one+'">' + key_one + $show_day_word + '</span>';

                                            // console.log( key_one );

                                            primary_count++;
                                        });

                                        html_one += '</div>';
                                        jQuery(".div_pactype").html(html_one);

                                        // primary_val = "7";
                                        var arr_unlimited_items = [];
                                        var arr_fixed_items = [];

                                        var html_three = '';
                                        html_three += '<div class="swatch-container div_dataplansel_container">';

                                        jQuery.each( loop_variations, function( key_one, value_one ) {
                                            // console.log( key_one );

                                            jQuery.each( value_one, function( key_two, value_two ) {
                                                var compare_base = parseInt(primary_val);
                                                var compare_loop = parseInt(key_one);

                                                // var unlimited_list = '';
                                                // var fixed_list = '';

                                                if(compare_base <= compare_loop) {
                                                    // console.log( compare_base + " - " + compare_loop );
                                                    // console.log( key_two );

                                                    jQuery.each( value_two, function( key_three, value_three ) {
                                                        // console.log( key_three );
                                                        // console.log( value_four );

                                                        var quote_selected = "";
                                                        var packid_selected = "";
                                                        var output_selected = "";
                                                        var days_selected = "";
                                                        var type_selected = "";
                                                        var selection_text = "";

                                                        jQuery.each( value_three, function( key_four, value_four ) {
                                                            // console.log( key_four + ": " + value_four );

                                                            if(key_four == "pro_id") {
                                                                packid_selected = value_four;
                                                            }

                                                            if(key_four == "output") {
                                                                output_selected = value_four;
                                                            }

                                                            if(key_four == "quote") {
                                                                quote_selected = value_four;
                                                            }

                                                            if(key_four == "period") {
                                                                days_selected = value_four;
                                                            }

                                                            if(key_four == "type") {
                                                                type_selected = value_four;

                                                                if(value_four == "Unlimited") {
                                                                    // "1GB Daily Unlimited";
                                                                    selection_text = quote_selected + " Daily " + value_four;
                                                                }
                                                                else {
                                                                    // "5GB, up to 10 Days";
                                                                    selection_text = quote_selected + " for " + days_selected;
                                                                }
                                                            }
                                                        });

                                                        if(compare_base <= compare_loop) {
                                                            if(type_selected == "Unlimited") {
                                                                if(compare_base == compare_loop) {
                                                                    // unlimited_list += '<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>';

                                                                    arr_unlimited_items.push('<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>');
                                                                }
                                                            }
                                                            else if(type_selected == "Fixed") {
                                                                if(compare_base <= compare_loop) {
                                                                    // fixed_list += '<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>';

                                                                    arr_fixed_items.push('<span class="div_dataplansel_item swatch" datadays="' + days_selected + '" dataid="' + quote_selected + '" datavalue="' + packid_selected+'">' + selection_text + '</span>');
                                                                }
                                                            }
                                                        }
                                                    });

                                                    // html_three += unlimited_list;
                                                    // html_three += fixed_list;
                                                }
                                            });
                                        });

                                        // console.log(arr_unlimited_items);
                                        // console.log(arr_fixed_items);

                                        if(arr_unlimited_items.length > 0) {
                                            html_three += arr_unlimited_items.join('');
                                            html_three += '<div style="clear:both;width:100%;"></div>';
                                        }
                                        
                                        html_three += arr_fixed_items.join('');

                                        html_three += '</div>';
                                        jQuery(".div_dataplansel").html(html_three);

                                        jQuery(".div_days").html("");

                                        product_days_variations()

                                        jQuery(".span_pactype").show();
                                        // jQuery(".span_days").show();
                                        jQuery(".span_dataplansel").show();
                                    }
                                    else {
                                        jQuery(".load_destination").hide();

                                        alert("Loading error... Page reload and try agian! Thank you.");
                                        location.reload();
                                    }
                                }
                            });
                        }
                        else {
                            // console.log("error block 2: realoding...");

                            jQuery(".load_destination").hide();

                            alert("Loading error... Page reload and try agian! Thank you.");
                            location.reload();
                        }

                        // console.log("error block 2: end");
                        
                        // // Hide the loading indicator
                        // jQuery(".load_region").hide();

                        // // Log the detailed error to the console for debugging
                        // console.error("AJAX Error: " + text_status + " - " + error_thrown);

                        // // Show a more user-friendly error message
                        // alert("An error occurred while trying to connect to the server. Please check your internet connection and try again.");
                    }
                });
            }
        });

        <?php
        /*
        jQuery(".ipt_dataplan").change( function(e) {
            e.preventDefault();

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

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

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

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

                    if(json.status == "pass") {
                        jQuery(".price_dataplan").html(json.html.output);
                        jQuery(".filterproid").val(json.html.pro_id); //this is the proid for woocommerce, no need for this because we dont use woocommerce
                        jQuery(".load_dataplan").hide();
                    }
                    else {
                        jQuery(".load_dataplan").hide();
                    }
                }
            });
        });
        */
        ?>

        /*jQuery(".chkbox_opts").click(function(e) {
            // e.preventDefault();

            var card_opt = jQuery(this).val();
            var card_opt_id = jQuery(this).attr("id");

            if(card_opt == "existing_card") {
                if(card_opt_id == "chkbox_id_convert_new") {
                    jQuery(".esim_main_lbl").addClass("card_opt_display");
                    jQuery(".esim_secd_lbl").removeClass("card_opt_display");
                    jQuery(".ipt_esim").val("Install new eSIM to use mobile data");
                    jQuery(".ipt_esim").attr("readonly", "readonly");
                }
                else {
                    jQuery(".esim_main_lbl").removeClass("card_opt_display");
                    jQuery(".esim_secd_lbl").addClass("card_opt_display");
                    jQuery(".ipt_esim").val("");
                    jQuery(".ipt_esim").removeAttr("readonly");
                }
            }
            else {
                jQuery(".esim_main_lbl").addClass("card_opt_display");
                jQuery(".esim_secd_lbl").removeClass("card_opt_display");
                jQuery(".ipt_esim").val("Install new eSIM to use mobile data");
                jQuery(".ipt_esim").attr("readonly", "readonly");
            }
        });*/

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

            jQuery(".span_topup_msg").html("");

            //voucher code
            jQuery(".res_vou_num").val("");
            jQuery(".res_vou_status").val("");
            jQuery(".res_vou_type").val("");
            jQuery(".res_vou_val").val("");
            jQuery(".span_vouchermsg").html("");
            jQuery(".span_vouchermsg").hide();
            
            jQuery(".span_agreementmsg").html("");
            jQuery(".span_agreementmsg").hide();

            jQuery(".btn_paystripe").hide();
            jQuery(".span_chkemail").hide();

            jQuery(".span_showttl").html("");
            
            var card_opt = jQuery(".chkbox_opts:checked").val();

            var esim = jQuery.trim(jQuery(".ipt_esim").val());
            var nonce = jQuery(".chkesimnonce").val();
            var voucher = jQuery.trim(jQuery(".ipt_vouchercode").val());

            // var planval = jQuery(".ipt_dataplan").find(":selected").val();
            var planval = jQuery(".ipt_dataplan").val();

            var proid = jQuery(".filterproid").val();

            //check select data plan
            if(planval == "") {
                alert("Please select your data plan. Thank you.");
            }
            else {
                if(card_opt == "existing_card") {
                    if(esim != "") {
                        jQuery(".load_esim").show();

                        jQuery.ajax({
                            type : "post",
                            url : "<?php echo admin_url( 'admin-ajax.php' ); ?>?t=" + Date.now(),
                            data : {action: "bonvoi_retail_generate_chkesim", p_esim : esim, nonce: nonce, p_voucher: voucher, p_card_opt: card_opt, p_planval: planval, p_proid: proid, cache_buster: Date.now()},
                            success: function(response) {
                                // Check for empty response
                                if(!response || response.trim() === '') {
                                    console.error("Empty response detected, redirecting with nocache...");
                                    
                                    alert("Server busy, please click OK for webpage to refresh. Then try again after refreshed");

                                    // Redirect with nocache parameter
                                    window.location.href = window.location.pathname + '?nocache=' + Date.now() + '&purge_key=' + cf_nonce;
                                    return;
                                }
                                
                                var json = jQuery.parseJSON(response);

                                //json.extra_act

                                if(json.status == "pass") {
                                    jQuery(".load_esim").hide();

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

                                    if(voucher != "" && json.vou.discount_status == "1") {
                                        jQuery(".span_vouchermsg").html("Voucher code successfully applied.");
                                        jQuery(".span_vouchermsg").show();
                                    }
                                    else if(voucher != "" && json.vou.discount_status == "2") {
                                        jQuery(".span_vouchermsg").html("Invalid voucher code. Voucher code failed to apply. You may continue without voucher code. Thank you.");
                                        jQuery(".span_vouchermsg").show();
                                    }
                                    else if(voucher != "" && json.vou.discount_status == "3") {
                                        // console.log("show error voucher");
                                        jQuery(".span_vouchermsg").html("Voucher has reached usage limit, you may continue without voucher code. Thank you.");
                                        jQuery(".span_vouchermsg").show();
                                    }

                                    <?php
                                    //$run_convert_code = get_option('automatic_convertion_process_run');

                                    //if($run_convert_code == 'Yes') {}
                                    //else {}
                                    ?>
                                    if(json.extra_act == "Yes") {
                                        if(json.convert.esim_convert_chk == "Yes") {
                                            jQuery(".ipt_esim_convert").val(json.convert.esim_convert_chk);

                                            var div_agree_content = '<div style="border:1px solid #f2cfcf;background:#fef9f9;padding:20px;">';
                                                div_agree_content += json.convert.esim_convert_msg;
                                                div_agree_content += '<div style="margin-top:20px;">';
                                                    div_agree_content += '<button type="button" name="val_chk_agr_accept" style="margin-right:10px;background:#3b43d1;border-color:#2e36cc;" class="val_chk_agr_accept button alt" style="font-family: Montserrat;">Accept</button>';

                                                    div_agree_content += '<button type="button" name="val_chk_agr_decline" style="background:#d6a9a9;border-color:#c28e8e;" class="val_chk_agr_decline button alt" style="font-family: Montserrat;">Decline</button>';
                                                div_agree_content += '</div>';
                                            div_agree_content += '</div>';

                                            jQuery(".span_agreementmsg").html(div_agree_content);
                                            jQuery(".span_agreementmsg").show();

                                            jQuery(".span_showttl").html(json.fttl);

                                            agreement_btns();
                                        }
                                        else {
                                            jQuery(".ipt_esim_convert").val(json.convert.esim_convert_chk);

                                            jQuery(".btn_paystripe").show();
                                            jQuery(".span_chkemail").show();

                                            jQuery(".span_showttl").html(json.fttl);
                                        }
                                    }
                                    else {
                                        jQuery(".btn_paystripe").show();
                                        jQuery(".span_chkemail").show();

                                        jQuery(".span_showttl").html(json.fttl);
                                    }
                                }
                                else {
                                    jQuery(".span_topup_msg").html(json.result);
                                    jQuery(".load_esim").hide();

                                    //voucher code
                                    jQuery(".res_vou_status").val(json.vou.discount_status);
                                }
                            },
                            error: function (request, status, error) {
                                jQuery(".span_topup_msg").html("Request timeout. Please Try Search Again. Thank You.");
                                jQuery(".load_esim").hide();
                            }
                        });
                    }
                    else {
                        alert("Please key-in your eSim number. Thank you.");
                    }
                }
                else {
                    jQuery(".load_esim").show();

                    jQuery.ajax({
                        type : "post",
                        url : "<?php echo admin_url( 'admin-ajax.php' ); ?>?t=" + Date.now(),
                        data : {action: "bonvoi_retail_generate_chkesim", p_esim : esim, nonce: nonce, p_voucher: voucher, p_card_opt: card_opt, p_planval: planval, p_proid: proid, cache_buster: Date.now()},
                        success: function(response) {
                            // Check for empty response
                            if(!response || response.trim() === '') {
                                console.error("Empty response detected, redirecting with nocache...");
                                
                                alert("Server busy, please click OK for webpage to refresh. Then try again after refreshed");

                                // Redirect with nocache parameter
                                window.location.href = window.location.pathname + '?nocache=' + Date.now() + '&purge_key=' + cf_nonce;
                                return;
                            }
                            
                            var json = jQuery.parseJSON(response);

                            if(json.status == "pass") {
                                jQuery(".load_esim").hide();

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

                                if(voucher != "" && json.vou.discount_status == "1") {
                                    jQuery(".span_vouchermsg").html("Voucher code successfully applied.");
                                    jQuery(".span_vouchermsg").show();
                                }
                                else if(voucher != "" && json.vou.discount_status == "2") {
                                    jQuery(".span_vouchermsg").html("Invalid voucher code. Voucher code failed to apply. You may continue without voucher code. Thank you.");
                                    jQuery(".span_vouchermsg").show();
                                }
                                else if(voucher != "" && json.vou.discount_status == "3") {
                                    // console.log("show error voucher");
                                    jQuery(".span_vouchermsg").html("Voucher has reached usage limit, you may continue without voucher code. Thank you.");
                                    jQuery(".span_vouchermsg").show();
                                }

                                jQuery(".btn_paystripe").show();
                                jQuery(".span_chkemail").show();

                                jQuery(".span_showttl").html(json.fttl);
                            }
                            else {
                                jQuery(".span_topup_msg").html(json.result);
                                jQuery(".load_esim").hide();

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

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

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

            var planval = jQuery(".ipt_dataplan").val();

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

            var esim_convert = jQuery(".ipt_esim_convert").val();
            var agree_convert = jQuery(".ipt_agree_convert").val();

            fbq('track', 'InitiateCheckout');
            <?php
            // fbq('track', 'InitiateCheckout', {
            //     value: 99.99,              // Payment amount
            //     currency: 'USD',           // Currency
            //     content_ids: ['123'],      // Product IDs
            //     content_type: 'product',
            //     num_items: 1
            // });
            ?>

            if(chkemail === "") {
                alert("Please Enter Your Email Address.");
            }
            else {
                if(!regex.test(chkemail)) {
                    alert("Invalid Email Address.");
                }
                else {
                    jQuery(".load_paystripe").show();
                    jQuery.ajax({
                        type : "post",
                        url : "<?php echo admin_url( 'admin-ajax.php' ); ?>?t=" + Date.now(),
                        data : {action: "bonvoi_retail_generate_chkoutpln", proid : proid, esim: esim, chkemail: chkemail, nonce: nonce, vou_code:vou_code, vou_num:vou_num, vou_status:vou_status, vou_type:vou_type, vou_val:vou_val, card_opt: card_opt, esim_convert: esim_convert, agree_convert: agree_convert, planval:planval, cache_buster: Date.now()},
                        success: function(response) {
                            // Check for empty response
                            if(!response || response.trim() === '') {
                                console.error("Empty response detected, redirecting with nocache...");
                                
                                alert("Server busy, please click OK for webpage to refresh. Then try again after refreshed");

                                // Redirect with nocache parameter
                                window.location.href = window.location.pathname + '?nocache=' + Date.now() + '&purge_key=' + cf_nonce;
                                return;
                            }
                            
                            var json = jQuery.parseJSON(response);

                            if(json.status == "pass") {
                                window.location = json.url;
                            }
                            else {
                                alert("Error, please try again. Thank you.");
                            }
                        }
                    });
                }
            }
        });

        <?php
        if(!empty($param_peo)) {
            if($param_peo == 'new_card') {
                ?>
                jQuery('.new_esim_option').trigger('click');
                <?php
            }
            else if($param_peo == 'existing_card') {
                ?>
                jQuery('.existing_esim_option').trigger('click');
                <?php
            }
        }
        ?>
    });
</script>
<style>
    .through_cls {
        text-decoration: line-through;
    }
    .card_opt_display {
        display:none;
    }
    .topupform .highlinelink {
        color:#7dbae6;
        text-decoration: underline;
    }
    .topupform .loadgif {
        width:12px;
        margin-top:-2px;
        margin-left:5px;
    }
    .topupform .goodnews {
        background: #edfff8;
        border:1px solid #dbf4ea;
        padding:20px 20px;
        margin-bottom:10px;
    }
    .topupform .badnews {
        background: #ffeded;
        border:1px solid #f4dbdb;
        padding:20px 20px;
        margin-bottom:10px;
    }
    .topupform .tpfdiv {
        margin-bottom:20px;
    }
    .topupform .btn_esim {
        margin-bottom:20px;
    }
    .topupform input, .topupform select {
        width:100%;
    }
    .span_vouchermsg {
        display:none;
        color:red;
    }
    /*.span_region, .span_destination, .span_dataplan, .span_chkemail, .btn_paystripe {
        display:none;
    }*/
    .span_chkemail, .btn_paystripe, .span_agreementmsg {
        display:none;
    }
    .load_esim, .load_region, .load_destination, .load_dataplan, .load_paystripe {
        display:none;
    }
    .hidesupportinfoblock {
        display:none;
    }
    .card_text_hide {
        display:none;
    }
    .topupform .infoprice {
        /*margin-top: 30px;
        font-weight: bold;
        font-size: 24px;*/
        font-weight:bold;
        color:#4a86e8;
        font-size: 22px;
    }
    .topupform .woocommerce-Price-amount, .topupform .woocommerce-Price-currencySymbol {
        font-size: 19px !important;
    }
    .topupform .infodesc {
        margin-top:5px;
    }
</style>