$(document).on('click', '.sd-btn-add-actions', function (e) {
    e.preventDefault();
    const url = $(this).data('url');
    Modal.open(url, null, {
        title: _t('CONFIGURE_AUTOMATIONS'),
        id: 'configure-actions',
        bodyClass: 'configure-actions-body',
        headerClass: 'configure-actions-header'
    }, true, 'xl');
});

$(document).on('click', '.entity-action-widget .add-new-element-btn', function () {
    $('body').data('current-entity-action-button', $(this));
});
$(document).on('click', '.show-actions-selector', function (e) {
    e.preventDefault();
    $('.actions-selector').show();
});
$(document).on('click', '.add-action', function (e) {
    e.preventDefault();
    addAction($(this).attr('data-action'));
    angular.element('.go_to_actionsListArea').click();
});

$(document).on('click', '.collapse-all .show-all', function (e) {
    e.preventDefault();
    angular.element('.collapse-list-container .collapse').each(function () {
        angular.element(this).collapse('show');
    })
});

$(document).on('click', '.collapse-all .hide-all', function (e) {
    e.preventDefault();
    angular.element('.collapse-list-container .collapse:visible').each(function () {
        angular.element(this).collapse('hide');
    })
});

$(document).on('click', '.remove-action', function (e) {
    e.preventDefault();
    removeAction($(this).attr('data-action'));
});

$(document).off('click', '#save-action').on('click', '#save-action', function (e) {
    e.preventDefault();
    hideCreateTemplateForm();
    changeManageIconsVisibility(0);
    saveAction();
});

$(document).off('click', '#save-action-create-template').on('click', '#save-action-create-template', function (e) {
    e.preventDefault();
    var selectedTemplate = $('#actionTemplates').val();
    var templateTitle = $('#create-template-title').val();
    if (!selectedTemplate) {
        showCreateTemplateForm();
        if (!templateTitle) return false;
    }
    $('#save-action-create-template').addClass('disabled');
    saveAction();
});

$(document).off('click', '#cancel-create-template').on('click', '#cancel-create-template', function (e) {
    e.preventDefault();
    hideCreateTemplateForm();
});

$(document).off('change', '#actionTemplates').on('change', '#actionTemplates', function (e) {
    e.preventDefault();
    var selectedTemplate = $(this).val();
    if (selectedTemplate) {
        changeManageIconsVisibility(1);
        $.get("/site/entityAction.ApplyActionsTemplate", {
            templateID: $(this).val(),
            entityID: $('#entityID').val(),
            entityType: $('#entityType').val()
        })
            .done(function (result) {
                var actionForms = jQuery.parseJSON(result);
                var messages = actionForms.messages;
                if (actionForms) {
                    $.each(actionForms, function (action, newForm) {
                        var actionMainContainer = $('.action-main-container-' + action);
                        var actionFormContainer = $('#action-view-' + action);
                        if (actionFormContainer.css('display') === 'none') {
                            actionFormContainer.empty().html(newForm);
                            initializeDirectives(actionMainContainer);
                            addAction(action, 0);
                        }
                    });
                    if (messages) {
                        $.each(messages, function (index, message) {
                            jGrowlNotify(message, {animateOpen: {height: "show"}, life: 4000});
                        });
                    }
                    $('#actionTemplates').val('').trigger('change');
                } else {
                    changeManageIconsVisibility(0, 0);
                }
                angular.element('.go_to_actionsListArea').click();
            });
    } else {
        changeManageIconsVisibility(0, 0);
    }
    hideCreateTemplateForm();
});

$(document).off('click', '.delete-template').on('click', '.delete-template', function (e) {
    e.preventDefault();
    var templateID = $('#actionTemplates').val();
    swal({
        title: 'Are you sure?',
        type: 'warning',
        showConfirmButton: true,
        showCancelButton: true
    }).then(function (result) {
        if (result.value) {
            $.ajax({
                type: "GET",
                url: '/site/entityAction.DeleteTemplate/',
                data: {
                    templateID: $('#actionTemplates').val()
                }
            })
                .done(function (status) {
                    $("#actionTemplates option[value='" + templateID + "']").remove();
                    changeManageIconsVisibility(0);
                    jGrowlNotify("Template has been successfully deleted.", {
                        animateOpen: {height: "show"},
                        life: 20000
                    });
                    angular.element('.go_to_actionsListArea').click();
                });
        }
    });
    return false;
});

