(function ($) {
    "use strict";

    /* ===================================
            Order Functions
    ====================================== */

    //Delivery Date/Time
    jQuery(document).ready(function () {
        let countdown = jQuery('#gn-order-delivery-countdown');
        let deliveryStr = countdown.data('gn-delivery');
        let nowStr = countdown.data('gn-now');

        if (countdown.length && deliveryStr) {


            let deliveryTime = new Date(deliveryStr.replace(' ', 'T'));
            let currentTime = new Date(nowStr.replace(' ', 'T'));

            var interval = setInterval(function () {
                var diff = deliveryTime - currentTime;

                if (isNaN(diff) || diff <= 0) {
                    clearInterval(interval);
                    jQuery('#gn-days, #gn-hours, #gn-minutes, #gn-seconds').text('00');
                    countdown.removeClass('gn-status-pending').addClass('gn-status-delivered');
                    return;
                }

                var days = Math.floor(diff / (1000 * 60 * 60 * 24));
                var hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
                var minutes = Math.floor((diff / (1000 * 60)) % 60);
                var seconds = Math.floor((diff / 1000) % 60);

                // Replace NaN with 0 before formatting
                days = isNaN(days) ? 0 : days;
                hours = isNaN(hours) ? 0 : hours;
                minutes = isNaN(minutes) ? 0 : minutes;
                seconds = isNaN(seconds) ? 0 : seconds;

                jQuery('#gn-days').text(('0' + days).slice(-2));
                jQuery('#gn-hours').text(('0' + hours).slice(-2));
                jQuery('#gn-minutes').text(('0' + minutes).slice(-2));
                jQuery('#gn-seconds').text(('0' + seconds).slice(-2));

                // increment current time by 1 second
                currentTime = new Date(currentTime.getTime() + 1000);
            }, 1000);
        }
    });

    $(document).on('click', '#service-order-cancel-request', function (e) {
        e.preventDefault();

        let proceed = true;
        let submit_btn = $(document).find('#service-order-cancel-request');
        let form_data = new FormData();
        let editor = tinymce.get('gn-order-cancel-description');
        let description = editor.getContent();
        let order_id = $(document).find('#gn-order-id').val();
        let reason = $(document).find('#gn-order-cancel-reason').val();

        form_data.append('action', 'gigneo_service_order_cancel_by_moderator');
        form_data.append('security', GigneoBackendCommon.security);
        form_data.append('order_id', order_id);
        form_data.append('reason', reason);
        form_data.append('description', description);

        // Force TinyMCE editors to save content to textarea
        if (typeof tinyMCE !== 'undefined') {
            tinyMCE.triggerSave();
        }

        proceed = window.GigneoRequiredFormFields.init(submit_btn.parents('.gn-modal-wrapper'), proceed);

        if (!proceed) {
            return false;
        }

        submit_btn.addClass('gn-loading');

        $.ajax({
            url: GigneoBackendCommon.ajax_url,
            method: 'POST',
            data: form_data,
            processData: false,
            contentType: false,
            success: function (response) {
                submit_btn.removeClass('gn-loading');
                location.reload();
                $('.gn-modal-wrapper').removeClass('gn-active');
                if (response.success && response.data.message) {
                    GigneoAlert.toast({
                        icon: 'success',
                        title: GigneoBackendCommon.success,
                        text: response.data.message
                    });
                }
            },
            error: function (xhr, status, error) {
                submit_btn.removeClass('gn-loading');
                location.reload();
                let error_message = xhr?.responseJSON?.data?.message || GigneoBackendCommon.went_wrong;
                GigneoAlert.toast({
                    icon: 'error',
                    title: GigneoBackendCommon.error,
                    text: error_message
                });
            }
        });
    });

    $(document).on('click', '#service-order-complete-request', function (e) {
        e.preventDefault();
        let _this = $(this);
        let proceed = true;
        let submit_btn = $(document).find('#service-order-complete-request');
        let form_data = new FormData();
        let editor = tinymce.get('gn-order-complete-description');
        let reason = $(document).find('#gn-order-complete-reason').val();
        let description = editor.getContent();
        let order_id = $(document).find('#gn-order-id').val();
        form_data.append('action', 'gigneo_service_order_complete_by_moderator');
        form_data.append('security', GigneoBackendCommon.security);
        form_data.append('order_id', order_id);
        form_data.append('reason', reason);
        form_data.append('description', description);


        // Force TinyMCE editors to save content to textarea
        if (typeof tinyMCE !== 'undefined') {
            tinyMCE.triggerSave();
        }
        proceed = window.GigneoRequiredFormFields.init(submit_btn.parents('.gn-modal-wrapper'), proceed);

        if (!proceed) {
            return false;
        }
        submit_btn.addClass('gn-loading');

        $.ajax({
            url: GigneoBackendCommon.ajax_url,
            method: 'POST',
            data: form_data,
            processData: false,
            contentType: false,
            success: function (response) {
                submit_btn.removeClass('gn-loading');
                location.reload();
                $('.gn-modal-wrapper').removeClass('gn-active');
                if (response.success && response.data.message) {
                    GigneoAlert.toast({
                        icon: 'success',
                        title: GigneoBackendCommon.success,
                        text: response.data.message
                    });
                }
            },
            error: function (xhr, status, error) {
                submit_btn.removeClass('gn-loading');
                location.reload();
                let error_message = xhr?.responseJSON?.data?.message || GigneoBackendCommon.went_wrong;
                GigneoAlert.toast({
                    icon: 'error',
                    title: GigneoBackendCommon.error,
                    text: error_message
                });
            }
        });
    });

    $(document).on('click', '#job-order-cancel-request', function (e) {
        e.preventDefault();

        let proceed = true;
        let submit_btn = $(document).find('#job-order-cancel-request');
        let form_data = new FormData();
        let editor = tinymce.get('gn-order-cancel-description');
        let description = editor.getContent();
        let order_id = $(document).find('#gn-order-id').val();
        let reason = $(document).find('#gn-order-cancel-reason').val();

        form_data.append('action', 'gigneo_job_order_cancel_by_moderator');
        form_data.append('security', GigneoBackendCommon.security);
        form_data.append('order_id', order_id);
        form_data.append('reason', reason);
        form_data.append('description', description);

        // Force TinyMCE editors to save content to textarea
        if (typeof tinyMCE !== 'undefined') {
            tinyMCE.triggerSave();
        }

        proceed = window.GigneoRequiredFormFields.init(submit_btn.parents('.gn-modal-wrapper'), proceed);

        if (!proceed) {
            return false;
        }

        submit_btn.addClass('gn-loading');

        $.ajax({
            url: GigneoBackendCommon.ajax_url,
            method: 'POST',
            data: form_data,
            processData: false,
            contentType: false,
            success: function (response) {
                submit_btn.removeClass('gn-loading');
                location.reload();
                $('.gn-modal-wrapper').removeClass('gn-active');
                if (response.success && response.data.message) {
                    GigneoAlert.toast({
                        icon: 'success',
                        title: GigneoBackendCommon.success,
                        text: response.data.message
                    });
                }
            },
            error: function (xhr, status, error) {
                submit_btn.removeClass('gn-loading');
                location.reload();
                let error_message = xhr?.responseJSON?.data?.message || GigneoBackendCommon.went_wrong;
                GigneoAlert.toast({
                    icon: 'error',
                    title: GigneoBackendCommon.error,
                    text: error_message
                });
            }
        });
    });

    $(document).on('click', '#job-order-complete-request', function (e) {
        e.preventDefault();
        let _this = $(this);
        let proceed = true;
        let submit_btn = $(document).find('#job-order-complete-request');
        let form_data = new FormData();
        let editor = tinymce.get('gn-order-complete-description');
        let reason = $(document).find('#gn-order-complete-reason').val();
        let description = editor.getContent();
        let order_id = $(document).find('#gn-order-id').val();
        form_data.append('action', 'gigneo_job_order_complete_by_moderator');
        form_data.append('security', GigneoBackendCommon.security);
        form_data.append('order_id', order_id);
        form_data.append('reason', reason);
        form_data.append('description', description);


        // Force TinyMCE editors to save content to textarea
        if (typeof tinyMCE !== 'undefined') {
            tinyMCE.triggerSave();
        }
        proceed = window.GigneoRequiredFormFields.init(submit_btn.parents('.gn-modal-wrapper'), proceed);

        if (!proceed) {
            return false;
        }
        submit_btn.addClass('gn-loading');

        $.ajax({
            url: GigneoBackendCommon.ajax_url,
            method: 'POST',
            data: form_data,
            processData: false,
            contentType: false,
            success: function (response) {
                submit_btn.removeClass('gn-loading');
                location.reload();
                $('.gn-modal-wrapper').removeClass('gn-active');
                if (response.success && response.data.message) {
                    GigneoAlert.toast({
                        icon: 'success',
                        title: GigneoBackendCommon.success,
                        text: response.data.message
                    });
                }
            },
            error: function (xhr, status, error) {
                submit_btn.removeClass('gn-loading');
                location.reload();
                let error_message = xhr?.responseJSON?.data?.message || GigneoBackendCommon.went_wrong;
                GigneoAlert.toast({
                    icon: 'error',
                    title: GigneoBackendCommon.error,
                    text: error_message
                });
            }
        });
    });

    //Order Invoice Download
    $(document).on('click', '.gn-service-order-invoice-download', function (e) {
        e.preventDefault();
        let _this = $(this);
        let invoice_id = _this.data('gn-invoice-id');

        if (invoice_id === '') {
            return false;
        }

        _this.addClass('gn-loading');

        $.ajax({
            url: GigneoBackendCommon.ajax_url,
            method: 'POST',
            data: {
                action: 'gigneo_moderator_invoice_download',
                id: invoice_id,
                security: GigneoBackendCommon.security
            },
            success: function (response) {
                _this.removeClass('gn-loading');
                if (response.data.file_data && response.data.file_name) {
                    const byteCharacters = atob(response.data.file_data);
                    const byteNumbers = new Array(byteCharacters.length);
                    for (let i = 0; i < byteCharacters.length; i++) {
                        byteNumbers[i] = byteCharacters.charCodeAt(i);
                    }
                    const byteArray = new Uint8Array(byteNumbers);
                    const blob = new Blob([byteArray], { type: 'application/pdf' });
                    const url = window.URL.createObjectURL(blob);

                    const a = document.createElement('a');
                    a.href = url;
                    a.download = response.data.file_name;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                } else {
                    GigneoAlert.toast({
                        icon: 'error', title: GigneoBackendCommon.error, text: GigneoBackendCommon.went_wrong
                    });
                }
            }, error: function (xhr, status, error) {
                _this.removeClass('gn-loading');
                let error_message = xhr?.responseJSON?.data.message || GigneoBackendCommon.went_wrong;
                GigneoAlert.toast({
                    icon: 'error', title: GigneoBackendCommon.error, text: error_message
                });
            }
        });

    });

    $(document).ready(function () {
        window.GigneoGoogleMap?.init();  //Init GoogleMap
    });


    $(document).ready(scrollToNewMessage);

    function scrollToNewMessage() {
        const $body = $('#gn-order-messages-body');
        if ($body.length) {
            $body.scrollTop($body[0].scrollHeight);
        }
    }

    $(document).on('click', '#gn-order-attachments .gn-attachment-filters > li', function (e) {
        e.preventDefault();

        let _this = $(this);
        let filter = _this.data('gn-filter');
        let wrapper = $('#gn-order-attachments .gn-attachment-list');

        if ('all' === filter) {
            wrapper.find('li.gn-attachment').show();
        } else {
            wrapper.find('li.gn-attachment').hide();
            wrapper.find(`li.gn-attachment.gn-${filter}`).show();
        }

        _this.siblings().removeClass('gn-active');
        _this.addClass('gn-active');
    });
    

}(jQuery));