/**
 * ConvesioPay Admin Payment Methods - Real-time Toggle Integration
 * Handles enabling/disabling payment methods with ConvesioPay API integration
 */

jQuery(document).ready(function($) {
    'use strict';


    // ConvesioPay gateway IDs to monitor
    const convesioPayGateways = [
        'peachpay_convesiopay_card',
        'peachpay_convesiopay_applepay', 
        'peachpay_convesiopay_btcpay'
    ];

    /**
     * Initialize real-time toggle monitoring
     */
    function initToggleMonitoring() {
        
        // Debug: Show all payment gateway toggles on the page
        const allToggles = $('input[name*="woocommerce_"][name*="_enabled"]');
        
        allToggles.each(function() {
        });

        // Debug: Look for PeachPay-style toggles and buttons
        const peachPayButtons = $('.activate-button, .deactivate-button, .setup-button, button[data-id*="convesiopay"]');
        
        peachPayButtons.each(function() {
        });
        
        // Debug: Look for any ConvesioPay-related elements
        const convesioElements = $('[class*="convesio"], [id*="convesio"], [data-id*="convesio"]');
        
        convesioElements.each(function() {
        });

        // Debug: Show ALL elements on the page that contain "peachpay" or "convesio" anywhere
        const allElements = $('*');
        let foundElements = [];
        
        allElements.each(function() {
            const element = $(this);
            const tagName = this.tagName;
            const className = element.attr('class') || '';
            const id = element.attr('id') || '';
            const dataId = element.attr('data-id') || '';
            const text = element.text().toLowerCase();
            const name = element.attr('name') || '';
            
            // Check if element contains peachpay or convesio in any attribute or text
            if (className.toLowerCase().includes('peachpay') || 
                className.toLowerCase().includes('convesio') ||
                id.toLowerCase().includes('peachpay') || 
                id.toLowerCase().includes('convesio') ||
                dataId.toLowerCase().includes('peachpay') || 
                dataId.toLowerCase().includes('convesio') ||
                name.toLowerCase().includes('peachpay') || 
                name.toLowerCase().includes('convesio') ||
                (text.includes('peachpay') || text.includes('convesio') || text.includes('crypto'))) {
                
                foundElements.push({
                    tag: tagName,
                    class: className,
                    id: id,
                    dataId: dataId,
                    name: name,
                    text: text.substring(0, 100) // First 100 chars of text
                });
            }
        });
        
        foundElements.forEach(function(el, index) {
        });
        
        // Debug: Look for any radio buttons or checkboxes related to payments
        const allPaymentInputs = $('input[type="radio"], input[type="checkbox"]');
        
        allPaymentInputs.each(function() {
            const element = $(this);
            const name = element.attr('name') || '';
            const id = element.attr('id') || '';
            const value = element.attr('value') || '';
            
            if (name.includes('payment') || name.includes('gateway') || name.includes('peachpay') || name.includes('convesio') ||
                id.includes('payment') || id.includes('gateway') || id.includes('peachpay') || id.includes('convesio') ||
                value.includes('payment') || value.includes('gateway') || value.includes('peachpay') || value.includes('convesio')) {
                    type: element.attr('type'),
                    name: name,
                    id: id,
                    value: value,
                    checked: element.is(':checked')
                });
            }
        });

        // Monitor WooCommerce-style toggles for ConvesioPay gateways
        convesioPayGateways.forEach(function(gatewayId) {
            
            // Look for the gateway row first using the correct data attribute
            const gatewayRow = $(`tr[data-gateway_id="${gatewayId}"]`);
            if (gatewayRow.length > 0) {
                
                // Look for WooCommerce-style toggle link within the row
                const toggleLink = gatewayRow.find('a.wc-payment-gateway-method-toggle-enabled');
                if (toggleLink.length > 0) {
                    setupWooCommerceToggle(gatewayId, toggleLink, gatewayRow);
                } else {
                }
            } else {
                
                // Fallback: Try standard WooCommerce input toggle
                const toggleSelector = `input[name="woocommerce_${gatewayId}_enabled"]`;
                const $toggle = $(toggleSelector);
                
                
                if ($toggle.length > 0) {
                    setupStandardToggle(gatewayId, $toggle);
                } else {
                }
            }
        });
    }

    /**
     * Set up WooCommerce-style toggle monitoring (for WooCommerce Settings > Payments page)
     */
    function setupWooCommerceToggle(gatewayId, toggleLink, gatewayRow) {
        
        // Get current state from the toggle span
        const toggleSpan = toggleLink.find('span.woocommerce-input-toggle');
        
        function getCurrentState() {
            return !toggleSpan.hasClass('woocommerce-input-toggle--disabled');
        }
        
        
        // Intercept clicks on the toggle link
        toggleLink.off('click.convesiopay').on('click.convesiopay', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            
            // Determine new state (opposite of current)
            const currentState = getCurrentState();
            const newState = !currentState;
            
            // Add loading state
            const originalHtml = toggleSpan.html();
            
            // Create a simple text-based loader that's guaranteed to be visible
            const spinnerHtml = '<span style="color: #0073aa; font-weight: bold; animation: blink 1s infinite;">●●●</span><style>@keyframes blink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0.3; } }</style>';
            toggleSpan.html(spinnerHtml);
            toggleLink.css('pointer-events', 'none').addClass('updating');
            
            
            // Since we're using a text-based loader, we don't need to check for .spinner class
            const loaderElement = toggleSpan.find('span')[0];
            if (loaderElement) {
            } else {
            }
            
            // Update the payment methods via API
            updatePaymentMethod(gatewayId, newState)
                .then(function(data) {
                    
                    // Remove loading state
                    toggleLink.css('pointer-events', 'auto').removeClass('updating');
                    
                    // Update the visual state
                    if (newState) {
                        toggleSpan.removeClass('woocommerce-input-toggle--disabled').addClass('woocommerce-input-toggle--enabled');
                        toggleSpan.text('Yes');
                        
                        // Update aria-label if it exists
                        const ariaLabel = toggleLink.attr('aria-label');
                        if (ariaLabel && ariaLabel.includes('currently disabled')) {
                            toggleLink.attr('aria-label', ariaLabel.replace('currently disabled', 'currently enabled'));
                        }
                    } else {
                        toggleSpan.removeClass('woocommerce-input-toggle--enabled').addClass('woocommerce-input-toggle--disabled');
                        toggleSpan.text('No');
                        
                        // Update aria-label if it exists
                        const ariaLabel = toggleLink.attr('aria-label');
                        if (ariaLabel && ariaLabel.includes('currently enabled')) {
                            toggleLink.attr('aria-label', ariaLabel.replace('currently enabled', 'currently disabled'));
                        }
                    }
                    
                    // Show success notification
                    
                    // localStorage synchronization disabled for now
                    
                    // Show user-friendly notification
                    const gatewayName = gatewayId.replace('peachpay_convesiopay_', '').replace('_', ' ');
                    const action = newState ? 'enabled' : 'disabled';
                    
                    // Create a temporary notification
                    const notification = $('<div class="notice notice-success is-dismissible" style="margin: 10px 0;"><p><strong>ConvesioPay:</strong> ' + 
                                          gatewayName.charAt(0).toUpperCase() + gatewayName.slice(1) + ' payment method ' + action + 
                                          ' successfully. Refresh the PeachPay admin page to see changes.</p></div>');
                    
                    // Insert notification at the top of the page
                    if ($('.wp-header-end').length) {
                        $('.wp-header-end').after(notification);
                    } else {
                        $('h1').first().after(notification);
                    }
                    
                    // Auto-remove notification after 10 seconds
                    setTimeout(function() {
                        notification.slideUp(500, function() {
                            notification.remove();
                        });
                    }, 10000);
                    
                    // Make dismissible button work
                    notification.find('.notice-dismiss').on('click', function() {
                        notification.slideUp(500, function() {
                            notification.remove();
                        });
                    });
                })
                .catch(function(error) {
                    console.error('ConvesioPay: API update failed for', gatewayId);
                    console.error('ConvesioPay: Error details:', error);
                    console.error('ConvesioPay: Error message:', error.message);
                    console.error('ConvesioPay: Error stack:', error.stack);
                    
                    // Remove loading state and restore original
                    toggleLink.css('pointer-events', 'auto').removeClass('updating');
                    toggleSpan.html(originalHtml);
                    
                    alert('Failed to update payment method: ' + (error.message || 'Unknown error'));
                });
        });
    }

    /**
     * Handle toggle button changes
     */
    function handleToggleChange(gatewayId, $toggle, event) {
        
        const isEnabled = $toggle.is(':checked');
        const originalState = $toggle.data('original-state');
        
        
        // Prevent the default form submission
        event.preventDefault();
        event.stopPropagation();
        
        // Show loading state
        showLoadingState($toggle, gatewayId);
        
        // Make API call to update ConvesioPay
        updatePaymentMethod(gatewayId, isEnabled)
            .then(function(response) {
                
                // Update original state to new state
                $toggle.data('original-state', isEnabled);
                
                // Show success feedback
                showSuccessMessage(gatewayId, isEnabled);
                
                // Remove loading state
                removeLoadingState($toggle, gatewayId);
            })
            .catch(function(error) {
                console.error('ConvesioPay: API update failed:', error);
                
                // Revert the toggle to original state
                $toggle.prop('checked', originalState).trigger('change');
                $toggle.data('original-state', originalState);
                
                // Show error message
                showErrorMessage(gatewayId, error.message || 'Failed to update payment method');
                
                // Remove loading state
                removeLoadingState($toggle, gatewayId);
            });
    }

    /**
     * Update payment method via ConvesioPay API
     */
    function updatePaymentMethod(gatewayId, enabled) {
        
        return new Promise(function(resolve, reject) {
            // Get nonce from the page (WooCommerce settings page should have this)
            const nonce = $('#woocommerce-settings-nonce').val() || $('input[name="_wpnonce"]').val();
            
            if (!nonce) {
                console.error('ConvesioPay: No nonce found on page');
                reject(new Error('Security token not found'));
                return;
            }
            
            $.ajax({
                url: window.convesioPayAdmin?.ajaxUrl || ajaxurl || window.ajaxurl,
                type: 'POST',
                data: {
                    action: 'peachpay_convesiopay_update_payment_methods',
                    gateway_id: gatewayId,
                    enabled: enabled.toString(),
                    nonce: nonce
                },
                timeout: 30000, // 30 second timeout
                success: function(response) {
                    
                    if (response.success) {
                        resolve(response.data);
                    } else {
                        reject(new Error(response.data?.message || 'Unknown error occurred'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('ConvesioPay: AJAX error:', {
                        status: xhr.status,
                        statusText: xhr.statusText,
                        responseText: xhr.responseText,
                        error: error
                    });
                    
                    let errorMessage = 'Network error occurred';
                    try {
                        const errorResponse = JSON.parse(xhr.responseText);
                        errorMessage = errorResponse.data?.message || errorMessage;
                    } catch (e) {
                        // Use default error message
                    }
                    
                    reject(new Error(errorMessage));
                }
            });
        });
    }

    /**
     * Show loading state on toggle
     */
    function showLoadingState($toggle, gatewayId) {
        
        // Disable the toggle during API call
        $toggle.prop('disabled', true);
        
        // Add loading class to the toggle container
        const $container = $toggle.closest('tr, .gateway');
        $container.addClass('convesiopay-updating');
        
        // Add spinner or loading indicator
        const $loadingIndicator = $('<span class="convesiopay-loading">⏳ Updating...</span>');
        $toggle.after($loadingIndicator);
    }

    /**
     * Remove loading state from toggle
     */
    function removeLoadingState($toggle, gatewayId) {
        
        // Re-enable the toggle
        $toggle.prop('disabled', false);
        
        // Remove loading class
        const $container = $toggle.closest('tr, .gateway');
        $container.removeClass('convesiopay-updating');
        
        // Remove loading indicator
        $toggle.siblings('.convesiopay-loading').remove();
    }

    /**
     * Show success message
     */
    function showSuccessMessage(gatewayId, enabled) {
        const message = `Payment method ${enabled ? 'enabled' : 'disabled'} successfully`;
        
        // Show WordPress admin notice
        showAdminNotice(message, 'success');
    }

    /**
     * Show error message
     */
    function showErrorMessage(gatewayId, errorMessage) {
        const message = `Failed to update payment method: ${errorMessage}`;
        console.error('ConvesioPay: Error -', message);
        
        // Show WordPress admin notice  
        showAdminNotice(message, 'error');
    }

    /**
     * Show WordPress-style admin notice
     */
    function showAdminNotice(message, type) {
        const noticeClass = type === 'error' ? 'notice-error' : 'notice-success';
        const $notice = $(`
            <div class="notice ${noticeClass} is-dismissible convesiopay-notice">
                <p><strong>ConvesioPay:</strong> ${message}</p>
                <button type="button" class="notice-dismiss">
                    <span class="screen-reader-text">Dismiss this notice.</span>
                </button>
            </div>
        `);
        
        // Remove any existing ConvesioPay notices
        $('.convesiopay-notice').remove();
        
        // Add the new notice at the top of the page
        if ($('.wrap h1').length > 0) {
            $('.wrap h1').after($notice);
        } else {
            $('.wrap').prepend($notice);
        }
        
        // Handle dismiss button
        $notice.find('.notice-dismiss').on('click', function() {
            $notice.fadeOut(200, function() {
                $(this).remove();
            });
        });
        
        // Auto-dismiss success notices after 5 seconds
        if (type !== 'error') {
            setTimeout(function() {
                $notice.fadeOut(200, function() {
                    $(this).remove();
                });
            }, 5000);
        }
    }

    /**
     * Initialize when page is ready
     */
    $(document).ready(function() {
        // Wait a bit for WooCommerce to initialize its elements
        setTimeout(initToggleMonitoring, 500);
        
        // Try again after a longer delay if nothing was found initially
        setTimeout(function() {
            const foundToggles = convesioPayGateways.filter(function(gatewayId) {
                return $(`input[name="woocommerce_${gatewayId}_enabled"]`).length > 0;
            });
            
            if (foundToggles.length === 0) {
                initToggleMonitoring();
            }
        }, 2000);
    });

    // Re-initialize if new content is loaded (for dynamic updates)
    $(document).on('wc-enhanced-select-init', initToggleMonitoring);
    
    // Also try when WooCommerce settings are updated
    $(document).on('woocommerce_settings_saved', initToggleMonitoring);
    
});