// phpcs:disable
(function($) {
    'use strict';

    $(document).ready(function() {
        var WC_checkoutForm = $('form.checkout').first();
        var CredoraxCCformFieldSelectors = {
            owner: '.payment_method_credorax #wc-credorax-cc-form input#credorax-card-owner',
            number: '.payment_method_credorax #wc-credorax-cc-form input#credorax-card-number',
            expiry: '.payment_method_credorax #wc-credorax-cc-form input#credorax-card-expiry',
            cvv: '.payment_method_credorax #wc-credorax-cc-form input#credorax-card-cvc',
            type: '.payment_method_credorax #wc-credorax-cc-form input#credorax-card-type',
            pkey: '.payment_method_credorax #wc-credorax-cc-form input#credorax-pkey',
            pkey_data: '.payment_method_credorax #wc-credorax-cc-form input#credorax-pkey-data',
            compind: '.payment_method_credorax #wc-credorax-cc-form input#credorax-3ds-compind',
            lang: '.payment_method_credorax #wc-credorax-cc-form input#credorax-browser-lang',
            token: '.payment_method_credorax .woocommerce-SavedPaymentMethods input[name="wc-credorax-payment-token"]:checked'
        }
        if (credorax_config.use_js_loader) {
            WC_checkoutForm.append('<div class="credorx-gateway-loader"><div></div></div>');
        }

        var getCCfield = function(field) {
            return $(CredoraxCCformFieldSelectors[field]);
        };

        var getCCfieldVal = function(field) {
            return getCCfield(field).length ? getCCfield(field).val() : null;
        };

        var setCCfieldVal = function(field, val) {
            return getCCfield(field).length ? getCCfield(field).val(val) : null;
        };

        var setCCfieldInvalid = function(field) {
            if (getCCfield(field).length) {
                getCCfield(field).closest('.form-row').removeClass('woocommerce-validated').addClass('woocommerce-invalid');
            }
        };

        var getToken = function() {
            var token = getCCfieldVal('token');
            if (token && token !== 'new') {
                return token;
            }
            return null;
        };

        var pad = function(num, size) {
            var s = num + "";
            while (s.length < size) s = "0" + s;
            return s;
        };

        var getKeyCreationParams = function() {
            var params = {
                "M": credorax_config.merchant_id,
                "RequestID": credorax_config.request_id,
                "Statickey": credorax_config.static_key,
                "b5": getCCfieldVal('cvv')
            };
            var token = getToken();
            if (token) {
                params["g1"] = token;
            } else {
                var expiry = $.payment.cardExpiryVal(getCCfieldVal('expiry'));
                params["b1"] = getCCfieldVal('number').replace(/\s/g, '');
                params["b3"] = expiry.month ? pad(expiry.month, 2) : null;
                params["b4"] = expiry.year ? expiry.year.toString().substr(-2) : null;
                params["c1"] = getCCfieldVal('owner');
            }

            return params;
        };

        var isValidCCform = function() {
            var valid = true;

            var token = getToken();
            if (!token) {
                if (getCCfieldVal('owner').length < 5) {
                    setCCfieldInvalid('owner');
                    valid = false;
                }

                if (!$.payment.validateCardNumber(getCCfieldVal('number')) || credorax_config.allowed_cctypes.indexOf($.payment.cardType(getCCfieldVal('number'))) < 0) {
                    setCCfieldInvalid('number');
                    setCCfieldVal('number', '');
                    setCCfieldVal('type', '');
                    valid = false;
                } else {
                    setCCfieldVal('type', $.payment.cardType(getCCfieldVal('number')));
                }

                var expiry = $.payment.cardExpiryVal(getCCfieldVal('expiry'));
                if (!$.payment.validateCardExpiry(expiry.month, expiry.year)) {
                    setCCfieldInvalid('expiry');
                    valid = false;
                }

                if (!$.payment.validateCardCVC(getCCfieldVal('cvv'))) {
                    setCCfieldInvalid('cvv');
                    valid = false;
                }
            }

            return valid;
        };

        var startLoader = function() {
            WC_checkoutForm.addClass('processing');
        }

        var stopLoader = function() {
            WC_checkoutForm.removeClass('processing');
        }

        setCCfieldVal('lang', navigator.language || navigator.userLanguage || 'en-US');

        $(document).on('change keyup', CredoraxCCformFieldSelectors.number, function() {
            var ccnum = getCCfieldVal('number');
            var type = $.payment.cardType(ccnum);
            if (!$.payment.validateCardNumber(ccnum) || credorax_config.allowed_cctypes.indexOf(type) < 0) {
                setCCfieldVal('type', '');
                type = '';
            } else {
                setCCfieldVal('type', type);
            }
            $('.payment_method_credorax .credorax-cc-type-icon').removeClass('active').removeClass('inactive');
            if (type || ccnum) {
                $('.payment_method_credorax .credorax-cc-type-icon').addClass('inactive');
            }
            if ($('.payment_method_credorax .credorax-cc-type-icon.credorax-' + type + '-icon').length) {
                $('.payment_method_credorax .credorax-cc-type-icon.credorax-' + type + '-icon').removeClass('inactive').addClass('active');
            }
        });

        WC_checkoutForm.on('checkout_place_order_credorax', function() {
            console.log('checkout_place_order_credorax')
            startLoader();
            if (!isValidCCform()) {
                stopLoader();
                return false;
            }

            var res = {};

            $.ajax({
                url: credorax_config.key_creation_url,
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                method: "POST",
                async: false,
                cache: false,
                crossDomain: true,
                dataType: "json",
                data: getKeyCreationParams()
            }).always(function(response) {
                res = response;
            });

            res['z2'] = parseInt(res['z2']);
            if (!res['PKey'] || res['z2']) {
                console.error(res);
                alert(credorax_config.pkey_default_error_message || 'Credorax transaction failed, please make sure that the payment details are correct.');
                stopLoader();
                return false;
            }

            setCCfieldVal('pkey', res['PKey']);
            setCCfieldVal('pkey_data', JSON.stringify(res));

            console.log( 'res', res);
            console.log( 'credoraxConfig', credorax_config );

            if (credorax_config.is_3d_secure_enabled && res['3ds_method'] && res['3ds_trxid']) {
                window.credorax_fingerprint_done = false;
                window.credorax_fingerprint_form_submitted = false;

                var credoraxFingerprintIframe = $('<iframe>', {
                    src: credorax_config.fingetprint_iframe_url + '&3ds_data=' + JSON.stringify({
                        "3ds_method": res['3ds_method'],
                        "3ds_trxid": res['3ds_trxid']
                    }),
                    id: 'credorax_fingerprint_iframe',
                    frameborder: 0,
                    scrolling: 'no',
                    css: {
                        "display": "none"
                    },
                });
                credoraxFingerprintIframe.appendTo('body');

                window.credoraxFingerprintObs = setInterval(function() {
                    if (window.credorax_fingerprint_form_submitted) {
                        clearInterval(window.credoraxFingerprintObs);
                        window.credoraxFingerprintObs = setInterval(function() {
                            if (window.credorax_fingerprint_done || Date.now() > window.credorax_fingerprint_form_submitted) {
                                credoraxFingerprintIframe.remove();
                                clearInterval(window.credoraxFingerprintObs);
                                setCCfieldVal('compind', window.credorax_3ds_compind || null);
                                return true;
                            }
                        }, 100);
                    }
                }, 100);
            } else {
                return true;
            }
        });

        stopLoader();
        return false;
    });
})(jQuery);
