"use strict";
(function ($) {
    $.view_checkout_default = function (element, options) {
        let defaults = {
            hotel:[],
            price_roomtype:0,
            symbol:'',
            nights:0
        };
        let plugin = this;
        plugin.settings = {}
        let $element = $(element);
        let rate = plugin.settings.rate;

        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $element.find('.counpon').click(function () {
                let $coupon_section=$(this).closest('.coupon-wrap');
                let $coupon_code=$coupon_section.find('input[name="coupon"]');
                let code=$coupon_code.val();
                if(code.trim()===""){
                    $.alert({
                        title: 'Error',
                        content: 'Please input coupon code !',
                    });
                    return;
                }
                plugin.check_coupon();
            });
            plugin.check_coupon = function () {
                let $coupon_section=$element.find('.coupon-wrap');
                let $coupon_code=$element.find('input[name="coupon"]');
                let code=$coupon_code.val();
                let hotel_id=plugin.settings.hotel.id;
                let symbol=plugin.settings.symbol;
                let rate = plugin.settings.rate;
                var tmp = null;
                $.ajax({
                    async: false,
                    global: false,
                    type: "POST",
                    dataType: "json",
                    url: wpbookinghotel_root_url + wpbookinghotel_api_task,
                    data: {
                        task:"checkout.check_coupon",
                        hotel_id:hotel_id,
                        code:code
                    },
                    beforeSend: function () {
                        $('body').loadingModal();
                    },
                    error: function (xhr) {
                        $.alert({
                            title: 'Error',
                            content: 'there are some error please contact admin !',
                        });
                    },
                    complete: function () {
                        $('body').loadingModal('destroy');
                    },
                    success: function (response) {
                        response = JSON.parse(response);
                        tmp = response.data;
                        let amount = tmp.amount;
                        if (response.result === "success") {
                            $coupon_section.find('.alert-success').addClass('active');
                            $element.find('.total-sub').html('- ' + symbol + ' ' + parseFloat((amount * rate)).toFixed(2));
                            $element.find('.total-sub1').html('- ' + symbol +' '+ parseFloat((amount * rate)).toFixed(2));
                            let total0ne = $element.find('.total-1').text();
                            let totaltwo  = total0ne.slice(1);
                            let ttpay = parseFloat(totaltwo).toFixed(2);
                            let amount1 = rate * (parseFloat(amount).toFixed(2));
                            let pay1 = plugin.formatNumber((ttpay - amount1).toFixed(2));
                            // $element.find('.total-pay').html(symbol +' '+ pay1);
                            if (ttpay > amount1){
                                $element.find('.total-pay').html(symbol +' '+ pay1);
                            }else {
                                $element.find('.total-pay').html(symbol +' '+ 0);
                            }
                        }else {
                            $.alert({
                                title: 'Error',
                                content: 'Incorrect coupon, please try again !',
                            });
                            $coupon_section.find('.alert-success').removeClass('active')
                        }
                    },
                });
                return tmp;
            }
            let hotel = plugin.settings.hotel;
            let list_service = hotel.list_service;
            let price_roomtype = plugin.settings.price_roomtype;
            let symbol = plugin.settings.symbol;
            let price_service = 0;
            let total = 0;
            let nights = parseInt(plugin.settings.nights);
            $element.find('.btn-next').on('click', function() {
                let menu_tab_block = $element.find('.menu-tab-block');
                let $menu_item = menu_tab_block.find('.menu-item');
                let $tab_content_current = $(this).closest('.tab-pane');
                let is_ok = true;
                let $currentTab = '';
                let first_name = $tab_content_current.find('input[name="first_name"]').val();
                let last_name = $tab_content_current.find('input[name="last_name"]').val();
                let email = $tab_content_current.find('input[name="email"]').val();
                let phone = $tab_content_current.find('input[name="phone"]').val();
                let address = $tab_content_current.find('input[name="address"]').val();
                let post_code = $tab_content_current.find('input[name="post_code"]').val();
                let city = $tab_content_current.find('input[name="city"]').val();
                let country_id = $tab_content_current.find('select[name="country_id"]').val();
                let company = $tab_content_current.find('input[name="company"]').val();
                for(let i = 0; i <  $menu_item.length; i ++) {
                    if($($menu_item[i]).hasClass('active')) {
                        $currentTab = $menu_item[i];
                        break;
                    }
                }
                if($tab_content_current.find('.block-input-item').length > 0) {
                    if(first_name === '') {
                        $tab_content_current.find('.first-name .notice-error-1').addClass('active');
                    } else if (/^[a-zA-Z\\s]*$/.test(first_name) === false) {
                        $tab_content_current.find('first-name .notice-error-1').removeClass('active');
                        $tab_content_current.find('.first-name .notice-error-2').addClass('active');
                    } else {
                        $tab_content_current.find('.first-name .notice-error-1').removeClass('active');
                        $tab_content_current.find('.first-name .notice-error-2').removeClass('active');
                    }
                    if(last_name === '') {
                        $tab_content_current.find('.last-name .notice-error-1').addClass('active');
                    } else if (/^[a-zA-Z\\s]*$/.test(last_name) === false) {
                        $tab_content_current.find('.last-name .notice-error-1').removeClass('active');
                        $tab_content_current.find('last-name .notice-error-2').addClass('active');
                    } else {
                        $tab_content_current.find('.last-name .notice-error-1').removeClass('active');
                        $tab_content_current.find('.last-name .notice-error-2').removeClass('active');
                    }
                    if(email === '') {
                        $tab_content_current.find('.email .notice-error-1').addClass('active');
                    } else if (/\S+@\S+\.\S+/.test(email) === false) {
                        $tab_content_current.find('.email .notice-error-1').removeClass('active');
                        $tab_content_current.find('.email .notice-error-2').addClass('active');
                    } else {
                        $tab_content_current.find('.email .notice-error-1').removeClass('active');
                        $tab_content_current.find('.email .notice-error-2').removeClass('active');
                    }
                    if(phone === '') {
                        $tab_content_current.find('.phone .notice-error-1').addClass('active');
                    } else if (/([ 0-9]){10,16}$/.test(phone) === false) {
                        $tab_content_current.find('.phone .notice-error-1').removeClass('active');
                        $tab_content_current.find('.phone .notice-error-2').addClass('active');
                    } else {
                        $tab_content_current.find('.phone .notice-error-1').removeClass('active');
                        $tab_content_current.find('.phone .notice-error-2').removeClass('active');
                    }
                    if(address === '') {
                        $tab_content_current.find('.address .notice-error-1').addClass('active');
                    } else {
                        $tab_content_current.find('.address .notice-error-1').removeClass('active');
                    }
                    if(post_code === '') {
                        $tab_content_current.find('.post-code .notice-error-1').addClass('active');
                    } else {
                        $tab_content_current.find('.post-code .notice-error-1').removeClass('active');
                    }
                    if(city === '') {
                        $tab_content_current.find('.city .notice-error-1').addClass('active')
                    } else {
                        $tab_content_current.find('.city .notice-error-1').removeClass('active');
                    }
                }
                if($tab_content_current.find('select[name="country_id"]').length > 0) {
                    if(country_id === '') {
                        $tab_content_current.find('.notice-error').addClass('active');
                    } else {
                        $tab_content_current.find('.notice-error').removeClass('active');
                    }
                }
                if(first_name === '' || last_name === '' || email === '' || phone ==='' || address==='' || post_code ==='' || city ==='' || country_id === '') {
                    is_ok=false;
                } else if(first_name === '' && last_name === '' && email === '' && phone ==='' && address==='' && post_code ==='' && city ==='' && country_id === '') {
                    is_ok=true;
                }
                if(is_ok) {
                    $('body').loadingModal();
                    $element.find('.customer-name').text(first_name + ' ' + last_name);
                    $element.find('.customer-email').text(email);
                    $element.find('.customer-phone').text(phone);
                    $element.find('.customer-address').text(address);
                    $element.find('.customer-postcode').text(post_code);
                    $element.find('.customer-city').text(city);
                    if(company !== '') {
                        let content = `<tr>
                                            <td class="hollow"></td>
                                            <td>
                                                <span class="info-booking">Company</span>
                                                <span class="detail-booking">${company}</span>
                                            </td>
                                        </tr>`;
                        let table_1 = $element.find('.table-1');
                        let tbody = table_1.find('tbody');
                        tbody.append(content);
                    }
                    setTimeout(function () {
                        $('body').loadingModal('destroy');
                        $($currentTab).removeClass('active');
                        $($currentTab).next().addClass('active');
                        $tab_content_current.removeClass('in active');
                        $tab_content_current.next().addClass('in active');
                    }, 3000);
                }
            });
            $element.find('input[type="text"]').on('change', function (e) {
                let $block_input = $(this).closest('.block-input-item');
                $block_input.find('.notice-error-1').removeClass('active');
                $block_input.find('.notice-error-2').removeClass('active');
            });
            $element.find('select').on('change', function (e) {
                let $block_input = $(this).closest('.block-input');
                $block_input.find('.notice-error').removeClass('active');
            });
            $element.find('.btn-confirm-booking').on('click', function () {
                $('body').loadingModal();

                let menu_tab_block = $element.find('.menu-tab-block');
                let $menu_item = menu_tab_block.find('.menu-item');
                let $tab_content_current = $(this).closest('.tab-pane');
                let $currentTab = '';
                for(let i = 0; i <  $menu_item.length; i ++) {
                    if($($menu_item[i]).hasClass('active')) {
                        $currentTab = $menu_item[i];
                        break;
                    }
                }
                setTimeout(function () {
                    $('body').loadingModal('destroy');
                    $($currentTab).removeClass('active');
                    $($currentTab).next().addClass('active');
                    $tab_content_current.removeClass('in active');
                    $tab_content_current.next().addClass('in active');
                },3000)
            });
            $element.find('.btn-previous').on('click', function () {
                $('body').loadingModal();
                let menu_tab_block = $element.find('.menu-tab-block');
                let $menu_item = menu_tab_block.find('.menu-item');
                let $tab_content_current = $(this).closest('.tab-pane');
                let $currentTab = '';
                for(let i = 0; i <  $menu_item.length; i ++) {
                    if($($menu_item[i]).hasClass('active')) {
                        $currentTab = $menu_item[i];
                        break;
                    }
                }
                setTimeout(function () {
                    $('body').loadingModal('destroy');
                    $($currentTab).removeClass('active');
                    $($currentTab).prev().addClass('active');
                    $tab_content_current.removeClass('in active');
                    $tab_content_current.prev().addClass('in active');
                },3000);
            });
            let table_3 = $element.find('table.table-3');
            let list_service_select = [];
            table_3.hide();


            $element.find('input[name="service_id[]"]').on('change', function () {
                let service_id = $(this).val();
                let rate = plugin.settings.rate;
                let service = list_service.find(function (service) {
                    return service.id === service_id;
                });

                if($(this).is(':checked')) {
                    price_service = parseFloat(price_service) +  (rate * (parseFloat(service.price_service)));
                    total =  ((parseFloat(price_roomtype) + price_service)* nights).toFixed(2);
                    list_service_select.push(service);
                    table_3.show();
                    if(list_service_select.length > 0) {
                        let tbody = table_3.find('tbody');
                        let content = `<tr class="service-item service-item-${service.id}">
                                            <td>${service.name}</td>
                                            <td>${nights}</td>
                                            <td>${symbol} + ${plugin.formatNumber((parseFloat(service.price_service) * nights * rate).toFixed(2))}</td>
                                        </tr>`;
                        tbody.append(content);
                    }
                } else {
                    price_service = parseFloat(price_service) -  (rate*(parseFloat(service.price_service)));
                    total =  ((parseFloat(price_roomtype) + price_service)* nights).toFixed(2);
                    list_service_select=list_service_select.filter(function (item) {
                        return item.id !== service.id;
                    });
                    let tbody = table_3.find('tbody');
                    let service_item = tbody.find(`service-item-${service.id}`);
                    if( list_service_select.length > 0) {
                        service_item.remove();
                    } else {
                        tbody.empty();
                        table_3.hide();
                    }
                }
                $element.find('.total-1').html(symbol +' '+ total);
                let coupon = $element.find('.total-sub').text();
                if (coupon !== ""){
                    let getValueCouponAjax = plugin.check_coupon();
                    let getAmounCoupon = rate * (parseFloat(getValueCouponAjax.amount).toFixed(2));
                    let total_pay = plugin.formatNumber((total - getAmounCoupon).toFixed(2));
                    if(total > getAmounCoupon){
                        $element.find('.total-pay').html( symbol +' '+ total_pay);
                    }else {
                        $element.find('.total-pay').html( symbol +' '+ 0);
                    }
                } else {
                    $element.find('.total-pay').html(symbol +' '+ total);
                }

            });
            let search = window.location.search;
            if(search.indexOf('order_id') > -1) {
                $element.find('.menu-item:last-child a').tab('show');
            }
            $element.find('.btn-select-payment').on('click', function () {
                let $form = $(this).closest('form[name="form-booking"]');
                if (!$form.valid()) {
                    return false;
                }
                $form.submit();
            });
        };
        plugin.formatNumber = function (num) {
            return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
        };
        plugin.example_function = function () {
        }
        plugin.init();
    }
    $.fn.view_checkout_default = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('view_checkout_default')) {
                let plugin = new $.view_checkout_default(this, options);
                $(this).data('view_checkout_default', plugin);
            }
        });
    }
})(jQuery);
