/**
 * Total Processing Gateway Logger - Admin JavaScript
 * 
 * Handles AJAX loading, filtering, and interactions
 */

(function($) {
    'use strict';
    
    var TPGatewayLogs = {
        orderId: 0,
        offset: 0,
        currentFilter: 'all',
        totalLogs: 0,
        hasMore: false,
        loading: false,
        
        init: function() {
            this.orderId = tpLogsData.order_id;
            this.bindEvents();
        },
        
        bindEvents: function() {
            var self = this;
            
            // Load logs button
            $('#tp-load-logs-btn').on('click', function(e) {
                e.preventDefault();
                self.loadLogs(true);
            });
            
            // Clear logs button
            $('#tp-clear-logs-btn').on('click', function(e) {
                e.preventDefault();
                self.clearLogs();
            });
            
            // Filter buttons
            $(document).on('click', '.tp-filter-btn', function(e) {
                e.preventDefault();
                var filter = $(this).data('filter');
                self.changeFilter(filter);
            });
            
            // Load more button
            $('#tp-load-more-btn').on('click', function(e) {
                e.preventDefault();
                self.loadMore();
            });
            
            // Toggle log data
            $(document).on('click', '.tp-toggle-data', function(e) {
                e.preventDefault();
                $(this).closest('.tp-log-entry').find('.tp-log-data').slideToggle();
                $(this).text($(this).text().includes('Show') ? '📦 Hide Data' : '📦 Show Data');
            });
            
            // Toggle stack trace
            $(document).on('click', '.tp-toggle-stack', function(e) {
                e.preventDefault();
                $(this).closest('.tp-log-entry').find('.tp-log-stack').slideToggle();
                $(this).text($(this).text().includes('Show') ? '📍 Hide Stack Trace' : '📍 Show Stack Trace');
            });
        },
        
        loadLogs: function(isInitial) {
            var self = this;
            
            if (self.loading) return;
            
            self.loading = true;
            self.showLoader();
            
            if (isInitial) {
                self.offset = 0;
                $('#tp-logs-content').empty();
            }
            
            $.ajax({
                url: tpLogsData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'tp_load_order_logs',
                    nonce: tpLogsData.nonce,
                    order_id: self.orderId,
                    offset: self.offset,
                    filter: self.currentFilter
                },
                success: function(response) {
                    if (response.success) {
                        if (isInitial) {
                            $('#tp-logs-content').html(response.data.html);
                            $('#tp-logs-filters').show();
                            $('#tp-clear-logs-btn').show();
                            $('#tp-load-logs-btn').hide();
                        } else {
                            $('#tp-logs-content').append(response.data.html);
                        }
                        
                        self.totalLogs = response.data.total;
                        self.offset = response.data.loaded;
                        self.hasMore = response.data.has_more;
                        
                        self.updateCounter();
                        self.updateLoadMoreButton();
                    } else {
                        self.showError(response.data.message);
                    }
                },
                error: function() {
                    self.showError('Failed to load logs. Please try again.');
                },
                complete: function() {
                    self.loading = false;
                    self.hideLoader();
                }
            });
        },
        
        loadMore: function() {
            this.loadLogs(false);
        },
        
        changeFilter: function(filter) {
            // Update button states
            $('.tp-filter-btn').removeClass('active');
            $('.tp-filter-btn[data-filter="' + filter + '"]').addClass('active');
            
            // Reset and reload with new filter
            this.currentFilter = filter;
            this.offset = 0;
            this.loadLogs(true);
        },
        
        clearLogs: function() {
            var self = this;
            
            if (!confirm('⚠️ Are you sure you want to delete all logs for this order?\n\nThis action cannot be undone.')) {
                return;
            }
            
            self.showLoader();
            
            $.ajax({
                url: tpLogsData.ajaxurl,
                type: 'POST',
                data: {
                    action: 'tp_clear_order_logs',
                    nonce: tpLogsData.nonce,
                    order_id: self.orderId
                },
                success: function(response) {
                    if (response.success) {
                        $('#tp-logs-content').html('<div class="tp-log-empty">No logs found for this order.</div>');
                        $('#tp-logs-filters').hide();
                        $('#tp-clear-logs-btn').hide();
                        $('#tp-load-more-container').hide();
                        $('#tp-load-logs-btn').show();
                        
                        self.offset = 0;
                        self.totalLogs = 0;
                        self.hasMore = false;
                        
                        alert('✅ ' + response.data.message);
                    } else {
                        alert('❌ ' + response.data.message);
                    }
                },
                error: function() {
                    alert('❌ An error occurred. Please try again.');
                },
                complete: function() {
                    self.hideLoader();
                }
            });
        },
        
        updateCounter: function() {
            var text = 'Showing ' + this.offset + ' of ' + this.totalLogs + ' logs';
            $('#tp-logs-count').text(text);
        },
        
        updateLoadMoreButton: function() {
            if (this.hasMore) {
                $('#tp-load-more-container').show();
            } else {
                $('#tp-load-more-container').hide();
            }
        },
        
        showLoader: function() {
            $('#tp-logs-loader').show();
        },
        
        hideLoader: function() {
            $('#tp-logs-loader').hide();
        },
        
        showError: function(message) {
            $('#tp-logs-content').html('<div class="tp-log-error">' + message + '</div>');
        }
    };
    
    // Initialize on document ready
    $(document).ready(function() {
        if ($('#tp-gateway-logs-container').length) {
            TPGatewayLogs.init();
        }
    });
    
})(jQuery);