$(document).off('change', '#apply-template-display-actions').on('change', '#apply-template-display-actions', function (e) {
    e.preventDefault();
    var selectedTemplate = $(this).val();
    const userUUID = $('#apply-template-userUUID').val();
    const ids = $('#apply-template-userIds').val();
    let type = $('#apply-template-for-multiple-users-type').val();
    if (selectedTemplate && (userUUID || ids)) {
        let data = {
            templateUUID: selectedTemplate,
            op: 'actions'
        };

        let url = '/site/entityAction.UserTriggerTemplate';
        if ($('#apply-template-for-multiple-users').val()) {
            url = '/site/entityAction.MultipleUserTriggerTemplate';
            data.ids = ids;
            data.type = type;
        } else {
            data.userUUID = userUUID;
        }

        $.get(url, data)
            .done(function (result) {
                $('.apply-template-actions-container').empty().html(result);
            });
    }
});

$(document).off('click', '#apply-template-trigger-actions').on('click', '#apply-template-trigger-actions', function (e) {
    e.preventDefault();
    $('.trigger-automations').addClass('disabled')
    $('#apply-template-trigger-actions').text(_t('PROCESSING'));
    var selectedTemplate = $('#apply-template-display-actions').val();
    let type = $('#apply-template-for-multiple-users-type').val();
    if (selectedTemplate) {
        let data = {
            templateUUID: selectedTemplate,
            op: 'trigger'
        };

        let url = '/site/entityAction.UserTriggerTemplate';
        if ($('#apply-template-for-multiple-users').val()) {
            url = '/site/entityAction.MultipleUserTriggerTemplate';
            data.type = type;
            data.ids = $('#apply-template-userIds').val();
        } else {
            data.userUUID = $('#apply-template-userUUID').val();
        }

        $.get(url, data)
            .done(function (data) {
                if (data) {
                    data = JSON.parse(data);
                }

                if (data.message) {
                    notify(data.message);
                } else {
                    notify(_t('ACTION_TEMPLATE_SAVED'));
                }

                angular.element('.modal').scope().$close();
            })
            .fail(function () {
                $('.trigger-automations').removeClass('disabled');
                $('#apply-template-trigger-actions').text(_t('TRIGGER'));
                notify(_t('SYSTEM_ERROR_GENERIC'));
            });
    } else {
        $(this).attr('disabled', false);
        jGrowlNotify(_t('SELECT_TEMPLATE'), {animateOpen: {height: "show"}, life: 20000});
    }

    return false;
});

$(document).off('click', '.add-new-data-point-field').on('click', '.add-new-data-point-field', function (e) {
    var key = $('#lastFormField').val();
    key++;
    $.ajax({
        type: "POST",
        url: '/site/entityAction.LoadFormField/',
        data: {
            entityID: $('#entityID').val(),
            entityType: $('#entityType').val(),
            key: key
        }
    })
        .done(function (result) {
            $('.form-fields').append(result);
            $('#lastFormField').val(key);
        });

    return false;
});
$(document).off('click', '.remove-data-point-field').on('click', '.remove-data-point-field', function (e) {
    var key = $(this).data('key');
    $('#data-point-field-' + key).remove();

    return false;
});

function changeManageIconsVisibility($show, $resetActionsSelector = 1) {
    if ($show === 1) {
        $('.delete-template').show();
    } else {
        if ($resetActionsSelector === 1) {
            $('#actionTemplates').val('').trigger('change');
        }
        $('.delete-template').hide();
    }
}

function showCreateTemplateForm() {
    $('.save-new-template').show();
    $('#create-template-value').val(1);
    $('.modal').animate({
        scrollTop: parseInt($(".save-new-template").offset().top)
    }, 2000);
}

function hideCreateTemplateForm() {
    $('#create-template-title').val('');
    $('.save-new-template').hide();
    $('#create-template-value').val(0);
}

function saveAction() {
    $('#save-action').addClass('disabled');
    $.post("/site/entityAction.CreateEntityAction", {
        data: $(".actions-form *:input").serialize(),
        entityID: $('#entityID').val(),
        entityType: $('#entityType').val(),
        roleID: $('#roleID').val(),
        closeAll: $('#closeAll').val()
    })
        .done(function (data) {
            processSaveActionResult(data);
            $('#save-action').removeClass('disabled');
        });
}

function addAction(action, resetBlock = 1) {
    $('#action-view-' + action).show();
    if (resetBlock === 1) {
        resetActionBlock(action);
    }
    $('#action-selector-' + action).addClass('d-none');
    $('.actions-selector').hide();
    $('#added-' + action).attr('value', 1);
    generateContractResetOptions()
    convertInvoiceResetOptions()
    hideShowEmptyMessage(true)
}

function resetActionBlock(action) {
    $('#action-view-' + action + ' *:input:not(select[multiple],input[type="checkbox"],input[type="text"],select,input[type="radio"],input[type="hidden"])').val(null);
    $('#action-view-' + action + ' select[multiple]').val([]);
    $('#action-view-' + action + ' select').trigger('change.select2');
    $('#action-view-' + action + ' .redactor-container').each(function () {
        var scope = $(this).scope();
        var model = $(this).attr('ng-model');
        scope[model] = '';
        try {
            scope.$digest();
        } catch (e) {
        }
    });
    $('#action-view-' + action).find('.errorMessage').remove();
    $('#action-view-' + action).find('.form-control').removeClass('error');
}

