(function ($) {
    'use strict';

    $(document).ready(function () {
        $('.salesloo-field__select select')
            .select2({
                placeholder: 'Select an option',
            })
            .on('select2:select', function (e) {
                saleslooFields();
            });

        $('.salesloo-field__select2 select').each(function (index, element) {
            let hasOptions = $(this).attr('data-options'),
                options = {};
            if (typeof hasOptions !== 'undefined' && hasOptions !== false) {
                options = JSON.parse(hasOptions);

                if ('ajaxurl' in options) {
                    ajaxurl = options.ajaxurl;
                    delete options.ajaxurl;
                }

                $(element)
                    .select2({
                        ajax: {
                            url: ajaxurl,
                            dataType: 'json',
                            data: function (params) {
                                let default_query = {
                                    search: params.term,
                                    page: params.page || 1,
                                };

                                let query = { ...default_query, ...options };
                                return query;
                            },
                        },
                    })
                    .on('select2:select', function (e) {
                        saleslooFields();
                    });
            } else {
                $(element)
                    .select2()
                    .on('select2:select', function (e) {
                        saleslooFields();
                    });
            }
        });

        $('.salesloo-field__daterangepicker input[type="text"]').each(
            function () {
                let hasOptions = $(this).attr('data-options'),
                    parseOptions = {},
                    defaultOptions = {
                        autoUpdateInput: false,
                        //autoApply: true,
                        locale: {
                            format: 'YYYY-MM-DD',
                            sparator: ' to ',
                        },
                        ranges: {
                            Today: [moment(), moment()],
                            Yesterday: [
                                moment().subtract(1, 'days'),
                                moment().subtract(1, 'days'),
                            ],
                            'Last 7 Days': [
                                moment().subtract(6, 'days'),
                                moment(),
                            ],
                            'Last 30 Days': [
                                moment().subtract(29, 'days'),
                                moment(),
                            ],
                            'This Month': [
                                moment().startOf('month'),
                                moment().endOf('month'),
                            ],
                            'Last Month': [
                                moment().subtract(1, 'month').startOf('month'),
                                moment().subtract(1, 'month').endOf('month'),
                            ],
                        },
                    },
                    options = {};
                if (typeof hasOptions !== 'undefined' && hasOptions !== false) {
                    parseOptions = JSON.parse(hasOptions);
                }

                options = { ...defaultOptions, ...parseOptions };
                $(this)
                    .daterangepicker(options)
                    .on('apply.daterangepicker', function (event, picker) {
                        saleslooFields();
                        $(this).val(
                            picker.startDate.format(picker.locale.format) +
                                ' to ' +
                                picker.endDate.format(picker.locale.format)
                        );
                    })
                    .on('cancel.daterangepicker', function (event, picker) {
                        saleslooFields();
                        $(this).val('');
                    });
            }
        );

        $('.salesloo-field__datepicker input[type="text"]').each(function () {
            let hasOptions = $(this).attr('data-options'),
                parseOptions = {},
                defaultOptions = {
                    autoUpdateInput: false,
                    singleDatePicker: true,
                    showDropdowns: true,
                    locale: {
                        format: 'YYYY-MM-DD hh:mm:ss',
                        cancelLabel: 'Clear',
                    },
                    timePicker: true,
                },
                options = {};
            if (typeof hasOptions !== 'undefined' && hasOptions !== false) {
                parseOptions = JSON.parse(hasOptions);
            }

            options = { ...defaultOptions, ...parseOptions };
            $(this)
                .daterangepicker(options)
                .on('apply.daterangepicker', function (event, picker) {
                    saleslooFields();
                    $(this).val(picker.startDate.format(picker.locale.format));
                })
                .on('cancel.daterangepicker', function (event, picker) {
                    saleslooFields();
                    $(this).val('');
                });
        });

        $('.salesloo-file-upload-box').sortable();

        $('.salesloo-file-upload-add').click(function () {
            let form = $(this).attr('data-row');
            $('.salesloo-file-upload-box').append(form);

            $('.salesloo-file-upload-remove').click(function () {
                $(this).parent().parent().remove();
            });

            $('.salesloo-file-upload-button').click(function () {
                let saleslooFileFrame;

                let target = $(this).parent().parent().find('.large-text');

                // Sets up the media library frame
                saleslooFileFrame = wp.media.frames.saleslooFileFrame =
                    wp.media({
                        title: 'Upload File',
                        button: { text: 'Use this file' },
                    });

                // Runs when an file is selected.
                saleslooFileFrame.on('select', function () {
                    // Grabs the attachment selection and creates a JSON representation of the model.
                    var media_attachment = saleslooFileFrame
                        .state()
                        .get('selection')
                        .first()
                        .toJSON();

                    // Sends the attachment URL to our custom file input field.
                    target.val(media_attachment.url);
                });

                // Opens the media library frame.
                saleslooFileFrame.open();
            });
        });

        $('.salesloo-tabs').tabs({
            show: function (event, ui) {},
        });

        $('.salesloo-field__image a.button').each(function () {
            $(this).click(function () {
                let saleslooImageFrame;

                let target1 = $(this).parent().find('input'),
                    target2 = $(this).parent().find('img');

                // Sets up the media library frame
                saleslooImageFrame = wp.media.frames.saleslooImageFrame =
                    wp.media({
                        title: 'Upload Image',
                        button: { text: 'Use this image' },
                        library: {
                            type: ['video', 'image'],
                        },
                    });

                // Runs when an image is selected.
                saleslooImageFrame.on('select', function () {
                    // Grabs the attachment selection and creates a JSON representation of the model.
                    var media_attachment = saleslooImageFrame
                        .state()
                        .get('selection')
                        .first()
                        .toJSON();

                    // Sends the attachment URL to our custom image input field.
                    target1.val(media_attachment.id);
                    target2.attr('src', media_attachment.url);
                });

                // Opens the media library frame.
                saleslooImageFrame.open();

                //saleslooFields();
            });
        });

        $('.salesloo-field__file a.button').each(function () {
            $(this).click(function () {
                let saleslooFileFrame;

                let target1 = $(this).parent().find('input');

                // Sets up the media library frame
                saleslooFileFrame = wp.media.frames.saleslooFileFrame =
                    wp.media({
                        title: 'Upload File',
                        button: { text: 'Use this file' },
                        // library: {
                        //     type: ['zip']
                        // }
                    });

                // Runs when an image is selected.
                saleslooFileFrame.on('select', function () {
                    // Grabs the attachment selection and creates a JSON representation of the model.
                    var media_attachment = saleslooFileFrame
                        .state()
                        .get('selection')
                        .first()
                        .toJSON();

                    // Sends the attachment URL to our custom image input field.
                    target1.val(media_attachment.url);
                });

                // Opens the media library frame.
                saleslooFileFrame.open();

                //saleslooFields();
            });
        });

        $('.salesloo-field__toggle input[type="checkbox"]').each(function () {
            $(this).change(function () {
                let value = 0;
                if ($(this).is(':checked')) {
                    value = 1;
                }

                $(this).parent().find('input[type="hidden"]').val(value);

                saleslooFields();
            });
        });

        $('.salesloo-field__checkbox input[type="checkbox"]').each(function () {
            $(this).change(function () {
                let value = 0;
                if ($(this).is(':checked')) {
                    value = 1;
                }

                $(this).parent().find('input[type="hidden"]').val(value);

                saleslooFields();
            });
        });

        $('.salesloo-field__radiobutton input[type="radio"]').each(function () {
            $(this).click(function () {
                $(this)
                    .parent()
                    .parent()
                    .find('input[type="radio"')
                    .each(function () {
                        $(this).prop('checked', false);
                    });

                $(this).prop('checked', true);
                $(this)
                    .parent()
                    .parent()
                    .find('input[type="hidden"')
                    .val($(this).val());

                saleslooFields();
            });
        });

        $('.salesloo-field__radio input[type="radio"]').each(function () {
            $(this).click(function () {
                $(this)
                    .parent()
                    .parent()
                    .find('input[type="radio"')
                    .each(function () {
                        $(this).prop('checked', false);
                    });

                $(this).prop('checked', true);
                $(this)
                    .parent()
                    .parent()
                    .find('input[type="hidden"')
                    .val($(this).val());

                saleslooFields();
            });
        });

        $('.salesloo-field__toggle input[type="checkbox"]').each(function () {
            $(this).click(function () {
                let current_value = $(this)
                    .parent()
                    .find('input[type="hidden"]')
                    .val();
            });
        });

        $('.salesloo-field__color_picker input[type="text"]').each(function () {
            $(this).wpColorPicker();
        });

        let saleslooFields = function () {
            $('.salesloo-field').each(function () {
                let hasConditionalData = $(this).attr('data-conditional'),
                    form = $(this).parents('form');

                if (
                    typeof hasConditionalData !== 'undefined' &&
                    hasConditionalData !== false
                ) {
                    let conditions = JSON.parse(hasConditionalData),
                        fieldShow = false,
                        compare = $(this).attr('data-conditional-compare');

                    fieldShow = saleslooFieldsCheckCompareConditions(
                        conditions,
                        compare,
                        form
                    );

                    //console.log(fieldShow);

                    if (fieldShow == true) {
                        $(this).css({ display: 'flex' });
                    } else {
                        $(this).css({ display: 'none' });
                    }
                }
            });
        };

        let saleslooFieldsCheckCompareConditions = function (
            conditions,
            compare,
            form
        ) {
            let result = false;

            if (Array.isArray(conditions)) {
                for (let i = 0; conditions.length > i; i++) {
                    let conditionTarget = form.find(
                        '[name=' + conditions[i].field + ']'
                    );

                    let targetValue = conditionTarget.val(),
                        match = false;

                    // if (conditionTarget.length > 1) {
                    //     let last = conditionTarget[conditionTarget.length - 1];
                    //     targetValue = jQuery(last).val();
                    // }

                    if (conditions[i].compare == '>=') {
                        if (targetValue >= conditions[i].value) {
                            match = true;
                        }
                    } else if (conditions[i].compare == '<=') {
                        if (targetValue <= conditions[i].value) {
                            match = true;
                        }
                    } else if (conditions[i].compare == '>') {
                        if (targetValue > conditions[i].value) {
                            match = true;
                        }
                    } else if (conditions[i].compare == '<') {
                        if (targetValue < conditions[i].value) {
                            match = true;
                        }
                    } else if (conditions[i].compare == '===') {
                        if (targetValue === conditions[i].value) {
                            match = true;
                        }
                    } else if (conditions[i].compare == '!==') {
                        if (targetValue !== conditions[i].value) {
                            match = true;
                        }
                    } else if (conditions[i].compare == '!=') {
                        if (targetValue != conditions[i].value) {
                            match = true;
                        }
                    } else {
                        if (targetValue == conditions[i].value) {
                            match = true;
                        }
                    }

                    if (compare == 'AND' && false == match) {
                        return false;
                    }

                    if (compare == 'OR' && true == match) {
                        return true;
                    }

                    result = match;
                }
            }

            return result;
        };

        saleslooFields();
    });
})(jQuery);
