(function ($) {
    "use strict";
    var dTable = null;
    var _id = null;
    var scheduleTempData = null;
    var currentEmpList = [];

    $(document).ready(function () {

        //load datatable
        Manager.GetDataList(0);
        Manager.LoadBranchDropDown();
        Manager.LoadServiceCategoryDropDown();
        Manager.LoadCustomerDropDown();
        Manager.LoadEmployeeDropDown();

        //generate datatabe serial no
        dTableManager.dTableSerialNumber(dTable);

        $("#conflictToggle").on("change", function () {
            Manager.GetDataList(1);
        });

        $("#btnFilter").on("click", function () {
            Manager.GetDataList(1);
        });

        $("#btnDownloadBookingInfo").on("click", function () {

            Manager.DownloadCSV();
        });

        $("#serviceId").on("keyup", function (e) {
            if (e.keyCode == 13) {
                Manager.GetDataList(1);
            }
        });

        $("#sch_service_category_id").on("change", function () {
            Manager.LoadServiceDropDown($(this).val());
            $("#sch_employee_id").html("").html("<option data-price='0' value=''>Select One</option>");
            $("#sch_employee_id").selectpicker('refresh');
        });

        $("#sch_service_id").on("change", function () {
            Manager.LoadStaffDropDown($(this).val());
        });

        //save change status
        JsManager.JqBootstrapValidation('#inputForm', (form, event) => {
            event.preventDefault();
            Manager.ChangeServiceStatus(form);

        });

        //show edit info modal
        $(document).on('click', '.dt-button-action', function () {
            Manager.ResetForm();
            var rowData = dTable.row($(this).parent()).data();
            scheduleTempData = rowData;
            _id = rowData.id;
            $('#id').val(rowData.id);
            $('#span-booking-no').text(rowData.id);
            $('#status').val(rowData.status);

            $("#frmModal").modal('show');
        });

        $(document).on("click", ".divTimeSlot", function () {
            $(".divTimeSlot").removeClass('border-red');
        });
    
        $(document).on("click", ".divTimeSlot", function () {
            $(this).find('input').prop('checked', true);
            $('.divTimeSlot').removeClass('divTimeSlotActive');
            $(this).addClass('divTimeSlotActive');
            Manager.SetServiceProperty($("#serviceDate").val(), $(this).find('.divStartTime').text());
        });

        // Toggle overflow style when modal is shown or hidden
        $('#modalViewScheduleDetails').on('show.bs.modal', function () {
            $('html').addClass('modal-open');
        });

        $('#modalViewScheduleDetails').on('hidden.bs.modal', function () {
            $('html').removeClass('modal-open');
        });

        $("#btn-schedule-edit").on("click", function() {
            JsManager.StartProcessBar();
            $("#modalViewScheduleDetails").modal('hide');
            var btnScheduleEdit = 1;
            $("#modalViewScheduleDetails").on('hidden.bs.modal', function () {
                if (btnScheduleEdit == 1) {
                    $("#frmAddScheduleModal").modal('show');
                    JsManager.EndProcessBar();
                    btnScheduleEdit = 0;
                }
            });

            var serviceDate = moment(scheduleTempData.date);
            $('#divServiceDate').datetimepicker('destroy');
            Manager.ServiceDatePicker(serviceDate);
            $("#serviceDate").val(serviceDate.format("YYYY-MM-DD"));

            $("#cmn_branch_id").val(scheduleTempData.cmn_branch_id);
            $("#sch_service_category_id").val(scheduleTempData.sch_service_category_id);
            $("#cmn_customer_id").val(scheduleTempData.cmn_customer_id).selectpicker('refresh');
            $("#cmn_payment_type_id").val(scheduleTempData.cmn_payment_type_id);
            $("#paid_amount").val(scheduleTempData.paid_amount);
            $("#bookingStatus").val(scheduleTempData.status);
            $("#remarks").val(scheduleTempData.remarks);
            Manager.LoadServiceDropDown($("#sch_service_category_id").val(), scheduleTempData.sch_service_id);
            Manager.LoadStaffDropDown($("#sch_service_id").val(), scheduleTempData.sch_employee_id);
            Manager.LoadServiceTimeSlot($("#sch_service_id").val(), $("#sch_employee_id").val());
            $.each($("#divServiceAvaiableTime > .divTimeSlot"), function (i, v) {
                if ($(v).attr('title') == scheduleTempData.start_time + "-" + scheduleTempData.end_time) {
                    $(v).addClass("divTimeSlotActive");
                    $(v).addClass("divTimeSlotActive");
                    $(v).find("input").attr("checked", "checked");
                }
            });
            $("#sch_service_id").selectpicker('refresh');
            $("#sch_employee_id").selectpicker('refresh');

        });


        // Update booking
        JsManager.JqBootstrapValidation('#inputFormBooking', (form, event) => {
            event.preventDefault();
            if (scheduleTempData != null) {
                Manager.UpdateBooking(form, scheduleTempData.id);
            }
        });


        // Delete booking
        $("#btn-schedule-delete").on("click", function () {
            if (scheduleTempData != null) {
                Manager.DeleteBooking(scheduleTempData.id);
                $("#modalViewScheduleDetails").modal('hide');
            }
        });

        // Cancel booking
        $("#btn-schedule-cancel").on("click", function () {
            if (scheduleTempData != null) {
                Manager.CancelBooking(scheduleTempData.id);
                $("#modalViewScheduleDetails").modal('hide');
            }
        });

        // Mark booking as done
        $("#btn-schedule-done").on("click", function () {
            if (scheduleTempData != null) {
                Manager.DoneBooking(scheduleTempData.id);
                $("#modalViewScheduleDetails").modal('hide');
            }
        });


        // View in Calendar
        $("#btn-view-calendar").on("click", function() {
            var branchId = scheduleTempData.cmn_branch_id;
            var date = scheduleTempData.date;
            var bookingId = scheduleTempData.id;

            // Construct URL to redirect to booking calendar
            var url = "/booking-calendar?branchId=" + encodeURIComponent(branchId) + "&date=" + encodeURIComponent(date) + "&bookingId=" + encodeURIComponent(bookingId);

            // Redirect to URL
            window.location.href = url;
        });

        // View details
        $("#btn-view-details").on("click", function () {
            JsManager.StartProcessBar();
            $("#frmModal").modal('hide');
            $("#modalViewScheduleDetails").modal('show');

            var jsonParam = { sch_service_booking_id: scheduleTempData.id };
            var serviceUrl = "get-booking-info-by-service-id";
            JsManager.SendJsonAsyncON('GET', serviceUrl, jsonParam, onSuccess, onFailed);
            function onSuccess(jsonData) {
                if (jsonData.status == 1) {
                    $("#modalViewScheduleDetails").modal('show');
                    var data = jsonData.data;
                    scheduleTempData = data;
                    $("#scheduleEmployeeImage").prop("src", JsManager.BaseUrl() + "/" + data.image_url);
                    $("#scheduleEmployee").text(data.employee);
                    $("#scheduleSpecialist").text(data.specialist);
                    $("#scheduleCustomer").text(data.customer);
                    $("#scheduleBranch").text(data.branch);
                    $("#scheduleCustomerPhone").text(data.phone_no);
                    $("#scheduleCustomerPhoneLink").attr('href', 'https://api.whatsapp.com/send/?phone=' + data.phone_no.replace(/^\++/, ''));
                    $("#scheduleCustomerEmail").text(data.email);
                    $("#scheduleServiceBookingDate").text(moment(data.created_at).format('YYYY-MM-DD'));
                    $("#scheduleServiceDate").text(moment(data.date).format('YYYY-MM-DD'));
                    $("#scheduleService").text(data.service);
                    $("#scheduleServiceTime").text(JsManager.MomentTime(data.start_time).format('HH:mm') + " | " + JsManager.MomentTime(data.end_time).format('HH:mm'));
                    $("#schedulePaidAmount").text(data.paid_amount);
                    $("#scheduleRemarks").text(data.remarks);
                    $("#scheduleSource").text(data.heard_from !== '' ? data.heard_from : '-');
                    $("#scheduleServiceStatus").text(Manager.ServiceStatus(data.status));
                }
                JsManager.EndProcessBar();
            }
            function onFailed(xhr, status, err) {
                JsManager.EndProcessBar();
                Message.Exception(xhr);
            }
        });
    });


    var Manager = {
        ResetForm: function () {
            $("#inputForm").trigger('reset');
        },
        ResetBookingForm: function () {
            $("#inputFormBooking").trigger('reset');
            var todayDate = moment(new Date(), 'YYYY-MM-DD');
            $('#divServiceDate').datetimepicker('destroy');
            Manager.ServiceDatePicker(todayDate);
            $("#divServiceAvaiableTime").empty();
            $("#sch_service_id").selectpicker('refresh');
            $("#sch_employee_id").selectpicker('refresh');
            $("#cmn_customer_id").selectpicker('refresh');
            $("#iSelectedServiceList").empty();
            $("#div-service-summary").addClass('d-none');
        },
        ServiceStatus: function (status) {
            var serviceStatus = ['Pending', 'Processing', 'Approved', 'Cancel', 'Done', 'Completed Appointment', 'Converted to Sales Only', 'Converted to Member Only', 'Converted to Sales Only', 'Converted to Member with Sales'];
            return serviceStatus[status];
        },
        ServiceFontColorClass: function (status) {
            var serviceColor = ['fc_pending', 'fc_processing', 'fc_approved', 'fc_cancel', 'fc_done'];
            return serviceColor[status];
        },
        ChangeServiceStatus: function (form) {
            if (Message.Prompt()) {
                JsManager.StartProcessBar();
                var jsonParam = form.serialize();
                var serviceUrl = "change-service-booking-status";
                JsManager.SendJson("POST", serviceUrl, jsonParam, onSuccess, onFailed);

                function onSuccess(jsonData) {
                    if (jsonData.status == "1") {
                        Message.Success("Successfully update service status to " + Manager.ServiceStatus($("#status").val()));
                        Manager.ResetForm();
                        $("#frmModal").modal('hide');
                        Manager.GetDataList(1); //reload datatable
                    } else {
                        Message.Error("Failed to update service status for " + Manager.ServiceStatus($("#status").val()));
                    }
                    JsManager.EndProcessBar();
                }
                function onFailed(xhr, status, err) {
                    JsManager.EndProcessBar();
                    Manager.ResetForm();
                    Message.Exception(xhr);
                }
            }
        },
        GetDataList: function (refresh) {
            JsManager.StartProcessBar();
            let conflictToggle = $("#conflictToggle").prop('checked');
            conflictToggle = conflictToggle ? 1 : null;
            var jsonParam = {
                dateFrom: $("#dateFrom").val(),
                dateTo: $("#dateTo").val(),
                employeeId: $("#employeeId").val(),
                customerId: $("#customerId").val(),
                serviceStatus: $("#serviceStatus").val(),
                bookingId: $("#serviceId").val(),
                customerSearch: $("#customerSearch").val(),
                conflictToggle: conflictToggle,
            };
            var serviceUrl = "get-service-booking-info";
            JsManager.SendJsonAsyncON('GET', serviceUrl, jsonParam, onSuccess, onFailed);

            function onSuccess(jsonData) {
                Manager.LoadDataTable(jsonData.data, refresh);

                JsManager.EndProcessBar();
            }

            function onFailed(xhr, status, err) {
                JsManager.EndProcessBar();
                Message.Exception(xhr);
            }
        },
        DownloadCSV: function () {
            JsManager.StartProcessBar();

            var jsonParam = {
                dateFrom: $("#dateFrom").val(),
                dateTo: $("#dateTo").val(),
                employeeId: $("#employeeId").val(),
                customerId: $("#customerId").val(),
                serviceStatus: $("#serviceStatus").val(),
                bookingId: $("#serviceId").val()
            };
            var serviceUrl = "get-service-booking-info";

            JsManager.SendJsonAsyncON('GET', serviceUrl, jsonParam, onSuccess, onFailed);

            function onSuccess(jsonData) {

                var data = jsonData.data;

                var startDate = new Date($("#dateFrom").val());
                var endDate = new Date($("#dateTo").val());

                var title = startDate.toLocaleDateString('en-GB', { day: 'numeric' }) + '_' +
                    startDate.toLocaleDateString('en-GB', { month: 'short' }) + '_to_' +
                    endDate.toLocaleDateString('en-GB', { day: 'numeric' }) + '_' +
                    endDate.toLocaleDateString('en-GB', { month: 'short' });

                var csv = 'No,Booking No,Date,Service,Customer Name,Phone No,Time,Due,Status,Branch,Staff/Employee, UTM source, UTM medium, UTM campaign, UTM content, Heard From\n';

                data.forEach(function (item, index) {
                    var date = moment(item.date).format('MMM DD YYYY');
                    var startTimeFormatted = moment(item.date + ' ' + item.start_time, 'YYYY-MM-DD HH:mm:ss').format('LT');
                    var endTimeFormatted = moment(item.date + ' ' + item.end_time, 'YYYY-MM-DD HH:mm:ss').format('LT');
                    var timeRange = startTimeFormatted + ' to ' + endTimeFormatted;
                    var formattedDue = parseFloat(item.due).toFixed(2);

                    var statusText = '';

                    switch (item.status) {
                        case 0:
                            statusText = 'Pending';
                            break;
                        case 3:
                            statusText = 'Cancel';
                            break;
                        case 2:
                            statusText = 'Approved';
                            break;
                        case 4:
                            statusText = 'Done';
                            break;
                        case 5:
                            statusText = 'Completed Appointment';
                            break;
                        case 6:
                            statusText = 'Converted to Sales Only';
                            break;
                        case 7:
                            statusText = 'Converted to Member Only';
                            break;
                        case 8:
                            statusText = 'Converted to Member with Sales';
                            break;
                        case 1:
                            statusText = 'Processing';
                            break;
                        default:
                            statusText = 'Unknown';
                    }
                    csv += (index + 1) + ',' + item.id + ',' + date + ',' + item.service + ',' + item.customer + ',' + item.customer_phone_no + ',' + timeRange + ',' + formattedDue + ',' + statusText + ',' + item.branch + ',' + item.employee + ',' + item.utm_source + ',' + item.utm_medium + ',' + item.utm_campaign + ',' + item.utm_content + ',' + item.heard_from +'\n';
                });

                // Create a Blob object from the CSV data
                var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });

                // Create a temporary URL for the Blob
                var url = URL.createObjectURL(blob);

                // Create a link element to trigger the download
                var link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', title + '_booking_info.csv');
                document.body.appendChild(link);

                // Click the link to initiate the download
                link.click();

                // Remove the link from the document
                document.body.removeChild(link);

                JsManager.EndProcessBar();
            }

            function onFailed(xhr, status, err) {
                JsManager.EndProcessBar();
                Message.Exception(xhr);
            }
        },
        LoadDataTable: function (data, refresh) {
            if (refresh == "0") {
                dTable = $('#tableElement').DataTable({
                    dom: "<'row'<'col-md-12'tr>>" + "<'row'<'col-md-4'i><'col-md-3 mt-2'l><'col-md-5 mt-7'p>>",
                    initComplete: function () {
                        dTableManager.Border(this, 450);
                    },
                    buttons: [],

                    scrollY: "450px",
                    scrollX: true,
                    scrollCollapse: true,
                    lengthMenu: [[50, 100, 500, -1], [50, 100, 500, "All"]],
                    columnDefs: [
                        { visible: false, targets: [] },
                        { "className": "dt-center", "targets": [3] }
                    ],
                    columns: [
                        {
                            data: null,
                            name: '',
                            'orderable': false,
                            'searchable': false,
                            title: '#SL',
                            width: 8,
                            render: function () {
                                return '';
                            }
                        },
                        {
                            data: 'id',
                            name: 'id',
                            title: 'No#'
                        },
                        {
                            data: 'date',
                            name: 'date',
                            title: 'Date',
                            render: function (data, type, row) {
                                return moment(data).format('MMM DD, YYYY');
                            }
                        },
                        {
                            data: 'service',
                            name: 'service',
                            title: 'Service Info',
                            render: function (data, type, row) {
                                return '<div class="flex-1 ml-3 pt-1">' +
                                    '<h6 class="text-uppercase fw-bold mb-1">' +
                                    row['service'] +
                                    '<span class="' + Manager.ServiceFontColorClass(row['status']) + ' pl-3">' + Manager.ServiceStatus(row['status']) + '</span>' +
                                    '</h6>' +
                                    '<span class="text-muted">' +
                                    row['customer'] + " | " + row['customer_phone_no'] + " | <span class='text-primary'>" + moment(row['date'] + ' ' + row['start_time']).format('LT') + " to " + moment(row['date'] + ' ' + row['end_time']).format('LT') + "</span><br/>" +
                                    "Due# <span class='text-danger'>" + parseFloat(row['due']).toFixed(2) + "</span> | " + (row['remarks'] == null ? "No remarks found!" : row['remarks'])
                                    + '</span>' +
                                    '</div>';
                            }
                        },
                        {
                            data: 'branch',
                            name: 'branch',
                            title: 'Branch'
                        },
                        {
                            data: 'employee',
                            name: 'employee',
                            title: 'Staff/Employee',
                            render: function (data, type, row) {
                                return row['employee'] + (row['is_conflict'] == 1 ? ' (ON LEAVE)<br/><i class="fas fa-exclamation-triangle" style="color:#FF4500;"></i>APPOINTMENT CONFLICT' : '');
                            }
                        },
                        {
                            data: 'utm_source',
                            name: 'utm_source',
                            title: 'UTM source'
                        },
                        {
                            data: 'utm_medium',
                            name: 'utm_medium',
                            title: 'UTM medium'
                        },
                        {
                            data: 'utm_campaign',
                            name: 'utm_campaign',
                            title: 'UTM campaign'
                        },
                        {
                            data: 'utm_content',
                            name: 'utm_content',
                            title: 'UTM content'
                        },
                        {
                            name: 'Option',
                            title: 'Option',
                            width: 70,
                            render: function (data, type, row) {
                                return '<button class="btn btn-sm btn-primary dt-button-action"><i class="fas fa-location-arrow"></i> Action</button>';
                            }
                        },
                    ],
                    fixedColumns: false,
                    data: data,
                    createdRow: function (row, data, dataIndex) {
                        if (data['is_conflict'] == '1') {
                            $(row).addClass('conflict-row');
                        }
                    }
                });
            } else {
                dTable.clear().rows.add(data).draw();
            }
        },
        LoadEmployeeDropDown: function () {
            var jsonParam = { branchId: 0 };
            var serviceUrl = "get-employee-dropdown";
            JsManager.SendJson('GET', serviceUrl, jsonParam, onSuccess, onFailed);

            function onSuccess(jsonData) {
                if (jsonData.data.length < 2) {
                    JsManager.PopulateComboSelectPicker("#employeeId", jsonData.data);
                } else {
                    JsManager.PopulateComboSelectPicker("#employeeId", jsonData.data, 'All Employee');
                }
                $("#employeeId").selectpicker('refresh');
            }

            function onFailed(xhr, status, err) {
                Message.Exception(xhr);
            }
        },
        LoadCustomerDropDown: function (nowInsertedCustomerId) {
            var jsonParam = '';
            var serviceUrl = "get-customer-dropdown";
            JsManager.SendJson('GET', serviceUrl, jsonParam, onSuccess, onFailed);

            function onSuccess(jsonData) {
                JsManager.PopulateComboSelectPicker("#cmn_customer_id", jsonData.data, "Select One");
                $("#cmn_customer_id").selectpicker('refresh');

                JsManager.PopulateComboSelectPicker("#customerId", jsonData.data, 'All Customer');
                $("#customerId").selectpicker('refresh');
            }
            function onFailed(xhr, status, err) {
                Message.Exception(xhr);
            }
        },
        ServiceDatePicker: function (startDate) {
            $('#divServiceDate').datetimepicker({
                format: 'Y-m-d',
                inline: true,
                timepicker: false,
                //minDate: new Date(),
                startDate: startDate._d,
                onChangeDateTime: function (dp, $input) {
                    $("#serviceDate").val($input.val());
                    Manager.SetServiceProperty($input.val());
                    Manager.LoadServiceTimeSlot($("#sch_service_id").val(), $("#sch_employee_id").val())
                }
            });
            Manager.SetServiceProperty(startDate);
        },
        SetServiceProperty: function (startDate, time) {
            let longDate = moment(startDate).format('dddd, MMMM, DD, yyyy');
            $("#serviceDate").val(JsManager.DateFormatDefault(startDate));
            $("#divDaysName").text(longDate);
            if (time) {
                $("#iSelectedServiceText").text("You've Selected " + time + " On " + longDate);
            } else {
                $("#iSelectedServiceText").text("You've Selected " + longDate);
            }
        },
        LoadServiceTimeSlot: function (serviceId, employeeId) {

            if (employeeId > 0 && serviceId > 0 && $("#serviceDate").val() && $("#cmn_branch_id").val() > 0) {
                JsManager.StartProcessBar();
                var jsonParam = {
                    sch_service_id: serviceId,
                    sch_employee_id: employeeId,
                    date: $("#serviceDate").val(),
                    cmn_branch_id: $("#cmn_branch_id").val()
                };
                var serviceUrl = "get-site-service-time-slot-mog";
                JsManager.SendJsonAsyncON('GET', serviceUrl, jsonParam, onSuccess, onFailed);
                function onSuccess(jsonData) {
                    if (jsonData.status == 1) {
                        $("#divServiceAvaiableTime").empty();
                        $.each(jsonData.data, function (i, v) {
                            let disabledClass = "";
                            let disabledServiceText = "";
                            if (v.is_avaiable == 0) {
                                disabledClass = "disabled-service";
                                disabledServiceText = "disabled-service-text";
                            }
                            let serviceTime = v.start_time + '-' + v.end_time;
                            $("#divServiceAvaiableTime").append(
                                '<div class="divTimeSlot ' + disabledClass + '" title="' + serviceTime + '">' +
                                '<div class="float-left w100">' +
                                '<div class="float-left">' +
                                '<input type="radio" class="serviceTime d-none" name="service_time" value="' + serviceTime + '"/>' +
                                '</div>' +
                                '<div class="float-left cp divStartTime text-center w100 ' + disabledServiceText + '">' + moment('1990-01-01 ' + v.start_time).format('hh:mm A') + '</div>' +
                                '</div>' +
                                '</div>');
                        });
                    }
                    JsManager.EndProcessBar();
                }
                function onFailed(xhr, status, err) {
                    $("#divServiceAvaiableTime").empty();
                    if (xhr.responseJSON.status == 5) {
                        $("#divServiceAvaiableTime").append('<div class="mt-3">' + xhr.responseJSON.data + '</div>');
                    } else if (xhr.responseJSON.status == 2) {
                        //service is not available today
                    } else {
                        Message.Exception(xhr);
                    }
                    JsManager.EndProcessBar();
                }
            } else {
                $("#divServiceAvaiableTime").empty();
            }
        },
        LoadBranchDropDown: function () {
            var jsonParam = '';
            var serviceUrl = "get-branch-dropdown";
            JsManager.SendJson('GET', serviceUrl, jsonParam, onSuccess, onFailed);

            function onSuccess(jsonData) {
                JsManager.PopulateCombo("#cmn_branch_id", jsonData.data);
            }
            function onFailed(xhr, status, err) {
                Message.Exception(xhr);
            }
        },
        LoadServiceCategoryDropDown: function () {
            var jsonParam = '';
            var serviceUrl = "get-site-service-category";
            JsManager.SendJson('GET', serviceUrl, jsonParam, onSuccess, onFailed);

            function onSuccess(jsonData) {
                JsManager.PopulateCombo("#sch_service_category_id", jsonData.data, "Select One", '');
            }
            function onFailed(xhr, status, err) {
                Message.Exception(xhr);
            }
        },
        LoadServiceDropDown: function (categoryId, selectedServiceId) {
            var jsonParam = { sch_service_category_id: categoryId };
            var serviceUrl = "get-service-by-category-dropdown";
            JsManager.SendJsonAsyncON('GET', serviceUrl, jsonParam, onSuccess, onFailed);
            function onSuccess(jsonData) {
                var cbmOptions = "<option data-price='0' value=''>Select One</option>";
                $.each(jsonData.data, function () {
                    cbmOptions += '<option ' + (selectedServiceId == this.id ? "selected" : "") + ' data-price="' + this.fees + '" value=\"' + this.id + '\">' + this.name + '</option>';
                });
                $("#sch_service_id").html(cbmOptions);
                $("#sch_service_id").selectpicker('refresh');
            }
            function onFailed(xhr, status, err) {
                Message.Exception(xhr);
            }
        },
        LoadStaffDropDown: function (serviceId, selectedEmployeeId) {
            var jsonParam = { sch_service_id: serviceId, cmn_branch_id: $("#cmn_branch_id").val(), date: $("#serviceDate").val(), include_off_day: 0 };
            var serviceUrl = "get-employee-by-service-mog";
            JsManager.SendJsonAsyncON('GET', serviceUrl, jsonParam, onSuccess, onFailed);
            function onSuccess(jsonData) {
                currentEmpList = jsonData.data;
                var cbmOptions = "<option data-price='0' value=''>Select One</option>";
                $.each(jsonData.data, function () {
                    cbmOptions += '<option ' + (selectedEmployeeId == this.id ? "selected" : "") + ' data-price="' + this.fees + '" value=\"' + this.id + '\">' + this.name + '</option>';
                });
                $("#sch_employee_id").html(cbmOptions);
                $("#sch_employee_id").selectpicker('refresh');
            }
            function onFailed(xhr, status, err) {
                Message.Exception(xhr);
            }
        },
        UpdateBooking: function (form, id, isForceBooking) {
            if (isForceBooking == 1 || Message.Prompt()) {
                JsManager.StartProcessBar();
                const preferences = {
					email: $("#email_notify_update").is(':checked') ? 1 : 0,
					whatsapp: $("#whatsapp_notify_update").is(':checked') ? 1 : 0
				};
				var serializedForm = form.serialize();
				var preferencesQuery = $.param({ preferences });
				var jsonParam = `${serializedForm}&id=${id}&isForceBooking=${isForceBooking}&${preferencesQuery}`;
                var serviceUrl = "update-service-booking";
                JsManager.SendJson("POST", serviceUrl, jsonParam, onSuccess, onFailed);

                function onSuccess(jsonData) {
                    if (jsonData.status == "1") {
                        Message.Success("update");
                        // if (scheduleClickedTempData != null) {
                        //     scheduleTable.deleteSchedule(scheduleTable, scheduleClickedTempData.item, scheduleClickedTempData.data);
                        //     scheduleClickedTempData = null;
                        // }
                        Manager.GetDataList(1);
                        Manager.ResetBookingForm();
                        $("#frmAddScheduleModal").modal('hide');
                    } else if (jsonData.status == "-1") {
                        if (Message.Prompt(jsonData.data)) {
                            Manager.UpdateBooking(form, id, 1);
                        }
                    } else {
                        Message.Error("update");
                    }
                    JsManager.EndProcessBar();
                }

                function onFailed(xhr, status, err) {
                    JsManager.EndProcessBar();
                    Message.Exception(xhr);
                }
            }
        },
        DeleteBooking: function (id) {
            if (Message.Prompt()) {
                JsManager.StartProcessBar();
                var jsonParam = { id: id };
                var serviceUrl = "delete-service-booking";
                JsManager.SendJson("POST", serviceUrl, jsonParam, onSuccess, onFailed);

                function onSuccess(jsonData) {
                    if (jsonData.status == "1") {
                        Message.Success("delete");
                        Manager.GetDataList(1);
                    } else {
                        Message.Error("delete");
                    }
                    JsManager.EndProcessBar();
                }

                function onFailed(xhr, status, err) {
                    JsManager.EndProcessBar();
                    Message.Exception(xhr);
                }
            }
        },
        DoneBooking: function (id) {
            if (Message.Prompt()) {
                JsManager.StartProcessBar();
                const preferences = {
					email: $("#view_email_notify").is(':checked') ? 1 : 0,
					whatsapp: $("#view_whatsapp_notify").is(':checked') ? 1 : 0
				};
                var jsonParam = { id: id, preferences: preferences };
                var serviceUrl = "done-service-booking";
                JsManager.SendJson("POST", serviceUrl, jsonParam, onSuccess, onFailed);

                function onSuccess(jsonData) {
                    if (jsonData.status == "1") {
                        Message.Success("Service Successfully Done.");
                        Manager.GetDataList(1);
                    } else {
                        Message.Error("Failed to Save");
                    }
                    JsManager.EndProcessBar();
                }

                function onFailed(xhr, status, err) {
                    JsManager.EndProcessBar();
                    Message.Exception(xhr);
                }
            }
        },
        CancelBooking: function (id) {
            if (Message.Prompt()) {
                JsManager.StartProcessBar();
                const preferences = {
					email: $("#view_email_notify").is(':checked') ? 1 : 0,
					whatsapp: $("#view_whatsapp_notify").is(':checked') ? 1 : 0
				};
                var jsonParam = { id: id, preferences: preferences };
                var serviceUrl = "cancel-service-booking";
                JsManager.SendJson("POST", serviceUrl, jsonParam, onSuccess, onFailed);

                function onSuccess(jsonData) {
                    if (jsonData.status == "1") {
                        Message.Success("cancel");
                        Manager.GetDataList(1);
                    } else {
                        Message.Error("cancel");
                    }
                    JsManager.EndProcessBar();
                }

                function onFailed(xhr, status, err) {
                    JsManager.EndProcessBar();
                    Message.Exception(xhr);
                }
            }
        },
    };
})(jQuery);