"use strict";
(function ($) {
    $.view_find_event = function (element, options) {
        let defaults = {
            service_item: '',
            visiblePages: 7,
            events: [],
            rates: [],
            current_page: 1,
            items_per_page: 10,
            base_price: 0,
            base_price_format: 0,
            person: 1
        };
        let plugin = this;
        plugin.settings = {};
        let $element = $(element);
        plugin.get_list_rate = function ($event_item) {
            let event_id = $event_item.data("event_id");
            let $wrapper_list_rate = $event_item.find('.wrapper-list-rate');
            $event_item.find('.wrapper-list-rate').slideDown();
            $event_item.find('.btn-booknow').addClass('hidden');
            $event_item.find('.btn-cancel').addClass('shown');
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: {
                    task: "rates.get_list_rate_by_event",
                    event_id: event_id
                },
                beforeSend: function () {
                    $wrapper_list_rate.loadingModal();
                },
                error: function (xhr) {
                    $('body').loadingModal('destroy');
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    $wrapper_list_rate.loadingModal('destroy');
                },
                success: function (response) {
                    response = JSON.parse(response);

                    if (response.result === "success") {
                        loadScripts(response);
                        plugin.settings.rates = response.data;
                        let rates = response.data;
                        console.log('rate', rates)
                        let $list_rate = $event_item.find('.list-rate');
                        $list_rate.empty();
                        let $ul = $(`<ul></ul>`);
                        let $h5_1=$(`<h5>Select Time: </h5>`);
                        let list_employee = [];
                        $.each(rates, function (index, rate) {
                            let $li = $(`<li><span data-rate_id="${rate.id}"  class="el-radio-button__inner rate-item"><i class="far fa-circle"></i> <i class="far fa-check-circle"></i> <span>${rate.start_time}-${rate.end_time}</span> </span></li>`);
                            $li.appendTo($ul);
                            list_employee = rate.list_employee;
                        });
                        $h5_1.appendTo($list_rate);
                        $ul.appendTo($list_rate);
                        let $wrapper_list_employee_select = $event_item.find('.wrapper-list-select');
                        $wrapper_list_employee_select.empty();
                        let $row=$(`<div class="row"></div>`)
                        let $ul2 = $(`<ul  class="list-employee"></ul>`);
                        let $h5_2=$(`<h5>Select Trainer: </h5>`);
                        $.each(list_employee, function (index, employee) {
                            let $li = $(`<div class="col-sm-4">
                                            <li >
                                                <div class="wrapper-employee" data-employee_id="${employee.id}">
                                                    <div class="selected" style="display: none"><i class="fas fa-check-circle"></i></div>
                                                    <div class="img-box">
                                                        <div>
                                                            <img class="employee-image-choose" src="${wpbookingpro_root_url_plugin}/${employee.image}" alt="" />
                                                        </div>
                                                    </div>
                                                    <div class="employee-name">${employee.full_name}</div>
                                                </div>
                                            </li>
                                        </div>`);
                            $li.appendTo($ul2);
                        });
                        $h5_2.appendTo($wrapper_list_employee_select);
                        $ul2.appendTo($row);
                        $row.appendTo($wrapper_list_employee_select);
                        $ul2.find('.wrapper-employee').click(function (e) {
                            $ul2.find('.wrapper-employee').removeClass('active');
                            let $self = $(this);
                            $self.addClass('active');
                            $element.find('.wrapper-employee .selected').hide();
                            let employee_id = $self.data('employee_id');
                            $self.find('.selected').show();
                            $element.find(`input[name="employee_id"]`).val(employee_id);
                        });
                        $ul.find('.rate-item').click(function (e) {
                            let $self = $(this);
                            $ul.find('.rate-item').removeClass('active');
                            $self.addClass('active');
                        });
                    }
                }
            });
        };
        plugin.getEvent = function (event_id) {
            event_id = parseInt(event_id);
            let data = plugin.settings.events;
            for (let i = 0; i < data.length; i++) {
                let event = data[i];
                if (parseInt(event.object_id) === event_id) {
                    return event;
                }
            }
            return false;
        };
        plugin.getRate = function (rate_id) {
            rate_id = parseInt(rate_id);
            let data = plugin.settings.rates;
            for (let i = 0; i < data.length; i++) {
                let rate = data[i];
                if (parseInt(rate.id) === rate_id) {
                    return rate;
                }
            }
            return false;
        };
        plugin.getEmployee = function (employee_id) {
            employee_id = parseInt(employee_id);
            let data = plugin.settings.events;
            for (let i = 0; i < data.length; i++) {
                let list_employee = data[i].list_employee;
                for (let i = 0; i < list_employee.length; i++) {
                    let employee = list_employee[i];
                    if (parseInt(employee.id) === employee_id) {
                        return employee;
                    }
                }
            }
            return false;
        };
        plugin.fill_data = function () {
            let data = plugin.settings.events;
            let total_result = data.length;
            $element.find('.count-result').text(total_result);
            let visiblePages = plugin.settings.visiblePages;
            let items_per_page = plugin.settings.items_per_page;
            let current_page = plugin.settings.current_page;
            let $list_result = $element.find('.wrapper-search-result .list-result');
            $list_result.empty();
            var data_page = data.slice((current_page - 1) * items_per_page, current_page * items_per_page);
            $.each(data_page, function (index, event) {
                let $event_item = $(plugin.settings.service_item);
                $event_item.attr('data-event_id', event.object_id);
                $event_item.data('event_id', event.object_id);
                let list_employee = event.list_employee;
                let $ul = $(`<ul class="list-employee-image"></ul>`);
                $.each(list_employee, function (index, employee) {
                    $ul.append(`<li><img class="employee-image" src="${wpbookingpro_root_url_plugin}/${employee.image}"></li>`);
                });
                $.each(event, function (key, value) {
                    $event_item.find(`.${key}`).html(value);
                });
                $event_item.find('.image-service-image').attr('src', `${wpbookingpro_root_url_plugin}/${event.service_image}`);
                $event_item.find('input[name="event_id"]').val(event.id);
                $event_item.find('.wrapper-employee').append($ul);
                $event_item.appendTo($list_result);
                $event_item.find('.wrapper-button-action').click(function (e) {
                    $(this).toggleClass('active');
                    if (!$event_item.find('.wrapper-list-rate').is(':visible')) {
                        let $current_service_item = $(this).closest('.service-item');
                        plugin.get_list_rate($current_service_item);
                    } else {
                        $event_item.find('.wrapper-list-rate').slideToggle();
                        $event_item.find('.btn-booknow').removeClass('hidden');
                        $event_item.find('.btn-cancel').removeClass('shown');

                    }
                });
                $event_item.find('.btn-book-now-by-current-rate-item').click(function (e) {
                    let $service_item = $(this).closest('.service-item');
                    let event_id = $service_item.data('event_id');
                    let event = plugin.getEvent(event_id);
                    let rate_id = $service_item.find('span.active.rate-item').data('rate_id');
                    let rate = plugin.getRate(rate_id);
                    let employee_id = $service_item.find('.wrapper-employee.active').data('employee_id');
                    let employee = plugin.getEmployee(employee_id);
                    if (typeof rate_id == "undefined") {
                        $.alert({
                            title:'',
                            content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please select your time</span>
                                   </div>
                                   <i class="icon-nb-hand"></i>`,
                            container:'.block-confirm',
                            buttons: {
                                formSubmit: {
                                    text: '<i class="icon-nb-close"></i>',
                                    btnClass: 'btn-red',
                                }
                            }
                        });
                        return false;
                    }
                    if (typeof employee_id == "undefined") {
                        $.alert({
                            title:'',
                            content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please select your employee</span>
                                   </div>
                                   <i class="icon-nb-hand"></i>`,
                            container:'.block-confirm',
                            buttons: {
                                formSubmit: {
                                    text: '<i class="icon-nb-close"></i>',
                                    btnClass: 'btn-red',
                                }
                            }
                        });
                        return false;
                    }
                    $("#dialog-confirm").dialog("open");
                    $('.custom-wrapper-dialog').find('.ui-widget-header').remove();
                    let time_rate = rate.start_time + ' - ' + rate.end_time;
                    let date_from = parseInt(new Date(rate.from).getDate());
                    let date_to = parseInt(new Date(rate.to).getDate());
                    let date_from_detail = new Date(rate.from).toLocaleDateString();
                    let date_to_detail = new Date(rate.to).toLocaleDateString();
                    $('#dialog-confirm').find('.address-detail').text(event.event_address);
                    $('#dialog-confirm').find('.time-detail').text(time_rate);
                    $('#dialog-confirm').find('.service-cover').attr('src', `${wpbookingpro_root_url_plugin}/${event.service_image}`);
                    $('#dialog-confirm').find('.service-name').text(event.service_name);
                    $('#dialog-confirm').find('.employee-cover').attr('src', `${wpbookingpro_root_url_plugin}/${employee.image}`);
                    $('#dialog-confirm').find('.employee-name').text(employee.full_name);
                    if (date_from === date_to) {
                        $('#dialog-confirm').find('.date-detail').text(date_from_detail);
                    } else {
                        $('#dialog-confirm').find('.date-detail').text(date_from_detail + ' - ' + date_to_detail);
                    }
                    let person = plugin.settings.person;
                    let base_price = event.event_price;
                    let base_price_format = event.event_price_format;
                    $('#dialog-confirm').find('.total-person').text(person);
                    $('#dialog-confirm').find('.base-price').html('<span>$</span>' + base_price * person);
                    $('#dialog-confirm').find('.total-cost-sum').html('<span>$</span>' + person * base_price);
                    $('#dialog-confirm').find('.counter-minus').click(function (e) {
                        person = $('#dialog-confirm').find('input[type="text"].increment-number').val();
                        $('#dialog-confirm').find('.total-person').text(person);
                        $('#dialog-confirm').find('.base-price').html('<span>$</span>' + base_price * person);
                        $('#dialog-confirm').find('.total-cost-sum').html('<span>$</span>' + person * base_price);
                    });
                    $('#dialog-confirm').find('.counter-plus').click(function (e) {
                        person = $('#dialog-confirm').find('input[type="text"].increment-number').val();
                        $('#dialog-confirm').find('.total-person').text(person);
                        $('#dialog-confirm').find('.base-price').html('<span>$</span>' + base_price * person);
                        $('#dialog-confirm').find('.total-cost-sum').html('<span>$</span>' + person * base_price);
                    });
                    $('#dialog-confirm').find('input[name="employee_id"]').val(employee_id);
                    $('#dialog-confirm').find('input[name="service_id"]').val(event.service_id);
                    $('#dialog-confirm').find('input[name="rate_id"]').val(rate_id);
                });
            });
        };
        plugin.search_by_filter = function () {
            let $ajax_search = {};
            $element.find("form.form-filter").serializeObject().done(function (data) {

                if (typeof $ajax_search.abort === "function") {
                    $ajax_search.abort();
                }
                let $list_result = $element.find('.list-result');
                $list_result.addClass('searching');
                $ajax_search = $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: wpbookingpro_root_url + wpbookingpro_api_task,
                    data: data,
                    beforeSend: function () {
                        $list_result.loadingModal('opacity', '0.2');
                    },
                    error: function (xhr) {
                        $list_result.loadingModal('destroy');
                        $.alert({
                            title: 'Error',
                            content: 'there are some error please contact admin !',
                        });
                        $list_result.removeClass('searching');
                    },
                    complete: function () {
                        $('body').loadingModal('destroy');
                        $list_result.removeClass('searching');
                    },
                    success: function (response) {
                        response = JSON.parse(response);

                        if (response.result === "success") {
                            loadScripts(response);
                            plugin.settings.events = response.data;
                            plugin.settings.current_page = 1;
                            plugin.fill_data();
                            let items_per_page = plugin.settings.items_per_page;
                            let visiblePages = plugin.settings.visiblePages;
                            $element.find('.pagination-list-service').twbsPagination({
                                totalPages: 5,
                                visiblePages: visiblePages,
                                onPageClick: function (event, current_page) {
                                    plugin.settings.current_page = current_page;

                                    $('#page-content').text('Page ' + current_page);
                                }
                            });
                        }
                    }
                });
            });
        };
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $("#dialog-confirm").find('form[name="client-form"]').each(function (e) {
                $(this).validate({
                    ignore: ""
                });
            });
            $("#dialog-confirm").find('.btn-booking-modal-now').click(function (e) {
                let $form = $(this).closest('form');
                $form.find('input[name="task"]').val('booking.book_now');
                if (!$form.valid()) {
                    return false;
                }
                $form.submit();
            });
            $("#dialog-confirm").find('.btn-add-to-cart').click(function (e) {
                let $form = $(this).closest('form');
                $form.find('input[name="task"]').val('cart.add_to_cart');
                if (!$form.valid()) {
                    return false;
                }
                $form.submit();
            });
            $element.find('.btn-close-modal').click(function (e) {
                $("#dialog-confirm").dialog("close");
            });
            $element.find('input.check-box-service').iCheck({
                checkboxClass: 'icheckbox_minimal',
                radioClass: 'iradio_minimal',
                increaseArea: '20%'
            });
            $element.find('select.list-location').select2();
            $element.find('select.list-employee').select2();
            $element.find('select.sorting-training').select2();
            $element.find("select").change(function (e) {
                plugin.search_by_filter();
            });
            $element.find("input").change(function (e) {
                plugin.search_by_filter();
            });
            $element.find('input.check-box-service').on('ifChanged', function (event) {
                plugin.search_by_filter();
            });
           plugin.search_by_filter();
            $element.find(".calendar").datepicker({
                altField: "#alternate",
                altFormat: "DD, d MM, yy",
                onSelect: function (date, instant) {
                    plugin.search_by_filter();
                },
            });
            $("#dialog-confirm").dialog({
                resizable: false,
                autoOpen: false,
                height: "auto",
                width: 900,
                modal: true,
                open: function (event, ui) {
                    $('body').addClass('show-form-modal');
                },
                close: function (event, ui) {
                    $('body').removeClass('show-form-modal');
                    $("#dialog-confirm").find('input[name="first_name"]').val('');
                    $("#dialog-confirm").find('input[name="last_name"]').val('');
                    $("#dialog-confirm").find('input[name="email"]').val('');
                    $("#dialog-confirm").find('input.countries').val('');
                    $("#dialog-confirm").find('input[name="phone"]').val('');
                    $("#dialog-confirm").find('input[name="number_person"]').val('1');
                }
            }).parent().addClass('custom-wrapper-dialog');
        };
        plugin.example_function = function () {
        };
        plugin.init();
    };
    $.fn.view_find_event = function (options) {
        return this.each(function () {
            if (undefined === $(this).data('view_find_event')) {
                let plugin = new $.view_find_event(this, options);
                $(this).data('view_find_event', plugin);
            }
        });
    }
})(jQuery);
