function booklyAlert(alert) {
    // Check if there are messages in alert.
    let not_empty = false;
    for (let type in alert) {
        if (['success', 'error'].includes(type) && alert[type].length) {
            not_empty = true;
            break;
        }
    }

    if (not_empty) {
        let $container = jQuery('#bookly-alert');
        if ($container.length === 0) {
            $container = jQuery('<div id="bookly-alert" class="bookly-alert" style="max-width:600px"></div>').appendTo('#bookly-tbs');
        }
        for (let type in alert) {
            alert[type].forEach(function (message) {
                const $alert = jQuery('<div class="alert"><button type="button" class="close" data-dismiss="alert">&times;</button></div>');

                switch (type) {
                    case 'success':
                        $alert
                            .addClass('alert-success')
                            .prepend('<i class="fas fa-check-circle fa-fw fa-lg text-success align-middle mr-1"></i>');
                        setTimeout(function () {
                            $alert.remove();
                        }, 10000);
                        break;
                    case 'error':
                        $alert
                            .addClass('alert-danger')
                            .prepend('<i class="fas fa-times-circle fa-fw fa-lg text-danger align-middle mr-1"></i>');
                        break;
                }

                $alert
                    .append('<b>' + message + '</b>')
                    .appendTo($container);
            });
        }
    }
}

function booklyModal(title, text, closeCaption, mainActionCaption) {
    let $mainButton = '',
        $modal = jQuery('<div>', {class: 'bookly-modal bookly-fade', tabindex: -1, role: 'dialog'});
    if (mainActionCaption) {
        $mainButton = jQuery('<button>', {
            class: 'btn ladda-button btn-success',
            type: 'button',
            title: mainActionCaption,
            'data-spinner-size': 40,
            'data-style': 'zoom-in'
        })
            .append('<span>', {class: 'ladda-label'}).text(mainActionCaption);
        $mainButton.on('click', function (e) {
            e.stopPropagation();
            $modal.trigger('bs.click.main.button', [$modal, $mainButton.get(0)]);
        });
    }

    $modal
        .append(
            jQuery('<div>', {class: 'modal-dialog'})
                .append(
                    jQuery('<div>', {class: 'modal-content'})
                        .append(
                            jQuery('<div>', {class: 'modal-header'})
                                .append(jQuery('<h5>', {class: 'modal-title', html: title}))
                                .append(
                                    jQuery('<button>', {class: 'close', 'data-dismiss': 'bookly-modal', type: 'button'})
                                        .append('<span>').text('×')
                                )
                        )
                        .append(
                            text ? jQuery('<div>', {class: 'modal-body', html: text}) : ''
                        )
                        .append(
                            jQuery('<div>', {class: 'modal-footer'})
                                .append($mainButton)
                                .append(
                                    jQuery('<button>', {
                                        class: 'btn ladda-button btn-default',
                                        'data-dismiss': 'bookly-modal',
                                        type: 'button'
                                    })
                                        .append('<span>').text(closeCaption)
                                )
                        )
                )
        );
    jQuery('#bookly-tbs').append($modal);

    $modal.on('hide.bs.modal', function () {
        setTimeout(function () {$modal.remove();}, 2000)
    });
    setTimeout(function () {$modal.booklyModal('show')}, 0);

    return $modal;
}

function getBooklyModalContainer(id) {
    if (!document.getElementsByClassName('bookly-modals-container').length) {
        let modalsContainer = document.createElement('div');
        modalsContainer.setAttribute('id', 'bookly-tbs');
        modalsContainer.className = 'bookly-modals-container';
        document.body.appendChild(modalsContainer);
    }
    if (!document.getElementById(id)) {
        let container = document.createElement('div');
        container.setAttribute('id', id);
        document.getElementsByClassName('bookly-modals-container')[0].appendChild(container);
    }

    return document.getElementById(id);
}

