/*!
 * Copyright 2024-2025 Simply.IN Sp. z o.o.
 *
 * NOTICE OF LICENSE
 * Licensed under the EUPL-1.2 or later.
 * You may not use this work except in compliance with the Licence.
 * Copy of the Licence is available at: https://joinup.ec.europa.eu/software/page/eupl
 * It is bundled with this package in the file LICENSE.txt
 *
 * @author    Simply.IN Sp. z o.o.
 * @copyright 2024-2025 Simply.IN Sp. z o.o.
 * @license   https://joinup.ec.europa.eu/software/page/eupl
 */

const $ = window.jQuery;
const simplyin = window.simplyin;

$(function () {
    window.SimplyInPayment.bindOnChangeDeliveryOption = function () {
        let self = this;
        let change_delivery_opt_interval = null;
        let cardFormInitialized = false;

        $(document).ajaxComplete(function (event, xhr, settings) {
            let max_calls = 10;
            if (settings.data && typeof settings.data === 'string' && settings.data.includes('action=selectDeliveryOption')) {
                if (change_delivery_opt_interval) {
                    clearInterval(change_delivery_opt_interval);
                }
                change_delivery_opt_interval = setInterval(function () {
                    if ($('#card-number').find('div').length == 0) {
                        window.SimplyInPayment.setupCardForm();
                        clearInterval(change_delivery_opt_interval);
                    } else {
                        max_calls--;
                        if (max_calls <= 0) {
                            clearInterval(change_delivery_opt_interval);
                        }
                    }
                }, 150);
            }
            self.addIcon();
        });
    };
    window.SimplyInPayment.bindBlikConfirmationEvents = function () {
        let self = this;
        if (typeof (tc_confirmOrderValidations) !== 'undefined') {
            tc_confirmOrderValidations['simplyin_blik'] = function () {
                $(self.errorMsgBlik).hide();
                $(self.successMsgBlik).hide();

                if (self.checkBlikCode()) {
                    let blik_code = self.getBlikCode();
                    let params = {
                        action: 'selectPaymentMethod',
                        ajax: 1,
                        ajax_token: simplyin.ajax_token,
                        cart_token: simplyin.cart_token,
                        payment_id: $('input[name="simplyin-payment-option"]:checked').val(),
                        payment_type: 'blik',
                        payment_provider: $('input[name="simplyin-payment-option"]:checked').data('payment-provider-name'),
                        provider_image: $('input[name="simplyin-payment-option"]:checked').data('provider-image'),
                        logo: $('input[name="simplyin-payment-option"]:checked').data('logo'),
                        blik_code: blik_code,
                    };

                    $.ajax({
                        url: simplyin.controllers.payment_ajax,
                        method: 'POST',
                        data: params,
                        dataType: 'json',
                    });
                    if (typeof checkAndHideGlobalError === 'function') {
                        checkAndHideGlobalError();
                    }

                    return true;
                } else {
                    $(self.errorMsgBlik).text(self.l('Invalid BLIK code')).show();

                    if ('function' === typeof scrollToElement) {
                        scrollToElement($(self.errorMsgBlik));
                    }
                    return false;
                }
            };
        }
    };

    window.SimplyInPayment.bindGeneralConfirmationEvent = function () {
        let self = this;
        if (typeof (tc_confirmOrderValidations) !== 'undefined') {
            tc_confirmOrderValidations['simplyin_general'] = function () {
                if ($('input[type="radio"][data-module-name^="simplyin"]:checked').length == 0) {
                    return true;
                }
                const selected = $('.simplyin-payment-option:checked');
                const errorContainer = $('#simplyin-payment-error');

                if (!selected.length) {
                    if (errorContainer) {
                        errorContainer.html(self.l('Please select a payment method'));
                        errorContainer.fadeIn();
                        $('.simplyin-payment-option-item').addClass('select-method');
                        if ('function' === typeof scrollToElement) {
                            scrollToElement(errorContainer);
                        }
                    }
                    return false;
                }

                if (errorContainer) {
                    errorContainer.fadeOut();
                }
            };
        }
    };

    window.SimplyInPayment.unbindGeneralConfirmationEvent = function () {
        if (typeof (tc_confirmOrderValidations) != 'undefined' && typeof (tc_confirmOrderValidations['simplyin_general']) != 'undefined') {
            delete tc_confirmOrderValidations['simplyin_general'];
        }
    };

    window.SimplyInPayment.unbindBlikConfirmationEvents = function () {
        if (typeof (tc_confirmOrderValidations) != 'undefined' && typeof (tc_confirmOrderValidations['simplyin_blik']) != 'undefined') {
            delete tc_confirmOrderValidations['simplyin_blik'];
        }
    };

    window.SimplyInPayment.bindCardConfirmationEvents = function () {
        const self = this;
        const showGlobalErrorTmp = typeof showGlobalError === 'function' ? showGlobalError : null;
        if (typeof (tc_confirmOrderValidations) !== 'undefined') {
            tc_confirmOrderValidations['simplyin_card'] = function () {
                if (self.ott_corect) return true;

                $(self.errorMsg).hide();
                $(self.successMsg).hide();
                if (typeof showGlobalError === 'function') {
                    showGlobalError = function () {};
                }
                self.cc.createToken().then((res) => {
                    if (res && res.oneTimeToken) {
                        $(self.successMsg).show();
                        let params = {
                            action: 'selectPaymentMethod',
                            ajax: 1,
                            ajax_token: simplyin.ajax_token,
                            cart_token: simplyin.cart_token,
                            payment_id: $('input[name="simplyin-payment-option"]:checked').val(),
                            payment_type: 'add-card',
                            payment_provider: $('input[name="simplyin-payment-option"]:checked').data('payment-provider-name'),
                            provider_image: $('input[name="simplyin-payment-option"]:checked').data('provider-image'),
                            logo: $('input[name="simplyin-payment-option"]:checked').data('logo'),
                        };
                        if ($('#simplyin-save-card').is(':checked')) {
                            params.card_name = $('#card-name').val();
                            params.card_save = '1';
                        } else {
                            params.card_name = '';
                            params.card_save = '0';
                        }
                        params.last_digits = res.last4digits;
                        params.card_provider = res.organization;
                        params.ott = res.oneTimeToken;
                        $.ajax({
                            url: simplyin.controllers.payment_ajax,
                            method: 'POST',
                            data: params,
                            dataType: 'json',
                        }).done(() => {
                            self.ott_corect = true;
                            $('#confirm_order').click();
                            showGlobalError = showGlobalErrorTmp;
                        });
                    } else {
                        if (typeof showGlobalError === 'function') {
                            showGlobalError = showGlobalErrorTmp;
                            showGlobalError();
                        }
                        $(self.errorMsg).text(self.l('Invalid tokenization response'));
                        $(self.errorMsg).show();
                        if ('function' === typeof scrollToElement) {
                            scrollToElement($(self.errorMsg));
                        }
                    }
                }).catch((err) => {
                    $(self.errorMsg).text(self.l('Problem processing card'));
                    $(self.errorMsg).show();
                });

                return false;
            };
        }
    };

    window.SimplyInPayment.unbindCardConfirmationEvents = function () {
        if (typeof (tc_confirmOrderValidations) != 'undefined' && typeof (tc_confirmOrderValidations['simplyin_card']) != 'undefined') {
            delete tc_confirmOrderValidations['simplyin_card'];
        }
    };
    window.SimplyInPayment.hideCardErrors = function () {
        const self = this;
        if ($('.ccIframe-component.has-focus').length) {
            if (typeof checkAndHideGlobalError === 'function') {
                checkAndHideGlobalError();
            }
            $(self.errorMsg).hide();
        }
    };
    window.SimplyInPayment.autoSelectPayment = function () {
        const self = this;
        let try_change = 0;
        let load_interval = setInterval(() => {
            if ($('input[type="radio"][data-module-name^="simplyin"]').length) {
                $('input[type="radio"][data-module-name^="simplyin"]').prop('checked', true).trigger('change');
                self.bindGeneralConfirmationEvent();
                clearInterval(load_interval);
            }
            try_change++;
            if (try_change > 10) {
                clearInterval(load_interval);
            }
            if (self.cc === null) {
                self.setupCardForm();
                self.addIcon();
            }
        }, 500);
    };
    window.SimplyInPayment.addIcon = function () {
        let self = this;
        if ($('.simplyin-logo-payment').length == 0) {
            var logoUrl = `${simplyin.files_url}/views/img/logo_smalln.svg`;
            var $logo = $('.payment-options div[data-payment-module="simplyin"] label').first();
            $logo.css({
                'margin-right': '5px',
                'display': 'flex',
                'flex-wrap': 'wrap',
                'gap': '10px',
            });
            if (self.newImg === false) {
                self.newImg = $('<img>', {
                    class: 'simplyin-logo-payment',
                    src: logoUrl,
                    alt: 'Simply.IN',
                    width: 20,
                    height: 20,
                });
            }
            $logo.find('img').css({ 'height': '20px' });
            $logo.find('img').before(self.newImg);
            $logo.find('img').first().after(' & ');
        }
    };

    // Never on the order-confirmation page: core.js's own dispatcher already wires that page
    // (initOrderConfirmation(): the live status poll plus the pay-again form), and TheCheckout's own
    // UI - the reason this whole file exists - is not there to hook `tc_confirmOrderValidations`
    // into. Excluded by the controller name rather than by checking whether that global exists: its
    // init-time availability on the real checkout page is TheCheckout's own concern, not something
    // to make this gate depend on.
    if (simplyin.checkout == 'thecheckout' && simplyin.controller !== 'orderconfirmation') {
        window.SimplyInPayment.init();
        window.SimplyInPayment.bindOnChangeDeliveryOption();
        if (typeof (doNotRefreshOnPaymentMethods) != 'undefined') {
            doNotRefreshOnPaymentMethods.push('simplyin');
        }
    }
});
