$(document).ready(function () {
    let host_url = $('#hosturl').val();

    let calendarEl = document.getElementById('beauty_calendar');
    if (calendarEl) {
        let $newForm = $('#new_form');
        let $editForm = $('#edit_form');
        let userIsDoctor = $('#userRoleIsDoctor').val();
        $newForm.validate();
        $('.select2').select2({
            allowClear: true
        });

        $('#search_patient_op').select2({
            minimumInputLength: 3,
            ajax: {
                delay: 250,
                url: host_url + '/controllers/beauty_calendar.php?ac=searchPatients',
                dataType: 'json',
                type: 'POST',
                data: function (params) {
                    return {
                        search_text: params
                    };
                },
                results: function (data) {
                    return {
                        results: data
                    };
                }
            }
        });

        let calendar = new FullCalendar.Calendar(calendarEl, {
            customButtons: {
                addOperation: {
                    text: 'Add new',
                    click: function () {
                        $('#add_modal').modal('show');
                        $('#room_id').select2('val', '');
                        $('#start_time').val('07:00');
                        $('#end_time').val('07:15');
                        $('#date').val(moment(new Date()).format('YYYY-MM-DD'));
                    }
                },
                fullScreen: {
                    text: '',
                    html: true,
                    click: function () {
                        let element = document;

                        $('.container').css('width', '100%');

                        if (element.requestFullscreen) {
                            element.requestFullscreen();
                        } else if (element.webkitRequestFullscreen) {
                            element.webkitRequestFullscreen();
                        } else if (element.msRequestFullscreen) {
                            element.msRequestFullscreen();
                        }

                        document.querySelector(".fc-fullScreen-button").disabled = true;
                        document.querySelector(".fc-exitFullScreen-button").disabled = false;

                        calendar.render();
                    }
                },
                exitFullScreen: {
                    text: '',
                    click: function () {
                        let element = document;

                        document.querySelector(".fc-fullScreen-button").disabled = false;
                        document.querySelector(".fc-exitFullScreen-button").disabled = true;

                        $('.container').removeAttr('style');

                        if (element.exitFullscreen) {
                            element.exitFullscreen();
                        } else if (element.webkitExitFullscreen) { /* Safari */
                            element.webkitExitFullscreen();
                        } else if (element.msExitFullscreen) { /* IE11 */
                            element.msExitFullscreen();
                        }

                        calendar.render();
                    }
                }
            },
            initialView: 'resourceTimeGridDay',
            initialDate: new Date(),
            editable: false,
            selectable: true,
            selectHelper: true,
            dayMaxEvents: true, // allow "more" link when too many events
            dayMinWidth: 200,
            scrollTime: '07:00:00',
            slotDuration: '00:15:00',
            slotLabelInterval: 15,
            displayEventEnd: false,
            stickyFooterScrollbar: true,
            direction: 'ltr',
            locale: 'en',
            width: '100%',
            headerToolbar: {
                left: userIsDoctor !== '1' ? 'prev,next today addOperation fullScreen exitFullScreen' : 'prev,next today fullScreen exitFullScreen',
                center: 'title',
                right: 'resourceTimeGridDay,resourceTimeGridWeek,dayGridMonth'
            },
            //allDaySlot: false,
            resourceOrder: 'sort',
            resources: host_url + '/controllers/beauty_calendar.php?ac=rooms',
            events: function (event, successCallback) {
                let start = moment(event.start).format('YYYY-MM-DD');
                let end = moment(event.end).format('YYYY-MM-DD');

                $.ajax({
                    url: host_url + '/controllers/beauty_calendar.php?ac=events',
                    type: 'POST',
                    dataType: 'json',
                    data: {start: start, end: end},
                    success: function (doc) {
                        successCallback(doc);
                    }
                });
            },
            eventClick: function (calEvent) {
                $(document).off("click", ".e-content").on('click', '.e-content', function () {
                    $.ajax({
                        url: host_url + '/controllers/beauty_calendar.php?ac=getVisit',
                        type: 'POST',
                        dataType: 'json',
                        data: {visit_id: calEvent.event.id},
                        success: function (doc) {
                            $('#edit_form').html(doc.html);
                            $('.select2edit').select2({
                                allowClear: true
                            });
                            $('#search_patient_op_edit').select2({
                                minimumInputLength: 3,
                                initSelection: function (element, callback) {
                                    let $data = {id: doc.patient.id, text: doc.patient.name};
                                    callback($data);
                                },
                                ajax: {
                                    url: host_url + '/controllers/beauty_calendar.php?ac=searchPatients',
                                    dataType: 'json',
                                    type: 'POST',
                                    data: function (params) {
                                        return {
                                            search_text: params
                                        };
                                    },
                                    results: function (data) {
                                        return {
                                            results: data
                                        };
                                    }
                                }
                            });
                            $('#edit_modal').modal('show');
                        }
                    });
                });
            },
            select: function (event) {
                if (userIsDoctor !== '1') {
                    let room_id = event.resource.id;
                    let start_time = moment(event.start).format('HH:mm');
                    let end_time = moment(event.end).format('HH:mm');
                    let date = moment(event.start).format('YYYY-MM-DD');

                    // open modal
                    $('#add_modal').modal('show');
                    $('#room_id').select2('val', room_id);
                    $('#start_time').val(start_time);
                    $('#end_time').val(end_time);
                    $('#date').val(date);
                }
            },
            eventDidMount: function (info) {
                let title = info.event.title;
                let start = moment(info.event.start).format('HH:mm');
                let end = moment(info.event.end).format('HH:mm');
                let doctor = info.event.extendedProps.doctor;
                let services = info.event.extendedProps.services;
                let user = info.event.extendedProps.user;
                let branch = info.event.extendedProps.branch;
                let the_date = info.event.extendedProps.the_date;
                let status_text = info.event.extendedProps.status_text;
                new Tooltip(info.el, {
                    title: '<div class="fc-content-tip text-center">' +
                            '<div >' + title + '</div>' +
                            '<div class="fc-time-tip">' + the_date + '</div>' +
                            '<div class="fc-time-tip">' + start + ' - ' + end + '</div>' +
                            '<div class="fc-doctor-tip">' + doctor + '</div>' +
                            '<div class="fc-operation-type-tip">' + services + '</div>' +
                            '<div class="fc-operation-type-tip">' + status_text + '</div>' +
                            '<div class="fc-user">' + user + '</div>' +
                            '<div class="fc-user">' + branch + '</div>' +
                            '</div>',
                    // content: info.event.extendedProps.desc,
                    placement: 'top',
                    trigger: 'hover',
                    container: 'body',
                    html: true
                });
            },
            eventContent: function (arg) {
                let event = arg.event;
                let title = event.title;
                let event_id = event.id;
                let content = '<div class="fc-content">' +
                        '<div class="fc-title">  <a href="javascript:" data-event-id="' + event_id + '" style="color: #fff;" class="remove_it">' +
                        '<i class="fa fa-close"></i></a> <span class="e-content"> ' + title + '</span></div>' +
                        '</div>';
                return {html: content}
            }
        });
        calendar.render();

        $(document).on('click', '#save_btn', function () {
            if ($newForm.valid()) {
                let data = $newForm.serialize();
                $.post(host_url + '/controllers/beauty_calendar.php?ac=saveVisit', data, function (response) {
                    if (response.status === 'success') {
                        $('#add_modal').modal('hide');
                        // empty form
                        $('#service_ids').select2('val', '');
                        $('select[name=doctor_id]').select2('val', '');
                        $('select[name=branch_id]').select2('val', '');
                        $('select[name=user_id]').select2('val', '');
                        $('select[name=status]').select2('val', '');
                        $('select[name=room_id]').select2('val', '');
                        $('input[name=patient_id]').select2('val', '');
                        $('#start_time').val('07:00');
                        $('#end_time').val('07:15');
                        $('#date').val(moment().format('YYYY-MM-DD'));

                        calendar.refetchEvents();
                    }
                }, 'json');
            }
        });
        $(document).on('click', '#update_btn', function () {
            if ($editForm.valid()) {
                let data = $editForm.serialize();
                $.post(host_url + '/controllers/beauty_calendar.php?ac=updateVisit', data, function (response) {
                    if (response.status === 'success') {
                        $('#edit_modal').modal('hide');
                        calendar.refetchEvents();
                    }
                }, 'json');
            }
        });
        $(document).on('click', '.remove_it', function () {
            let event_id = $(this).data('event-id');
            bootbox.dialog({
                message: "Do you want to delete this item?",
                title: "Delete confirmation",
                buttons: {
                    danger: {
                        label: "Cancel",
                        className: "btn-danger"
                    },
                    main: {
                        label: "Delete",
                        className: "btn-primary",
                        callback: function () {
                            $.post(host_url + '/controllers/beauty_calendar.php?ac=removeVisit', {event_id: event_id}, function (response) {
                                if (response.status === 'success') {
                                    calendar.refetchEvents();
                                }
                            }, 'json');
                        }
                    }
                }
            })


        });

        document.querySelector(".fc-fullScreen-button").innerHTML = "<i class='fa fa-expand'></i>";
        document.querySelector(".fc-exitFullScreen-button").innerHTML = '<i class="fa fa-compress"></i>';

        $(document).on('change', '#service_ids', function () {
            let service_ids = $(this).val();
            $.post(host_url + '/controllers/beauty_calendar.php?ac=getServiceTime', {service_ids: service_ids}, function (response) {
                if (response.status === 'success') {
                    let start_time = moment($('#start_time').val(), 'HH:mm').add(response.time, 'minutes').format('HH:mm');
                    $('#end_time').val(start_time);
                    let start_time_edit = moment($('#start_time_edit').val(), 'HH:mm').add(response.time, 'minutes').format('HH:mm');
                    $('#end_time_edit').val(start_time_edit);
                }
            }, 'json');
        });

    }

});