var ScheduledEmailReportsView = Backbone.View.extend({
    events: {
        'click .card-panel-entity': 'highlightCard',
        'click .edit-schedule-trigger': 'editSchedule',
        'click #add-schedule-button': 'addSchedule',
        'click .save-button': 'saveSchedule',
        'click #deleteScheduledEmailReportBtn': 'openConfirmDeleteModal',
        'click #delete-scheduled-email-report-confirm': 'deleteSchedule',

    },

    scheduledReports: [],

    breadcrumb: [{
        path: '#/scheduled-email-reports',
        label: '{Literal}Scheduled Email Reports{/Literal}'
    }],

    styles: [
        'ap-blue',
        '#31619e'
    ],

    reports:{
        "z_reset_summary": { name:"{Literal}Last Z Reset Summary{/Literal}", options:['till']},
        "z_out_summary": { name:"{Literal}Z-Out Summary Report{/Literal}", options:[]},
        "z_out_cloud_summary": { name:"{Literal}Cloud Summary Report{/Literal}", options:['locations']},
        "employee_hour_report": { name:"{Literal}Employee Hour Report{/Literal}", options:['employee']},
        "sales_by_hour": { name:"{Literal}Sales by Hour Report{/Literal}", options:['till']},
        "sales_by_user": { name:"{Literal}Sales by User{/Literal}", options:[]},
        "sales_by_customer": { name:"{Literal}Sales by Customer{/Literal}", options:['customer']},
        "sales_by_item_category": { name:"{Literal}Sales by Item Category{/Literal}", options:[]},
        "sales_by_item_type": { name:"{Literal}Sales by Item Types Report{/Literal}", options:[]},
        "gratuity_report": { name:"{Literal}Gratuity Report{/Literal}", options:[]},
        "sales_tax": { name:'{Literal}Sales Tax Report{/Literal}', options:[]},
        "account_receivables_by_date_range": { name:'{Literal}Account Receivables By Date Range{/Literal}', options:[]},
    },

    initialize: async function (options) {
        var that = this;
        App.setBreadcrumbs(this.breadcrumb);
        this.options = options;
        this.model = options.model;
        this.formTemplate = options.formTemplate;
        this.template = _.template(options.template);
        if(!App.serverInfo.hasCloudReporting)
            delete this.reports['z_out_cloud_summary'];

        if(App.serverInfo.hasCloudReporting && !App.cloudLocations)
            await this.getLocations();

        if(!App.tillsList)
            await this.getTills();

        this.getSchedulesList();

        if(App.serverInfo.hasDesktopAccounting && App.serverInfo.country == 'IL') {
            this.reports['movein.zip'] = { name:"{Literal}Movein Report{/Literal}", options:[]};
        }
    },

    render: function () {
        // this.$el.detach();

        this.$el.html(this.template({
            scheduledReports: this.scheduledReports,
            reports: this.reports
        }));
        return this;
    },

    editSchedule: async function (e) {
        var that = this;
        var element = $(e.currentTarget);
        var id = $(element).attr('data-id');
        var selectedScheduledReport = this.scheduledReports.find( i => i.id == id);
        this.scheduledEmailReportsFormView = new ScheduledEmailReportsFormView({
            template: this.formTemplate,
            reports: this.reports,
            scheduledReport: selectedScheduledReport,
        });

        this.$el.find('#scheduled-email-reports-form-modal').html(this.scheduledEmailReportsFormView.render().el);
        this.formModal = this.$el.find('#scheduled-email-reports-form-modal').modal();
        this.formModal.modal('open');
    },
    addSchedule: async function (e) {
        var that = this;
        this.scheduledEmailReportsFormView = new ScheduledEmailReportsFormView({
            template: this.formTemplate,
            reports: this.reports,
            scheduledReport: { reportName: 'z_reset_summary', emailList:[''], id: 0, time: 0, locations: '', active: true},
        });

        this.$el.find('#scheduled-email-reports-form-modal').html(this.scheduledEmailReportsFormView.render().el);
        this.formModal = this.$el.find('#scheduled-email-reports-form-modal').modal();
        this.formModal.modal('open');
    },

    saveSchedule: function () {
        var that = this;
        var isValidForm = this.validateForm();
        var formValues = this.getFormValues();
        if(!isValidForm)
            return;
        $.ajax({
            url: "data/save-scheduled-reports",
            data: {
                token: getCookie(),
                schedule: JSON.stringify(formValues)
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                if(data.success) {
                    M.toast({html:"{Literal}Data Saved{/Literal}"});
                    that.formModal.modal('close');

                }else {
                    M.toast({html:"{Literal}There was a problem fetching data from the server{/Literal}"});
                }
                that.getSchedulesList();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else {
                    M.toast({
                        html:
                            "{Literal}There was a problem fetching data from the server{/Literal}",
                    });
                }
            },
        });
    },

    validateForm: function () {
        var isValid = true;
        var element = document.getElementById('description');
        if(element.value == '') {
            isValid = false;
            element.classList.add('invalid');
        }

        var emailElements = document.querySelectorAll('.email[type=email]');
        for (const emailInput of emailElements) {
            isValid = isValid && !emailInput.classList.contains('invalid');
        }
        
        return isValid;

    },

    getFormValues: function () {
        var formValues = {
            emailList: [],
        }

        var selectedReport = document.getElementById('reportName').value;
        formValues.reportName = selectedReport;
        formValues.description = document.getElementById('description').value;
        formValues.id = document.getElementById('id').value;
        formValues.active = document.getElementById('active').checked;
        formValues.sendEvery = document.getElementById('sendEvery').value;
        if(formValues.sendEvery.includes('Week'))
            formValues.dayOfWeek = document.getElementById('dayOfWeek').value;
        if(formValues.sendEvery.includes('Month'))
            formValues.dayOfMonth = document.getElementById('dayOfMonth').value;

        var time = document.getElementById('time').value;
        var timeValue = parseInt( time.split(':')[0]);
        if(time.includes('PM'))
            timeValue += 12;

        formValues.time = timeValue;

        // var date = document.getElementById('startDate').value;
        // var time = document.getElementById('startTime').value;
        // hour = parseInt( time.split(':')[0]);
        // if(time.includes('PM'))
        //     hour += 12;

        // formValues.startFrom = `${date}T${hour}:00:00Z`

        var reportOptions = this.reports[selectedReport].options;

        reportOptions.forEach( option => {
            var thisOptionEl = document.querySelector(`div[data-option="${option}"]`);
            if(thisOptionEl.style.display == 'block'){
                var el = thisOptionEl.querySelector('#'+option);
                var isMultiSelect = el.hasAttribute('multiple');
                if(isMultiSelect)
                    formValues[option] = el.M_FormSelect.getSelectedValues().join(';');
                else
                    formValues[option] = el.value;
            }
            
        })

        var emailInputs = document.querySelectorAll('.email');
        for(input of emailInputs){
            if(input.value != '')
                formValues.emailList.push(input.value);
        }

        return formValues;
    },

    highlightCard: function (e) {
        this.$el.find('.edit').hide();
        this.$el.find('.card-panel-entity').removeClass('active');
        var element = $(e.currentTarget);
        var selected = $(element).attr('data-selected') === '1';
        
        if (selected) {
            $(element).removeAttr('data-selected');
            $(element).removeClass('active');
            $(element).find('.edit').hide();
        } else {
            $(element).removeAttr('data-selected');
            $(element).attr('data-selected', '1');
            $(element).find('.edit').show();
            $(element).addClass('active');
        }
    },

    getSchedulesList: async function () {
        var that = this;
        var sessionToken = getCookie();

        return $.ajax({
            url: "data/get-scheduled-reports",
            data: {
                token: sessionToken,
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                data.scheduledReports.sort( (a,b) => {return a.id - b.id});
                that.scheduledReports = data.scheduledReports;
                that.render();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else {
                    M.toast({
                        html:
                            "{Literal}There was a problem fetching data from the server{/Literal}",
                    });
                }
            },
        });
    },
    getLocations: async function () {
        var that = this;
        var sessionToken = getCookie();

        return $.ajax({
            url: "data/get-locations",
            data: {
                token: sessionToken,
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                App.cloudLocations = data.results;
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else {
                    M.toast({
                        html:
                            "{Literal}There was a problem fetching data from the server{/Literal}",
                    });
                }
            },
        });
    },
    getTills: async function () {
        var sessionToken = getCookie();
        var that = this;
        $.ajax({
            url: '/data/get-tills-list',
            data: {
                token: sessionToken,
                includeInactive: false
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                App.tillsList = data.results;
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({
                        html: '{Literal}There was a problem fetching tills from the server{/Literal}'
                    });
                }
            }
        });
    },
    openConfirmDeleteModal: function() {
        this.formModal = this.$el.find('#delete-scheduled-email-report-modal').modal();
        this.formModal.modal('open');
    },

    deleteSchedule: function () {
        var that = this;
        var id = document.getElementById('id').value;

        $.ajax({
            url: "data/delete-scheduled-reports",
            data: {
                token: getCookie(),
                id: id
            },
            dataType: "json",
            type: "POST",
            success: function (data) {
                if(data.success) {
                    M.toast({html:"{Literal}Data Saved{/Literal}"});
                }else {
                    M.toast({html:"{Literal}There was a problem fetching data from the server{/Literal}"});
                }
                that.getSchedulesList();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                } else {
                    M.toast({
                        html:
                            "{Literal}There was a problem fetching data from the server{/Literal}",
                    });
                }
            },
        });
    }
})