"use strict";

var arf_paypal_actions = [];

function arf_add_paypal_action(action_name, callback, priority) {
    if (!priority) {
        priority = 10;
    }
    if (priority > 100) {
        priority = 100;
    }
    if (priority < 0) {
        priority = 0;
    }
    if (typeof arf_paypal_actions[action_name] == 'undefined') {
        arf_paypal_actions[action_name] = [];
    }
    if (typeof arf_paypal_actions[action_name][priority] == 'undefined') {
        arf_paypal_actions[action_name][priority] = []
    }
    arf_paypal_actions[action_name][priority].push(callback);
    if ('undefined' != typeof window.arf_actions) {
        var arf_action_keys = Object.keys(window.arf_actions);
        if (arf_action_keys.length > 0) {
            window.arf_actions[action_name] = arf_paypal_actions[action_name];
        } else {
            window.arf_actions = arf_paypal_actions;
        }
    }
}
arf_add_paypal_action('reset_field_in_outsite', 'arf_check_paypal_form', 10);

function arf_check_paypal_form(params) {
    var object = params[0];
    var result = params[1];
    try {
        result = jQuery.parseJSON(result);
        if ('addon' == result.conf_method && jQuery("#arf_paypal_form").length > 0) {
            jQuery("#arf_paypal_form").find("input[type='submit']").hide();
            jQuery("#arf_paypal_form").submit();
        }
    } catch (e) {
        console.warn(result);
        console.warn(e);
    }
}
jQuery(document).ready(function() {
    if ('undefined' != typeof MutationObserver) {
        var mutationObserver = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
            	if( jQuery("#arf_paypal_form").length > 0 && mutation.addedNodes[0] == jQuery("#arf_paypal_form")[0] ){
                    jQuery("#arf_paypal_form").find("input[type='submit']").hide();
                	jQuery('#arf_paypal_form').submit();
            	}
            });
        });
        mutationObserver.observe(document.documentElement, {
            attributes: true,
            characterData: true,
            childList: true,
            subtree: true,
            attributeOldValue: true,
            characterDataOldValue: true
        });
    }

    if( jQuery('form.arf_paypal_form_normal').length > 0 ){
        jQuery('form.arf_paypal_form_normal').submit();
    }
});

jQuery(document).ready(function() {

    if (typeof arfDynamicPayPalConfigs === 'undefined' || arfDynamicPayPalConfigs === null) {
        return;
    }

    jQuery.each(arfDynamicPayPalConfigs, function(key, config) {

        var form = jQuery(`form[data-form-id="form_${config.form_key}"]`);
        if (form.length === 0) return;

        var amountField = form.find(`[id^="field_${config.amount_field_key}"]`);
        if (amountField.length === 0) return;

        var submitWrapper = form.find('.arf_submit_div.top_container');
        if (submitWrapper.length === 0) return;

        var paypalContainerId = 'arf-paypal-button-container-' + config.form_key;
        let paypalContainer = form.find(`#${paypalContainerId}`);
        if (paypalContainer.length === 0) {
            paypalContainer = jQuery(`<div id="${paypalContainerId}" style="display: none;" class="arf_submit_div top_container"></div>`);
            submitWrapper.after(paypalContainer);
        }

        let isPayPalRendered = false;
        let canSubmit = !config.is_submit_conditional; 

        var getAmount = () => {
            if(1 < amountField.length ){
                let firstField = amountField[0];
                if( firstField.classList.contains('arfslider') ){
                    amountField = jQuery(amountField[1]);
                }
            }
            var val = amountField.val();
            if (typeof val === 'string' && val.includes('|')) {
                return parseFloat(val.split('|')[1]) || 0;
            }
            return parseFloat(val) || 0;
        };
        
        var updateButtonState = () => {
            var amount = getAmount();
            if (canSubmit && amount > 0) {
                submitWrapper.hide();
                paypalContainer.show();
            } else {
                submitWrapper.show();
                paypalContainer.hide();
            }
        };
        
        /**
         * Gathers data and calls the AJAX check.
         */
        var checkConditionsAjax = () => {
            let posted_data = {};
            config.conditional_fields.forEach(function(field) {
                let fieldEl = form.find(`[id^="field_${field.key}"]`);
                posted_data[field.id] = fieldEl.val();
            });

            $.post(config.ajax_url, {
                action: 'arf_paypal_check_submit_conditions',
                nonce: config.nonce,
                form_id: config.form_id,
                posted_data: posted_data
            }, function(response) {
                if (response.success) {
                    canSubmit = response.data.condition_met;
                    // console.log("ARForms PayPal Debug: AJAX response received. Condition met:", canSubmit);
                    updateButtonState();
                }
            });
        };

        var renderPayPalOnce = () => {
            
            if (typeof window.paypal === 'undefined') return;

            var targetDiv = document.getElementById(paypalContainerId);
            if (!isPayPalRendered && targetDiv) {
                let buttonLabel = 'paypal';
                
                if (config.single_payment_type === 'donation') {
                    buttonLabel = 'donate';
                } else if (config.single_payment_type === 'subscription') {
                    buttonLabel = 'subscribe';
                }
                window.paypal.Buttons({
                    style: { layout: 'vertical', color: 'gold', shape: 'pill', label: buttonLabel, height: 35 },
                    createOrder: (data, actions) => {
                        var currentAmount = getAmount();
                        return actions.order.create({ purchase_units: [{ amount: { value: currentAmount.toFixed(2) } }] });
                    },
                    onApprove: (data, actions) => {
                        return actions.order.capture().then(details => {
                            if (details.status === 'COMPLETED') {
                                var hiddenFields = { 'arf_paypal_transaction_id': details.id, 'arf_paypal_payment_status': details.status, 'arf_paypal_payer_email': details.payer.email_address, 'arf_paypal_payment_date': details.update_time, 'arf_paypal_payer_fname': details.payer.name.given_name, 'arf_paypal_payer_lname': details.payer.name.surname };
                                for (var name in hiddenFields) {
                                    let input = form.find(`[name="${name}"]`);
                                    if (input.length === 0) { input = jQuery(`<input type="hidden" name="${name}">`); form.append(input); }
                                    input.val(hiddenFields[name]);
                                }
                                submitWrapper.find('.arf_submit_btn').click();
                            } else { alert('Payment not completed.'); }
                        });
                    },
                    onError: (err) => { console.error('PayPal Button Error:', err); alert('An error occurred with PayPal.'); }
                }).render(targetDiv);
                isPayPalRendered = true;
                updateButtonState();
            }
        };

        var loadPayPalSdk = () => {
            if (jQuery('#arf-paypal-sdk-script').length > 0) {
                renderPayPalOnce();
                return;
            }
            var script = document.createElement('script');
            script.id = 'arf-paypal-sdk-script';
            script.src = `https://www.paypal.com/sdk/js?client-id=${config.client_id}&currency=${config.currency}&disable-funding=credit,card`;
            script.onload = renderPayPalOnce; 
            document.head.appendChild(script);
        };

        if (config.is_submit_conditional) {
            // console.log("ARForms PayPal Debug: Conditional logic is enabled. Attaching listeners.");
            config.conditional_fields.forEach(function(field) {
                form.on('change input keyup', `[id^="field_${field.key}"]`, checkConditionsAjax);
            });
            checkConditionsAjax();
        }

        amountField.on('change input keyup', updateButtonState);

        loadPayPalSdk();
        updateButtonState();
    });

    if (jQuery('form.arf_paypal_form_normal').length > 0) {
        jQuery('form.arf_paypal_form_normal').submit();
    }
});