
// PayGate Settings JavaScript

$(document).ready(function() {
    
    // Test Connection AJAX
    $(document).on('click', '#pg-test-connection-btn', function(e) {
        e.preventDefault();
        
        var btn = $(this);
        var originalHtml = btn.html();
        var form = $('#paygate-settings-form');
        
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Testing...');
        
        $.ajax({
            url: $(this).data('url'),
            type: 'POST',
            data: form.serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    var detailsHtml = '';
                    if (response.details) {
                        detailsHtml = '<ul class="mb-0">' +
                            '<li><strong>Environment:</strong> ' + response.details.environment + '</li>' +
                            '<li><strong>API URL:</strong> ' + response.details.api_url + '</li>' +
                            '<li><strong>Merchant Code:</strong> ' + response.details.merchant_code + '</li>' +
                            '<li><strong>Terminal:</strong> ' + response.details.terminal + '</li>' +
                            '<li><strong>Currency:</strong> ' + response.details.currency + '</li>' +
                            '</ul>';
                    }
                    
                    $('#connection-result').html(
                        '<div class="alert alert-success alert-dismissible fade show" role="alert">' +
                        '<h5><i class="fas fa-check-circle"></i> Success!</h5>' +
                        '<p>' + response.message + '</p>' +
                        detailsHtml +
                        '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
                        '<span aria-hidden="true">&times;</span>' +
                        '</button>' +
                        '</div>'
                    );
                } else {
                    $('#connection-result').html(
                        '<div class="alert alert-danger alert-dismissible fade show" role="alert">' +
                        '<h5><i class="fas fa-exclamation-circle"></i> Configuration Error</h5>' +
                        '<p>' + response.message + '</p>' +
                        '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
                        '<span aria-hidden="true">&times;</span>' +
                        '</button>' +
                        '</div>'
                    );
                }
            },
            error: function(xhr, status, error) {
                $('#connection-result').html(
                    '<div class="alert alert-danger alert-dismissible fade show" role="alert">' +
                    '<h5><i class="fas fa-times-circle"></i> Connection Test Failed</h5>' +
                    '<p>An error occurred while testing the connection. Please try again.</p>' +
                    '<small>Error: ' + error + '</small>' +
                    '<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
                    '<span aria-hidden="true">&times;</span>' +
                    '</button>' +
                    '</div>'
                );
            },
            complete: function() {
                btn.prop('disabled', false).html(originalHtml);
            }
        });
    });

    // Environment change handler
    $('#settingsform-environment').on('change', function() {
        var env = $(this).val();
        var envInfo = '';
        
        if (env === 'sandbox') {
            envInfo = '<div class="alert alert-warning mt-2">' +
                '<i class="fas fa-flask"></i> <strong>Sandbox Mode:</strong> ' +
                'You are using the test environment. No real transactions will be processed.' +
                '</div>';
        } else if (env === 'production') {
            envInfo = '<div class="alert alert-danger mt-2">' +
                '<i class="fas fa-exclamation-triangle"></i> <strong>Production Mode:</strong> ' +
                'You are using the live environment. Real transactions will be processed and charged.' +
                '</div>';
        }
        
        $('#environment-info').remove();
        $(this).closest('.form-group').append('<div id="environment-info">' + envInfo + '</div>');
    });

    // Currency information
    $('#settingsform-currency').on('change', function() {
        var currency = $(this).val();
        var currencyInfo = {
            '978': 'EUR - Euro',
            '826': 'GBP - British Pound',
            '840': 'USD - US Dollar'
        };
        
        if (currency && currencyInfo[currency]) {
            var info = '<small class="text-muted">Selected: ' + currencyInfo[currency] + '</small>';
            $('#currency-info').remove();
            $(this).closest('.form-group').append('<div id="currency-info" class="col-sm-offset-4 col-sm-8">' + info + '</div>');
        }
    });

    // Transaction type information
    $('#settingsform-transaction_type').on('change', function() {
        var type = $(this).val();
        var typeInfo = {
            '0': 'Standard authorization - Payment is captured immediately',
            'A': 'Pre-authorization - Amount is reserved, needs confirmation later',
            '1': 'Pre-authorization confirmation - Confirms a previous pre-authorization'
        };
        
        if (type && typeInfo[type]) {
            var info = '<div class="alert alert-info mt-2"><small>' + typeInfo[type] + '</small></div>';
            $('#transaction-type-info').remove();
            $(this).closest('.form-group').append('<div id="transaction-type-info" class="col-sm-offset-4 col-sm-8">' + info + '</div>');
        }
    });

    // Form validation enhancement
    $('#paygate-settings-form').on('beforeSubmit', function(e) {
        var form = $(this);
        
        // Additional client-side validation
        var merchantCode = $('#settingsform-merchant_code').val();
        var secretKey = $('#settingsform-secret_key').val();
        
        if (merchantCode && !/^\d{1,9}$/.test(merchantCode)) {
            alert('Merchant code must be numeric (max 9 digits)');
            return false;
        }
        
        if (secretKey && secretKey.length < 20) {
            if (!confirm('The secret key seems short. Are you sure it\'s correct?')) {
                return false;
            }
        }
        
        return true;
    });

    // Show/hide sensitive fields toggle
    $('.toggle-password').on('click', function() {
        var input = $(this).siblings('input');
        var icon = $(this).find('i');
        
        if (input.attr('type') === 'password') {
            input.attr('type', 'text');
            icon.removeClass('fa-eye').addClass('fa-eye-slash');
        } else {
            input.attr('type', 'password');
            icon.removeClass('fa-eye-slash').addClass('fa-eye');
        }
    });

});
