/*!
 * 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
 */
$(function () {

    SimplyIn.initEventListenersNewAccount = function () {
        const self = this;

        if (self.is_login || (simplyin.customer_email != '' && simplyin.customer_email == self.customer_email)) {
            return;
        }

        if (simplyin.hide_phone_field === true) {
            return;
        }

        if (self.phoneCheckboxManager) {
            self.phoneCheckboxManager.showCheckbox();

            setTimeout(function () {
                $(document).off('change.simplyin', '#simply-save-checkbox');
                $(document).on('change.simplyin', '#simply-save-checkbox', function () {
                    var isChecked = $(this).is(':checked');
                    var fullPhone = '';

                    if (isChecked) {
                        $('#simplyin-phone-checkbox .simplyin-phone-input').show();
                        var prefix = $('#simplyin-phone-checkbox .phone-country-select .prefix').text();
                        var phoneNumber = $('#simplyin-phone-input').val();
                        fullPhone = prefix + ' ' + phoneNumber;
                    } else {
                        $('#simplyin-phone-checkbox .simplyin-phone-input').hide();
                        fullPhone = '0';
                    }

                    $.ajax({
                        url: self.ajax,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            ajax: true,
                            action: 'storeNewAccountDetails',
                            ajax_token: simplyin.ajax_token,
                            phone: fullPhone
                        },
                        success: function (response) {
                            if (response.success) {
                            }
                        },
                        error: function (xhr, status, error) {
                        }
                    });
                });

                $(document).off('change.simplyin', '#simplyin-phone-input, #simplyin-phone-country');
                $(document).on('change.simplyin', '#simplyin-phone-input, #simplyin-phone-country', function () {
                    var isChecked = $('#simply-save-checkbox').is(':checked');

                    if (isChecked) {
                        var prefix = $('#simplyin-phone-checkbox .phone-country-select .prefix').text();
                        var phoneNumber = $('#simplyin-phone-input').val();
                        var fullPhone = prefix + ' ' + phoneNumber;

                        $.ajax({
                            url: self.ajax,
                            type: 'POST',
                            dataType: 'json',
                            data: {
                                ajax: true,
                                action: 'storeNewAccountDetails',
                                ajax_token: simplyin.ajax_token,
                                phone: fullPhone
                            },
                            success: function (response) {
                                if (response.success) {
                                }
                            }
                        });
                    }
                });

                $(document).off('input.simplyin', '#simplyin-phone-input');
                $(document).on('input.simplyin', '#simplyin-phone-input', function () {
                    var isChecked = $('#simply-save-checkbox').is(':checked');

                    if (isChecked) {
                        var phoneNumber = $(this).val();
                        
                        if (phoneNumber && phoneNumber.length >= 9) {
                            var prefix = $('#simplyin-phone-checkbox .phone-country-select .prefix').text();
                            var fullPhone = prefix + ' ' + phoneNumber;

                            $.ajax({
                                url: self.ajax,
                                type: 'POST',
                                dataType: 'json',
                                data: {
                                    ajax: true,
                                    action: 'storeNewAccountDetails',
                                    ajax_token: simplyin.ajax_token,
                                    phone: fullPhone
                                },
                                success: function (response) {
                                    if (response.success) {
                                    }
                                }
                            });
                        }
                    }
                });
            }, 500);

            var checkInterval = setInterval(function () {
                var checkboxPhoneInput = $('#simplyin-phone-checkbox .phone-input input');

                if (checkboxPhoneInput.length > 0) {
                    clearInterval(checkInterval);
                    var addressPhoneField = $('.address-fields input[name="phone"]');
                    if (addressPhoneField.length && addressPhoneField.val() !== '') {
                        var phoneValue = addressPhoneField.val();

                        if (self.phoneCheckboxManager &&
                            typeof self.phoneCheckboxManager.parseAndSetPhoneNumber === 'function') {
                            self.phoneCheckboxManager.parseAndSetPhoneNumber(phoneValue);
                        }
                    }
                }
            }, 100);

            setTimeout(function () {
                clearInterval(checkInterval);
            }, 5000);
            return;
        }

        if (typeof SimplyInPhoneCheckboxManager !== 'undefined') {
            self.phoneCheckboxManager = new SimplyInPhoneCheckboxManager({
                checkoutType: 'thecheckout',
                emailFieldSelector: '.account-fields input[name="email"]',
                containerSelector: '#confirm_order',
                ajaxUrl: self.ajax,
                ajaxToken: simplyin.ajax_token,
                debug: false
            });

            self.phoneCheckboxManager.showCheckbox();

            setTimeout(function () {
                $(document).off('change.simplyin', '#simply-save-checkbox');
                $(document).on('change.simplyin', '#simply-save-checkbox', function () {
                    var isChecked = $(this).is(':checked');
                    var fullPhone = '';

                    if (isChecked) {
                        $('#simplyin-phone-checkbox .simplyin-phone-input').show();
                        var prefix = $('#simplyin-phone-checkbox .phone-country-select .prefix').text();
                        var phoneNumber = $('#simplyin-phone-input').val();
                        fullPhone = prefix + ' ' + phoneNumber;
                    } else {
                        $('#simplyin-phone-checkbox .simplyin-phone-input').hide();
                        fullPhone = '0';
                    }

                    $.ajax({
                        url: self.ajax,
                        type: 'POST',
                        dataType: 'json',
                        data: {
                            ajax: true,
                            action: 'storeNewAccountDetails',
                            ajax_token: simplyin.ajax_token,
                            phone: fullPhone
                        },
                        success: function (response) {
                            if (response.success) {
                            }
                        },
                        error: function (xhr, status, error) {
                        }
                    });
                });

                $(document).off('change.simplyin', '#simplyin-phone-input, #simplyin-phone-country');
                $(document).on('change.simplyin', '#simplyin-phone-input, #simplyin-phone-country', function () {
                    var isChecked = $('#simply-save-checkbox').is(':checked');

                    if (isChecked) {
                        var prefix = $('#simplyin-phone-checkbox .phone-country-select .prefix').text();
                        var phoneNumber = $('#simplyin-phone-input').val();
                        var fullPhone = prefix + ' ' + phoneNumber;

                        $.ajax({
                            url: self.ajax,
                            type: 'POST',
                            dataType: 'json',
                            data: {
                                ajax: true,
                                action: 'storeNewAccountDetails',
                                ajax_token: simplyin.ajax_token,
                                phone: fullPhone
                            },
                            success: function (response) {
                                if (response.success) {
                                }
                            }
                        });
                    }
                });
            }, 500);

            var checkInterval = setInterval(function () {
                var checkboxPhoneInput = $('#simplyin-phone-checkbox .phone-input input');

                if (checkboxPhoneInput.length > 0) {
                    clearInterval(checkInterval);
                    var addressPhoneField = $('.address-fields input[name="phone"]');

                    if (addressPhoneField.length && addressPhoneField.val() !== '') {
                        var phoneValue = addressPhoneField.val();

                        if (self.phoneCheckboxManager &&
                            typeof self.phoneCheckboxManager.parseAndSetPhoneNumber === 'function') {
                            self.phoneCheckboxManager.parseAndSetPhoneNumber(phoneValue);
                        }
                    }
                }
            }, 100);

            setTimeout(function () {
                clearInterval(checkInterval);
            }, 5000);
        }
    };

    SimplyIn.showChangeDataButton = function () {
        const self = this;

        if ((!self.is_login && !simplyin.customer.has_token) || !self.customer_email) {
            return;
        }

        if ($('.simplyin-show-popup').length > 0) {
            return;
        }

        var emailField = $('.account-fields input[name="email"]');
        var staticCustomerInfo = $('#static-customer-info-container');

        if (emailField.length === 0 && staticCustomerInfo.length === 0) {
            return;
        }

        var emailFormGroup = emailField.closest('.form-group');
        var appendTarget = emailFormGroup.length > 0 ? emailFormGroup : staticCustomerInfo;

        var popupHtml = `
            <div class="simplyin-show-popup">
                <div class="simplyin-show-popup-icon">
                    <img width="30" height="30" src="${simplyin.files_url}/views/img/logo_smalln.svg"/>
                    <svg width="12" height="13" viewBox="0 0 12 13" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect y="0.5" width="12" height="12" rx="6" fill="#33CC40"></rect>
                    <path d="M3.23096 6.54276L5.07711 8.38892L8.76942 4.38892" stroke="white" stroke-width="1.23077" stroke-linecap="round" stroke-linejoin="round"></path>
                    </svg>
                </div>
                <div class="simplyin-show-popup-edit">
                    <span>${simplyin.labels.data_completed}</span>
                    <div class="simplyin-show-popup-edit-bottom">
                    <span>${simplyin.labels.change}</span>
                    <svg width="14" height="15" viewBox="0 0 14 15" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M8.41604 2.74719L8.97217 2.19107C9.89359 1.26964 11.3875 1.26964 12.3089 2.19107C13.2304 3.11249 13.2304 4.60641 12.3089 5.52783L11.7528 6.08396M8.41604 2.74719C8.41604 2.74719 8.48556 3.92897 9.5283 4.97171C10.571 6.01445 11.7528 6.08396 11.7528 6.08396M8.41604 2.74719L3.30329 7.85994C2.957 8.20624 2.78385 8.37939 2.63494 8.5703C2.45928 8.79551 2.30868 9.03919 2.18581 9.29701C2.08164 9.51558 2.00421 9.74789 1.84934 10.2125L1.3535 11.7M11.7528 6.08396L6.64006 11.1967C6.29376 11.543 6.12061 11.7162 5.9297 11.8651C5.70449 12.0407 5.46082 12.1913 5.20299 12.3142C4.98442 12.4184 4.75211 12.4958 4.28751 12.6507L2.8 13.1465M2.8 13.1465L1.8375 13.4673C1.60887 13.5435 1.35679 13.484 1.18638 13.3136C1.01596 13.1432 0.956457 12.8911 1.03267 12.6625L1.3535 11.7M2.8 13.1465L1.3535 11.7" stroke="#2D40F6" stroke-width="1.6"></path>
                    </svg>
                    </div>
                </div>
            </div>
        `;

        appendTarget.after(popupHtml);
        
        $('.simplyin-field-badge').hide();

        $(document).off('click.simplyin', '.simplyin-show-popup');
        $(document).on('click.simplyin', '.simplyin-show-popup', function () {
            self.showLastPopup();
        });
    };

    SimplyIn.initOpcTheCheckout = function () {
        const self = this;
        this.email_field = '.account-fields input[name="email"]';

        if ($(this.email_field).length) {
            var email_field = $(this.email_field);
            var form_group = email_field.parents('.form-group');

            if (self.barEnabled() && $('.simplyin-logo-container').length === 0) {
                email_field.closest('.account-fields').prepend(self.barHtml());
            }
            if (self.badgeEnabled()) {
                self.injectFieldBadge(this.email_field);
            }

            if (form_group.length) {
                var fieldValue = $.trim(email_field.val());

                if (fieldValue && fieldValue !== '') {
                    this.customer_email = fieldValue;
                } else {
                    this.customer_email = simplyin.customer_email;
                }

                if (this.customer_email && this.customer_email !== '') {
                    if (simplyin.customer_email != '' && simplyin.customer_email == this.customer_email) {
                        self.showChangeDataButton();
                    } else {
                        self.submitEmail(false);
                    }
                }

                $(document).off('input', this.email_field);
                $(document).off('input.simplyin.thecheckout keyup.simplyin.thecheckout', this.email_field);
                $(document).on('input.simplyin.thecheckout', this.email_field, function () {
                    let logout = false;
                    if (self.is_login && self.customer_email != $(this).val()) {
                        logout = true;
                    }

                    let newEmail = $.trim($(this).val());

                    if (self.customer_email != newEmail) {
                        self.customer_email = newEmail;
                        self.submitEmail(logout);
                    }
                });
            }
        } else if ($('#static-customer-info-container').length) {
            this.customer_email = simplyin.customer_email;

            if (self.barEnabled() && $('.simplyin-logo-container').length === 0) {
                $('#static-customer-info-container').before(self.barHtml());
            }

            if (this.customer_email && this.customer_email !== '') {
                if (simplyin.customer.has_token) {
                    self.showChangeDataButton();
                }
            }
        }

        $(document).off('change.simplyin', '.address-fields input[name="phone"]');
        $(document).on('change.simplyin', '.address-fields input[name="phone"]', function () {
            var simplyinPhoneInput = $('#simplyin-phone-checkbox .phone-input input');

            if (simplyinPhoneInput.length && simplyinPhoneInput.val() == '') {
                let phone_value = $(this).val();

                if (phone_value.indexOf('+') === 0 && !self.phoneCheckboxManager) {
                    return;
                }

                if (self.phoneCheckboxManager &&
                    typeof self.phoneCheckboxManager.parseAndSetPhoneNumber === 'function') {

                    self.phoneCheckboxManager.parseAndSetPhoneNumber(phone_value);
                    
                    setTimeout(function() {
                        var checkbox = $('#simply-save-checkbox');
                        if (checkbox.is(':checked')) {
                            var prefix = $('#simplyin-phone-checkbox .phone-country-select .prefix').text();
                            var phoneNumber = $('#simplyin-phone-input').val();
                            var fullPhone = prefix + ' ' + phoneNumber;
                            
                            if (phoneNumber && phoneNumber !== '') {
                                $.ajax({
                                    url: self.ajax,
                                    type: 'POST',
                                    dataType: 'json',
                                    data: {
                                        ajax: true,
                                        action: 'storeNewAccountDetails',
                                        ajax_token: simplyin.ajax_token,
                                        phone: fullPhone
                                    },
                                    success: function (response) {
                                        if (response.success) {
                                        }
                                    }
                                });
                            }
                        }
                    }, 300);
                } else {
                    if (phone_value.indexOf('+') !== 0) {
                        simplyinPhoneInput.val(phone_value).trigger('change');
                    }
                }
            }
        });
    };

    SimplyIn.submitEmail = function (logout) {
        this.last_popup = '';
        const self = this;

        if (this.is_login == false || logout) {
            this.is_login = false;
            var email = this.customer_email;

            if (!this.isValidEmailAddress(email) && this.force_login === false) {
                return;
            }

            const formData = new URLSearchParams();
            formData.append('action', 'submitEmail');
            formData.append('ajax', '1');
            formData.append('ajax_token', simplyin.ajax_token);
            formData.append('email', email);
            formData.append('logout', logout);
            formData.append('force_login', this.force_login ? '1' : '0');

            fetch(self.ajax, {
                method: 'POST',
                body: formData
            }).then(function (response) {
                return response.json();
            }).then(function (data) {
                if (data.success && data.show_popup) {
                    if (self.phoneCheckboxManager) {
                        self.phoneCheckboxManager.hideCheckbox();
                    }

                    self.userUsedPushNotifications = data.userUsedPushNotifications;
                    self.last_popup = data.html;
                    self.showPopupByContent(data.html);
                    self.focusOnCode();
                    self.showIcon();

                    if (data.userUsedPushNotifications) {
                        self.checkPushNotification();
                    } else {
                        self.codeStartCounting();
                    }
                }

                if (data.error == 'NOT_FOUND') {
                    self.hideIcon();
                    if (email === self.customer_email) {
                        simplyin.hide_phone_field = false;
                        self.initEventListenersNewAccount();
                    }
                }
            });
        }
    };

    SimplyIn.initCheckout = function () {
        this.initOpcTheCheckout();

        if (simplyin.customer.need_login && simplyin.controller == 'order') {
            simplyin.customer.need_login = false;
            this.force_login = true;
            this.submitEmail(false);
        }
    };

    if (simplyin.checkout == 'thecheckout') {
        SimplyIn.init();
    }

});