function generateContractResetOptions() {
    $('#generate-contact-type').val('contact');
    $('#generate-estimate-type').val('estimate');
    $('#generate-invoice-type').val('invoice');
    $('#generate-proposal-type').val('proposal');
}

function convertInvoiceResetOptions() {
    $('#ConvertProposal_redirectAfterConvert').val(0).prop("checked", false);
    $('#ConvertProposal_sendEmail').val(0).prop("checked", false);
    $("#ConvertProposal_redirectAfterConvert").change(function () {
        if (this.checked) {
            $("#ConvertProposal_redirectAfterConvert").val(1);
        } else {
            $("#ConvertProposal_redirectAfterConvert").val(0);
        }
    });
    $("#ConvertProposal_sendEmail").change(function () {
        if (this.checked) {
            $("#ConvertProposal_sendEmail").val(1);
        } else {
            $("#ConvertProposal_sendEmail").val(0);
        }
    });
}

function removeAction(action) {
    $('#action-view-' + action).hide();
    $('#action-selector-' + action).removeClass('d-none');
    $('#added-' + action).attr('value', false);
    hideShowEmptyMessage(false)
}

function processSaveActionResult($result) {
    var IS_JSON = true;
    var saveButton = $('#save-action');
    try {
        var json = $.parseJSON($result);
    } catch (err) {
        IS_JSON = false;
    }
    if (!IS_JSON) {
        var $injector = angular.element(document.body).injector();
        $injector.invoke(($rootScope, $compile, $timeout) => {
            const element = angular.element('.actions-form').parent()
            element.html($result);
            angular.element('[uib-datepicker-popup-wrap]').remove()
            $compile(angular.element('.actions-form'))($rootScope);
        });
    } else {
        if (json.status === 'success') {
            if (typeof json.entityID !== 'undefined') {
                $('#entityID').val(json.entityID);
            }
            if (typeof json.refreshGridID !== 'undefined') {
                var $injector = angular.element('#' + json.refreshGridID).injector();
                $injector.invoke(($uibModalStack) => {
                    if (json.closeAll) {
                        $uibModalStack.dismissAll();
                    } else {
                        angular.element('.modal').scope().$close();
                        refreshConfiguredList();
                    }
                    var $scope = angular.element('#' + json.refreshGridID).scope();
                    $scope.GridView.update()
                });

            } else {
                angular.element('.modal').scope().$close();
                refreshConfiguredList();
            }
            notify(json.message);


        }
        if (json.status === 'error') {
            angular.element('.modal').scope().$close();
            notify(json.message);
        }
    }
}

function refreshConfiguredList() {
    $.get("/site/entityAction.DisplayConfigured",
        {
            entityID: $('#entityID').val(),
            entityType: $('#entityType').val(),
            roleID: $('#roleID').val(),
        },
        function (data) {
            const $button = $('body').data('current-entity-action-button');
            if ($button !== undefined) {
                $button.parents('.entity-action-widget-outer').find('.configured-actions').empty().html(data);
            }
        });
}