function requiredBooklyPro() {
    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'bookly_required_bookly_pro',
            csrf_token: BooklyL10nGlobal.csrf_token
        },
        success: function (response) {
            if (response.success) {
                let $features = jQuery('<div>', {class: 'col-12'}),
                    $content = jQuery('<div>')
                ;
                response.data.features.forEach(function (feature, f) {
                    $features.append(jQuery('<div>', {html: feature}).prepend(jQuery('<i>', {class: 'fa-fw mr-1 fas fa-check text-success'})));
                });

                $content
                    .append(jQuery('<div>', {class: 'm-n3'})
                        .append(
                            jQuery('<img/>', {src: response.data.image, alt: 'Bookly Pro', class: 'img-fluid'})
                        )
                    ).append(jQuery('<div>', {class: 'row'})
                    .append(jQuery('<div>', {class: 'mx-auto h4 mt-4 text-bookly', html: response.data.caption}))
                ).append(jQuery('<div>', {class: 'row'})
                    .append(jQuery('<div>', {class: 'col text-center', html: response.data.body}))
                ).append(jQuery('<div>', {class: 'form-row mt-3'})
                    .append($features)
                );

                booklyModal('', $content, response.data.close, response.data.upgrade)
                    .on('bs.click.main.button', function (event, modal, mainButton) {
                        Ladda.create(mainButton).start();
                        window.location.href = 'https://www.booking-wp-plugin.com/pricing';
                        modal.booklyModal('hide');
                    })
                    .on('show.bs.modal', function () {
                        jQuery('.modal-header', jQuery(this)).remove();
                    });
            }
        },
    });
}

(function ($) {

    window.booklySerialize = {
        form: function ($form) {
            let data = {},
                serialized = $form.serializeArray();
            $('input[type=radio]:not(:checked)', $form).each(function () {
                if (this.name) {
                    let find = false,
                        that = this;
                    serialized.forEach(function (item) {
                        if (!find && item.name === that.name) {
                            find = true;
                        }
                    });
                    if (!find) {
                        serialized.push({name: this.name, value: null});
                    }
                }
            });
            $('input[type=checkbox]:not(:checked)', $form).each(function () {
                if (this.name) {
                    serialized.push({name: this.name, value: null});
                }
            });
            $.map(serialized, function (n) {
                const keys = n.name.match(/[a-zA-Z0-9_-]+|(?=\[\])/g);
                if (keys.length > 1) {
                    let tmp = data, key = keys.pop();
                    for (let i = 0; i < keys.length, j = keys[i]; i++) {
                        tmp[j] = (!tmp[j]
                                ? (key == '' && i == keys.length - 1) ? [] : {}
                                : tmp[j]
                        );
                        tmp = tmp[j];
                    }
                    if (n.value !== null) {
                        if (Array.isArray(tmp)) {
                            tmp.push(n.value);
                        } else {
                            tmp[key] = n.value;
                        }
                    }
                } else data[keys.pop()] = n.value;
            });

            return data;
        },
        buildRequestDataFromForm: function (action, $form) {
            return this.buildRequestData(action, this.form($form));
        },
        buildRequestData: function (action, data) {
            return {
                action: action,
                csrf_token: BooklyL10nGlobal.csrf_token,
                json_data: JSON.stringify(data),
            }
        }
    }

    window.booklyRequest = {
        objectToQueryString: function (initialObj) {
            const reducer = (obj, parentPrefix = null) => (prev, key) => {
                const val = obj[key];
                key = encodeURIComponent(key);
                const prefix = parentPrefix ? `${parentPrefix}[${key}]` : key;

                if (val == null || typeof val === 'function') {
                    prev.push(`${prefix}=`);
                    return prev;
                }

                if (['number', 'boolean', 'string'].includes(typeof val)) {
                    prev.push(`${prefix}=${encodeURIComponent(val)}`);
                    return prev;
                }

                prev.push(Object.keys(val).reduce(reducer(val, prefix), []).join('&'));
                return prev;
            };

            return Object.keys(initialObj).reduce(reducer(initialObj), []).join('&');
        },
        /**
         * @param data
         * @returns {Promise<unknown>}
         */
        send: function (data) {
            return new Promise((resolve, reject) => {
                fetch(ajaxurl, {
                    method: 'POST',
                    body: this.objectToQueryString(data),
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                    .then(response => {
                        if (!response.ok) {
                            return response.json().then(err => {
                                throw new Error(err.message || 'Something went wrong');
                            });
                        }

                        return response.json();
                    })
                    .then(data => resolve(data))
                    .catch(error => {
                        console.log('Invalid response for ' + (data?.action || 'request') + '. Reason ' + error.message);
                        reject(error);
                    });
            });
        }
    }
})(jQuery);