(function ($) {

    $('#voucher_bgcolor, #voucher_color, #color_text_voucher').wpColorPicker();

    $('.wpgiftv-row .nav-tab').on('click', function (e) {
        e.preventDefault();
        $('.wpgiftv-row .nav-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');
        var tab = $(this).attr('href');
        $('.wpgiftv-row .tab-content').removeClass('tab-content-active');
        $(tab).addClass('tab-content-active');
    });

})(jQuery);

(function(){
    var container = document.getElementById('wpgv-quotes-list');
    var addBtn = document.getElementById('wpgv-add-quote');
    if(!container || !addBtn){return;}
    addBtn.addEventListener('click', function(){
        var div = document.createElement('div');
        div.className = 'wpgv-quote-row';
        div.style.cssText = 'display:flex;gap:8px;align-items:center;margin-bottom:6px;';
        div.innerHTML = '<input type="text" name="wpgv_quotes_item[]" value="" class="regular-text" style="flex:1;" />' +
                        '<button class="button wpgv-remove-quote" type="button">&times;</button>';
        container.appendChild(div);
    });
    container.addEventListener('click', function(e){
        if(e.target && e.target.classList.contains('wpgv-remove-quote')){
            var row = e.target.closest('.wpgv-quote-row');
            if(row){ row.remove(); }
        }
    });
})();

function redeemVoucher(voucher_id, amount) {
    var voucherAmountInput = jQuery('#voucher_amount' + voucher_id);
    var inputValue = voucherAmountInput.val().trim();

    if (!/^\d+(\.\d{1,2})?$/.test(inputValue)) {
        alert('Please enter a valid number with up to 2 decimal places.');
        voucherAmountInput.focus();
        return;
    }

    var voucher_amount = parseFloat(inputValue);

    if (isNaN(voucher_amount) || voucher_amount <= 0) {
        alert('Please enter a valid amount greater than 0.');
        voucherAmountInput.focus();
        return;
    }

    jQuery("#redeem_Voucher").attr("disabled", true);
    jQuery(".voucher_amount").attr("disabled", true);

    if (amount >= voucher_amount) {
        var data = {
            'action': 'wpgv_redeem_voucher',
            'voucher_id': voucher_id,
            'voucher_amount': voucher_amount
        };

        jQuery.post(ajaxurl, data, function (response) {
            alert('Got this from the server: ' + response);
            location.reload();
        }).fail(function () {
            alert('An error occurred while processing your request. Please try again.');
            jQuery("#redeem_Voucher").attr("disabled", false);
            jQuery(".voucher_amount").attr("disabled", false);
        });
    } else {
        alert('Please enter an amount less than or equal to the remaining balance.');
        jQuery("#redeem_Voucher").attr("disabled", false);
        jQuery(".voucher_amount").attr("disabled", false);
        voucherAmountInput.focus();
    }
}

// admin add gift voucher order

var formVoucher = jQuery("#example-advanced-form").show();

formVoucher.steps({
    headerTag: "h3",
    bodyTag: "fieldset",
    transitionEffect: "slideLeft",
    onStepChanging: function (event, currentIndex, newIndex) {
        // Allways allow previous action even if the current form is not valid!
        if (currentIndex > newIndex) {
            return true;
        }
        // Forbid next action on "Warning" step if the user is to young

        // Needed in some cases if the user went back (clean up)
        if (currentIndex < newIndex) {
            // To remove error styles
            formVoucher.find(".body:eq(" + newIndex + ") label.error").remove();
            formVoucher.find(".body:eq(" + newIndex + ") .error").removeClass("error");
        }
        formVoucher.validate().settings.ignore = ":disabled,:hidden";
        return formVoucher.valid();
    },
    onStepChanged: function (event, currentIndex, priorIndex) {
        if (currentIndex === 2) {
            var template_name = jQuery('input[name=template_id]:checked').data("title");
            jQuery(".wpgv-itemtitle").html(template_name);
        }

        if (currentIndex === 3) {
            jQuery(".wizard .actions a[href='#finish']").hide();
        }
    },
    onFinishing: function (event, currentIndex) {
        formVoucher.validate().settings.ignore = ":disabled";
        return formVoucher.valid();
    },
    onFinished: function (event, currentIndex) {
        alert("Submitted!");
    },
    labels: {
        finish: "finish",
        next: "Continue",
        previous: "Back",
    }
}).validate({
    errorPlacement: function errorPlacement(error, element) { element.after(error); },

});


jQuery("#buying_for_selectbox").change(function () {
    var selected_option = jQuery('#buying_for_selectbox').val();
    if (selected_option == "yourself") {
        jQuery("#shipping_email").val("");
        jQuery("#wpgv-shipping_email").hide();
        jQuery(".shippingasemail").hide();
        jQuery("#buying_for").val("yourself");
        jQuery(".fromname").hide();
        jQuery(".voucherrecipientname").hide();
    } else {
        jQuery("#wpgv-shipping_email").show();
        jQuery(".shippingasemail").show();
        jQuery("#buying_for").val("someone_else");
        jQuery(".fromname").show();
        jQuery(".voucherrecipientname").show();
    }
});

jQuery("#shipping_selectbox").change(function () {
    var selected_option = jQuery('#shipping_selectbox').val();
    if (selected_option == "shipping_as_email") {
        var buuing_for_val = jQuery("#buying_for_selectbox").val();
        if (buuing_for_val == "yourself") {
            jQuery("#shipping_email").val("");
            jQuery("#wpgv-shipping_email").hide();
            jQuery(".shippingasemail").hide();
        } else {
            jQuery("#wpgv-shipping_email").show();
            jQuery(".shippingasemail").show();
        }

        jQuery(".shipping_as_post_fields").hide();
        jQuery(".order_details_preview .wpgv_shipping_box").hide();
        var $website_commission_price = jQuery('#website_commission_price');
        var voucher_value = jQuery("#voucherAmount").val();
        var totalprice = parseFloat(voucher_value) + parseFloat($website_commission_price.data('price'));
        jQuery("#totalprice span").html(totalprice);
        jQuery(".voucherShippingInfo").html("Shipping via Email");
        jQuery("#shipping").val("shipping_as_email");
    } else {
        jQuery("#shipping_email").val("");
        jQuery("#wpgv-shipping_email").hide();
        jQuery(".shippingasemail").hide();
        jQuery(".shipping_as_post_fields").show();
        jQuery(".order_details_preview .wpgv_shipping_box").show();
        var shipping_price = jQuery('input[name=shipping_method]:checked').data("price");
        var shipping_string_value = jQuery('input[name=shipping_method]:checked').val();
        var $website_commission_price = jQuery('#website_commission_price');
        var voucher_value = jQuery("#voucherAmount").val();
        var totalprice = parseFloat(voucher_value) + parseFloat(shipping_price) + parseFloat($website_commission_price.data('price'));
        jQuery("#shippingprice span").html(shipping_price);
        jQuery("#totalprice span").html(totalprice);
        jQuery(".voucherShippingInfo").html("Shipping via Post");
        jQuery(".voucherShippingMethodInfo").html(shipping_string_value);
        jQuery("#shipping").val("shipping_as_post");
    }
});

jQuery('#voucherForName').on('input blur', function () {
    var dInput = this.value;
    jQuery("#autoyourname").html(dInput);
    jQuery(".voucherYourNameInfo").html(dInput);
});

jQuery('#voucherFromName').on('input blur', function () {
    var dInput = this.value;
    jQuery(".voucherReceiverInfo").html(dInput);
});

jQuery('#voucherAmount').on('input blur', function () {
    var dInput = this.value;
    var $website_commission_price = jQuery('#website_commission_price');
    var totalprice = parseFloat(dInput) + parseFloat($website_commission_price.data('price'));
    jQuery("#itemprice span").html(dInput);
    jQuery("#totalprice span").html(totalprice);
    jQuery(".voucherAmountInfo b").html(dInput);
});

jQuery('#voucherMessage').on('input blur', function () {
    var dInput = this.value;
    jQuery(".voucherMessageInfo").html(dInput);
});

jQuery("input[name=shipping_method]").change(function () {
    var shipping_price = jQuery('input[name=shipping_method]:checked').data("price");
    var shipping_string_value = jQuery('input[name=shipping_method]:checked').val();
    var $website_commission_price = jQuery('#website_commission_price');
    var voucher_value = jQuery("#voucherAmount").val();
    var totalprice = parseFloat(voucher_value) + parseFloat(shipping_price) + parseFloat($website_commission_price.data('price'));
    jQuery("#shippingprice span").html(shipping_price);
    jQuery("#totalprice span").html(totalprice);
    jQuery(".voucherShippingMethodInfo").html(shipping_string_value);
});

jQuery('#voucherFirstName').on('input blur', function () {
    var dInput = this.value;
    jQuery(".voucherFirstNameInfo").html(dInput);
});
jQuery('#voucherLastName').on('input blur', function () {
    var dInput = this.value;
    jQuery(".voucherLastNameInfo").html(dInput);
});
jQuery('#voucherEmail').on('input blur', function () {
    var dInput = this.value;
    jQuery(".voucherEmailInfo").html(dInput);
});
jQuery('#shipping_email').on('input blur', function () {
    var dInput = this.value;
    jQuery(".voucherShippingEmailInfo").html(dInput);
});
jQuery('#voucherAddress').on('input blur', function () {
    var dInput = this.value;
    jQuery(".voucherAddressInfo").html(dInput);
});
jQuery('#voucherPincode').on('input blur', function () {
    var dInput = this.value;
    jQuery(".voucherPincodeInfo").html(dInput);
});

if (jQuery('#coupon_code_length').length) {

    var numberlenght = jQuery('#coupon_code_length').val()
    var stringlenght = '1';
    var stringlenght1 = '9';
    for (var i = 0; i < numberlenght - 1; i++) {
        stringlenght += 0
        stringlenght1 += 0
    }
    stringlenght = parseFloat(stringlenght);
    stringlenght1 = parseFloat(stringlenght1);
    jQuery('.codeCard').val(Math.floor(stringlenght + Math.random() * stringlenght1));
}

