/**
 * Admin Payment Methods Script
 *
 * Handles the display of payment methods when a gateway is selected in the form editor.
 *
 * @package Wpayme\WordPress\Pay\Forms
 */

(function($) {
    'use strict';

    // Initialize when document is ready
    $(document).ready(function() {
        console.log('Payment methods script initialized');
        
        // Cache DOM elements
        const $gatewaySelect = $('#_wpayme_payment_form_config_id');
        const $infoButton = $('#wpayme-payment-methods-info');
        
        console.log('Info button found:', $infoButton.length);
        
        // Remove any existing modal
        $('#wpayme-payment-methods-modal').remove();
        
        // Create modal elements
        const $modalHtml = $(`
            <div id="wpayme-payment-methods-modal" style="display:none; position:fixed; z-index:999999; left:0; top:0; width:100%; height:100%; background-color:rgba(0,0,0,0.5);">
                <div class="wpayme-modal-content" style="position:relative; background-color:#fefefe; margin:10% auto; padding:0; border:1px solid #888; width:600px; max-width:90%; box-shadow:0 4px 20px 0 rgba(0,0,0,0.3); border-radius:4px;">
                    <div class="wpayme-modal-header" style="padding:15px 20px; border-bottom:1px solid #e5e5e5; position:relative;">
                        <span id="wpayme-modal-close" class="wpayme-modal-close" style="position:absolute; right:20px; top:15px; color:#aaa; font-size:24px; font-weight:bold; cursor:pointer;">&times;</span>
                        <h2 style="margin:0; padding:0; font-size:18px; line-height:1.4;">Available Payment Methods</h2>
                    </div>
                    <div class="wpayme-modal-body" style="padding:20px; max-height:70vh; overflow-y:auto;">
                        <div id="wpayme-payment-methods-container">
                            <p>Loading payment methods...</p>
                        </div>
                    </div>
                </div>
            </div>
        `);
        
        // Append modal to body
        $('body').append($modalHtml);
        
        // Get new references
        const $modal = $('#wpayme-payment-methods-modal');
        const $paymentMethodsContainer = $('#wpayme-payment-methods-container');
        const $closeButton = $('#wpayme-modal-close');
        
        console.log('Modal created:', $modal.length);
        
        // Function to fetch and display payment methods
        function updatePaymentMethods() {
            const configId = $gatewaySelect.val();
            console.log('Updating payment methods for config ID:', configId);
            
            // Clear current payment methods
            $paymentMethodsContainer.html('<p>Loading payment methods...</p>');
            
            if (!configId || configId === '') {
                $paymentMethodsContainer.html('<p>Please select a gateway configuration to view available payment methods.</p>');
                return;
            }
            
            // Fetch payment methods via AJAX
            $.ajax({
                url: wpaymePayFormsAdmin.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wpayme_get_gateway_payment_methods',
                    config_id: configId,
                    nonce: wpaymePayFormsAdmin.nonce
                },
                success: function(response) {
                    console.log('Payment methods response:', response);
                    if (response.success) {
                        if (response.data.methods && response.data.methods.length > 0) {
                            let html = '<ul class="wpayme-payment-methods-list" style="margin:0; padding:0; list-style:none;">';
                            
                            response.data.methods.forEach(function(method) {
                                html += '<li style="display:flex; align-items:center; padding:8px 0; border-bottom:1px solid #eee;">';
                                html += '<span style="flex:1; font-weight:500;">' + method.name + '</span>';
                                
                                // Add status indicator
                                if (method.status === 'active') {
                                    html += '<span style="margin-left:10px; padding:3px 8px; border-radius:3px; font-size:12px; font-weight:500; background-color:#dff0d8; color:#3c763d;">Active</span>';
                                } else {
                                    html += '<span style="margin-left:10px; padding:3px 8px; border-radius:3px; font-size:12px; font-weight:500; background-color:#f2dede; color:#a94442;">Inactive</span>';
                                }
                                
                                // Add recurring indicator if applicable
                                if (method.supports_recurring) {
                                    html += '<span style="margin-left:10px; padding:3px 8px; background-color:#d9edf7; color:#31708f; border-radius:3px; font-size:12px; font-weight:500;">Supports Recurring</span>';
                                }
                                
                                html += '</li>';
                            });
                            
                            html += '</ul>';
                            $paymentMethodsContainer.html(html);
                        } else {
                            $paymentMethodsContainer.html('<p>No payment methods available for this gateway configuration.</p>');
                        }
                    } else {
                        $paymentMethodsContainer.html('<p>Error: ' + (response.data.message || 'Could not retrieve payment methods.') + '</p>');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX error:', status, error);
                    $paymentMethodsContainer.html('<p>Error: Could not connect to the server.</p>');
                }
            });
        }
        
        // Modal functionality
        function openModal() {
            console.log('Opening modal');
            $modal.show();
            updatePaymentMethods();
        }
        
        function closeModal() {
            console.log('Closing modal');
            $modal.hide();
        }
        
        // Event listeners
        $infoButton.on('click', function(e) {
            e.preventDefault();
            console.log('Info button clicked');
            openModal();
            return false;
        });
        
        $closeButton.on('click', function() {
            closeModal();
        });
        
        // Close when clicking outside the modal content
        $modal.on('click', function(e) {
            if ($(e.target).is($modal)) {
                closeModal();
            }
        });
        
        // Update payment methods when gateway selection changes
        $gatewaySelect.on('change', function() {
            console.log('Gateway selection changed');
            if ($modal.is(':visible')) {
                updatePaymentMethods();
            }
        });
    });
    
})(jQuery); 