jQuery(function($){

    Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
        return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
    });
    Handlebars.registerHelper('nameToTitle', function(arg) {
        var parse = arg.split('_');
        var output = [];
        $.each(parse, function( a, b ){
            if(b.length <= 3){
                output.push(b.toUpperCase());
            }else{
                output.push(b);
            }
        });
        return output.join(' ');
    });
    Handlebars.registerHelper('parsePaymentInfo', function(arg) {
        var explode = arg.split('-');
        var explode2 = explode[0].split(':::');
        var gateway = explode2[0].split('_').join(' ');
        var channel = explode2[1];
        return gateway + ' - ' + channel;
    });
    Handlebars.registerHelper('ifKeyExists', function(key, obj, options) {
        // Check if the key exists in the object
        if (obj && obj.hasOwnProperty(key)) {
            // If it exists, execute the block
            return options.fn(this);
        }
        // If it does not exist, execute the inverse block (if provided)
        return options.inverse(this);
    });

    function ucWords(input) {
        return input
            .replace(/_/g, ' ') // Replace underscores with spaces
            .toLowerCase() // Convert entire string to lowercase first
            .replace(/^(.)/, function(char) { return char.toUpperCase(); }) // Capitalize the first letter of the first word
            .replace(/ (.)/g, function(char) { return char.toUpperCase(); }); // Capitalize the first letter after each space
    }

    let order_id = $('#order_id').val();

    function load_order_data() {

        $.ajax({
            type: 'post',
            url: formipay_order_details_page.ajax_url,
            data: {
                action: 'formipay_load_order_data',
                order: order_id,
                _wpnonce: formipay_order_details_page.nonce
            },
            success: function (res) {
                console.log(res);
                var source = $("#order-item-row-template").html();
                var template = Handlebars.compile(source);
                var context = {
                    items: res.items
                };
                var html = template(context);
                $("#order-items-table tbody").html(html);
                $('#order-total').html(res.total_formatted);
                $('#order_status').val(res.status);

                var source = $("#form-data-item-template").html();
                var template = Handlebars.compile(source);
                var context = {
                    datas: res.form_data
                };
                var html = template(context);
                $("#form-data-list").html(html);
                var editFormDataButton = $('.edit-transaction-data').attr('data-loaded-button-text');
                $('.edit-transaction-data').text(editFormDataButton).prop('disabled', false);

                var source = $("#form-data-item-template").html();
                var template = Handlebars.compile(source);
                var meta_data = [];
                $.each(res.meta_data, function(index, meta){
                    if(meta.name !== 'access_method' && meta.name !== 'access_password'){
                        meta_data.push(meta);
                    }
                });
                var context = {
                    datas: meta_data
                };
                var html = template(context);
                $("#submission-detail-list").html(html);

                var source = $("#notification-data-template").html();
                var template = Handlebars.compile(source);
                var context = {
                    datas: res.notification.sort().reverse()
                };
                var html = template(context);
                $("#notification-list").html(html);

                var source = $("#transaction-timeline-item").html();
                var template = Handlebars.compile(source);
                var context = {
                    datas: res.transaction_timeline.sort().reverse()
                };
                var html = template(context);
                $("#transaction-list").html(html);

                var passMethod = {
                    'magic_link': 'Magic Link',
                    'static_password': 'Static Password'
                }
                var source = $('#thankyou-access-template').html();
                var template  = Handlebars.compile(source);
                var context = {
                    data: {
                        link: res.thankyou.link,
                        pass_method: res.thankyou.pass_method,
                        pass_method_label: passMethod[res.thankyou.pass_method],
                        pass_word: res.thankyou.pass_word
                    }
                };
                var html = template(context);
                $('#access-detail-list').html(html);
                $('#access_method').val(res.thankyou.pass_method).trigger('change');
                var editFormDataButton = $('.edit-access-data').attr('data-loaded-button-text');
                $('.edit-access-data').text(editFormDataButton).prop('disabled', false);
                if(res.thankyou.pass_method == 'static_password'){
                    $('li.access-password p').text(res.thankyou.pass_word);
                    $('li.access-password').removeClass('d-none');
                }
                
            }
        });

    }

    function set_loading_button(selector, loadingText = '') {
        var buttonText = selector.text();
        selector.attr('data-button-text', buttonText);
        selector.prop('disabled', true);
        if(loadingText !== '') {
            selector.html(`
                <span class="spinner-border spinner-border-sm" aria-hidden="true"></span>
                <span role="status">${loadingText}</span>
            `);
        }else{
            selector.html(`
                <span class="spinner-border spinner-border-sm" aria-hidden="true"></span>
                <span class="visually-hidden" role="status">${loadingText}</span>
            `);
        }
    }

    function remove_loading_button(selector) {
        var buttonText = selector.attr('data-button-text');
        selector.prop('disabled', false);
        selector.html(buttonText);
    }

    load_order_data();

    $(document).on('click', '.timeline-item-image', function(){
        var imageSrc = $(this).attr('src');
        $('#image-ligthbox img').attr('src', imageSrc);
        $('#image-ligthbox').modal('show');
    });

    $('#order_status').on('change', function() {
        var status = $(this).val();
        var order_id = $(this).data('order-id');
        Swal.fire({
            html: formipay_order_details_page.order_detail.change_order_status_confirmation,
            icon: 'question',
            confirmButtonText: formipay_order_details_page.order_detail.change_order_status_button_confirm,
            cancelButtonText: formipay_order_details_page.order_detail.change_order_status_button_cancel,
            showCancelButton: true,
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    type: 'post',
                    url: formipay_order_details_page.ajax_url,
                    data: {
                        action: 'formipay_change_order_status',
                        id: order_id,
                        status: status,
                        _wpnonce: formipay_order_details_page.nonce
                    },
                    success: function (res) {
                        if(res.success){
                            Swal.fire({
                                html: res.data.message,
                                icon: 'success'
                            });
                        }else{
                            Swal.fire({
                                html: res.data.message,
                                icon: 'error'
                            });
                        }
                    }
                });
            }
        });
    });

    $('.edit-transaction-data').on('click', function(e) {
        e.preventDefault();
        var $this_button = $(this);
        $.ajax({
            type: 'post',
            url: formipay_order_details_page.ajax_url,
            data: {
                action: 'formipay_check_editable_field',
                order_id: formipay_order_details_page.order_id,
                _wpnonce: formipay_order_details_page.nonce
            },
            beforeSend: function() {
                set_loading_button($this_button, formipay_order_details_page.order_detail.edit_button_loading_text);
            },
            success: function(res) {
                remove_loading_button($this_button);
                $('.edit-transaction-data').addClass('d-none');
                $('.update-transaction-buttons').removeClass('d-none');
                $.each(res, function(config, field_data){
                    var field_id = field_data.field_id;
                    var field_current_value = $(`[data-field-name=${field_id}]`).text();
                    $(`[data-field-name=${field_id}]`).attr('data-current-value', field_current_value);

                    $(`[data-field-name=${field_id}]`).html(`
                        <input type="${field_data.field_type}" name="${field_id}" value="${$.trim(field_current_value)}" class="form-control rounded border border-secondary-subtle">
                    `);
                });
            }
        })
        
    });

    $('.update-transaction-data').on('click', function(e){
        e.preventDefault();

        var $this_button = $(this);
        var editable_inputs = $('#form-data-list').find('input');
        var editable_field_values = [];
        $.each(editable_inputs, function(i, input){
            var this_input = {
                name: $(input).attr('name'),
                value: $(input).val()
            }
            editable_field_values.push(this_input);
        });

        $.ajax({
            type: 'post',
            url: formipay_order_details_page.ajax_url,
            data: {
                action: 'formipay_update_editable_field_data',
                order_id: formipay_order_details_page.order_id,
                new_values: editable_field_values,
                _wpnonce: formipay_order_details_page.nonce
            },
            beforeSend: function() {
                set_loading_button($this_button, formipay_order_details_page.order_detail.update_button_loading_text);
            },
            success: function(res){
                remove_loading_button($this_button);
                if(res.success){
                    $('.edit-transaction-data').removeClass('d-none');
                    $('.update-transaction-buttons').addClass('d-none');
                    $.each(editable_inputs, function(i, input){
                        var new_value = $(input).val();
                        $(input).parent().removeAttr('data-current-value');
                        $(input).parent().text(new_value);
                    });
                    Swal.fire({
                        html: res.data.message,
                        icon: 'success'
                    });
                }else{
                    $.each(editable_inputs, function(i, input){
                        var current_value = $(input).parent().attr('data-current-value');
                        $(input).val(current_value);
                    });
                    Swal.fire({
                        html: res.data.message,
                        icon: 'error'
                    });
                }
            }
        });

    });

    $('.cancel-transaction-data').on('click', function(e){
        e.preventDefault();

        var editable_inputs = $('#form-data-list').find('input');
        $.each(editable_inputs, function(i, input){
            var current_value = $(input).parent().attr('data-current-value');
            $(input).parent().text(current_value);
        });
        $('.edit-transaction-data').removeClass('d-none');
        $('.update-transaction-buttons').addClass('d-none');

    });

    $('.edit-access-data').on('click', function(e){
        e.preventDefault();
        var $this_button = $(this);
        set_loading_button($this_button, formipay_order_details_page.order_detail.edit_button_loading_text);

        var current_method = $('li.access-method').attr('data-access-method');
        $('li.access-method').find('p').after(`
            <select name="access_method" id="access_method" class="form-select w-100 rounded border border-secondary-subtle" data-order-id="${$('#order_id').val()}" style="max-width: unset;">
                <option value="magic_link" ${(current_method == 'magic_link') ? 'selected' : ''}>${formipay_order_details_page.order_detail.pass_method.magic_link}</option>
                <option value="static_password" ${(current_method == 'static_password') ? 'selected' : ''}>${formipay_order_details_page.order_detail.pass_method.static_password}</option>
            </select>    
        `);
        $('#access_method').trigger('change');
        $('li.access-method').find('p').addClass('d-none');
        remove_loading_button($this_button);
        $('.edit-access-data').addClass('d-none');
        $('.update-access-buttons').removeClass('d-none');
    });

    $(document).on('change', '#access_method', function(){
        var access_password_li = $(this).closest('li').siblings('.access-password');
        if($(this).val() == 'static_password'){
            var password = access_password_li.attr('data-access-password');
            access_password_li.removeClass('d-none');
            access_password_li.find('p').after(`
                <input type="text" id="access_password" class="form-control w-100 rounded border border-secondary-subtle" value="${ password}">
            `);
            access_password_li.find('p').addClass('d-none');
        }else{
            access_password_li.addClass('d-none');
            access_password_li.find('input').remove();
        }
    });

    function normalize_access_data_card() {
        var accessMethod = $('li.access-method').attr('data-access-method');
        var accessPassword = $('li.access-password').attr('data-access-password');
        $('li.access-method select').remove();
        $('li.access-method p').removeClass('d-none');
        $('.edit-access-data').removeClass('d-none');
        $('.update-access-buttons').addClass('d-none');
        if( accessMethod == 'magic_link'){
            $('li.access-password').addClass('d-none');
        }
        $('li.access-method p').text(ucWords(accessMethod)).removeClass('d-none');
        $('li.access-password p').text(ucWords(accessPassword)).removeClass('d-none');
        $('li.access-password input').remove();
    }

    $('.cancel-access-data').on('click', function(e){
        e.preventDefault();
        normalize_access_data_card();
    });

    $('.update-access-data').on('click', function(e){
        e.preventDefault();

        var $this_button = $(this);
        var this_method = $('#access_method').val();
        var this_password = $('#access_password').val()

        $.ajax({
            type: 'post',
            url: formipay_order_details_page.ajax_url,
            data: {
                action: 'formipay_update_digital_access',
                order_id: formipay_order_details_page.order_id,
                method: this_method,
                password: this_password,
                _wpnonce: formipay_order_details_page.nonce
            },
            beforeSend: function() {
                set_loading_button($this_button, formipay_order_details_page.order_detail.update_button_loading_text);
            },
            success: function(res){
                remove_loading_button($this_button);
                if(res.success){
                    $('li.access-method').attr('data-access-method', this_method)
                    if(this_method == 'static_password'){
                        $('li.access-password').attr('data-access-password', this_password)
                    }
                    Swal.fire({
                        html: res.data.message,
                        icon: 'success'
                    });
                }else{
                    Swal.fire({
                        html: res.data.message,
                        icon: 'error'
                    });
                }
                normalize_access_data_card();
            }
        });

    });

    $(document).on('click', '.formipay-copy-button', function(e) {
        e.preventDefault();
        var $this = $(this);
        var copiedtext = $(this).attr("data-copy-value");
        if (navigator.clipboard) {
            navigator.clipboard.writeText(copiedtext)
                .then(() => {
                    $this.html('<i class="bi bi-check-circle-fill"></i> '+$this.attr('data-copied-text'));
                    setTimeout(() => {
                        $this.html('<i class="bi bi-copy"></i> '+$this.attr('data-copy-text'));
                    }, 1200);
                })
                .catch((error) => {
                    $this.html('<i class="bi bi-exclamation-circle-fill"></i> '+$this.attr('data-not-copied-text'));
                    setTimeout(() => {
                        $this.html('<i class="bi bi-copy"></i> '+$this.attr('data-copy-text'));
                    }, 1200);
                });
        } else {
            $this.html('<i class="bi bi-check-circle-fill"></i> '+$this.attr('data-not-copied-text'));
            setTimeout(() => {
                $this.html('<i class="bi bi-copy"></i> '+$this.attr('data-copy-text'));
            }, 1200);
        }

    });

});