jQuery('#voucherPaymentButton').on('click', function () {
    var $button = jQuery(this); // Store a reference to the button

    // Check if the button is already disabled to prevent multiple submissions
    if ($button.prop('disabled')) {
        return false; // Or just return;
    }

    // Disable the button and change its text (optional)
    $button.prop('disabled', true);
    var originalButtonText = $button.text(); // Save the original button text
    $button.text('Processing...'); // Change the text to inform the user

    var nonce = jQuery('input[name=voucher_form_verify]').val(),
        templates_id = wpgv_b64EncodeUnicode(jQuery('input[name=template_id]:checked').val()),
        buying_for = wpgv_b64EncodeUnicode(jQuery('#buying_for').val()),
        forName = wpgv_b64EncodeUnicode(jQuery('#voucherForName').val()),
        fromName = wpgv_b64EncodeUnicode(jQuery('#voucherFromName').val()),
        voucherValue = wpgv_b64EncodeUnicode(jQuery('#itemprice span').html()),
        message = wpgv_b64EncodeUnicode(jQuery('#voucherMessage').val()),
        shipping = wpgv_b64EncodeUnicode(jQuery('#shipping').val()),
        shipping_email = wpgv_b64EncodeUnicode(jQuery('#shipping_email').val()),
        firstName = wpgv_b64EncodeUnicode(jQuery('#voucherFirstName').val()),
        lastName = wpgv_b64EncodeUnicode(jQuery('#voucherLastName').val()),
        email = wpgv_b64EncodeUnicode(jQuery('#voucherEmail').val()),
        address = wpgv_b64EncodeUnicode(jQuery('#voucherAddress').val()),
        pincode = wpgv_b64EncodeUnicode(jQuery('#voucherPincode').val()),
        shipping_method = wpgv_b64EncodeUnicode(jQuery('input[name=shipping_method]:checked').val()),
        expiry = wpgv_b64EncodeUnicode(jQuery('.expiryCard').val()),
        style = wpgv_b64EncodeUnicode(jQuery('#chooseStyle').val()),
        code = wpgv_b64EncodeUnicode(jQuery('.codeCard').val());

    jQuery.ajax({
        url: ajaxurl,
        type: "POST",
        data: {
            action: 'admin_wpgv_doajax_voucher_pdf_save_func',
            nonce: nonce,
            template: templates_id,
            buying_for: buying_for,
            for: forName,
            from: fromName,
            value: voucherValue,
            message: message,
            expiry: expiry,
            code: code,
            shipping: shipping,
            shipping_email: shipping_email,
            firstname: firstName,
            lastname: lastName,
            email: email,
            address: address,
            pincode: pincode,
            shipping_method: shipping_method,
            style: style
        },
        success: function (response) {
            try {
                var data = jQuery.parseJSON(response);
                if (data.status == 1) {
                    window.location.replace(data.url);
                    // No need to re-enable the button here because the page will be reloaded/redirected
                    // If the redirect fails, the 'complete' callback will still run
                } else {
                    alert("Error in adding gift voucher order: " + (data.message || "Unknown error"));
                    // The button will be re-enabled in 'complete'
                }
            } catch (e) {

                alert("An error occurred while processing your request. Invalid server response.");
                // The button will be re-enabled in 'complete'
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // Handle AJAX errors (e.g., network error, server error 500, etc.)
            alert("A network or server error occurred. Please try again.");
            // The button will be re-enabled in 'complete'
        },
        complete: function () {
            // This callback will always be called after 'success' or 'error'
            // Only re-enable the button if the page is not redirected
            // (Actually, if there's a redirect, this code on the current page might not run
            // or have a visible effect because the page is navigating away)
            // However, it's crucial for error cases or when there's no redirect.

            var responseData;
            try {
                // arguments[0] is the jqXHR object in the complete callback
                responseData = jQuery.parseJSON(arguments[0].responseText);
            } catch (e) {
                responseData = null;
            }

            // Re-enable the button if there was no successful redirect
            if (!(responseData && responseData.status == 1 && responseData.url)) {
                $button.prop('disabled', false);
                $button.text(originalButtonText); // Restore the original text
            }
            // If the redirect was successful, the button on the new page will be in its default state.
        }
    });
});

function wpgv_b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
        return String.fromCharCode(parseInt(p1, 16))
    }))
}

function wpgv_b64DecodeUnicode(str) {
    return decodeURIComponent(Array.prototype.map.call(atob(str), function (c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
    }).join(''))
}

