"use strict";
(function ($) {
    $.view_list_hotels = function (element, options) {
        let defaults = {
            render_hotel_grid:"",
            render_hotel_list:"",
            items_per_page: 9,
            visiblePages: 3,
        };
        let plugin = this;
        plugin.settings = {}
        let $element = $(element);
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $element.find('select.block-sort').select2();
            let nowDate = new Date();
            let rate = plugin.settings.rate;
            let symbol=plugin.settings.symbol;
            let today = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 0, 0, 0, 0);
            $element.find('input[id="check-in"]').on('change', function () {
                let date = moment($element.find('input[id="check-in"]').val(), "YYYY-MM-DD").add(1, 'd');
                $element.find('input[id="check-out"]').data('daterangepicker').minDate = date;
                $element.find('input[id="check-out"]').data('daterangepicker').startDate = date;
                $element.find('input[id="check-out"]').val(date.format("YYYY-MM-DD"));
                $element.find('input[name="check_out"]').val(date.format("YYYY-MM-DD"));
            });
            $element.find('input[id="check-out"]').on('change', function () {
                let date = moment($element.find('input[id="check-out"]').val(), "YYYY-MM-DD").subtract(1, 'd');
                $element.find('input[id="check-in"]').data('daterangepicker').maxDate = date;
            });

            let $wrapper_hotel_grid = $element.find('.wrapper-hotel-grid');
            let $wrapper_hotel_list = $element.find('.wrapper-hotel-list');
            let $render_hotel_grid = $(plugin.settings.render_hotel_grid);
            let $render_hotel_list = $(plugin.settings.render_hotel_list);
            let $hotel_render_item_grid = $render_hotel_grid.filter('.hotel-render-item');
            let $hotel_render_item_list = $render_hotel_list.filter('.hotel-render-item');
            let items_per_page = plugin.settings.items_per_page;
            let total_result = $hotel_render_item_grid.length;
            let total_page = Math.ceil(total_result / items_per_page);
            let visiblePages = (total_page <= 4) ? (total_page % 4): 4;
            let $show = $element.find('.content-right .show');
            $element.find('#slider-container-1').slider({
                range: true,
                min: 0,
                max: 500,
                values: [0, 500],
                create: function () {
                    $("#amount_1").val(symbol+' 0'+' - '+symbol+' '+parseFloat((500 * rate)).toFixed(2));
                },
                slide: function (event, ui) {
                    $("#amount_1").val(symbol + parseFloat((ui.values[0] * rate)).toFixed(2) + ' - '+symbol + parseFloat((ui.values[1] * rate)).toFixed(2));
                    var mi = rate*ui.values[0];
                    var mx = rate*ui.values[1];
                    plugin.filterSystem(mi, mx);
                },
                change: function(event, ui) {
                    var mi = rate*ui.values[0];
                    var mx = rate*ui.values[1];
                    let price_value=[];
                    price_value.push(mi);
                    price_value.push(mx);
                    $element.find(`input[name="price_search"]`).val(JSON.stringify(price_value)).trigger('change');
                }
            });

            $element.find('input.input-near-me').on('change', function () {
                if($(this).is(":checked")) {
                    if(navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition(function(position) {
                            var latitude = position.coords.latitude;
                            var longitude = position.coords.longitude;
                            $element.find('input[name="latitude"]').val(latitude).trigger('change');
                            $element.find('input[name="longitude"]').val(longitude).trigger('change');
                        }, function () {
                            $element.find('input[name="latitude"]').val('').trigger('change');
                            $element.find('input[name="longitude"]').val('').trigger('change');
                        })
                    } else {
                        alert("Sorry, your browser does not support HTML5 geolocation.");
                    }
                } else {
                    $element.find('input[name="latitude"]').val('').trigger('change');
                    $element.find('input[name="longitude"]').val('').trigger('change');
                }
            })

            $element.find('.block-filter-price').slideUp();
            $element.find('.srat-ratings').slideUp();
            $element.find('.block-location-near-me').slideUp();
            $element.find('.rooms-types').slideUp();
            $element.find('p.more-option').on('click',function (e) {
                let $block_more_option = $(this).closest('.filter-more');
                $block_more_option.find('.block-filter-price').slideToggle();
                $block_more_option.find('.srat-ratings').slideToggle();
                $block_more_option.find('.block-location-near-me').slideToggle();
                $block_more_option.find('.rooms-types').slideToggle();
            });

            $element.find('.pagination-hotel').twbsPagination({
                totalPages: (total_page === 0)?1:total_page ,
                visiblePages: visiblePages,
                hideOnlyOnePage:true,
                first: '',
                prev: '<i class="fas fa-arrow-left"></i>',
                next: '<i class="fas fa-arrow-right"></i>',
                last: '',
                onPageClick: function (event, page) {
                    var data_page_grid = $hotel_render_item_grid.slice((page - 1) * items_per_page, page * items_per_page);
                    var data_page_list = $hotel_render_item_list.slice((page - 1) * items_per_page, page * items_per_page);
                    $wrapper_hotel_grid.empty();
                    $wrapper_hotel_list.empty();
                    if(total_result < items_per_page) {
                        $show.html(`<span>Showing ${(page-1)*items_per_page + 1} - ${page* total_result} of ${total_result} results</span>`)
                    } else {
                        $show.html(`<span>Showing ${(page-1)*items_per_page + 1} - ${page* items_per_page} of ${total_result} results</span>`)
                    }

                    $.each(data_page_grid, function (index, hotel) {
                        $wrapper_hotel_grid.append(hotel.outerHTML);
                    });
                    $.each(data_page_list, function (index, hotel) {
                        $wrapper_hotel_list.append(hotel.outerHTML);
                    });

                    $('body,html').animate({
                        scrollTop: $element.offset().top
                    },500,"linear");

                }
            });

            $element.find('.sort-display a').on('click',function (e) {
                let $form = $(this).closest('form[name="filter-form"]')
                let key_sort=$(this).data('key_sort');
                let direction=$(this).data('direction');
                $element.find('input[name="key_sort"]').val(key_sort).trigger('change');
                $element.find('input[name="direction"]').val(direction).trigger('change');
                $form.submit();
            });
            let $select_sort_item = $element.find('.sort-display a.select-sort-item');
            $.each($select_sort_item, function (index, item) {
                if($(item).hasClass('active')) {
                    let text = $(item).text();
                    $element.find('span.select-by-default').text(text);
                }
            });

            $element.find('.sort-by-block .dropdown').on('click', function () {
                $(this).find('i').addClass('active');
                if($(this).hasClass('open') === false) {
                    $(this).find('i').removeClass('active');
                }
            });
            let cookie = $element.find(".currency-selector option:selected");
            $element.find(".currency-symbol").text($.cookie('symbol'));
            $element.find('.currency-addon-fixed').text(cookie.text($.cookie('currency')));

            $element.find(".currency-selector").on("change", function () {
                plugin.updateSymbol();
            });

        };
        plugin.updateSymbol = function () {
            let cookie = document.cookie;
            cookie = $element.find(".currency-selector option:selected");
            $element.find(".currency-symbol").text(cookie.data("symbol"));
            $element.find('.currency-addon-fixed').text(cookie.text());
            $.cookie('currency', cookie.val());
            $.cookie('symbol', cookie.data("symbol"));
            let currency = $.cookie('currency');
            let symbol = $.cookie('symbol');
            plugin.change_Currency_Ajax(currency,symbol);
        }
        plugin.change_Currency_Ajax = function(currency,symbol){
            let data = {
                currency: currency,
                symbol: symbol,
                task: "hotels.changeCurrencyAjax"
            };
            $.ajax({
                cache: false,
                type: "POST",
                dataType: "json",
                url: wpbookinghotel_root_url + wpbookinghotel_api_task,
                data: data,
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                    $.alert({
                        title: 'Error',
                        content: 'there are some error please contact admin !',
                    });
                },
                complete: function () {
                    location.reload(true);
                    $('body').loadingModal('destroy');
                },
                success: function (response) {
                    response = JSON.parse(response);
                    console.log(response)
                }
            });
        }
        plugin.filterSystem = function (minPrice, maxPrice) {
            $("#computers div.system").hide().filter(function () {
                var price = parseInt($(this).data("price"), 10);
                return price >= minPrice && price <= maxPrice;
            }).show();
        }

        
        plugin.example_function = function () {
        }
        plugin.init();
    }
    $.fn.view_list_hotels = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('view_list_hotels')) {
                let plugin = new $.view_list_hotels(this, options);
                $(this).data('view_list_hotels', plugin);
            }
        });
    }
})(jQuery);
