"use strict";
(function ($) {
    $.view_form_booking = function (element, options) {
        let defaults = {
            link_checkout: "",
            booking_style: "integrate",
            list_rate: []
        };
        let plugin = this;
        plugin.settings = {};
        let $element = $(element);
        plugin.get_data_rate_available_date = function (data) {
            let data_post = {
                task: 'rates.get_rate_available_date',
                data: data
            };
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: data_post,
                beforeSend: function () {
                    $('body').loadingModal();
                },
                error: function (xhr) {
                },
                complete: function () {
                    $('body').loadingModal('destroy');
                },
                success: function (response) {
                    response = JSON.parse(response);
                    if (response.result === "success") {
                        let list_rate = response.data;
                        console.log('list_rate',list_rate);
                        $element.find('.view-content').find('.form-search').removeClass('col-md-offset-3');
                        $element.find('.view-content').find('.form-search').removeClass('col-sm-offset-3');
                        if($element.find('.pick-date-time').is(':visible')) {
                            $element.find(".calendar").datepicker({
                                altField: "#alternate",
                                altFormat: "DD, d MM, yy",
                                beforeShowDay: function (date) {
                                    let string = jQuery.datepicker.formatDate('yy-mm-dd', date);
                                    var date = moment(date);
                                    for (let i = 0; i < list_rate.length; i++) {
                                        let current_rate = list_rate[i];
                                        let startDate = moment(current_rate.from);
                                        let endDate = moment(current_rate.to);
                                        if (date.isBefore(endDate) && date.isAfter(startDate) || (date.isSame(startDate) || date.isSame(endDate))) {
                                            return [true, `date-${string}`];
                                        }
                                    }
                                    return [false, `date-${string}`];
                                },
                                onSelect: function (date, instant) {
                                    $element.find('.btn-book-now').hide();
                                    $element.find('.btn-add-to-cart').hide();
                                    plugin.get_rates_of_date(date);
                                },
                            });
                            $element.find(".calendar").datepicker("option", "showAnim", "fadeIn");
                        } else {
                            $element.find('.pick-date-time').slideToggle("slow", function () {
                                $element.find(".calendar").datepicker({
                                    altField: "#alternate",
                                    altFormat: "DD, d MM, yy",
                                    beforeShowDay: function (date) {
                                        let string = jQuery.datepicker.formatDate('yy-mm-dd', date);
                                        var date = moment(date);
                                        for (let i = 0; i < list_rate.length; i++) {
                                            let current_rate = list_rate[i];
                                            let startDate = moment(current_rate.from);
                                            let endDate = moment(current_rate.to);
                                            if (date.isBefore(endDate) && date.isAfter(startDate) || (date.isSame(startDate) || date.isSame(endDate))) {
                                                return [true, `date-${string}`];
                                            }
                                        }
                                        return [false, `date-${string}`];
                                    },
                                    onSelect: function (date, instant) {
                                        $element.find('.btn-book-now').hide();
                                        $element.find('.btn-add-to-cart').hide();
                                        plugin.get_rates_of_date(date);
                                    },
                                });
                                $element.find(".calendar").datepicker("option", "showAnim", "fadeIn");
                            });
                            $element.find(".calendar").datepicker("option", "showAnim", "fadeIn");
                        }
                    } else {
                    }
                }
            });
        };
        plugin.get_rates_of_date = function (date) {
            $element.find('form.basic-data').serializeObject().done(function (data) {
                data.date = date;
                let $select_date_time = $element.find('.select-date-time');
                let data_post = {
                    task: "rates.get_rates_of_date",
                    data: data
                };
                setTimeout(function () {
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        url: wpbookingpro_root_url + wpbookingpro_api_task,
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify(data_post),
                        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);
                            if (response.result === "success") {
                                let data = response.data;
                                plugin.settings.list_rate = data;
                                if(data.length > 0) {
                                    let list_rate = [];
                                    $.each(data, function (index, rate) {
                                        list_rate.push(`<div class="rate-item"><button type="button" data-event_id="${rate.id}" class="time btn btn-info btn-sm"><i class="fas fa-check"></i><p>${moment(rate.from).format('HH:mm A')}-${moment(rate.to).format('HH:mm A')}</p></button><input style="display: none" value="${rate.id}" type="checkbox" name="rate_id"></div>`);
                                    });
                                    list_rate = list_rate.join('');

                                    let moment_date = moment(date);
                                    let date_item = moment_date.format('YYYY-MM-DD');
                                    let $td = $element.find(`.calendar td.date-${date_item}`);
                                    let $tr = $td.closest('tr');
                                    let $insert_tr = $(`<tr><td colspan="8"><div class="list-range-time">${list_rate}</div></td></tr>`);

                                    $insert_tr.insertAfter($tr);
                                    $insert_tr.find('button.time').click(function (e) {
                                        let $list_range = $(this).closest('.list-range-time');
                                        let $rate_item = $(this).closest('.rate-item');
                                        $list_range.find('button.time').removeClass('active').removeClass('btn-success').addClass('btn-info');
                                        $(this).addClass('active').removeClass('btn-info').addClass('btn-success');
                                        $element.find('.btn-book-now').show();
                                        $element.find('.btn-add-to-cart').show();
                                        $list_range.find('input[name="rate_id"]').prop('checked', false);
                                        $list_range.find('input[name="rate_id"]').attr('data-checked', "fasle");
                                        $rate_item.find('input[name="rate_id"]').prop('checked', true);
                                        $rate_item.find('input[name="rate_id"]').attr('data-checked', "true");
                                    });
                                }
                            }
                        }
                    });
                }, 700);
            });
        };
        plugin.booking_integrate = function () {
            $element.find('form.basic-data').serializeObject().done(function (data) {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: wpbookingpro_root_url + wpbookingpro_api_task,
                    data: {
                        task: "booking.ajax_add_rate_to_cart",
                        data_form: data
                    },
                    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);

                        if (response.result === "success") {
                            let data = response.data;
                            let link_checkout = plugin.settings.link_checkout;
                            window.location.href = link_checkout;
                        }
                    }
                });
            });
            return;
            let list_range_time = [];
            let $list_range_time = $element.find('.list-range-time button');
            $list_range_time.each(function (index, item) {
                let self = $(this);
                if (self.hasClass('active')) {
                    let event_id = self.data('event_id');
                    list_range_time.push(event_id);
                }
            });
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: {
                    action: "my_action",
                    task: "booking.ajax_add_rate_to_cart",
                    list_range_time: list_range_time
                },
                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);

                    if (response.result === "success") {
                        let data = response.data;
                        let link_checkout = plugin.settings.link_checkout;
                    }
                }
            });
        };
        plugin.booking_inline = function () {
            let id = $element.find('select[name="service_id"]').val();
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: {
                    id: id,
                    task: "service.ajax_get_json_item"
                },
                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);

                    if (response.result === "success") {
                        let service = JSON.parse(response.data);
                        let disable_payment_online = service.disable_payment_online;
                        let field_paymentsimage = $('.field-paymentsimage').data('field_paymentsimage');
                        disable_payment_online = parseInt(disable_payment_online);
                        field_paymentsimage.hide_payment_online(disable_payment_online);

                        $element.find('.form-input-info').modal('show');
                        let rate = plugin.getRateSelected();

                        let event_price_format = rate.event_price_format;
                        $element.find('p.base-price').html(event_price_format);
                        $element.find('.service-cover').attr('src', `${wpbookingpro_root_url_plugin}/${service.image}`);
                        $element.find('.service-name').text(service.name);
                        let employee = service.list_employee[0];
                        $element.find('.employee-cover').attr('src', `${wpbookingpro_root_url_plugin}/${employee.cover}`);
                        $element.find('.employee-name').text(employee.full_name);
                        $element.find('.date-detail').text(`${moment(rate.from).format('LL')} - ${moment(rate.to).format('LL')}`);
                        $element.find('.time-detail').text(`${moment(rate.from).format('HH:mm A')} - ${moment(rate.to).format('HH:mm A')}`);
                        $element.find('.location-detail').text(rate.event_address);
                    }
                }
            });
        };
        plugin.getRateSelected = function () {
            let list_rate = plugin.settings.list_rate;
            let rate_id = $element.find('input[name="rate_id"]:checked').val();
            for (let i = 0; i < list_rate.length; i++) {
                let rate = list_rate[i];
                if (rate.id === rate_id) {
                    return rate;
                }
            }
            return null;
        };
        plugin.booking_now = function (data) {
            data.task = "booking.booking_now";
            $.ajax({
                type: "POST",
                dataType: "json",
                url: wpbookingpro_root_url + wpbookingpro_api_task,
                data: data,
                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);

                    if (response.result === "success") {
                        let data = response.data;
                    }
                }
            });
        };
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $element.find('.btn-get-date-available').click(function (e) {
                let check_ok = true;
                let field_services_service_id = $element.find('.field-services-service_id').data('field_services');
                let service = field_services_service_id.getValue();
                if (service === "") {
                    check_ok = false;
                    $.alert({
                        title:'',
                        content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please select your service</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;
                }
                let field_location_location_id = $element.find('.field-location-location_id').data('field_location');
                let location = field_location_location_id.getValue();
                if (location === "") {
                    check_ok = false;
                    $.alert({
                        title:'',
                        content: `<div class="wrapper-alert">
                                        <span class="title-box">Check your information</span>
                                        <span class="content-box">Please select your location</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;
                }
                let field_employees_employee_id = $element.find('.field-employee-employee_id').data('field_employees');
                let employee = field_employees_employee_id.getValue();
                if (employee === "") {
                    check_ok = false;
                    $.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;
                }
                if($element.find('.pick-date-time').is(':visible')) {
                    $element.find(".calendar").datepicker('destroy');
                }
                if (check_ok) {
                    $element.find('input[name="service_id"]').val(service);
                    $element.find('form').serializeObject().done(function (data) {
                        plugin.get_data_rate_available_date(data);
                    });
                }
            });
            $element.find('.btn-back').click(function (e) {
                $element.find(".calendar").datepicker('destroy');
                $element.find('.pick-date-time').slideToggle("slow", function () {
                    $element.find('.view-content').find('.form-search').addClass('col-md-offset-3');
                    $element.find('.view-content').find('.form-search').addClass('col-sm-offset-3');
                });
            });
            $element.find('.btn-book-now').click(function (e) {
                let rate = plugin.getRateSelected();
                let value = 1;
                    let base_price = rate.event_price;
                let total = parseFloat(base_price) * value;
                $element.find('.base-price').html(`<span>$</span>${total}`);
                $element.find('.total-cost-sum').html(`<span>$</span>${total}`);
                plugin.booking_inline();
            });
            $element.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();
            });
            $element.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('form.basic-data').validate({
                ignore: ""
            });
            let $field_incrementnumber = $('.field-incrementnumber').data('field_incrementnumber');
            $field_incrementnumber.onChange = function (value) {
                $element.find('.total-person').html(value);
                let rate = plugin.getRateSelected();
                let base_price = rate.event_price;
                let total = parseFloat(base_price) * value;
                if (value == 1) {
                    $element.find('.base-price').html(`<span>$</span>${total}`);
                    $element.find('.total-cost-sum').html(`<span>$</span>${total}`);
                } else {
                    $element.find('.base-price').html(`<span>$</span>${total}`);
                    $element.find('.total-cost-sum').html(`<span>$</span>${total}`);
                }
            }
        };
        plugin.example_function = function () {
        };
        plugin.init();
    };
    $.fn.view_form_booking = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('view_form_booking')) {
                let plugin = new $.view_form_booking(this, options);
                $(this).data('view_form_booking', plugin);
            }
        });
    }
})(jQuery);
