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

    let calendarElRes = document.getElementById('residence_rooms_calendar');
    let calendarEl = document.getElementById('operation_rooms_calendar');
    if (calendarElRes && calendarEl) {

        $('.timepicker-custom').timepicker({
            autoclose: true,
            minuteStep: 15,
            showSeconds: false,
            showMeridian: true
        });

        let $newOperationForm = $('#new_operation_form');
        let $editForm = $('#edit_form');
        $newOperationForm.validate();
        $('.select2').select2({
            allowClear: true
        });
        $('#search_patient_op').select2({
            minimumInputLength: 3,
            allowClear: true,
            ajax: {
                delay: 250,
                url: host_url + '/controllers/operations_calendar.php?ac=searchPatients',
                dataType: 'json',
                type: 'POST',
                data: function (params) {
                    return {
                        search_text: params
                    };
                },
                results: function (data) {
                    return {
                        results: data
                    };
                }
            }
        });

        let calendarRes = new FullCalendar.Calendar(calendarElRes, {
            customButtons: {
                addOperation: {
                    text: 'أضافه جديد',
                    click: function () {
                        $('#add_operation_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) {
                            /!* Safari *!/
                            element.webkitRequestFullscreen();
                        } else if (element.msRequestFullscreen) {
                            /!* IE11 *!/
                            element.msRequestFullscreen();
                        }

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

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

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

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

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

                        calendarRes.render();
                    }
                }*/
            },
            initialView: 'resourceTimeGridDay',
            initialDate: new Date(),
            editable: false,
            selectable: true,
            selectHelper: true,
            dayMaxEvents: true, // allow "more" link when too many events
            dayMinWidth: 100,
            scrollTime: '07:00:00',
            slotDuration: '00:60:00',
            slotLabelInterval: 60,
            displayEventEnd: false,
            stickyFooterScrollbar: true,
            direction: 'rtl',
            locale: 'ar',
            width: '100%',
            expandRows: true,
            aspectRatio: 1,
            allDaySlot: false,
            headerToolbar: {
                left: 'prev,next today addOperation',
                center: 'title',
                right: 'resourceTimeGridDay,resourceTimeGridWeek,dayGridMonth'
            },
            resourceOrder: '-floor_no',
            resourceLabelDidMount: function (info) {
                if (info.resource.extendedProps.floor_no == 6) {
                    info.el.style.backgroundColor = '#ffcaa7';
                } else if (info.resource.extendedProps.floor_no == 7) {
                    info.el.style.backgroundColor = '#a7ffba';
                } else {
                    info.el.style.backgroundColor = '#a7b9ff';
                }

            },
            //filterResourcesWithEvents: true,
            resources: host_url + '/controllers/operations_calendar.php?ac=residenceRooms',
            events: function (event, successCallback, failureCallback, info) {
                let start = moment(event.start).format('YYYY-MM-DD');
                let end = moment(event.end).format('YYYY-MM-DD');

                $.ajax({
                    url: host_url + '/controllers/operations_calendar.php?ac=events',
                    type: 'POST',
                    dataType: 'json',
                    data: {start: start, end: end, residence_cal: 1},
                    success: function (doc) {
                        successCallback(doc);
                    }
                });
            },
            eventClick: function (calEvent) {
                $(document).off("click", ".e-content").on('click', '.e-content', function () {
                    $.ajax({
                        url: host_url + '/controllers/operations_calendar.php?ac=getOperation',
                        type: 'POST',
                        dataType: 'json',
                        data: {operation_id: calEvent.event.id},
                        success: function (doc) {
                            $('#edit_form').html(doc.html);
                            $('.select2edit').select2({
                                allowClear: true
                            });
                            $('.timepicker-custom').timepicker({
                                autoclose: true,
                                minuteStep: 15,
                                showSeconds: false,
                                showMeridian: true
                            });

                            $('#search_patient_op_edit').select2({
                                allowClear: true,
                                minimumInputLength: 3,
                                initSelection: function (element, callback) {
                                    let $data = {id: doc.patient.id, text: doc.patient.name};
                                    callback($data);
                                },
                                ajax: {
                                    url: host_url + '/controllers/operations_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) {
                let room_id = event.resource.id;
                let start = moment(event.start).format('YYYY-MM-DD HH:mm:ss');
                let end = moment(event.end).format('YYYY-MM-DD HH:mm:ss');
                let start_time = moment(event.start).format('hh:mm A');
                let end_time = moment(event.end).format('hh:mm A');
                let date = moment(event.start).format('YYYY-MM-DD');
                console.log(room_id, start, end);

                // open modal
                $('#add_operation_modal').modal('show');
                $('#res_room_id').select2('val', room_id);
                $('#res_start_time').val(start_time);
                $('#res_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 A');
                let end = moment(info.event.end).format('hh:mm A');
                let doctor = info.event.extendedProps.doctor;
                let operation_type = info.event.extendedProps.operation_type;
                let user = info.event.extendedProps.user;
                new Tooltip(info.el, {
                    title: '<div class="fc-content-tip text-center">' +
                        '<div >' + title + '</div>' +
                        '<div class="fc-time-tip">' + start + ' - ' + end + '</div>' +
                        '<div class="fc-doctor-tip">' + doctor + '</div>' +
                        '<div class="fc-operation-type-tip">' + operation_type + '</div>' +
                        '<div class="fc-user">' + user + '</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 doctor = event.extendedProps.doctor;
                let operation_type = event.extendedProps.operation_type;
                let content = '<div class="fc-content">' +
                    '<div class="fc-title">  <a href="javascript:" data-event-id="' + event_id + '" style="color: #000;" class="remove_it">' +
                    '<i class="fa fa-close"></i></a> <span class="e-content">' + doctor + ' - ' + operation_type + '' +
                    '<div class="fc-title ">' + title + '</div></span></div>' +
                    '</div>';
                return {html: content}
            }
        });
        calendarRes.render();
        let calendar = new FullCalendar.Calendar(calendarEl, {
            customButtons: {
                addOperation: {
                    text: 'أضافه جديد',
                    click: function () {
                        $('#add_operation_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) {
                            /!* Safari *!/
                            element.webkitRequestFullscreen();
                        } else if (element.msRequestFullscreen) {
                            /!* IE11 *!/
                            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;

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

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

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

                        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: 'rtl',
            locale: 'ar',
            width: '100%',
            expandRows: true,
            aspectRatio: 1,
            allDaySlot: false,
            headerToolbar: {
                left: 'prev,next today addOperation',
                center: 'title',
                right: 'resourceTimeGridDay,resourceTimeGridWeek,dayGridMonth'
            },
            //allDaySlot: false,
            resourceOrder: '-floor_no',
            resources: host_url + '/controllers/operations_calendar.php?ac=rooms',
            resourceLabelDidMount: function (info) {
                if (info.resource.extendedProps.floor_no == 6) {
                    info.el.style.backgroundColor = '#ffcaa7';
                } else if (info.resource.extendedProps.floor_no == 7) {
                    info.el.style.backgroundColor = '#a7ffba';
                } else {
                    info.el.style.backgroundColor = '#a7b9ff';
                }

            },
            events: function (event, successCallback, failureCallback, info) {
                let start = moment(event.start).format('YYYY-MM-DD');
                let end = moment(event.end).format('YYYY-MM-DD');

                $.ajax({
                    url: host_url + '/controllers/operations_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/operations_calendar.php?ac=getOperation',
                        type: 'POST',
                        dataType: 'json',
                        data: {operation_id: calEvent.event.id},
                        success: function (doc) {
                            $('#edit_form').html(doc.html);
                            $('.select2edit').select2({
                                allowClear: true
                            });
                            $('.timepicker-custom').timepicker({
                                autoclose: true,
                                minuteStep: 15,
                                showSeconds: false,
                                showMeridian: true
                            });

                            $('#search_patient_op_edit').select2({
                                allowClear: true,
                                minimumInputLength: 3,
                                initSelection: function (element, callback) {
                                    let $data = {id: doc.patient.id, text: doc.patient.name};
                                    callback($data);
                                },
                                ajax: {
                                    url: host_url + '/controllers/operations_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) {
                let room_id = event.resource.id;
                let start = moment(event.start).format('YYYY-MM-DD HH:mm:ss');
                let end = moment(event.end).format('YYYY-MM-DD HH:mm:ss');
                let start_time = moment(event.start).format('hh:mm A');
                let end_time = moment(event.end).format('hh:mm A');
                let date = moment(event.start).format('YYYY-MM-DD');
                console.log(room_id, start, end);

                // open modal
                $('#add_operation_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 A');
                let end = moment(info.event.end).format('hh:mm A');
                let doctor = info.event.extendedProps.doctor;
                let operation_type = info.event.extendedProps.operation_type;
                let user = info.event.extendedProps.user;
                new Tooltip(info.el, {
                    title: '<div class="fc-content-tip text-center">' +
                        '<div >' + title + '</div>' +
                        '<div class="fc-time-tip">' + start + ' - ' + end + '</div>' +
                        '<div class="fc-doctor-tip">' + doctor + '</div>' +
                        '<div class="fc-operation-type-tip">' + operation_type + '</div>' +
                        '<div class="fc-user">' + user + '</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 doctor = event.extendedProps.doctor;
                let operation_type = event.extendedProps.operation_type;
                let content = '<div class="fc-content">' +
                    '<div class="fc-title">  <a href="javascript:" data-event-id="' + event_id + '" style="color: #000;" class="remove_it">' +
                    '<i class="fa fa-close"></i></a> <span class="e-content">' + doctor + ' - ' + operation_type + '' +
                    '<div class="fc-title ">' + title + '</div></span></div>' +
                    '</div>';
                return {html: content}
            }
        });
        calendar.render();

        $(document).on('click', '#save_operation_btn', function () {
            if ($newOperationForm.valid()) {
                let data = $newOperationForm.serialize();
                $.post(host_url + '/controllers/operations_calendar.php?ac=saveOperation', data, function (response) {
                    console.log(response);
                    if (response.status === 'success') {
                        $('#add_operation_modal').modal('hide');
                        calendar.refetchEvents();
                        calendarRes.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', '#operation_type_id', function () {
            let operation_type_id = $(this).val();
            $.post(host_url + '/controllers/operations_calendar.php?ac=getOperationTime', {operation_type_id: operation_type_id}, function (response) {
                if (response.status === 'success') {

                    let start_time = moment($('#start_time').val(), 'hh:mm A').add(response.time, 'minutes').format('hh:mm A');
                    $('#end_time').val(start_time);
                    $('#start_time').attr('data-time-plus', response.time);
                    $('#start_time_edit').attr('data-time-plus', response.time);
                    let start_time_edit = moment($('#start_time_edit').val(), 'hh:mm A').add(response.time, 'minutes').format('hh:mm A');
                    $('#end_time_edit').val(start_time_edit);

                    let res_start_time = moment($('#res_start_time').val(), 'hh:mm A').add(response.res_time, 'hour').format('hh:mm A');
                    $('#res_end_time').val(res_start_time);
                    $('#res_start_time').attr('data-time-plus', response.res_time);
                    $('#res_start_time_edit').attr('data-time-plus', response.res_time);
                    let res_start_time_edit = moment($('#res_start_time_edit').val(), 'hh:mm A').add(response.res_time, 'hour').format('hh:mm A');
                    $('#res_end_time_edit').val(res_start_time_edit);

                    $('#cost').val(response.cost);
                    $('#cost_edit').val(response.cost);
                    $('#cost_details').val(response.cost_details);
                    $('#cost_details_edit').val(response.cost_details);
                    $('#instructions').val(response.instructions);
                    $('#instructions_edit').val(response.instructions);
                }
            }, 'json');
        });

        $(document).on('click', '#update_btn', function () {
            if ($editForm.valid()) {
                let data = $editForm.serialize();
                $.post(host_url + '/controllers/operations_calendar.php?ac=updateOperation', data, function (response) {
                    if (response.status === 'success') {
                        $('#edit_modal').modal('hide');
                        calendar.refetchEvents();
                        calendarRes.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/operations_calendar.php?ac=removeOperation', {event_id: event_id}, function (response) {
                                if (response.status === 'success') {
                                    calendar.refetchEvents();
                                    calendarRes.refetchEvents();
                                }
                            }, 'json');
                        }
                    }
                }
            })


        });

        $(document).on('change', '.filters_inputs', function () {
            let doctor_id = $('#filter_doctor').val();
            let operation_type = $('#filter_operation_type').val();
            calendar.setOption('events', function (event, successCallback, failureCallback, info) {
                let start = moment(event.start).format('YYYY-MM-DD');
                let end = moment(event.end).format('YYYY-MM-DD');

                $.ajax({
                    url: host_url + '/controllers/operations_calendar.php?ac=events',
                    type: 'POST',
                    dataType: 'json',
                    data: {start: start, end: end, doctor_id: doctor_id, operation_type: operation_type},
                    success: function (doc) {
                        successCallback(doc);
                    }
                });
            });
            calendar.refetchEvents();
        });

        $(document).on('change', '.start_time_change', function () {
            let type = $(this).data('type');
            let current_time = $(this).val();
            let plus_time = $(this).attr('data-time-plus');

            if (type === 'residence') {
                let start_time = moment(current_time, 'hh:mm A').add(plus_time, 'hour').format('hh:mm A');
                $('#res_end_time').val(start_time);
                $('#res_end_time_edit').val(start_time);
            } else {
                let start_time = moment(current_time, 'hh:mm A').add(plus_time, 'minutes').format('hh:mm A');
                $('#end_time').val(start_time);
                $('#end_time_edit').val(start_time);
            }

            console.log(type, current_time, plus_time);
        })


        $('body').on('click','.fc-button', function() {
            let calendar_id = $(this).closest('.has-toolbar').attr('id');
            // check if click on prev or next button
            if($(this).hasClass('fc-next-button')) {
                if(calendar_id === 'residence_rooms_calendar') {
                    calendar.next();
                }else{
                    calendarRes.next();
                }
            }else if($(this).hasClass('fc-prev-button')) {
                if(calendar_id === 'residence_rooms_calendar') {
                    calendar.prev();
                }else{
                    calendarRes.prev();
                }
            }





        });

    }


    let $body = $('body');
    $body.on('click', '#print_page', function () {
        $.print("#list_container");
    });
    $body.on('click', '.contacted_patient', function () {
        let id = $(this).data('id');
        let value = $(this).is(':checked') ? 1 : 0;

        $.post(host_url + '/controllers/operations_reports.php?ac=contactedPatient', {id: id, value: value}, function (response) {
            if (response.status === 'success') {
                $('#contacted_user_' + id).html(response.name);

                if (value === 0) {
                    $('#sms_message_' + id).removeAttr('disabled');
                    $('#sms_btn_' + id).removeAttr('disabled');
                    $('#notes_' + id).removeAttr('disabled');
                } else {
                    $('#sms_message_' + id).attr('disabled', 'disabled');
                    $('#sms_btn_' + id).attr('disabled', 'disabled');
                    $('#notes_' + id).attr('disabled', 'disabled');
                }
                alert('تم التعديل بنجاح');
            }
        }, 'json');
    });
    $body.on('change', '.updateColData', function () {
        var tableName = $(this).attr("data-table-name");
        var colName = $(this).attr("data-col-name");
        var id = $(this).attr("data-id");
        var value = $(this).val();
        $.post(hosturl + '/controllers/operations_reports.php?ac=updateCol',
            {table: tableName, col: colName, id: id, value: value},
            function (data) {
                if (data.status === 'success') {
                    alert('تم التعديل بنجاح');
                }
            }, 'json');

    })
    $body.on('click', '.send_sms', function () {
        let id = $(this).data('id');
        $.post(host_url + '/controllers/operations_reports.php?ac=sendSms', {id: id}, function (response) {
            console.log(response);
            if (response.status === 'success') {
                alert('تم الإرسال بنجاح');
            }
        });
    });

});