/**
 * VMPFence Audit Log JavaScript
 *
 * @package VMPFence
 * @since 2.1.0
 * @since 2.2.2 Added auto-refresh functionality, dynamic update intervals
 */

(function($) {
    'use strict';

    const AuditLog = {
        lastCheckTime: 0,
        refreshInterval: null,

        init: function() {
            this.bindEvents();
            this.lastCheckTime = Date.now() / 1000;
            // Auto-refresh every 30 seconds
            this.startAutoRefresh();
        },

        bindEvents: function() {
            // View details button (only for audit log entries with entry-id)
            $(document).on('click', '.view-details[data-entry-id]', this.viewDetails);

            // Close modal
            $(document).on('click', '.audit-modal-close, .audit-modal', function(e) {
                if (e.target === this) {
                    $('#audit-details-modal').fadeOut();
                }
            });

            // Refresh button
            $('#refresh-audit-log').on('click', this.refreshPage);

            // Export button
            $('#export-audit-log').on('click', this.exportCSV);

            // ESC key to close modal
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape') {
                    $('#audit-details-modal').fadeOut();
                }
            });

            // Audit Log Options toggle
            $('#audit-log-options-toggle').on('click', function() {
                const content = $('.audit-log-options-content');
                const panel = $('.audit-log-options-panel');
                
                if (content.is(':visible')) {
                    content.slideUp(300);
                    panel.removeClass('expanded');
                } else {
                    content.slideDown(300);
                    panel.addClass('expanded');
                }
            });

            // Toggle button group (for future functionality)
            $('.audit-log-toggle-btn').on('click', function() {
                if (!$(this).prop('disabled')) {
                    $(this).siblings().removeClass('active');
                    $(this).addClass('active');
                }
            });

            // Save changes button
            $(document).on('click', '#audit-log-save-changes', function(e) {
                e.preventDefault();
                AuditLog.saveOptions();
            });

            // Restore defaults button
            $(document).on('click', '#audit-log-restore-defaults', function(e) {
                e.preventDefault();
                
                VMPFenceNotifications.showConfirmModal({
                    title: 'Restore Defaults',
                    message: 'Are you sure you want to restore default audit log settings?',
                    confirmText: 'Yes, Restore',
                    cancelText: 'Cancel',
                    type: 'warning'
                }).then(function(confirmed) {
                    if (confirmed) {
                        AuditLog.restoreDefaults();
                    }
                });
            });

            // Cancel changes button
            $(document).on('click', '#audit-log-cancel-changes', function(e) {
                e.preventDefault();
                AuditLog.cancelChanges();
            });
        },

        viewDetails: function(e) {
            e.preventDefault();
            const entryId = $(this).data('entry-id');
            AuditLog.loadEntryDetails(entryId);
        },

        loadEntryDetails: function(entryId) {
            const $modal = $('#audit-details-modal');
            const $content = $('#audit-details-content');

            $modal.fadeIn();
            $content.html('<div class="loading"><span class="spinner is-active"></span> Loading details...</div>');

            $.ajax({
                url: vmpfenceAuditLog.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_audit_entry',
                    nonce: vmpfenceAuditLog.nonce,
                    entry_id: entryId
                },
                success: function(response) {
                    if (response.success && response.data.entry) {
                        AuditLog.renderEntryDetails(response.data.entry);
                    } else {
                        $content.html('<div class="error-message">Failed to load entry details.</div>');
                    }
                },
                error: function() {
                    $content.html('<div class="error-message">An error occurred while loading entry details.</div>');
                }
            });
        },

        renderEntryDetails: function(entry) {
            const $content = $('#audit-details-content');
            
            let html = '<div class="entry-details">';
            
            // Basic Information
            html += '<div class="detail-section">';
            html += '<h3>Basic Information</h3>';
            html += '<table class="detail-table">';
            html += '<tr><th>Time:</th><td>' + AuditLog.escapeHtml(entry.time_formatted) + '</td></tr>';
            html += '<tr><th>Event Type:</th><td><span class="event-badge event-' + AuditLog.sanitizeClass(entry.event_type) + '">' + AuditLog.escapeHtml(entry.event_type.replace(/_/g, ' ').toUpperCase()) + '</span></td></tr>';
            html += '<tr><th>Action:</th><td>' + AuditLog.escapeHtml(entry.action) + '</td></tr>';
            html += '<tr><th>Message:</th><td>' + AuditLog.escapeHtml(entry.message) + '</td></tr>';
            html += '</table>';
            html += '</div>';

            // User Information
            html += '<div class="detail-section">';
            html += '<h3>User Information</h3>';
            html += '<table class="detail-table">';
            html += '<tr><th>User ID:</th><td>' + (entry.user_id || 'N/A') + '</td></tr>';
            html += '<tr><th>Username:</th><td>' + AuditLog.escapeHtml(entry.username || 'System') + '</td></tr>';
            html += '<tr><th>User Role:</th><td>' + AuditLog.escapeHtml(entry.user_role || 'N/A') + '</td></tr>';
            html += '<tr><th>IP Address:</th><td>' + AuditLog.escapeHtml(entry.ip_formatted) + '</td></tr>';
            html += '<tr><th>User Agent:</th><td class="wrap-text">' + AuditLog.escapeHtml(entry.user_agent || 'N/A') + '</td></tr>';
            html += '</table>';
            html += '</div>';

            // Object Information
            if (entry.object_type || entry.object_id || entry.object_name) {
                html += '<div class="detail-section">';
                html += '<h3>Object Information</h3>';
                html += '<table class="detail-table">';
                if (entry.object_type) html += '<tr><th>Object Type:</th><td>' + AuditLog.escapeHtml(entry.object_type) + '</td></tr>';
                if (entry.object_id) html += '<tr><th>Object ID:</th><td>' + AuditLog.escapeHtml(entry.object_id) + '</td></tr>';
                if (entry.object_name) html += '<tr><th>Object Name:</th><td>' + AuditLog.escapeHtml(entry.object_name) + '</td></tr>';
                html += '</table>';
                html += '</div>';
            }

            // Changed Values
            if (entry.old_value || entry.new_value) {
                html += '<div class="detail-section">';
                html += '<h3>Changed Values</h3>';
                html += '<table class="detail-table">';
                if (entry.old_value) {
                    html += '<tr><th>Old Value:</th><td><pre>' + AuditLog.escapeHtml(JSON.stringify(entry.old_value, null, 2)) + '</pre></td></tr>';
                }
                if (entry.new_value) {
                    html += '<tr><th>New Value:</th><td><pre>' + AuditLog.escapeHtml(JSON.stringify(entry.new_value, null, 2)) + '</pre></td></tr>';
                }
                html += '</table>';
                html += '</div>';
            }

            // Additional Information
            if (entry.additional_info && Object.keys(entry.additional_info).length > 0) {
                html += '<div class="detail-section">';
                html += '<h3>Additional Information</h3>';
                html += '<pre class="json-data">' + AuditLog.escapeHtml(JSON.stringify(entry.additional_info, null, 2)) + '</pre>';
                html += '</div>';
            }

            html += '</div>';

            $content.html(html);
        },

        refreshPage: function(e) {
            e.preventDefault();
            window.location.reload();
        },

        exportCSV: function(e) {
            e.preventDefault();
            
            const $button = $(this);
            const originalText = $button.html();
            
            $button.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> Exporting...');

            // Get current filters from URL
            const params = new URLSearchParams(window.location.search);
            
            $.ajax({
                url: vmpfenceAuditLog.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'vmpfence_export_audit_log',
                    nonce: vmpfenceAuditLog.nonce,
                    event_type: params.get('filter_event_type') || '',
                    user_id: params.get('filter_user') || '',
                    date_from: params.get('filter_date_from') || '',
                    date_to: params.get('filter_date_to') || '',
                    search: params.get('filter_search') || ''
                },
                success: function(response) {
                    if (response.success && response.data.download_url) {
                        // Trigger download
                        window.location.href = response.data.download_url;
                        
                        $button.prop('disabled', false).html(originalText);
                        
                        // Show success message
                        AuditLog.showNotice('Export completed successfully!', 'success');
                    } else {
                        $button.prop('disabled', false).html(originalText);
                        AuditLog.showNotice('Export failed: ' + (response.data.message || 'Unknown error'), 'error');
                    }
                },
                error: function() {
                    $button.prop('disabled', false).html(originalText);
                    AuditLog.showNotice('Export failed due to a server error.', 'error');
                }
            });
        },

        startAutoRefresh: function() {
            // Get update interval from settings (default 10 seconds, converted to milliseconds)
            var updateInterval = (typeof vmpfence_admin !== 'undefined' && vmpfence_admin.update_interval) 
                ? parseInt(vmpfence_admin.update_interval) * 1000 
                : 10000;
            
            // console.log('[Audit Log] Starting auto-refresh (' + (updateInterval / 1000) + ' second interval)');
            
            this.refreshInterval = setInterval(function() {
                AuditLog.checkForNewEntries();
            }, updateInterval);
        },

        checkForNewEntries: function() {
            // Pause if window loses focus
            if (window.VMPFenceAdmin && window.VMPFenceAdmin.shouldPauseLiveUpdates()) {
                return;
            }
            
            $.ajax({
                url: vmpfenceAuditLog.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'vmpfence_get_recent_audit_entries',
                    nonce: vmpfenceAuditLog.nonce,
                    since_time: this.lastCheckTime,
                    limit: 5
                },
                success: function(response) {
                    if (response.success && response.data.count > 0) {
                        // console.log('[Audit Log] Found ' + response.data.count + ' new entries - refreshing table');
                        // Reload the entire table content
                        AuditLog.reloadTable();
                    } else {
                        // console.log('[Audit Log] No new entries');
                    }
                    AuditLog.lastCheckTime = Date.now() / 1000;
                },
                error: function(xhr, status, error) {
                    // Silently fail for auto-refresh errors to avoid annoying users
                    // But log to console for debugging
                    // if (console && console.log) {
                    //     console.log('[Audit Log] Auto-refresh failed:', error);
                    // }
                }
            });
        },

        saveOptions: function() {
            const formData = $('#vmpfence-audit-log-options-form').serialize();

            $.ajax({
                url: vmpfenceToolsData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_save_audit_log_options',
                    nonce: vmpfenceToolsData.nonce,
                    options: formData
                },
                success: function(response) {
                    if (response.success) {
                        VMPFenceNotifications.showSuccess('Audit log settings saved successfully!', 3000);
                        // Refresh page after 1.5 seconds to reflect menu changes
                        setTimeout(function() {
                            location.reload();
                        }, 1500);
                    } else {
                        VMPFenceNotifications.showError('Error saving settings: ' + (response.data.message || 'Unknown error'), 6000);
                    }
                },
                error: function() {
                    VMPFenceNotifications.showError('Failed to save settings. Please try again.', 6000);
                }
            });
        },

        restoreDefaults: function() {
            // Reset to default values
            $('.audit-log-toggle-btn').removeClass('active');
            $('.audit-log-toggle-btn[data-mode="preview"]').addClass('active');
            $('#audit_log_logging_mode').val('preview');
            $('#display_audit_log_menu').prop('checked', true);
            
            // Save the defaults immediately
            const formData = $('#vmpfence-audit-log-options-form').serialize();

            $.ajax({
                url: vmpfenceToolsData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'vmpfence_save_audit_log_options',
                    nonce: vmpfenceToolsData.nonce,
                    options: formData
                },
                success: function(response) {
                    if (response.success) {
                        VMPFenceNotifications.showSuccess('Default settings restored successfully!', 3000);
                        // Refresh page after 1.5 seconds
                        setTimeout(function() {
                            location.reload();
                        }, 1500);
                    } else {
                        VMPFenceNotifications.showError('Error restoring defaults: ' + (response.data.message || 'Unknown error'), 6000);
                    }
                },
                error: function() {
                    VMPFenceNotifications.showError('Failed to restore defaults. Please try again.', 6000);
                }
            });
        },

        cancelChanges: function() {
            // Reload the page to reset all changes
            window.location.reload();
        },

        reloadTable: function() {
            var $tbody = $('.vmpfence-audit-log tbody, .vmpfence-audit-log-embedded tbody');
            if (!$tbody.length) return;

            // Get current URL parameters to maintain filters
            var urlParams = new URLSearchParams(window.location.search);
            
            $.ajax({
                url: vmpfenceAuditLog.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'vmpfence_reload_audit_table',
                    nonce: vmpfenceAuditLog.nonce,
                    filter_event_type: urlParams.get('filter_event_type') || '',
                    filter_user: urlParams.get('filter_user') || '',
                    filter_date_from: urlParams.get('filter_date_from') || '',
                    filter_date_to: urlParams.get('filter_date_to') || '',
                    filter_search: urlParams.get('filter_search') || '',
                    paged: urlParams.get('paged') || 1
                },
                success: function(response) {
                    if (response.success && response.data.html) {
                        // Replace table content with fade effect
                        $tbody.fadeOut(200, function() {
                            $tbody.html(response.data.html);
                            $tbody.fadeIn(200);
                        });
                        
                        // Show toast notification
                        // if (typeof VMPFenceNotifications !== 'undefined') {
                        //     VMPFenceNotifications.showInfo(
                        //         'Audit log updated with ' + response.data.count + ' new ' + (response.data.count === 1 ? 'entry' : 'entries') + '.',
                        //         3000
                        //     );
                        // }
                    }
                },
                error: function(xhr, status, error) {
                    console.log('[Audit Log] Table reload failed:', error);
                }
            });
        },

        escapeHtml: function(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text.toString();
            return div.innerHTML;
        },

        sanitizeClass: function(str) {
            if (!str) return '';
            return str.toString().toLowerCase().replace(/[^a-z0-9-]/g, '-');
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        if ($('.vmpfence-audit-log').length || $('.vmpfence-audit-log-embedded').length) {
            AuditLog.init();
        }
    });

})(jQuery);