jQuery(document).ready(function ($) {

    const $codeTypeSelect = $('#coupon_code_type');
    const $codeLengthInput = $('#coupon_code_length');
    const $startInput = $('#starting_coupon_number');
    const $currentInput = $('#current_coupon_number');
    const $startNotice = $('#starting_notice');
    const $currentNotice = $('#current_notice');

    function toggleRequiredAndConstraints() {
        const codeType = $codeTypeSelect.val();
        const len = parseInt($codeLengthInput.val());
        const isIncremental = codeType === 'incremental';
        const mustValidate = isIncremental && len === 8;

        if (mustValidate) {
            $startInput.attr('required', true);
        } else {
            $startInput.removeAttr('required');
            $startNotice.hide().text('');
        }

        $currentInput.removeAttr('required');
        $currentNotice.hide().text('');

        updateInputConstraints(mustValidate);
    }

    function updateInputConstraints(validateStart) {
        const len = parseInt($codeLengthInput.val());
        if (!isNaN(len)) {
            const pattern = '\\d{' + len + '}';
            const min = String(1).padStart(len, '0');
            const max = ''.padStart(len, '9');

            $startInput.attr({
                maxlength: len,
                pattern: pattern,
                min: min,
                max: max,
                placeholder: $startInput.val().length !== len ? min : $startInput.attr('placeholder')
            });

            $currentInput.attr({
                maxlength: len,
                pattern: pattern,
                min: min,
                max: max,
                placeholder: $currentInput.val().length !== len ? min : $currentInput.attr('placeholder')
            });

            if (validateStart) {
                validateStartInput(len);
            }

            validateCurrentInput(len);
        }
    }

    function validateStartInput(len) {
        const val = $startInput.val().trim();
        const regex = new RegExp('^\\d{' + len + '}$');
        const zeroString = '0'.repeat(len);

        if (val === '') {
            $startNotice.text('This field is required.').show();
        } else if (!regex.test(val)) {
            $startNotice.text('Must be exactly ' + len + ' digits.').show();
        } else if (val === zeroString) {
            $startNotice.text('Cannot be all zeros (e.g., ' + zeroString + ').').show();
        } else if (val.charAt(len - 1) === '0') {
            $startNotice.text('Last digit cannot be 0.').show();
        } else {
            $startNotice.hide().text('');
        }
    }

    function validateCurrentInput(len) {
        const val = $currentInput.val().trim();
        const regex = new RegExp('^\\d{' + len + '}$');
        const zeroString = '0'.repeat(len);

        if (val === '') {
            $currentNotice.hide().text('');
            return;
        }

        if (!regex.test(val)) {
            $currentNotice.text('Must be exactly ' + len + ' digits.').show();
        } else if (val === zeroString) {
            $currentNotice.text('Cannot be all zeros (e.g., ' + zeroString + ').').show();
        } else if (val.charAt(len - 1) === '0') {
            $currentNotice.text('Last digit cannot be 0.').show();
        } else {
            $currentNotice.hide().text('');
        }
    }

    toggleRequiredAndConstraints();

    $codeTypeSelect.on('change', toggleRequiredAndConstraints);
    $codeLengthInput.on('input', toggleRequiredAndConstraints);

    $startInput.on('input', function () {
        const codeType = $codeTypeSelect.val();
        const len = parseInt($codeLengthInput.val());
        if (codeType === 'incremental' && len === 8) {
            validateStartInput(len);
        } else {
            $startNotice.hide().text('');
        }
    });

    $currentInput.on('input', function () {
        const len = parseInt($codeLengthInput.val());
        if (!isNaN(len)) {
            validateCurrentInput(len);
        } else {
            $currentNotice.hide().text('');
        }
    });



    // event upload logo company voucher_setting.php
    jQuery('.upload_logo_voucher').click(function (e) {
        e.preventDefault();
        var mediaUploader = wp.media({
            title: 'Add Voucher Logo',
            button: {
                text: 'Upload Logo'
            },
            multiple: false // Set this to true to allow multiple files to be selected
        })
            .on('select', function () {
                var attachment = mediaUploader.state().get('selection').first().toJSON();
                var urlLogo = attachment.url;
                jQuery('.image_src_logo').attr('src', attachment.url).show();
                jQuery('#company_logo_voucher').attr('value', urlLogo)
                jQuery('#remove_logo_voucher').show();
            })
            .open();
    });
    // event upload logo company voucher_setting.php

    // get parameter from url
    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
    // get parameter from url

    var jsontemplate;
    var pngtemplate;
    var getlogocompany;
    var stage = null;
    var get_action = getParameterByName('action');
    var resize_logo = null;

    // Global variables for barcode checking
    var currentTemplateForBarcode = null;
    var shouldCheckBarcode = false;

    function isValidUrl(string) {
        try {
            new URL(string);
            return true;
        } catch (e) {
            return false;
        }
    }

    // Function to check if fonts are loaded
    function checkFontsLoaded(callback) {
        if (document.fonts && document.fonts.ready) {
            document.fonts.ready.then(function() {
                // Fonts are loaded, wait a bit more for rendering
                setTimeout(callback, 300);
            });
        } else {
            // Fallback for older browsers
            setTimeout(callback, 1000);
        }
    }

    function getJsonTemplate(getjson, getpng, getlogo) {
        if (!getjson && !getpng && !getlogo) return;

        var dataJson = null;

        function fetchData(callback) {
            if (typeof getjson == 'object') {
                dataJson = getjson;
                callback();
            } else if (typeof getjson == 'string' && isValidUrl(getjson)) {
                $.getJSON(getjson, function (json) {
                    dataJson = json;
                    callback();
                }).fail(function () {
                    console.error('Error fetching JSON');
                });
            } else if (typeof getjson == 'string' && !isValidUrl(getjson)) {
                const parsedJson = safeJsonParse(getjson);
                dataJson = parsedJson;
                callback();
            }
        }

        fetchData(function () {
            if (dataJson) {
                initializeTemplate(dataJson, getpng, getlogo);
                // Ensure stage is fully rendered after initialization
                setTimeout(function() {
                    if (typeof stage !== 'undefined') {
                        stage.draw();
                    }
                }, 500);
            }
        });
    }

    function processJsonTemplate(jsontemplate) {
        let jsongiftcard = {};

        if (typeof jsontemplate === 'object') {
            jsongiftcard = jsontemplate;
            updateInputsFromJson(jsongiftcard);
        } else if (typeof jsontemplate === 'string' && isValidUrl(jsontemplate)) {
            $.getJSON(jsontemplate, function (json) {
                jsongiftcard = json;
                updateInputsFromJson(jsongiftcard);
            }).fail(function () {
                console.error('Error fetching JSON');
            });
        } else if (typeof jsontemplate === 'string' && !isValidUrl(jsontemplate)) {
            try {
                jsongiftcard = safeJsonParse(jsontemplate);
                updateInputsFromJson(jsongiftcard);
            } catch (e) {
                console.error('Error parsing JSON string:', e);
            }
        } else {
            console.error('Invalid data format.');
        }
    }

    function updateInputsFromJson(data) {
        const fields = [
            { id: "giftfrom_label", inputId: "#edit_gift_from" },
            { id: "giftfrom_input", inputId: "#edit_giftform_temp" },
            { id: "giftto_label", inputId: "#edit_gift_to" },
            { id: "giftto_input", inputId: "#edit_giftto_temp" },
            { id: "giftto_input", inputId: "#edit_giftto_temp" },
            { id: "giftcard_des", inputId: "#edit_desc_temp" },
            { id: "gift_title_first", inputId: "#edit_title_voucher_first" },
            { id: "gift_title_last", inputId: "#edit_title_voucher_last" },
            { id: "gift_title_end", inputId: "#edit_title_voucher_end" },
            { id: "giftcard_monney", inputId: "#edit_gift_value" },
            { id: "giftcard_date_gift_label", inputId: "#edit_date_gift_label" },
            { id: "giftcard_counpon_label", inputId: "#edit_counpon_label" },
        ];

        fields.forEach(field => {
            $(field.inputId).hide();
            const fieldData = data.children[0].children.find(child => child.attrs.id === field.id);
            if (fieldData && fieldData.attrs.text) {
                $(field.inputId).val(fieldData.attrs.text);
                $(field.inputId).show();
            }
        });
        const canvasDimensions = data.attrs;
        if (canvasDimensions) {
            $('.wpgv_gift_card_size').hide();
            const width = Math.round(canvasDimensions.width || 0);
            const height = Math.round(canvasDimensions.height || 0);
            if (width && height) {
                $('.wpgv_gift_card_size').show();
                $('.wpgv_gift_card_size').html(`Width: ${width}px, Height: ${height}px`);
            }

        }
    }




    function initializeTemplate(dataJson, getpng, getlogo) {

        if (dataJson != null || getpng != null || getlogo != null) {
            data = dataJson;
            var get_plus_day = jQuery("#voucher_expiry_value").val();
            var someDate = new Date();
            someDate.setDate(someDate.getDate() + parseInt(get_plus_day));
            var dateFormated = someDate.toISOString().substr(0, 10);
            var dateAr = dateFormated.split('-');
            var newDate = dateAr[2] + '.' + dateAr[1] + '.' + dateAr[0].slice(-2);
            // Counpon number random 8 digits
            counpon = (Math.random() + ' ').substring(2, 10);

            var htmlJson = JSON.stringify(data);
            // get json template for input json_template
            jQuery('#json_template').attr('value', htmlJson);
            jQuery('#json_template').attr('data-json-template', htmlJson);
            stage = Konva.Node.create(data, 'container-template-chosse-template');
            stageWidth = stage.getAttr('width');
            stageHeight = stage.getAttr('height');

            // add background template
            if (pngtemplate !== "") {
                const stageWidth = stage.getAttr('width');
                const stageHeight = stage.getAttr('height');

                stage.find('#giftcard_bg').forEach(imageNode => {
                    const nativeImage = new window.Image();
                    nativeImage.onload = () => {
                        const imageAspectRatio = nativeImage.width / nativeImage.height;
                        const stageAspectRatio = stageWidth / stageHeight;
                        let newWidth, newHeight;

                        if (imageAspectRatio > stageAspectRatio) {
                            newHeight = stageHeight;
                            newWidth = stageHeight * imageAspectRatio;
                        } else {
                            newWidth = stageWidth;
                            newHeight = stageWidth / imageAspectRatio;
                        }

                        const x = (stageWidth - newWidth) / 2;
                        const y = (stageHeight - newHeight) / 2;

                        imageNode.image(nativeImage);
                        imageNode.width(newWidth);
                        imageNode.height(newHeight);
                        imageNode.x(x);
                        imageNode.y(y);

                        imageNode.getLayer().batchDraw();
                    };

                    nativeImage.src = getpng;
                });
            }

            // add background template

            //add logo template

            if (typeof stage.find('#giftcard_logo')[0] !== 'undefined') {
                stage.find('#giftcard_logo').forEach(imageNode => {
                    const nativeImage = new window.Image();
                    nativeImage.onload = () => {
                        imageNode.image(nativeImage);
                        var maxWidth = 40;
                        var maxHeight = 40;
                        var ratio = 0;
                        var width = nativeImage.width;
                        var height = nativeImage.height;

                        if (width > maxWidth) {
                            ratio = maxWidth / width;
                            height = height * ratio;
                            width = width * ratio;
                        }
                        // Check if current height is larger than max
                        if (height > maxHeight) {
                            ratio = maxHeight / height;
                            width = width * ratio;
                            height = height * ratio;
                        }
                        imageNode.width(width);
                        imageNode.height(height);
                        imageNode.getLayer().batchDraw();
                        imageNode.draggable(true);

                        // Force stage redraw after logo loads
                        setTimeout(function() {
                            if (typeof stage !== 'undefined') {
                                stage.draw();
                            }
                        }, 100);
                    }
                    nativeImage.src = getlogo;
                    style_cursor_pointer(stage.find('#giftcard_logo')[0]);
                });

                // Resize logo
                var layer = new Konva.Layer();
                stage.add(layer);
                var MAX_WIDTH = 100;
                var resize_logo = new Konva.Transformer({
                    boundBoxFunc: function (oldBoundBox, newBoundBox) {
                        if (Math.abs(newBoundBox.width) > MAX_WIDTH) {
                            return oldBoundBox;
                        }

                        return newBoundBox;
                    },
                });
                layer.add(resize_logo);


                var selectionRectangle = new Konva.Rect({
                    fill: 'rgba(255,255,255,1)',
                    stroke: 'black',
                    draggable: true,
                    visible: false,
                });
                layer.add(selectionRectangle);
                var scale_after = stage.find('#giftcard_logo')[0].scaleX();
                var scale_before = null;
                resize_logo.on('transformend', function () {
                    scale_before = stage.find('#giftcard_logo')[0].scaleX();
                    if (scale_after != scale_before) {
                        jQuery('#check_temp_custom').attr('value', "1");
                        stage.draw();
                        var json = stage.toJSON();
                        jQuery("#json_template").attr('value', json);
                    }
                });


                $("body").click((event) => {
                    if (!$(event.target).closest('#container-template-chosse-template').length) {
                        resize_logo.nodes([]);
                        return;
                    }
                });

                stage.on('click', function (e) {

                    if (selectionRectangle.visible()) {
                        return;
                    }
                    if (e.target.hasName('giftcard_logo')) {
                        resize_logo.nodes([e.target]);

                    } else {
                        resize_logo.nodes([]);
                        return;
                    }

                });

            }
            //add logo template

            function makeDraggableAndUpdate(id) {
                var element = stage.find(id)[0];
                if (typeof element !== 'undefined') {
                    element.draggable(true);
                    style_cursor_pointer(element);
                    element.on('dragmove', function () {
                        jQuery('#check_temp_custom').attr('value', "1");
                        stage.draw();
                        var json = stage.toJSON();
                        jQuery("#json_template").attr('value', json);
                    });
                    stage.draw();
                }
            }


            // Use the makeDraggableAndUpdate function for elements that need to be draggable
            makeDraggableAndUpdate('#gift_title_first');
            makeDraggableAndUpdate('#gift_title_last');
            makeDraggableAndUpdate('#gift_title_end');

            // Picker color all text
            var colorVoucher = '#000';
            jQuery('#color_text_voucher').iris({
                defaultColor: true,
                change: function (event, ui) {
                    colorVoucher = ui.color.toString();
                    jQuery(".wp-color-result.wp-picker-open").attr("style", "background-color:" + colorVoucher);
                    updateFillColor();
                    jQuery('#check_temp_custom').attr('value', "1");
                },
                clear: function () { },
                hide: true,
                palettes: true
            });

            // function add style cursor pointer to text
            function style_cursor_pointer(get_element_by_id) {
                get_element_by_id.on('mouseover', function () {
                    document.body.style.cursor = 'move';
                });
                get_element_by_id.on('mouseout', function () {
                    document.body.style.cursor = 'default';
                });
            }
            // function add style cursor pointer to text

            // update color name voucher
            function updateFillColorNameVoucher() {
                var gift_title_first = stage.find('#gift_title_first')[0];
                if (typeof gift_title_first !== 'undefined') {
                    gift_title_first.fill(colorVoucher);
                }
                var gift_title_last = stage.find('#gift_title_last')[0];
                if (typeof gift_title_last !== 'undefined') {
                    gift_title_last.fill(colorVoucher);
                }
                var gift_title_end = stage.find('#gift_title_end')[0];
                if (typeof gift_title_end !== 'undefined') {
                    gift_title_end.fill(colorVoucher);
                }
                stage.draw();
                var json = stage.toJSON();
                jQuery("#json_template").attr('value', json);
            }
            // update color price
            function updateFillColorPrice() {
                var giftcard_monney = stage.find('#giftcard_monney')[0];
                if (typeof giftcard_monney !== 'undefined') {
                    giftcard_monney.fill(colorVoucher);
                }
                var giftcard_monney_label_color = stage.find('#giftcard_monney_label')[0];
                if (typeof giftcard_monney_label_color !== 'undefined') {
                    giftcard_monney_label_color.fill(colorVoucher);
                }
                stage.draw();
                var json = stage.toJSON();
                jQuery("#json_template").attr('value', json);
            }
            // Update colors for all text elements
            function updateFillColor() {
                var elementIds = [
                    '#gift_title_company', '#giftfrom_input', '#giftfrom_label',
                    '#giftto_input', '#giftto_label', '#giftcard_date_gift_input',
                    '#giftcard_date_gift_label', '#giftcard_counpon', '#giftcard_counpon_label',
                    '#giftcard_des', '#giftcard_email', '#giftcard_website', '#giftcard_note', '#gift_title_first', '#giftcard_monney', '#gift_title_last', '#gift_title_end'
                ];

                elementIds.forEach(function (id) {
                    var element = stage.find(id)[0];
                    if (typeof element !== 'undefined') {
                        element.fill(colorVoucher);
                    }
                });

                stage.draw();
                var json = stage.toJSON();
                jQuery("#json_template").attr('value', json);
            }


            // List of draggable elements
            var draggableElements = [
                '#giftcard_note',
                '#gift_title_first',
                '#gift_title_last',
                '#giftcard_monney_label',
                '#giftto_input',
                '#giftfrom_input',
                '#giftcard_date_gift_input',
                '#giftcard_email',
                '#giftcard_website',
                '#gift_title_company',
                '#giftcard_counpon',
                '#giftcard_monney',
                '#giftcard_monney_label',
                '#giftcard_des',
                '#giftfrom_label',
                '#giftto_label',
                '#giftcard_date_gift_label',
                '#giftcard_counpon_label',
                '#giftcard_logo',
                '#giftto',
                '#giftfrom',
                '#giftdate',
                '#giftemail',
                '#giftwebsite',
                '#gifttitlecompany',
                '#giftcoupon',
                '#giftmonney',
                '#giftdes',
                '#giftfrom_label',
                '#giftto_label',
                '#giftdate_label',
                '#giftcoupon_label',
                '#giftcard_monney_label'
            ];

            // Function to handle the dragmove event for each draggable element
            function handleDragMove(element) {
                jQuery('#check_temp_custom').attr('value', "1");
                stage.draw();
                var json = stage.toJSON();
                jQuery("#json_template").attr('value', json);
            }

            // Loop through each selector, find element, make it draggable, and add event listener
            draggableElements.forEach(function (selector) {
                var element = stage.find(selector)[0];
                if (element !== undefined) {
                    element.draggable(true);
                    style_cursor_pointer(element);
                    element.on('dragmove', function () {
                        handleDragMove(element);
                    });
                }
            });


            function handleFieldChange(selector, targetSelector) {
                $(selector).on('change keyup', function () {
                    if (typeof stage.find(targetSelector)[0] !== 'undefined') {
                        var changeElement = stage.find(targetSelector)[0];
                        var sanitizedValue = sanitizeJsonInput(jQuery(this).val());
                        jQuery(this).val(sanitizedValue);

                        // Delay để đợi font loading và metrics calculation
                        setTimeout(function() {
                            changeElement.text(sanitizedValue);
                            stage.draw();

                            // Force re-render để đảm bảo font metrics được tính toán đúng
                            setTimeout(function() {
                                var originalText = changeElement.text();
                                // Trigger re-calculation bằng cách thêm/xóa space
                                changeElement.text(originalText + ' ');
                                changeElement.text(originalText);
                                stage.draw();

                                var json = stage.toJSON();
                                jQuery("#json_template").attr('value', json);
                                jQuery('#check_temp_custom').attr('value', "1");
                            }, 50); // Delay 50ms trong force re-render

                        }, 100); // Delay 100ms để đợi browser tính toán font metrics
                    }
                });
            }


            handleFieldChange('#edit_gift_value', '#giftcard_monney');
            handleFieldChange('#edit_title_voucher_first', '#gift_title_first');
            handleFieldChange('#edit_title_voucher_last', '#gift_title_last');
            handleFieldChange('#edit_title_voucher_end', '#gift_title_end');
            handleFieldChange('#edit_gift_to', '#giftto_label');
            handleFieldChange('#edit_gift_from', '#giftfrom_label');
            handleFieldChange('#edit_giftto_temp', '#giftto_input');
            handleFieldChange('#edit_giftform_temp', '#giftfrom_input');
            handleFieldChange('#edit_desc_temp', '#giftcard_des');
            handleFieldChange('#edit_name_v1_temp', '#gift_title_first');
            handleFieldChange('#edit_name_v2_temp', '#gift_title_last');
            handleFieldChange('#edit_date_gift_label', '#giftcard_date_gift_label');
            handleFieldChange('#edit_counpon_label', '#giftcard_counpon_label');

            // validation form
            jQuery('#modal_edit_template #edit_desc_temp').on('keydown', function (e) {
                newLines = jQuery(this).val().split("\n").length;
                jQuery('#modal_edit_template .group_input_edit_temp .maxchar').html("Total Characters:: " + (this.value.length));
                if ((e.keyCode == 13 && newLines >= 3) || (e.keyCode != 8 && this.value.length > 250)) {
                    return false;
                }
            });
            jQuery('#modal_edit_template #edit_name_v1_temp').on('keydown', function (e) {
                newLines = jQuery(this).val().split("\n").length;
                jQuery('#modal_edit_template .group_input_edit_temp .maxchar_name_v1').html("Total Characters:: " + (this.value.length));
                if ((e.keyCode == 13 && newLines >= 3) || (e.keyCode != 8 && this.value.length > 20)) {
                    return false;
                }
            });
            jQuery('#modal_edit_template #edit_name_v2_temp').on('keydown', function (e) {
                newLines = jQuery(this).val().split("\n").length;
                jQuery('#modal_edit_template .group_input_edit_temp .maxchar_name_v2').html("Total Characters:: " + (this.value.length));
                if ((e.keyCode == 13 && newLines >= 3) || (e.keyCode != 8 && this.value.length > 20)) {
                    return false;
                }
            });
            jQuery('#modal_edit_template #edit_giftform_temp').on('keydown', function (e) {
                if (e.keyCode != 8 && this.value.length > 20 && e.keyCode != 46) {
                    return false;
                }
            });
            jQuery('#modal_edit_template #edit_giftto_temp').on('keydown', function (e) {
                if (e.keyCode != 8 && this.value.length > 20 && e.keyCode != 46) {
                    return false;
                }
            });

            // validation form

            // Delay để đợi font loading và metrics calculation
            setTimeout(function() {
                // check input undefined
                if (typeof stage.find('#giftcard_counpon')[0] !== 'undefined') {
                    var giftcard_counpon_label = stage.find('#giftcard_counpon')[0];
                    giftcard_counpon_label.text(counpon);

                    // Force re-render để đảm bảo font metrics được tính toán đúng
                    setTimeout(function() {
                        var originalText = giftcard_counpon_label.text();
                        giftcard_counpon_label.text(originalText + ' ');
                        giftcard_counpon_label.text(originalText);
                        stage.draw();
                    }, 50);
                }
                if (typeof stage.find('#giftcard_date_gift_input')[0] !== 'undefined') {
                    var stage_date = stage.find('#giftcard_date_gift_input')[0];
                    stage_date.text(newDate);

                    // Force re-render để đảm bảo font metrics được tính toán đúng
                    setTimeout(function() {
                        var originalText = stage_date.text();
                        stage_date.text(originalText + ' ');
                        stage_date.text(originalText);
                        stage.draw();
                    }, 50);
                }
            }, 100); // Delay 100ms để đợi browser tính toán font metrics

            // Delay để đợi font loading và metrics calculation cho các input fields
            setTimeout(function() {
                var get_input_giftto = jQuery('#edit_giftto_temp').val();
                if (get_input_giftto.length > 0) {
                    if (typeof stage.find('#giftto_input')[0] !== 'undefined') {
                        var check_giftto = stage.find('#giftto_input')[0];
                        check_giftto.text(get_input_giftto);

                        // Force re-render để đảm bảo font metrics được tính toán đúng
                        setTimeout(function() {
                            var originalText = check_giftto.text();
                            check_giftto.text(originalText + ' ');
                            check_giftto.text(originalText);
                            stage.draw();
                        }, 50);
                    }
                }
                var get_input_giftfrom = jQuery('#edit_giftform_temp').val();
                if (get_input_giftfrom.length > 0) {
                    if (typeof stage.find('#giftfrom_input')[0] !== 'undefined') {
                        var check_giftfrom = stage.find('#giftfrom_input')[0];
                        check_giftfrom.text(get_input_giftfrom);

                        // Force re-render để đảm bảo font metrics được tính toán đúng
                        setTimeout(function() {
                            var originalText = check_giftfrom.text();
                            check_giftfrom.text(originalText + ' ');
                            check_giftfrom.text(originalText);
                            stage.draw();
                        }, 50);
                    }
                }
                var get_input_giftdes = jQuery('#edit_desc_temp').val();
                if (get_input_giftdes.length > 0) {
                    if (typeof stage.find('#giftcard_des')[0] !== 'undefined') {
                        var check_giftdes = stage.find('#giftcard_des')[0];
                        check_giftdes.text(get_input_giftdes);

                        // Force re-render để đảm bảo font metrics được tính toán đúng
                        setTimeout(function() {
                            var originalText = check_giftdes.text();
                            check_giftdes.text(originalText + ' ');
                            check_giftdes.text(originalText);
                            stage.draw();
                        }, 50);
                    }
                }
                if (typeof stage.find('#giftcard_email')[0] !== 'undefined') {
                    var stageEmail = stage.find('#giftcard_email')[0];
                    stageEmail.text(jQuery("#get_name_email").val());

                    // Force re-render để đảm bảo font metrics được tính toán đúng
                    setTimeout(function() {
                        var originalText = stageEmail.text();
                        stageEmail.text(originalText + ' ');
                        stageEmail.text(originalText);
                        stage.draw();
                    }, 50);
                }

                if (typeof stage.find('#giftcard_website')[0] !== 'undefined') {
                    var stageWebsite = stage.find('#giftcard_website')[0];
                    stageWebsite.text(jQuery("#get_name_site").val());

                    // Force re-render để đảm bảo font metrics được tính toán đúng
                    setTimeout(function() {
                        var originalText = stageWebsite.text();
                        stageWebsite.text(originalText + ' ');
                        stageWebsite.text(originalText);
                        stage.draw();
                    }, 50);
                }
                if (typeof stage.find('#gift_title_company')[0] !== 'undefined') {
                    var stage_title_company = stage.find('#gift_title_company')[0];
                    stage_title_company.text(jQuery("#get_company_name").val());

                    // Force re-render để đảm bảo font metrics được tính toán đúng
                    setTimeout(function() {
                        var originalText = stage_title_company.text();
                        stage_title_company.text(originalText + ' ');
                        stage_title_company.text(originalText);
                        stage.draw();
                    }, 50);
                }
            }, 150); // Delay 150ms để đợi browser tính toán font metrics
            // Delay cuối cùng để đảm bảo tất cả fonts đã được render đúng
            setTimeout(function() {
                // Force re-render tất cả text elements một lần nữa
                stage.find('Text').forEach(function(textNode) {
                    var originalText = textNode.text();
                    textNode.text(originalText + ' ');
                    textNode.text(originalText);
                });
                stage.draw();

                // Tạo dataURL sau khi đã đảm bảo fonts được render đúng
                var dataURL = stage.toDataURL({
                    pixelRatio: 1
                });
                addImagesGiftCard(dataURL);
            }, 200); // Delay 200ms để đảm bảo tất cả fonts đã sẵn sàng

            // Check and add barcode if needed (after stage is fully set up)
            setTimeout(function() {
                checkAndAddBarcode(dataJson);
            }, 300);
        }
    }

    // Add image loading + Before event ajax change value get_chosse_temp = lanscape or portail
    function getDataChosse() {
        jQuery("#wpgv_trigger_template").css("pointer-events", "none");
        jQuery(".wpgv_select_style_temp:checked").closest("label").addClass("wpgv_loading_temp");
        if (typeof jQuery(".wpgv_select_style_temp:checked").attr("data-chosse") != "undefined") {
            var data_chosse = jQuery(".wpgv_select_style_temp:checked").attr("data-chosse");
            jQuery("#get_chosse_temp").attr("value", data_chosse);
        } else {
            var chosse_template = jQuery("#chosse_template:checked").attr("value");
            jQuery("#get_chosse_temp").attr("value", chosse_template);
            var get_value_data_checked = jQuery("input[name=chosse_template]:checked").attr('data-checked');
            if (get_value_data_checked == "1") {
                var get_json_data = jQuery("#get_json_db").val();
                jQuery("#json_template").attr('value', get_json_data);

            }
        }
    }
    // Add image loading + Before event ajax change value get_chosse_temp = lanscape or portail

    // function get canvas

    if (get_action == "edit") {
        var get_src_image = jQuery("#wpgv_trigger_template").attr("data-tem-style");
        if (get_src_image != 0) {
            jQuery(".wpgv-template-box #wpgv_src_result").closest(".wpgv_line_tr").css("display", "table-row");
        }

        // check post created
        var selectedRadio = jQuery("[name='select_template']:checked").val();
        if (typeof selectedRadio === "undefined") {
            // check select template undefined
            jQuery("#chosse_template").closest("tr").hide();
            jQuery("#template-style").closest("tr").hide();
            var get_tem = jQuery(".wpgv_select_style_temp:checked").attr("id");
            if (typeof get_tem != "undefined") {
                jQuery("#select_template").prop("checked", true);
                jQuery("#template-style").closest("tr").show();
                var getlogocompany = jQuery("#get_option_url").val();
                jQuery(document).on("click", ".wpgv_select_style_temp", function () {

                    // Kiểm tra template có cần hiển thị barcode không
                    if (file_name === 'template-voucher-portail-44.png' || file_name === 'template-voucher-portail-45.png') {
                        window.checkBarcodeInTemplate = true;
                        window.currentTemplateName = file_name;
                        currentTemplateForBarcode = file_name;
                        shouldCheckBarcode = true;

                    } else {
                        window.checkBarcodeInTemplate = false;
                        window.currentTemplateName = null;
                        currentTemplateForBarcode = null;
                        shouldCheckBarcode = false;
                    }
                    $.ajax({
                        type: "post",
                        dataType: "html",
                        url: wpgv_admin_url,
                        data: {
                            action: "wpgv_curl_file_server",
                            file_name: file_name,
                        },
                        beforeSend: function (results) {
                            getDataChosse()
                        },
                        success: function () {
                            jQuery("#wpgv_load_temp label").removeClass("wpgv_loading_temp");
                            jQuery("#wpgv_wrap_custom_template label").removeClass("wpgv_loading_temp");
                            jQuery('#modal_edit_template').fadeIn(200);
                            var getId = jQuery(".wpgv_select_style_temp:checked").attr("id");
                            get_link_temp = jQuery("#wpgv_get_svg").val();
                            if (getId === "template-style") {
                                jQuery("#get_template_style").attr("value", file_name);
                                var getValue_temp_style = jQuery(".wpgv_select_style_temp:checked").val().replace(".png", "");
                                jsontemplate = "https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/version-1.2/json/" + getValue_temp_style + ".json";
                                pngtemplate = get_link_temp + getValue_temp_style + ".svg";
                                jQuery('#check_temp_custom').attr('value', 0);
                                var get_link_bg_s3 = jQuery("#template-style:checked").val();
                                if (typeof get_link_bg_s3 != "undefined") {
                                    var get_name_tem = get_link_temp + get_link_bg_s3.replace(".png", "") + ".svg";
                                    jQuery("#id_bg_template").attr("value", get_name_tem);
                                }
                            } else if (getId === "chosse_template") {
                                var getValue_chosse_temp = jQuery(".wpgv_select_style_temp:checked").val();
                                if (getValue_chosse_temp == "lanscape") {
                                    jQuery("#get_template_style").attr("value", "template-custom-lanscape.png");
                                    jsontemplate = get_link_temp + "template-custom-lanscape.json";
                                    pngtemplate = "";
                                } else if (getValue_chosse_temp == "portail") {
                                    jQuery("#get_template_style").attr("value", "template-custom-portail.png");
                                    jsontemplate = get_link_temp + "template-custom-portail.json";
                                    pngtemplate = "";
                                }
                            }

                            processJsonTemplate(jsontemplate);
                            getJsonTemplate(jsontemplate, pngtemplate, getlogocompany);
                            setTimeout(function () {
                                document.getElementById("wpgv_draw_stage").click();
                            }, 1000)

                        }
                    });
                })
            } else {
                var getlogocompany = jQuery("#get_option_url").val();
                jQuery(document).on("click", ".wpgv_select_style_temp", function () {
                    jQuery('body').addClass('wpgv-overflow-hidden');
                    jQuery('#id_bg_template').attr('value', '');
                    jQuery(".wpgv_select_style_temp").each(function () {

                        if (!jQuery(this).is(':checked')) {
                            jQuery(this).prop('disabled', true);
                            jQuery(this).closest("label").find(".voucher-content-step").addClass("wpgv_opacity_temp");
                        }
                    });
                    var wpgv_admin_url = jQuery("#wpgv_admin_url").val();
                    var file_name = jQuery(".wpgv_select_style_temp:checked").val();


                    if (file_name === 'template-voucher-portail-44.png' || file_name === 'template-voucher-portail-45.png') {
                        window.checkBarcodeInTemplate = true;
                        window.currentTemplateName = file_name;
                        currentTemplateForBarcode = file_name;
                        shouldCheckBarcode = true;

                    } else {
                        window.checkBarcodeInTemplate = false;
                        window.currentTemplateName = null;
                        currentTemplateForBarcode = null;
                        shouldCheckBarcode = false;
                    }
                    $.ajax({
                        type: "post",
                        dataType: "html",
                        url: wpgv_admin_url,
                        data: {
                            action: "wpgv_curl_file_server",
                            file_name: file_name,
                        },
                        beforeSend: function (results) {
                            getDataChosse()
                        },
                        success: function () {
                            jQuery("#wpgv_load_temp label").removeClass("wpgv_loading_temp");
                            jQuery("#wpgv_wrap_custom_template label").removeClass("wpgv_loading_temp");
                            jQuery('#modal_edit_template').fadeIn(200);
                            var getId = jQuery(".wpgv_select_style_temp:checked").attr("id");
                            get_link_temp = jQuery("#wpgv_get_svg").val();
                            if (getId === "template-style") {
                                jQuery("#get_template_style").attr("value", file_name);
                                var getValue_temp_style = jQuery(".wpgv_select_style_temp:checked").val().replace(".png", "");

                                jsontemplate = "https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/version-1.2/json/" + getValue_temp_style + ".json";
                                pngtemplate = get_link_temp + getValue_temp_style + ".svg";
                                jQuery('#check_temp_custom').attr('value', 0);
                                var get_link_bg_s3 = jQuery("#template-style:checked").val();
                                if (typeof get_link_bg_s3 != "undefined") {
                                    var get_name_tem = get_link_temp + get_link_bg_s3.replace(".png", "") + ".svg";
                                    jQuery("#id_bg_template").attr("value", get_name_tem);
                                }
                            } else if (getId === "chosse_template") {
                                var getValue_chosse_temp = jQuery(".wpgv_select_style_temp:checked").val();
                                if (getValue_chosse_temp == "lanscape") {
                                    jQuery("#get_template_style").attr("value", "template-custom-lanscape.png");
                                    jsontemplate = get_link_temp + "template-custom-lanscape.json";
                                    pngtemplate = "";
                                } else if (getValue_chosse_temp == "portail") {
                                    jQuery("#get_template_style").attr("value", "template-custom-portail.png");
                                    jsontemplate = get_link_temp + "template-custom-portail.json";
                                    pngtemplate = "";
                                }
                            }

                            processJsonTemplate(jsontemplate);
                            getJsonTemplate(jsontemplate, pngtemplate, getlogocompany);
                            setTimeout(function () {
                                document.getElementById("wpgv_draw_stage").click();
                            }, 1000)

                        }
                    });
                })
            }
        } else {
            var getlogocompany = jQuery("#get_option_url").val();
            var checkInputChecked = jQuery(".wpgv_select_style_temp:checked").attr("id");
            if (selectedRadio == "default") {

                // checked select template default
                jQuery("#template-style").closest("tr").show();
                jQuery(document).on("click", ".wpgv_select_style_temp", function () {
                    jQuery('body').addClass('wpgv-overflow-hidden');
                    jQuery(".wpgv_select_style_temp").each(function () {
                        jQuery(this).removeAttr('checked');
                        if (!jQuery(this).is(':checked')) {
                            jQuery(this).prop('disabled', true);
                            jQuery(this).closest("label").find(".voucher-content-step").addClass("wpgv_opacity_temp");
                        }
                    });
                    jQuery(this).prop('checked', true);
                    var wpgv_admin_url = jQuery("#wpgv_admin_url").val();
                    var file_name = jQuery(".wpgv_select_style_temp:checked").val();


                    if (file_name === 'template-voucher-portail-44.png' || file_name === 'template-voucher-portail-45.png') {
                        window.checkBarcodeInTemplate = true;
                        window.currentTemplateName = file_name;
                        currentTemplateForBarcode = file_name;
                        shouldCheckBarcode = true;

                    } else {
                        window.checkBarcodeInTemplate = false;
                        window.currentTemplateName = null;
                        currentTemplateForBarcode = null;
                        shouldCheckBarcode = false;
                    }
                    $.ajax({
                        type: "post",
                        dataType: "html",
                        url: wpgv_admin_url,
                        data: {
                            action: "wpgv_curl_file_server",
                            file_name: file_name,
                        },
                        beforeSend: function (results) {
                            getDataChosse()
                        },
                        success: function () {
                            jQuery("#wpgv_load_temp label").removeClass("wpgv_loading_temp");
                            jQuery("#wpgv_wrap_custom_template label").removeClass("wpgv_loading_temp");
                            jQuery('#modal_edit_template').fadeIn(200);
                            var getId = jQuery(".wpgv_select_style_temp:checked").attr("id");
                            var get_link_temp = jQuery("#wpgv_get_svg").val();
                            if (getId === "template-style") {
                                jQuery("#get_template_style").attr("value", file_name);
                                var getValue_temp_style = jQuery(".wpgv_select_style_temp:checked").val().replace(".png", "");
                                jsontemplate = "https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/version-1.2/json/" + getValue_temp_style + ".json";
                                pngtemplate = get_link_temp + getValue_temp_style + ".svg";
                                jQuery('#check_temp_custom').attr('value', 0);
                                var data_checked_temp = jQuery(this).attr("data-checked-temp");
                                if (data_checked_temp == 0) {
                                    jQuery("#id_bg_template").attr("value", "");
                                }
                                var get_link_bg_s3 = jQuery("#template-style:checked").val();
                                if (typeof get_link_bg_s3 != "undefined") {
                                    var get_name_tem = get_link_temp + get_link_bg_s3.replace(".png", "") + ".svg";
                                    jQuery("#id_bg_template").attr("value", get_name_tem);
                                }
                            } else if (getId === "chosse_template") {
                                var getValue_chosse_temp = jQuery(".wpgv_select_style_temp:checked").val();
                                                                    var get_json_input = jQuery("#json_template").val();
                                    if (get_json_input != "") {
                                        var get_json_parse = safeJsonParse(get_json_input);
                                    var get_bg_input = jQuery("#wpgv_src_json").attr('src');
                                    if (getValue_chosse_temp == "lanscape") {
                                        jQuery("#get_template_style").attr("value", "template-custom-lanscape.png");
                                        var get_data_checked = jQuery(".chosse_template:checked").attr('data-checked');
                                        if (get_data_checked == "0") {
                                            jsontemplate = get_link_temp + "template-custom-lanscape.json";
                                            pngtemplate = "";
                                        } else {
                                            jsontemplate = get_json_parse;
                                            pngtemplate = get_bg_input;
                                        }
                                    } else if (getValue_chosse_temp == "portail") {
                                        jQuery("#get_template_style").attr("value", "template-custom-portail.png");
                                        var get_data_checked = jQuery(".chosse_template:checked").attr('data-checked');
                                        if (get_data_checked == "1") {
                                            jsontemplate = get_json_parse;
                                            pngtemplate = get_bg_input;
                                        } else {
                                            jsontemplate = get_link_temp + "template-custom-portail.json";
                                            pngtemplate = "";
                                        }
                                    }
                                } else {
                                    if (getValue_chosse_temp == "lanscape") {
                                        jQuery("#get_template_style").attr("value", "template-custom-lanscape.png");
                                        jsontemplate = get_link_temp + "template-custom-lanscape.json";
                                        pngtemplate = "";
                                    } else if (getValue_chosse_temp == "portail") {
                                        jQuery("#get_template_style").attr("value", "template-custom-portail.png");
                                        jsontemplate = get_link_temp + "template-custom-portail.json";
                                        pngtemplate = "";
                                    }
                                }
                            }

                            processJsonTemplate(jsontemplate);
                            getJsonTemplate(jsontemplate, pngtemplate, getlogocompany);
                            setTimeout(function () {
                                document.getElementById("wpgv_draw_stage").click();
                            }, 1000)
                        }
                    });
                })

            } else if (selectedRadio == "custom") {
                // checked select template custom
                var checkInputChecked = jQuery(".wpgv_select_style_temp:checked").attr("id");
                jQuery("#chosse_template").closest("tr").show();
                if (typeof checkInputChecked === "undefined") {
                    jQuery(document).on("click", ".wpgv_select_style_temp", function () {

                        jQuery('body').addClass('wpgv-overflow-hidden');
                        jQuery(".wpgv_select_style_temp").each(function () {
                            if (!jQuery(this).is(':checked')) {
                                jQuery(this).prop('disabled', true);
                                jQuery(this).closest("label").find(".voucher-content-step").addClass("wpgv_opacity_temp");
                            }
                        });
                        var wpgv_admin_url = jQuery("#wpgv_admin_url").val();
                        var file_name = jQuery(".wpgv_select_style_temp:checked").val();
                        $.ajax({
                            type: "post",
                            dataType: "html",
                            url: wpgv_admin_url,
                            data: {
                                action: "wpgv_curl_file_server",
                                file_name: file_name,
                            },
                            beforeSend: function (results) {
                                getDataChosse()
                            },
                            success: function () {
                                jQuery("#wpgv_load_temp label").removeClass("wpgv_loading_temp");
                                jQuery("#wpgv_wrap_custom_template label").removeClass("wpgv_loading_temp");
                                jQuery('#modal_edit_template').fadeIn(200);
                                var getId = jQuery(".wpgv_select_style_temp:checked").attr("id");
                                var get_link_temp = jQuery("#wpgv_get_svg").val();
                                if (getId === "template-style") {
                                    jQuery("#get_template_style").attr("value", file_name);
                                    var getValue_temp_style = jQuery(".wpgv_select_style_temp:checked").val().replace(".png", "");

                                    jsontemplate = "https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/version-1.2/json/" + getValue_temp_style + ".json";
                                    pngtemplate = get_link_temp + getValue_temp_style + ".svg";
                                    jQuery('#check_temp_custom').attr('value', 0);
                                } else if (getId === "chosse_template") {
                                    var getValue_chosse_temp = jQuery(".chosse_template:checked").val();
                                    var get_json_input = jQuery("#json_template").val();

                                    var get_bg_input = jQuery("#wpgv_src_json").attr('src');

                                    if (getValue_chosse_temp === "lanscape") {
                                        jQuery("#get_template_style").attr("value", "template-custom-lanscape.png");
                                        var get_data_checked = jQuery(".chosse_template:checked").attr('data-checked');
                                        if (get_data_checked == "0") {
                                            jsontemplate = get_link_temp + "template-custom-lanscape.json";
                                            pngtemplate = "";
                                        } else {
                                            if (get_json_input != "") {
                                                var get_json_parse = safeJsonParse(get_json_input);
                                                jsontemplate = get_json_parse;
                                                pngtemplate = get_bg_input;
                                            } else {
                                                jsontemplate = get_link_temp + "template-custom-lanscape.json";
                                                pngtemplate = "";
                                            }
                                        }
                                    } else if (getValue_chosse_temp === "portail") {
                                        jQuery("#get_template_style").attr("value", "template-custom-portail.png");
                                        var get_data_checked = jQuery(".chosse_template:checked").attr('data-checked');
                                        if (get_data_checked == "1") {
                                            if (get_json_input != "") {
                                                var get_json_parse = safeJsonParse(get_json_input);
                                                jsontemplate = get_json_parse;
                                                pngtemplate = get_bg_input;
                                            } else {
                                                jsontemplate = get_link_temp + "template-custom-portail.json";
                                                pngtemplate = "";
                                            }
                                        } else {
                                            jsontemplate = get_link_temp + "template-custom-portail.json";
                                            pngtemplate = "";
                                        }
                                    }
                                }

                                processJsonTemplate(jsontemplate);
                                getJsonTemplate(jsontemplate, pngtemplate, getlogocompany);
                                setTimeout(function () {
                                    document.getElementById("wpgv_draw_stage").click();
                                }, 1000)

                            }
                        });
                    })
                } else {
                    jQuery(document).on("click", ".wpgv_select_style_temp", function () {
                        jQuery('body').addClass('wpgv-overflow-hidden');
                        jQuery(".wpgv_select_style_temp").each(function () {
                            if (!jQuery(this).is(':checked')) {
                                jQuery(this).prop('disabled', true);
                                jQuery(this).closest("label").find(".voucher-content-step").addClass("wpgv_opacity_temp");
                            }
                        });
                        var wpgv_admin_url = jQuery("#wpgv_admin_url").val();
                        var file_name = jQuery(".wpgv_select_style_temp:checked").val();

                        $.ajax({
                            type: "post",
                            dataType: "html",
                            url: wpgv_admin_url,
                            data: {
                                action: "wpgv_curl_file_server",
                                file_name: file_name,
                            },
                            beforeSend: function (results) {
                                getDataChosse()
                            },
                            success: function () {

                                jQuery('#modal_edit_template').fadeIn(200);
                                jQuery("#wpgv_load_temp label").removeClass("wpgv_loading_temp");
                                jQuery("#wpgv_wrap_custom_template label").removeClass("wpgv_loading_temp");
                                var getId = jQuery(".wpgv_select_style_temp:checked").attr("id");
                                var get_link_temp = jQuery("#wpgv_get_svg").val();
                                if (getId === "template-style") {
                                    jQuery("#get_template_style").attr("value", file_name);
                                    jQuery('#id_bg_template').attr('value', 0);
                                    var getValue_temp_style = jQuery(".wpgv_select_style_temp:checked").val().replace(".png", "");

                                    jsontemplate = "https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/version-1.2/json/" + getValue_temp_style + ".json";
                                    pngtemplate = get_link_temp + getValue_temp_style + ".svg";
                                    jQuery('#check_temp_custom').attr('value', 0);
                                    var get_link_bg_s3 = jQuery("#template-style:checked").val();
                                    if (typeof get_link_bg_s3 != "undefined") {
                                        var get_name_tem = get_link_temp + get_link_bg_s3.replace(".png", "") + ".svg";
                                        jQuery("#id_bg_template").attr("value", get_name_tem);

                                    }
                                } else if (getId === "chosse_template") {
                                    var getValue_chosse_temp = jQuery(".wpgv_select_style_temp:checked").val();
                                    var get_json_input = jQuery("#json_template").val();
                                    var get_json_parse = safeJsonParse(get_json_input);
                                    var get_bg_input = jQuery("#wpgv_src_json").attr('src');
                                    if (getValue_chosse_temp == "lanscape") {
                                        jQuery("#get_template_style").attr("value", "template-custom-lanscape.png");
                                        var get_data_checked = jQuery("input[name=chosse_template]:checked").attr('data-checked');
                                        var get_url_bg = jQuery("#id_bg_template").attr("data-id-bg");
                                        if (get_data_checked == "1") {

                                            var data_id_bg = jQuery('#id_bg_template').attr('data-id-bg');

                                            if (data_id_bg != "") {
                                                jQuery('#id_bg_template').attr('value', data_id_bg);
                                                var data_id_result = jQuery('#bg_result').attr('data-id-result');
                                                jQuery('#bg_result').attr('value', data_id_result);
                                                jsontemplate = get_json_parse;
                                                pngtemplate = get_url_bg;
                                            } else {

                                                var getValue_chosse_template = jQuery('#chosse_template').attr('data-bg-temp').replace(".png", "");
                                                var get_link_temp = jQuery("#wpgv_get_svg").val();
                                                jsontemplate = get_json_parse;
                                                pngtemplate = get_link_temp + getValue_chosse_template + ".svg";

                                            }
                                        } else {

                                            jQuery('#id_bg_template').attr('value', 0);
                                            jQuery('#bg_result').attr('value', 0);
                                            jsontemplate = get_link_temp + "template-custom-lanscape.json";
                                            pngtemplate = "";
                                        }
                                    } else if (getValue_chosse_temp == "portail") {
                                        jQuery("#get_template_style").attr("value", "template-custom-portail.png");
                                        var get_data_checked = jQuery("input[name=chosse_template]:checked").attr('data-checked');
                                        var get_url_bg = jQuery("#id_bg_template").attr("data-id-bg");
                                        if (get_data_checked == "1") {
                                            var data_id_bg = jQuery('#id_bg_template').attr('data-id-bg');
                                            if (data_id_bg != "") {
                                                jQuery('#id_bg_template').attr('value', data_id_bg);
                                                var data_id_result = jQuery('#bg_result').attr('data-id-result');
                                                jQuery('#bg_result').attr('value', data_id_result);
                                                jsontemplate = get_json_parse;
                                                pngtemplate = get_url_bg;
                                            } else {
                                                var getValue_chosse_template = jQuery('#chosse_template').attr('data-bg-temp').replace(".png", "");
                                                var get_link_temp = jQuery("#wpgv_get_svg").val();
                                                jsontemplate = get_json_parse;
                                                pngtemplate = get_link_temp + getValue_chosse_template + ".svg";
                                            }
                                        } else {
                                            jQuery('#id_bg_template').attr('value', 0);
                                            jQuery('#bg_result').attr('value', 0);
                                            jsontemplate = get_link_temp + "template-custom-portail.json";
                                            pngtemplate = "";
                                        }
                                    }
                                }
                                processJsonTemplate(jsontemplate);
                                getJsonTemplate(jsontemplate, pngtemplate, getlogocompany);
                                setTimeout(function () {
                                    document.getElementById("wpgv_draw_stage").click();
                                }, 1000)

                            }
                        });
                    })
                }
            }
        }
    } else {
        // check post not created
        var getlogocompany = jQuery("#get_option_url").val();
        jQuery(document).on("click", ".wpgv_select_style_temp", function () {

            jQuery('body').addClass('wpgv-overflow-hidden');
            jQuery('#id_bg_template').attr('value', '');
            jQuery(".wpgv_select_style_temp").each(function () {
                if (!jQuery(this).is(':checked')) {
                    jQuery(this).prop('disabled', true);
                    jQuery(this).closest("label").find(".voucher-content-step").addClass("wpgv_opacity_temp");
                }
            });
            var wpgv_admin_url = jQuery("#wpgv_admin_url").val();
            var file_name = jQuery(".wpgv_select_style_temp:checked").val();


            if (file_name === 'template-voucher-portail-44.png' || file_name === 'template-voucher-portail-45.png') {
                window.checkBarcodeInTemplate = true;
                window.currentTemplateName = file_name;
                currentTemplateForBarcode = file_name;
                shouldCheckBarcode = true;

            } else {

                window.checkBarcodeInTemplate = false;
                window.currentTemplateName = null;
                currentTemplateForBarcode = null;
                shouldCheckBarcode = false;
            }
            $.ajax({
                type: "post",
                dataType: "html",
                url: wpgv_admin_url,
                data: {
                    action: "wpgv_curl_file_server",
                    file_name: file_name,
                },
                beforeSend: function (results) {

                    getDataChosse()
                },
                success: function () {

                    jQuery("#wpgv_load_temp label").removeClass("wpgv_loading_temp");
                    jQuery("#wpgv_wrap_custom_template label").removeClass("wpgv_loading_temp");
                    jQuery('#modal_edit_template').fadeIn(200);
                    var getId = jQuery(".wpgv_select_style_temp:checked").attr("id");
                    get_link_temp = jQuery("#wpgv_get_svg").val();
                    if (getId === "template-style") {
                        jQuery("#get_template_style").attr("value", file_name);
                        var getValue_temp_style = jQuery(".wpgv_select_style_temp:checked").val().replace(".png", "");

                        jsontemplate = "https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/version-1.2/json/" + getValue_temp_style + ".json";
                        pngtemplate = get_link_temp + getValue_temp_style + ".svg";
                        jQuery('#check_temp_custom').attr('value', 0);
                        var get_link_bg_s3 = jQuery("#template-style:checked").val();
                        if (typeof get_link_bg_s3 != "undefined") {
                            var get_name_tem = get_link_temp + get_link_bg_s3.replace(".png", "") + ".svg";
                            jQuery("#id_bg_template").attr("value", get_name_tem);
                        }
                    } else if (getId === "chosse_template") {
                        var getValue_chosse_temp = jQuery(".wpgv_select_style_temp:checked").val();
                        if (getValue_chosse_temp == "lanscape") {
                            jQuery("#get_template_style").attr("value", "template-custom-lanscape.png");
                            jsontemplate = get_link_temp + "template-custom-lanscape.json";
                            pngtemplate = "";
                        } else if (getValue_chosse_temp == "portail") {
                            jQuery("#get_template_style").attr("value", "template-custom-portail.png");
                            jsontemplate = get_link_temp + "template-custom-portail.json";
                            pngtemplate = "";
                        }
                    }

                    processJsonTemplate(jsontemplate);
                    getJsonTemplate(jsontemplate, pngtemplate, getlogocompany);
                    setTimeout(function () {
                        document.getElementById("wpgv_draw_stage").click();
                    }, 1000)

                }
            });
        })

    }





    // change backgound template
    jQuery('#upload_bg_template').click(function (event_upload) {
        event_upload.preventDefault();
        var bgTemplate;
        if (bgTemplate) {
            bgTemplate.open();
            return;
        }
        var bgTemplate = wp.media({
            title: 'Add Background Template',
            button: {
                text: 'Upload Background Template'
            },
            multiple: false
        })
            .on('select', function () {
                var attachmentBackground = bgTemplate.state().get('selection').first().toJSON();
                var urlBackground = attachmentBackground.url;
                var imageObj = new Image();

                imageObj.onload = function () {
                    var canvasWidth = stage.width();
                    var canvasHeight = stage.height();
                    var imgAspectRatio = imageObj.width / imageObj.height;
                    var canvasAspectRatio = canvasWidth / canvasHeight;
                    var newWidth, newHeight, offsetX, offsetY;

                    if (imgAspectRatio > canvasAspectRatio) {
                        newHeight = canvasHeight;
                        newWidth = newHeight * imgAspectRatio;
                        offsetX = (canvasWidth - newWidth) / 2;
                        offsetY = 0;
                    } else {
                        newWidth = canvasWidth;
                        newHeight = newWidth / imgAspectRatio;
                        offsetX = 0;
                        offsetY = (canvasHeight - newHeight) / 2;
                    }

                    var bgImage = stage.find('#giftcard_bg')[0];
                    bgImage.image(imageObj);
                    bgImage.size({ width: newWidth, height: newHeight });
                    bgImage.position({ x: offsetX, y: offsetY });
                    stage.draw();
                };

                imageObj.src = urlBackground;

                var json = stage.toJSON();
                jQuery("#json_template").attr('value', json);
                jQuery('#id_bg_template').attr('value', attachmentBackground.id);
                jQuery('#check_temp_custom').attr('value', "1");
            })
            .open();
    });

    // click select template
    function status_checked() {
        jQuery(".wpgv-template-box .wpgv_select_style_temp").each(function () {
            if ($(this).is(":checked")) {
                $(this).removeAttr('checked');
            }
            if ($(this).data("checked") == 1) {
                $(this).prop("checked", true);
            }
        });
    }
    jQuery(document).on("click", ".select_template", function (event) {
        // jQuery(".select_template").removeAttr("checked");
        // jQuery(this).prop("checked", true);
        var selectedRadio = jQuery("input[type='radio'][name='select_template']:checked").val();

        if (get_action == "edit") {
            if (selectedRadio == "default") {
                jQuery("#template-style").closest("tr").fadeIn(200);
                jQuery("#chosse_template").closest("tr").fadeOut(200);
                status_checked();
                var check_select = jQuery(this).data("select");
                if (check_select == 1) {
                    jQuery(".wpgv-template-box #wpgv_src_result").closest(".wpgv_line_tr").css("display", "table-row");
                    var get_id_result = jQuery("#bg_result").data("id-result");
                    var get_template_style = jQuery("#get_template_style").data("template-style");
                    var data_id_bg = jQuery('#id_bg_template').data('id-bg');
                    var data_chosse_temp = jQuery('#get_chosse_temp').data('chosse-temp');
                    var data_status_temp = jQuery('#check_temp_custom').data('status-temp');

                    jQuery("#bg_result").attr("value", get_id_result);
                    jQuery("#get_template_style").attr("value", get_template_style);
                    jQuery('#id_bg_template').attr('value', data_id_bg);
                    jQuery('#get_chosse_temp').attr('value', data_chosse_temp);
                    jQuery('#check_temp_custom').attr('value', data_status_temp);
                } else {
                    jQuery(".wpgv-template-box #wpgv_src_result").closest(".wpgv_line_tr").css("display", "none");
                    jQuery("#bg_result").attr("value", 0);
                    jQuery("#get_template_style").attr("value", 0);
                    jQuery('#id_bg_template').attr('value', 0);
                    jQuery('#get_chosse_temp').attr('value', 0);
                    jQuery('#check_temp_custom').attr('value', 0);
                }
            } else if (selectedRadio == "custom") {
                jQuery("#chosse_template").closest("tr").fadeIn(200);
                jQuery("#template-style").closest("tr").fadeOut(200);
                status_checked();
                var check_select = jQuery(this).data("select");
                if (check_select == 1) {
                    jQuery(".wpgv-template-box #wpgv_src_result").closest(".wpgv_line_tr").css("display", "table-row");
                    var get_id_result = jQuery("#bg_result").data("id-result");
                    var get_template_style = jQuery("#get_template_style").data("template-style");
                    var data_id_bg = jQuery('#id_bg_template').data('id-bg');
                    var data_chosse_temp = jQuery('#get_chosse_temp').data('chosse-temp');
                    var data_status_temp = jQuery('#check_temp_custom').data('status-temp');

                    jQuery("#bg_result").attr("value", get_id_result);
                    jQuery("#get_template_style").attr("value", get_template_style);
                    jQuery('#id_bg_template').attr('value', data_id_bg);
                    jQuery('#get_chosse_temp').attr('value', data_chosse_temp);
                    jQuery('#check_temp_custom').attr('value', data_status_temp);
                } else {
                    jQuery(".wpgv-template-box #wpgv_src_result").closest(".wpgv_line_tr").css("display", "none");
                    jQuery("#bg_result").attr("value", 0);
                    jQuery("#get_template_style").attr("value", 0);
                    jQuery('#id_bg_template').attr('value', 0);
                    jQuery('#get_chosse_temp').attr('value', 0);
                    jQuery('#check_temp_custom').attr('value', 0);
                }
            }
        } else {
            if (selectedRadio == "default") {
                jQuery("#template-style").closest("tr").fadeIn(200);
                jQuery("#chosse_template").closest("tr").fadeOut(200);
            } else if (selectedRadio == "custom") {
                jQuery("#chosse_template").closest("tr").fadeIn(200);
                jQuery("#template-style").closest("tr").fadeOut(200);
            }
        }

    });

    // click hide modal
    jQuery('.close_popup').click(function () {
        jQuery("#wpgv_trigger_template").css("pointer-events", "auto");
        jQuery("#wpgv_trigger_template").removeClass("wpgv_loading_temp");
        jQuery(".wpgv_select_style_temp:checked").closest("label").removeClass("disable_loding_temp");
        var get_json_db = jQuery('#get_json_db').val();
        jQuery("#json_template").attr("data-json-template", get_json_db);
        jQuery("#json_template").attr("value", get_json_db);

        jQuery(".wp-color-result").attr("style", "");
        jQuery('body').removeClass('wpgv-overflow-hidden');
        jQuery(".wpgv_select_style_temp").each(function () {
            $(this).prop('disabled', false);
            jQuery(this).closest("label").find(".voucher-content-step").removeClass("wpgv_opacity_temp");
        });
        jQuery('.modal_edit_template').fadeOut(300);

        if (get_action == "edit") {
            let data_select = $('[name="select_template"]:checked').attr('data-select');
            if (data_select == 1) {
                jQuery(".wpgv-template-box .wpgv_select_style_temp").each(function () {
                    jQuery(this).prop("checked", false);
                    var data_checked = jQuery(this).attr("data-checked");
                    if (data_checked == 1) {
                        jQuery(this).prop("checked", true);
                    }
                    var get_id_result = jQuery("#bg_result").data("id-result");
                    var get_template_style = jQuery("#get_template_style").attr("data-template-style");
                    var data_id_bg = jQuery('#id_bg_template').data('id-bg');
                    var data_chosse_temp = jQuery('#get_chosse_temp').data('chosse-temp');
                    var data_status_temp = jQuery('#check_temp_custom').data('status-temp');

                    jQuery("#bg_result").attr("value", get_id_result);
                    jQuery("#get_template_style").attr("value", get_template_style);
                    jQuery('#id_bg_template').attr('value', data_id_bg);
                    jQuery('#get_chosse_temp').attr('value', data_chosse_temp);
                    jQuery('#check_temp_custom').attr('value', data_status_temp);
                })
            } else {
                jQuery("#bg_result").attr("value", 0);
                jQuery("#get_template_style").attr("value", 0);
                jQuery('#id_bg_template').attr('value', 0);
                jQuery('#get_chosse_temp').attr('value', 0);
                jQuery('#check_temp_custom').attr('value', 0);
            }
        } else {
            var json = stage.toJSON();
            jQuery('#json_template').attr('value', json);
            jQuery('#get_chosse_temp').attr('value', 0);
            jQuery(".wpgv-template-box .wpgv_select_style_temp").each(function () {
                $(this).removeAttr('checked');
            });
        }

    });

    // uncheck radio button template chosse_template
    jQuery('.template-style').click(function () {
        var selectedChosse = jQuery("input[type='radio'][name='chosse_template']:checked");
        if (selectedChosse.length > 0) {
            selectedChosse.prop('checked', false);
        }
    });

    // uncheck radio button template dafault
    jQuery('.chosse_template').click(function () {
        var selectedChosse = jQuery("input[type='radio'][name='template-style']:checked");
        if (selectedChosse.length > 0) {
            selectedChosse.prop('checked', false);
        }
    });

    jQuery('#wpgv_tripger_all').on('click', function (event) {
        jQuery(window).off('beforeunload');
        event.preventDefault();
        $('body').trigger('click');

        // get base image
        jQuery("#modal_edit_template .dialog_template").addClass("wpgv_loading_modal");
        jQuery(".wpgv_select_style_temp").each(function () {
            $(this).prop('disabled', false);
        });
        jQuery("#wpgv_appendImage").trigger("click");
        var wpgv_admin_url = jQuery("#wpgv_admin_url").val();
        var base64_img = jQuery("#show-preview-gift-card").attr("href");
        var get_id_bg_result = jQuery("#bg_result").val();
        var data_id_result = jQuery("#bg_result").attr("data-id-result");
        var get_id_template_style = jQuery("input[name=template-style]:checked").attr("id");
        if (get_id_template_style == "template-style") {
            var getValue_temp_style = jQuery(".wpgv_select_style_temp:checked").val().replace("png", "svg");
            var wpgv_get_svg = jQuery("#wpgv_get_svg").val();
            jsontemplate = wpgv_get_svg + getValue_temp_style;
        }
        $.ajax({
            type: "post",
            dataType: "json",
            url: wpgv_admin_url,
            data: {
                action: "wpgv_save_image",
                base64_img: base64_img,
                title: counpon,
                get_id_bg_result: get_id_bg_result,
                data_id_result: data_id_result,
            },
            success: function (response) {
                try {
                    if (response && response.success && response.data) {
                        var attachId = response.data.id;
                        var attachUrl = response.data.url;
                        jQuery("#bg_result").val(attachId);
                        jQuery("#bg_result").attr('data-id-result', attachId);

                        // Ensure the preview image element exists, then set src and show it
                        var $img = jQuery('#wpgv_src_result');
                        if ($img.length === 0) {
                            // If no img exists, insert one into the form table next to the field
                            jQuery('.wpgv-template-box').find('tbody').prepend('<tr class="wpgv_line_tr"><th></th><td><img id="wpgv_src_result" src="' + attachUrl + '"/></td></tr>');
                        } else {
                            $img.attr('src', attachUrl).show();
                            $img.closest('.wpgv_line_tr').css('display', 'table-row');
                        }

                        // submit the post form
                        $(".post-type-voucher_template #post").submit();
                    } else {
                        console.error('Upload failed', response);
                        alert('Upload failed. Please try again.');
                    }
                } catch (e) {
                    console.error('Error parsing response', e, response);
                    alert('An error occurred while saving the image.');
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log('Error', textStatus, errorThrown);
                alert('An error occurred while saving the image.');
            }
        });
    });

    function addImagesGiftCard(dataURL) {
        if (jQuery('.wrap_template').find('#show-preview-gift-card').length > 0) {
            jQuery('.wrap_template').find('#show-preview-gift-card').attr('href', dataURL);
        } else {
            jQuery('.wrap_template').append('<a id="show-preview-gift-card" href="' + dataURL + '"></a>');
        }
    }
    jQuery('#wpgv_draw_stage').on('click', function (event) {
        setTimeout(function () {
            stage.draw();
        }, 200)
        setTimeout(function () {
            stage.draw();
        }, 1000)
    });

    jQuery('#wpgv_appendImage').on('click', function (event) {
        event.preventDefault();
        if (stage != null) {
            var dataURL = stage.toDataURL({
                pixelRatio: 1 // or other value you need
            });
            addImagesGiftCard(dataURL);
        }
    });
    // jQuery(".post-type-voucher_template #publish").click(function() {
    //     jQuery("#wpgv_tripger_all").trigger("click");
    //     return false;
    // });
    jQuery("#wpgv_set_default_json").click(function () {

        jQuery("#edit_giftto_temp").prop("value", "");
        jQuery("#edit_giftform_temp").prop("value", "");
        jQuery("#edit_desc_temp").prop("value", "");

        jQuery("#title_voucher_first").prop("value", "");
        jQuery("#title_voucher_last").prop("value", "");
        jQuery("#edit_gift_to").prop("value", "");
        jQuery("#edit_gift_from").prop("value", "");

        jQuery(".wp-color-result").attr("style", "");

        var get_data_json_template = jQuery("#json_template").attr("data-json-template");
        jQuery("#json_template").val(get_data_json_template);
        var getlogocompany = jQuery("#get_option_url").val();
        get_link_temp = jQuery("#wpgv_get_svg").val();
        var pngtemplate = null;
        var getId = jQuery(".wpgv_select_style_temp:checked").attr("id");
        if (getId === "template-style") {
            var getValue_temp_style = jQuery(".wpgv_select_style_temp:checked").val().replace(".png", "");
            pngtemplate = get_link_temp + getValue_temp_style + ".svg";
            jQuery("#check_temp_custom").val(0);
        } else if (getId === "chosse_template") {
            var getValue_chosse_temp = jQuery(".wpgv_select_style_temp:checked").val();
            var getValue_bg_temp = jQuery("#id_bg_template").attr("data-id-bg");
            if (getValue_chosse_temp == "lanscape") {
                pngtemplate = getValue_bg_temp;
            } else if (getValue_chosse_temp == "portail") {
                jsontemplate = get_link_temp + "template-custom-portail.json";
                pngtemplate = getValue_bg_temp;
            }
        }

        var json_par = safeJsonParse(get_data_json_template);
        getJsonTemplate(json_par, pngtemplate, getlogocompany);
    });
            jQuery("#wpgv_trigger_template").click(function () {
        jQuery(this).addClass("wpgv_loading_temp");
        jQuery('body').addClass('wpgv-overflow-hidden');

        var get_active_style = jQuery(this).closest("#wpgv_trigger_template").data("tem-style");
        var get_active_chosse = jQuery(this).closest("#wpgv_trigger_template").data("chosse-tem");
        var modalShown = false;

        jQuery(".wpgv_select_style_temp:checked").each(function () {
            jQuery(this).closest("label").addClass("disable_loding_temp");
            get_id_checked = jQuery(this).attr("id");
            if (get_id_checked == "template-style") {
                get_tem_checked = jQuery(this).val();
                if (get_active_style == get_tem_checked) {
                    jQuery(this).prop("checked", true);
                    jQuery(this).trigger("click");
                    modalShown = true;
                }
            } else if (get_id_checked == "chosse_template") {
                get_tem_checked = jQuery(this).val();
                if (get_active_chosse == get_tem_checked) {
                    jQuery(this).prop("checked", true);
                    jQuery(this).trigger("click");
                    modalShown = true;
                }
            }
        });

        // If no matching radio button found or modal not shown, show modal directly with correct template
        if (!modalShown) {
            // Check if fonts are loaded before showing modal
            checkFontsLoaded(function() {
                jQuery('#modal_edit_template').fadeIn(200);

                // Get the correct template based on data attributes
                var getlogocompany = jQuery("#get_option_url").val();
                var get_link_temp = jQuery("#wpgv_get_svg").val();
                var jsontemplate, pngtemplate;

                // Determine which template to load based on data attributes
                if (get_active_style) {
                    // Template style template
                    jsontemplate = "https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/version-1.2/json/" + get_active_style.replace(".png", "") + ".json";
                    pngtemplate = get_link_temp + get_active_style.replace(".png", "") + ".svg";
                } else if (get_active_chosse) {
                    // Custom template
                    if (get_active_chosse == "lanscape") {
                        jsontemplate = get_link_temp + "template-custom-lanscape.json";
                        pngtemplate = "";
                    } else if (get_active_chosse == "portail") {
                        jsontemplate = get_link_temp + "template-custom-portail.json";
                        pngtemplate = "";
                    }
                } else {
                    // Fallback to landscape template
                    jsontemplate = get_link_temp + "template-custom-lanscape.json";
                    pngtemplate = "";
                }

                processJsonTemplate(jsontemplate);
                getJsonTemplate(jsontemplate, pngtemplate, getlogocompany);
                // Increased timeout and added retry logic for better stage loading
                setTimeout(function () {
                    if (document.getElementById("wpgv_draw_stage")) {
                        document.getElementById("wpgv_draw_stage").click();
                    }
                }, 1500);

                // Additional retry to ensure stage is fully loaded
                setTimeout(function () {
                    if (document.getElementById("wpgv_draw_stage") && typeof stage !== 'undefined') {
                        stage.draw();
                        document.getElementById("wpgv_draw_stage").click();
                    }
                }, 2500);
            });
        }

        return false;
    });


    function getURLParameter(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    }

    const getTaxonomy = getURLParameter('taxonomy');
    const topLevelLi = $('#toplevel_page_wpgv-gift-cards');
    const taxonomyMapping = {
        'wpgv_voucher_category': 'Giftcard standard Categories',
        'category_voucher_template': 'Giftcard modern Categories'
    };

    if (getTaxonomy && topLevelLi.length > 0) {
        const taxonomyText = taxonomyMapping[getTaxonomy];
        const giftcardTemplateLink = topLevelLi.find(`a:contains("${taxonomyText}")`);
        if (giftcardTemplateLink.length > 0) {
            giftcardTemplateLink.addClass('current').attr('aria-current', 'page');
            giftcardTemplateLink.closest('li').addClass('current');
        }
    }
    $(function () {
        // Initialize the tabs
        $('#tabs ul li a').click(function () {
            // Get the ID of the clicked tab
            var tabId = $(this).attr('href');

            // Hide all the tabs
            $('.tab-pane').hide();

            // Show the tab with the ID of the clicked tab
            $('#' + tabId).show();

            // Set the active tab
            $('#tabs ul li a').removeClass('active');
            $(this).addClass('active');
        });
    });

    function sanitizeJsonInput(input) {
        const forbiddenCharacters = ['{', '}', '[', ']', ':', ',', '\\', "'", '/', ';'];
        let sanitizedInput = input;

        forbiddenCharacters.forEach(char => {
            const regex = new RegExp(`\\${char}`, 'g');
            sanitizedInput = sanitizedInput.replace(regex, '');
        });

        return sanitizedInput;
    }

    // Function to safely escape JSON string
    function escapeJsonString(jsonString) {
        if (typeof jsonString !== 'string') {
            return jsonString;
        }

        // Escape single quotes and other problematic characters
        return jsonString
            .replace(/\\/g, '\\\\')  // Escape backslashes first
            .replace(/'/g, "\\'")    // Escape single quotes
            .replace(/"/g, '\\"')    // Escape double quotes
            .replace(/\n/g, '\\n')   // Escape newlines
            .replace(/\r/g, '\\r')   // Escape carriage returns
            .replace(/\t/g, '\\t');  // Escape tabs
    }

    // Function to safely unescape JSON string
    function unescapeJsonString(jsonString) {
        if (typeof jsonString !== 'string') {
            return jsonString;
        }

        // Unescape the string
        return jsonString
            .replace(/\\t/g, '\t')   // Unescape tabs
            .replace(/\\r/g, '\r')   // Unescape carriage returns
            .replace(/\\n/g, '\n')   // Unescape newlines
            .replace(/\\"/g, '"')    // Unescape double quotes
            .replace(/\\'/g, "'")    // Unescape single quotes
            .replace(/\\\\/g, '\\'); // Unescape backslashes
    }

    // Function to safely parse JSON with error handling
    function safeJsonParse(jsonString) {
        try {
            // First try to parse as is
            return JSON.parse(jsonString);
        } catch (e) {
            try {
                // If failed, try to unescape and parse
                const unescaped = unescapeJsonString(jsonString);
                return JSON.parse(unescaped);
            } catch (e2) {

                return null;
            }
        }
    }

    // Function to safely stringify JSON
    function safeJsonStringify(obj) {
        try {
            return JSON.stringify(obj);
        } catch (e) {
            return null;
        }
    }

    // When the document is ready
    $(document).ready(function () {
        // When the user clicks on the "Create Plugin's Default Pages" button
        var wpgv_admin_url = jQuery("#wpgv_admin_url").val();
        $('#create_data_demo').on('click', function (e) {
            e.preventDefault();
            showLoadingPopup();
            createDefaultPages(); // Call the PHP function to create default pages
        });

        // Function to display the loading popup effect
        function showLoadingPopup() {
            $('#loading-popup').show();
        }

        // Function to hide the loading popup effect
        function hideLoadingPopup() {
            $('#loading-popup').hide();
        }

        // Function to call the PHP code to create default pages
        function createDefaultPages() {
            // Send an AJAX request to the PHP code to create default pages
                jQuery.ajax({
                    url: wpgv_admin_url,
                    type: 'GET',
                    data: {
                        'action': 'create_default_pages'
                    },
                success: function (response) {
                    hideLoadingPopup();
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: 'Default pages have been created successfully!',
                    });
                },
                error: function () {
                    hideLoadingPopup();
                    // Show an error message using SweetAlert2
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: 'Unable to create default pages.',
                    });
                }
            });
        }
    });
    function toggleRecaptchaRequired() {
        var selectedValue = jQuery('#enable_recaptcha').val();

        if (selectedValue == '1') {
            jQuery('#recaptcha_site_key, #recaptcha_secret_key').attr('required', 'required');
        } else {
            jQuery('#recaptcha_site_key, #recaptcha_secret_key').removeAttr('required');
        }
    }

    toggleRecaptchaRequired();

    jQuery('#enable_recaptcha').on('change', function () {
        toggleRecaptchaRequired();
    });

    function checkAndAddBarcode(dataJson) {
        var needToCheckBarcode = (window.checkBarcodeInTemplate === true && window.currentTemplateName) ||
                                 (shouldCheckBarcode && currentTemplateForBarcode);

        if (needToCheckBarcode) {
            var templateName = window.currentTemplateName || currentTemplateForBarcode;
            // Check and get coordinates from JSON before adding barcode
            hasBarcodeInJson(dataJson);

            // Always add barcode image for required templates
            addBarcodeImage();
        }
    }

    // Function to check if giftcard_barcode exists in JSON and get coordinates
    function hasBarcodeInJson(dataJson) {
        // Reset coordinates before searching
        window.barcodeCoordinates = null;

        try {
            // Search for giftcard_barcode in JSON structure and get coordinates
            function searchForBarcode(obj) {
                if (typeof obj === 'object' && obj !== null) {
                    for (let key in obj) {
                        if (key === 'giftcard_barcode' || (key === 'id' && obj[key] === 'giftcard_barcode')) {
                            // Save barcode coordinates to global variable
                            if (obj.attrs) {
                                window.barcodeCoordinates = {
                                    x: obj.attrs.x,
                                    y: obj.attrs.y,
                                    width: obj.attrs.width,
                                    height: obj.attrs.height
                                };
                            }
                            return true;
                        }
                        if (typeof obj[key] === 'object') {
                            if (searchForBarcode(obj[key])) {
                                return true;
                            }
                        }
                    }
                }
                return false;
            }

            const result = searchForBarcode(dataJson);
            return result;
        } catch (e) {
            return false;
        }
    }

    // Function to add barcode image to template
    function addBarcodeImage() {
        if (typeof stage !== 'undefined' && stage) {
            // Create barcode image from assets/img/barcode.png
            const barcodeImage = new window.Image();
            barcodeImage.onload = function() {
                // Prioritize coordinates from JSON, fallback to default coordinates
                var coordinates = window.barcodeCoordinates;

                if (!coordinates) {
                    // Default coordinates ensure barcode always displays
                    coordinates = {
                        x: 15,
                        y: 410,
                        width: 200,
                        height: 20
                    };
                }

                // Create Konva Image node for barcode
                const barcodeNode = new Konva.Image({
                    x: coordinates.x,
                    y: coordinates.y,
                    image: barcodeImage,
                    width: coordinates.width,
                    height: coordinates.height,
                    id: 'giftcard_barcode_image'
                });

                // Add to first layer of stage
                const firstLayer = stage.find('Layer')[0];
                if (firstLayer) {
                    firstLayer.add(barcodeNode);
                    stage.draw();
                }
            };


            // Path to barcode image - using hidden input
            var barcodeUrl = jQuery("#wpgv_barcode_url").val();
            barcodeImage.src = barcodeUrl;
        }
    }

});