window.getUrlParameter = function (keyword, query_string) {
    keyword = keyword.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp(keyword + '=([^&#]*)');
    var results = regex.exec(query_string);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

//Document ready is triggered multiple times for Contracts Templates Actions
var loaded = false;
$(document).ready(() => {
    if (!loaded) {
        openActions();
        openInvoice();
        loaded = true
    }
});

function openInvoice() {
    if (getUrlParameter('open-invoice', window.location.search)) {
        var id = getUrlParameter('ref', window.location.search);
        if (id) {
            Modal.open('/invoices/' + id, null, {title: 'Invoice Info'}, true)
        }
    }
}

function openActions() {
    if (getUrlParameter('open-actions-modal', window.location.search)) {
        $('.entity-action-widget .add-new-element-btn').trigger('click');
    }
}

function initializeDirectives($element) {
    var $injector = angular.element(document.body).injector();
    $injector.invoke(['$compile', '$rootScope', function ($compile, $rootScope) {
        $compile($element)($rootScope);
        try {
            $rootScope.$digest();
        } catch (e) {
        }
    }]);
}

$(document).off('change', '#customField').on('change', '#customField', function (e) {
    $.ajax({
        type: "POST",
        url: '/site/entityAction.LoadCustomField/',
        data: {
            fieldID: $('#customField').val(),
            entityID: $('#entityID').val(),
            entityType: $('#entityType').val()
        }
    })
        .done(function (result) {
            if ($('#customField-' + $('#customField').val()).length == 0) {
                $('#customFieldValue').append(result);
                initializeDirectives($('#customField-' + $('#customField').val()));
            }
        });
});

$(document).off('change', '.communitiesSelect').on('change', '.communitiesSelect', function () {
    let communityUUID = $(this).val();
    if (!communityUUID) return;

    let model = $(this).attr('model');
    let that = $(this);
    let communityDivID = '#community-' + model + '-' + communityUUID;

    if ($(communityDivID).length > 0) {
        $(this).val('').trigger('change');
        return;
    }

    $(this).prop('disabled', true);

    $.ajax({
        type: "POST",
        url: '/site/entityAction.LoadCommunity/',
        data: {communityUUID: communityUUID, model: model}
    })
        .done(function (result) {
            $('#communitiesValue' + model).append(result);
            initializeDirectives($(communityDivID));
            $(that).val(null).trigger('change').prop('disabled', false);
        });
});

$(document).on('change', '.allSpacesCheckbox, .allPrivateSpacesCheckbox', function () {
    let select = $(this).closest('.divCommunitySpacesRemoveUserFromCommunities').find('.communitiesSpacesSelect');
    let disabled = false;
    if ($(this).is(":checked")) {
        disabled = true;
        $(select).val(null);
    }

    $(select).prop('disabled', disabled).trigger('change');
})

// this event was implemented because on multiple select after the dropdown is cleared and an option is selected
// the "Make a selection" placeholder became a selected option and this event remove this value
$(document).on('change', '.communitiesSpacesSelect', function () {
    let selectedValues = $(this).val();
    if (!selectedValues) return;

    let remove = false;
    if (selectedValues[0] == '') {
        selectedValues.shift();
        remove = true;
    }

    if (remove) {
        $(this).val(selectedValues).trigger('change');
    }
})

$(document).off('change', '.invoiceProfileAction').on('change', '.invoiceProfileAction', function (e) {
    let invoiceProfileId = $(this).val();

    $.ajax({
        type: "GET",
        url: '/site/entityAction.LoadDynamicInvoiceProfileItem?id=' + invoiceProfileId,
    })
        .done(function (result) {
            let element = $('#dynamic-row');
            element.html(result);
            initializeDirectives(element);
        });
});

function deleteCustomField(elem) {
    $(elem).closest('div.form-group').remove();
}

function hideShowEmptyMessage(hideDirectly) {
    if (angular.element('.collapse-list-container .chain-link:visible').length || hideDirectly) {
        angular.element('.actions-form .empty-message').hide()
        angular.element('.actions-form .save-btn-bottom').show()
        angular.element('.actions-form .save-template').removeClass('disabled')
    } else {
        angular.element('.actions-form .empty-message').show()
        angular.element('.actions-form .save-btn-bottom').hide()
        angular.element('.actions-form .save-template').addClass('disabled')
    }
}

$(document).off('change', '.enable-data-calculation-switcher').on('change', '.enable-data-calculation-switcher', function (e) {
    $(this).closest(".customFieldValueLine").find('.form-group_customized-input-label-block input').val('');
});

$(document).off('change', '.set-current-date-switcher').on('change', '.set-current-date-switcher', function (e) {
    console.log($(this).closest(".customFieldValueLine").find('.enable-data-calculation-switcher-div span'));
    $(this).closest(".customFieldValueLine").find('.form-group_customized-input-label-block input').val('');
    if ($(this).is(":checked")) {
        if ($(this).closest(".customFieldValueLine").find('.enable-data-calculation-switcher').is(":checked")) {
            $(this).closest(".customFieldValueLine").find('.enable-data-calculation-switcher').trigger('click');
        }

        $(this).closest(".customFieldValueLine").find('.form-group_customized-input-label-block input').attr('readonly', true);
    } else {
        $(this).closest(".customFieldValueLine").find('.form-group_customized-input-label-block input').attr('readonly', false);
    }

});

// Event for cancel-subscriptions dropdown change
$(document).off('change', '#cancel-subscriptions').on('change', '#cancel-subscriptions', function (e) {
    // Get the selected values from the cancel dropdown
    var selectedValues = $(this).val();

    // Remove all options except the placeholder (option with empty value)
    $('#payment-method-source option:not([value=""])').remove();

    // Loop through the selected values and append them to the source dropdown
    if (selectedValues && selectedValues.length > 0) {
        $.each(selectedValues, function (index, value) {
            // Get the text of the selected option
            var optionText = $('#cancel-subscriptions option[value="' + value + '"]').text();

            // Append the new option to the source dropdown without setting it as selected
            $('#payment-method-source').append(
                $('<option></option>').attr('value', value).text(optionText)
            );
        });
    }
});


