/**
 * Email Reports Admin JavaScript
 * Modern, clean interactions with sidebar section selection
 */
(function($) {
    'use strict';

    var EmailReports = {
        currentSection: null,
        hasUnsavedChanges: false,
        initialFormState: null,

        init: function() {
            this.bindEvents();
            this.initColorPicker();
            this.initMediaUploader();
            this.initSectionSelection();
            this.initUnsavedChangesTracking();
            this.loadHistoryIfNeeded();
        },

        bindEvents: function() {
            var self = this;

            // Schedule type toggle
            $('#setting_schedule').on('change', function() {
                var value = $(this).val();
                $('.day-of-week-row').toggle(value === 'weekly');
                $('.day-of-month-row').toggle(value === 'monthly');
            });

            // Send test email
            $('#send-test-btn').on('click', function(e) {
                e.preventDefault();
                self.sendTestEmail($(this));
            });

            // Send now (manual trigger)
            $('#send-now-btn').on('click', function(e) {
                e.preventDefault();
                if (confirm(switchboardEmailReports.i18n.confirmSend)) {
                    self.sendNow($(this));
                }
            });

            // Refresh section preview (per-section button)
            $(document).on('click', '.sb-er-refresh-preview', function(e) {
                e.preventDefault();
                var sectionId = $(this).data('section');
                self.loadSectionPreview(sectionId);
            });

            // Refresh full preview (on preview tab)
            $('#refresh-full-preview-btn').on('click', function(e) {
                e.preventDefault();
                self.loadPreview();
            });

            // Delete history entry
            $(document).on('click', '.delete-history-btn', function(e) {
                e.preventDefault();
                if (confirm(switchboardEmailReports.i18n.confirmDelete)) {
                    self.deleteHistoryEntry($(this).data('id'));
                }
            });

            // Section item click in sidebar - select section
            $(document).on('click', '.sb-er-section-item', function() {
                var sectionId = $(this).data('section');
                if (!$(this).hasClass('disabled')) {
                    self.selectSection(sectionId);
                }
            });

            // Recipients type toggle - show/hide custom recipients
            $(document).on('change', '.sb-er-recipients-type', function() {
                var sectionId = $(this).data('section');
                var $customRecipientsField = $('#custom-recipients-field-' + sectionId);

                if ($(this).val() === 'custom') {
                    $customRecipientsField.slideDown(200);
                } else {
                    $customRecipientsField.slideUp(200);
                }
            });

            // Delivery mode toggle - show/hide global recipients and toggle section recipients
            $('#setting_delivery_mode').on('change', function() {
                var mode = $(this).val();
                self.updateDeliveryModeUI(mode);
            });

            // Global recipients type toggle
            $('#setting_global_recipients_type').on('change', function() {
                if ($(this).val() === 'custom') {
                    $('#global-custom-recipients-wrapper').slideDown(200);
                } else {
                    $('#global-custom-recipients-wrapper').slideUp(200);
                }
            });

            // Section enabled toggle - auto-refresh preview
            $(document).on('change', 'input[name^="section_settings["][name$="][enabled]"]', function() {
                var match = $(this).attr('name').match(/section_settings\[([^\]]+)\]\[enabled\]/);
                if (match && match[1]) {
                    var sectionId = match[1];
                    // If we're viewing this section or in combined mode, refresh preview
                    if (self.currentSection === sectionId || $('#setting_delivery_mode').val() === 'combined') {
                        self.loadSectionPreview(self.currentSection);
                    }
                }
            });
        },

        initSectionSelection: function() {
            // Settings panel is shown by default, so currentSection should be 'settings'
            var $activeItem = $('.sb-er-section-item.active').first();
            if ($activeItem.length) {
                this.currentSection = $activeItem.data('section');
            }

            // Initialize delivery mode UI state
            var mode = $('#setting_delivery_mode').val() || 'combined';
            this.updateDeliveryModeUI(mode);
        },

        updateDeliveryModeUI: function(mode) {
            if (mode === 'combined') {
                // Show global recipients settings
                $('#global-recipients-wrapper').slideDown(200);

                // Show/hide global custom recipients based on type
                if ($('#setting_global_recipients_type').val() === 'custom') {
                    $('#global-custom-recipients-wrapper').slideDown(200);
                } else {
                    $('#global-custom-recipients-wrapper').slideUp(200);
                }

                // Grey out individual section recipients
                $('.sb-er-section-recipients').addClass('sb-er-recipients-disabled');
            } else {
                // Hide global recipients settings
                $('#global-recipients-wrapper').slideUp(200);
                $('#global-custom-recipients-wrapper').slideUp(200);

                // Enable individual section recipients
                $('.sb-er-section-recipients').removeClass('sb-er-recipients-disabled');
            }
        },

        selectSection: function(sectionId) {
            if (this.currentSection === sectionId) {
                return; // Already selected
            }

            this.currentSection = sectionId;

            // Update sidebar active states
            $('.sb-er-section-item').removeClass('active');
            $('.sb-er-section-item[data-section="' + sectionId + '"]').addClass('active');

            // Hide all panels
            $('.sb-er-panel').hide();

            if (sectionId === 'settings') {
                // Show settings panel
                $('#settings-panel').show();
            } else {
                // Show the section panel
                $('#section-panel-' + sectionId).show();

                // Auto-load preview when section is selected
                this.loadSectionPreview(sectionId);
            }
        },

        loadSectionPreview: function(sectionId) {
            if (!sectionId) {
                return;
            }

            var self = this;
            var $preview = $('.sb-er-section-preview[data-section="' + sectionId + '"]');

            if (!$preview.length) {
                return;
            }

            $preview.html(
                '<div class="sb-er-preview-loading">' +
                    '<span class="spinner is-active"></span>' +
                    '<span>' + (switchboardEmailReports.i18n.loading || 'Loading preview...') + '</span>' +
                '</div>'
            );

            // Check delivery mode - if combined, show all enabled sections together
            var deliveryMode = $('#setting_delivery_mode').val() || 'combined';
            var sectionsToPreview = sectionId;

            if (deliveryMode === 'combined') {
                // Collect all enabled section IDs from their panel checkboxes
                var enabledSections = [];
                $('input[name^="section_settings["][name$="][enabled]"]').each(function() {
                    if ($(this).is(':checked')) {
                        // Extract section ID from name like "section_settings[track-404s][enabled]"
                        var match = $(this).attr('name').match(/section_settings\[([^\]]+)\]\[enabled\]/);
                        if (match && match[1]) {
                            enabledSections.push(match[1]);
                        }
                    }
                });
                sectionsToPreview = enabledSections.length > 0 ? enabledSections.join(',') : sectionId;
            }

            $.ajax({
                url: switchboardEmailReports.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'switchboard_email_reports_preview_section',
                    nonce: switchboardEmailReports.nonce,
                    section: sectionsToPreview
                },
                success: function(response) {
                    if (response.success) {
                        // Create iframe to display HTML
                        var iframe = document.createElement('iframe');
                        $preview.empty().append(iframe);

                        var doc = iframe.contentWindow.document;
                        doc.open();
                        doc.write(response.data.html);
                        doc.close();

                        // Adjust iframe height based on content
                        setTimeout(function() {
                            try {
                                var height = doc.body.scrollHeight + 40;
                                iframe.style.height = Math.max(height, 300) + 'px';
                            } catch(e) {}
                        }, 100);
                    } else {
                        $preview.html(
                            '<div class="sb-er-preview-loading" style="color: #ef4444;">' +
                                (response.data && response.data.message ? response.data.message : 'Failed to load preview.') +
                            '</div>'
                        );
                    }
                },
                error: function() {
                    $preview.html('<div class="sb-er-preview-loading" style="color: #ef4444;">Connection error.</div>');
                }
            });
        },

        initColorPicker: function() {
            // Sync color picker with text input
            $('#setting_primary_color_picker').on('input', function() {
                $('#setting_primary_color').val($(this).val());
            });

            $('#setting_primary_color').on('input', function() {
                var val = $(this).val();
                if (/^#[0-9A-Fa-f]{6}$/.test(val)) {
                    $('#setting_primary_color_picker').val(val);
                }
            });
        },

        initMediaUploader: function() {
            var mediaUploader;

            $('#upload-logo-btn').on('click', function(e) {
                e.preventDefault();

                if (mediaUploader) {
                    mediaUploader.open();
                    return;
                }

                mediaUploader = wp.media({
                    title: switchboardEmailReports.i18n.selectImage,
                    button: {
                        text: switchboardEmailReports.i18n.useImage
                    },
                    multiple: false,
                    library: {
                        type: 'image'
                    }
                });

                mediaUploader.on('select', function() {
                    var attachment = mediaUploader.state().get('selection').first().toJSON();
                    var url = attachment.sizes && attachment.sizes.medium
                        ? attachment.sizes.medium.url
                        : attachment.url;

                    $('#setting_logo_id').val(attachment.id);
                    $('#logo-preview').html('<img src="' + url + '" alt="">').show();
                    $('#remove-logo-btn').show();
                });

                mediaUploader.open();
            });

            $('#remove-logo-btn').on('click', function(e) {
                e.preventDefault();
                $('#setting_logo_id').val('');
                $('#logo-preview').hide().empty();
                $(this).hide();
            });
        },

        showFeedback: function(type, message) {
            var $feedback = $('#email-feedback');
            $feedback
                .removeClass('success error warning')
                .addClass(type)
                .text(message)
                .slideDown(200);

            // Auto-hide success messages
            if (type === 'success') {
                setTimeout(function() {
                    $feedback.slideUp(200);
                }, 5000);
            }
        },

        hideFeedback: function() {
            $('#email-feedback').slideUp(200);
        },

        // Toast notifications
        showToast: function(type, message) {
            // Remove existing toast
            $('.sb-er-toast').remove();

            var iconSvg = type === 'success'
                ? '<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" width="20" height="20"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>'
                : '<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" width="20" height="20"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>';

            var $toast = $('<div class="sb-er-toast sb-er-toast-' + type + '">' +
                '<span class="sb-er-toast-icon">' + iconSvg + '</span>' +
                '<span class="sb-er-toast-message">' + message + '</span>' +
                '<button type="button" class="sb-er-toast-close">&times;</button>' +
                '</div>');

            $('body').append($toast);

            // Animate in
            setTimeout(function() {
                $toast.addClass('show');
            }, 10);

            // Close button
            $toast.find('.sb-er-toast-close').on('click', function() {
                $toast.removeClass('show');
                setTimeout(function() { $toast.remove(); }, 300);
            });

            // Auto-hide after 5 seconds
            setTimeout(function() {
                $toast.removeClass('show');
                setTimeout(function() { $toast.remove(); }, 300);
            }, 5000);
        },

        // Unsaved changes tracking
        initUnsavedChangesTracking: function() {
            var self = this;
            var $form = $('#sb-er-settings-form');

            if (!$form.length) return;

            // Store initial form state
            this.initialFormState = $form.serialize();

            // Track changes on form inputs
            $form.on('change input', 'input, select, textarea', function() {
                var currentState = $form.serialize();
                var hasChanges = currentState !== self.initialFormState;

                if (hasChanges !== self.hasUnsavedChanges) {
                    self.hasUnsavedChanges = hasChanges;
                    self.updateUnsavedChangesBar();
                }
            });

            // Intercept form submit
            $form.on('submit', function(e) {
                e.preventDefault();
                self.saveSettings();
            });

            // Warn before leaving with unsaved changes
            $(window).on('beforeunload', function() {
                if (self.hasUnsavedChanges) {
                    return switchboardEmailReports.i18n.unsavedChanges || 'You have unsaved changes.';
                }
            });
        },

        updateUnsavedChangesBar: function() {
            var $badge = $('#sb-er-unsaved-badge');

            if (this.hasUnsavedChanges) {
                if (!$badge.length) {
                    $badge = $('<span id="sb-er-unsaved-badge" class="sb-er-unsaved-badge">' +
                        (switchboardEmailReports.i18n.unsavedChanges || 'Unsaved changes') +
                        '</span>');
                    // Insert after the status badge in header
                    $('.sb-er-wrap .sb-module-header-right').prepend($badge);
                }
                $badge.css('display', 'inline-flex');
            } else {
                $badge.hide();
            }
        },

        saveSettings: function() {
            var self = this;
            var $form = $('#sb-er-settings-form');
            var $saveBtn = $form.find('button[type="submit"]');
            var originalText = $saveBtn.text();

            $saveBtn.prop('disabled', true).text(switchboardEmailReports.i18n.saving || 'Saving...');

            $.ajax({
                url: window.location.href,
                type: 'POST',
                data: $form.serialize(),
                success: function(response) {
                    // Update initial state to current
                    self.initialFormState = $form.serialize();
                    self.hasUnsavedChanges = false;
                    self.updateUnsavedChangesBar();

                    self.showToast('success', switchboardEmailReports.i18n.settingsSaved || 'Settings saved successfully!');
                },
                error: function() {
                    self.showToast('error', switchboardEmailReports.i18n.saveFailed || 'Failed to save settings.');
                },
                complete: function() {
                    $saveBtn.prop('disabled', false).text(originalText);
                }
            });
        },

        sendTestEmail: function($btn) {
            var self = this;
            var originalText = $btn.text();

            $btn.prop('disabled', true).text(switchboardEmailReports.i18n.sending);
            self.hideFeedback();

            $.ajax({
                url: switchboardEmailReports.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'switchboard_email_reports_test',
                    nonce: switchboardEmailReports.nonce
                },
                success: function(response) {
                    if (response.success) {
                        self.showFeedback('success', response.data.message);
                    } else {
                        self.showFeedback('error', response.data.message);
                    }
                },
                error: function() {
                    self.showFeedback('error', switchboardEmailReports.i18n.connectionErr);
                },
                complete: function() {
                    $btn.prop('disabled', false).text(originalText);
                }
            });
        },

        sendNow: function($btn) {
            var self = this;
            var originalText = $btn.text();

            $btn.prop('disabled', true).text(switchboardEmailReports.i18n.sending);
            self.hideFeedback();

            $.ajax({
                url: switchboardEmailReports.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'switchboard_email_reports_send_now',
                    nonce: switchboardEmailReports.nonce
                },
                success: function(response) {
                    if (response.success) {
                        self.showFeedback('success', response.data.message);
                    } else {
                        self.showFeedback('error', response.data.message);
                    }
                },
                error: function() {
                    self.showFeedback('error', switchboardEmailReports.i18n.connectionErr);
                },
                complete: function() {
                    $btn.prop('disabled', false).text(originalText);
                }
            });
        },

        loadPreview: function() {
            var $frame = $('#preview-frame');

            $frame.html(
                '<div class="sb-er-preview-loading">' +
                    '<span class="spinner is-active"></span>' +
                    '<span>' + switchboardEmailReports.i18n.loading + '</span>' +
                '</div>'
            );

            $.ajax({
                url: switchboardEmailReports.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'switchboard_email_reports_preview',
                    nonce: switchboardEmailReports.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Create iframe to display HTML
                        var iframe = document.createElement('iframe');
                        $frame.empty().append(iframe);

                        var doc = iframe.contentWindow.document;
                        doc.open();
                        doc.write(response.data.html);
                        doc.close();

                        // Adjust iframe height based on content
                        setTimeout(function() {
                            try {
                                iframe.style.height = (doc.body.scrollHeight + 40) + 'px';
                            } catch(e) {}
                        }, 100);
                    } else {
                        $frame.html('<div class="sb-er-preview-loading" style="color: #ef4444;">Failed to load preview.</div>');
                    }
                },
                error: function() {
                    $frame.html('<div class="sb-er-preview-loading" style="color: #ef4444;">Connection error.</div>');
                }
            });
        },

        historySection: '',
        historyStatus: 'all',
        historyPage: 1,

        loadHistoryIfNeeded: function() {
            if ($('#report-history-body').length && window.location.search.indexOf('tab=history') > -1) {
                this.initHistoryEvents();
                this.loadHistory(1);
            }
        },

        initHistoryEvents: function() {
            var self = this;

            // Section filter buttons
            $(document).on('click', '.sb-er-history-filter', function() {
                var section = $(this).data('section') || '';
                var sectionName = $(this).find('.sb-er-section-item-name').text().trim();
                $('.sb-er-history-filter').removeClass('active');
                $(this).addClass('active');
                self.historySection = section;

                // Update the title in main content area
                if (section) {
                    $('#history-title').text(sectionName);
                    $('#history-desc').text('Reports containing this section');
                } else {
                    $('#history-title').text('All Reports');
                    $('#history-desc').text('View previously sent reports');
                }

                self.loadHistory(1);
            });

            // Status filter buttons
            $(document).on('click', '.sb-er-status-filter', function() {
                var status = $(this).data('status') || 'all';
                $('.sb-er-status-filter').removeClass('active');
                $(this).addClass('active');
                self.historyStatus = status;
                self.loadHistory(1);
            });

            // Pagination
            $('#history-prev').on('click', function() {
                if (self.historyPage > 1) {
                    self.loadHistory(self.historyPage - 1);
                }
            });

            $('#history-next').on('click', function() {
                self.loadHistory(self.historyPage + 1);
            });

            // Clear all
            $('#clear-history-btn').on('click', function() {
                if (confirm(switchboardEmailReports.i18n.confirmClearAll || 'Are you sure you want to clear all history?')) {
                    self.clearAllHistory();
                }
            });
        },

        loadHistory: function(page) {
            var self = this;
            var $tbody = $('#report-history-body');

            $tbody.html(
                '<tr class="loading-row">' +
                    '<td colspan="6">' +
                        '<div class="sb-er-empty-state">' +
                            '<div class="sb-er-empty-state-icon"><span class="spinner is-active" style="float:none;"></span></div>' +
                            '<p class="sb-er-empty-state-title">' + (switchboardEmailReports.i18n.loading || 'Loading...') + '</p>' +
                        '</div>' +
                    '</td>' +
                '</tr>'
            );

            $.ajax({
                url: switchboardEmailReports.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'switchboard_email_reports_history',
                    nonce: switchboardEmailReports.nonce,
                    page: page,
                    section: self.historySection,
                    status: self.historyStatus
                },
                success: function(response) {
                    if (response.success) {
                        self.historyPage = page;
                        self.renderHistory(response.data);
                        self.updateHistoryStats(response.data);
                        self.updateHistoryPagination(response.data);
                    } else {
                        $tbody.html(
                            '<tr class="no-items">' +
                                '<td colspan="6">' +
                                    '<div class="sb-er-empty-state">' +
                                        '<div class="sb-er-empty-state-icon"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24" width="48" height="48"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg></div>' +
                                        '<p class="sb-er-empty-state-title">Failed to load</p>' +
                                        '<p class="sb-er-empty-state-desc">Unable to load report history.</p>' +
                                    '</div>' +
                                '</td>' +
                            '</tr>'
                        );
                    }
                },
                error: function() {
                    $tbody.html(
                        '<tr class="no-items">' +
                            '<td colspan="6">' +
                                '<div class="sb-er-empty-state">' +
                                    '<div class="sb-er-empty-state-icon"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24" width="48" height="48"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg></div>' +
                                    '<p class="sb-er-empty-state-title">Connection Error</p>' +
                                    '<p class="sb-er-empty-state-desc">Please check your connection and try again.</p>' +
                                '</div>' +
                            '</td>' +
                        '</tr>'
                    );
                }
            });
        },

        renderHistory: function(data) {
            var $tbody = $('#report-history-body');
            $tbody.empty();

            if (!data.items || data.items.length === 0) {
                $tbody.html(
                    '<tr class="no-items">' +
                        '<td colspan="6">' +
                            '<div class="sb-er-empty-state">' +
                                '<div class="sb-er-empty-state-icon"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24" width="48" height="48"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path></svg></div>' +
                                '<p class="sb-er-empty-state-title">No Reports Yet</p>' +
                                '<p class="sb-er-empty-state-desc">Reports will appear here once they\'ve been sent.</p>' +
                            '</div>' +
                        '</td>' +
                    '</tr>'
                );
                return;
            }

            $.each(data.items, function(i, item) {
                var statusBadge = item.status === 'sent'
                    ? '<span class="sb-er-status-badge sb-er-status-sent">✓ ' + item.status_label + '</span>'
                    : '<span class="sb-er-status-badge sb-er-status-failed">✕ ' + item.status_label + (item.error ? ' <span title="' + EmailReports.escapeHtml(item.error) + '">ⓘ</span>' : '') + '</span>';

                var row = '<tr>' +
                    '<td class="sb-er-date-cell">' +
                        '<div class="sb-er-date-relative">' + item.date + '</div>' +
                        '<div class="sb-er-date-absolute">' + item.date_full + '</div>' +
                    '</td>' +
                    '<td><span class="sb-er-type-badge">' + item.type + '</span></td>' +
                    '<td title="' + item.recipient_count + ' recipient(s)">' + item.recipients + '</td>' +
                    '<td class="sb-er-date-cell">' + item.period + '</td>' +
                    '<td>' + statusBadge + '</td>' +
                    '<td>' +
                        '<div class="sb-er-row-actions" style="opacity:1;">' +
                            '<button type="button" class="delete-history-btn" data-id="' + item.id + '" title="Delete">🗑️</button>' +
                        '</div>' +
                    '</td>' +
                    '</tr>';
                $tbody.append(row);
            });
        },

        updateHistoryStats: function(data) {
            // Update status filter counts
            if (data.counts) {
                $('#count-all').text(data.counts.all || 0);
                $('#count-sent').text(data.counts.sent || 0);
                $('#count-failed').text(data.counts.failed || 0);

                // Update section counts
                if (data.counts.sections) {
                    $.each(data.counts.sections, function(sectionId, count) {
                        $('#count-' + sectionId).text(count || 0);
                    });
                }
            }

            // Update stats
            if (data.stats) {
                $('#stat-total-sent').text(data.stats.total_sent || '0');
                $('#stat-last-report').text(data.stats.last_report || 'Never');
                $('#stat-success-rate').text(data.stats.success_rate || '0%');
            }
        },

        updateHistoryPagination: function(data) {
            var pageInfo = data.total > 0
                ? 'Showing ' + ((data.current - 1) * 20 + 1) + '-' + Math.min(data.current * 20, data.total) + ' of ' + data.total
                : 'No results';

            $('#history-page-info').text(pageInfo);
            $('#history-prev').prop('disabled', data.current <= 1);
            $('#history-next').prop('disabled', data.current >= data.pages);
        },

        clearAllHistory: function() {
            var self = this;
            $.ajax({
                url: switchboardEmailReports.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'switchboard_email_reports_clear_all',
                    nonce: switchboardEmailReports.nonce
                },
                success: function(response) {
                    if (response.success) {
                        self.loadHistory(1);
                    }
                }
            });
        },

        escapeHtml: function(text) {
            var div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        },

        deleteHistoryEntry: function(id) {
            var self = this;

            $.ajax({
                url: switchboardEmailReports.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'switchboard_email_reports_delete',
                    nonce: switchboardEmailReports.nonce,
                    id: id
                },
                success: function(response) {
                    if (response.success) {
                        self.loadHistory(1);
                    }
                }
            });
        }
    };

    $(document).ready(function() {
        EmailReports.init();
    });

})(jQuery);
