
//Location And Capacity
function openCreateLocationDialog(src,obj) {
    
    var oFieldLoc0 = new sap.m.Input({  });
    var oFieldLoc1 = new sap.m.Input({ enabled:false });
    var oFieldLoc2 = new sap.m.Input({ enabled:false });
    var oFieldLoc3 = new sap.m.Input({ enabled:false });
    var oFieldLoc4 = new sap.m.Input({ enabled:false });
    var oFieldLoc5 = new sap.m.Input({ enabled:false });
    var oFieldLoc6 = new sap.m.ComboBox({
        selectedKey:'0',
        items:[    
            new sap.ui.core.ListItem({key:1,text:oBundle.getText("Yes")}),
            new sap.ui.core.ListItem({key:0,text:oBundle.getText("No")}),
        ],
        change: function (oEvent) {
            let enteredValue = oEvent.getParameter("value");
            let isValid = oFieldLoc6.getItems().some(item => item.getText() === enteredValue);             

            if (!isValid) {
                sap.m.MessageBox.error(oBundle.getText("Please_select_a_valid_value_from_the_list"));
                oFieldLoc6.setSelectedKey(0);
            }
        }
    }).addEventDelegate({onAfterRendering: function(e) {oFieldLoc6.$().find("input").attr("readonly", true);}});
     
    var oFieldLoc7 = new sap.m.Select({
        items: [
            new sap.ui.core.Item({ key: "Active", text: "Active" }),
            new sap.ui.core.Item({ key: "Inactive", text: "Inactive" })
        ]
    });

    function handleLiveChange(oEvent) {
        let value = oEvent.getParameter("value");
        let roundedValue = Math.round(value); // Rounds to nearest integer
        oEvent.getSource().setValue(roundedValue); // Sets the rounded value to the input field
    }
    
    var oFieldLoc8 = new sap.m.Input({ type: "Number", liveChange: handleLiveChange });
    var oFieldLoc9 = new sap.m.Input({ type: "Number", liveChange: handleLiveChange });
    var oFieldLoc10 = new sap.m.Input({ type: "Number", liveChange: handleLiveChange });
    var oFieldLoc11 = new sap.m.Input({ type: "Number", liveChange: handleLiveChange });
    var oFieldLoc12 = new sap.m.Input({ type: "Number",liveChange: handleLiveChange });
    var oFieldLoc13 = new sap.m.Input({ type: "Number",liveChange: handleLiveChange });
    var oFieldLoc14 = new sap.m.Input({ type: "Number",liveChange: handleLiveChange });
    var oFieldLoc15 = new sap.m.Input({ type: "Number",liveChange: handleLiveChange });
    var oFieldLoc16 = new sap.m.Input({ type: "Number",liveChange: handleLiveChange });
    var oFieldLoc17 = new sap.m.Input({ type: "Number",liveChange: handleLiveChange });
    var oFieldLoc18 = new sap.m.Input({ type: "Number", liveChange: handleLiveChange });


    const oFormCreateLocation = new sap.ui.layout.form.Form({
        editable: true,
        layout: new sap.ui.layout.form.ResponsiveGridLayout({
            labelSpanL: 4,
            labelSpanM: 4,
            columnsL: 2,
            columnsM: 2
        }),
        formContainers: [
            
            new sap.ui.layout.form.FormContainer({
                title: oBundle.getText("Location_Information"),
                formElements: [
                    new sap.ui.layout.form.FormElement({ label: "Location ID", fields: [oFieldLoc1] }),
                    new sap.ui.layout.form.FormElement({ label: "Location Name", fields: [oFieldLoc2] }),
                    new sap.ui.layout.form.FormElement({ label: "Type", fields: [oFieldLoc3] }),
                    new sap.ui.layout.form.FormElement({ label: "City ID", fields: [oFieldLoc4] }),
                    new sap.ui.layout.form.FormElement({ label: "City Name", fields: [oFieldLoc5] }),
                    new sap.ui.layout.form.FormElement({ label: "Checkpoint", fields: [oFieldLoc6] }),
                    new sap.ui.layout.form.FormElement({ label: "Status", fields: [oFieldLoc7] }),
                    new sap.ui.layout.form.FormElement({ label: "Notes", fields: [oFieldLoc0] })
                ]
            }),
            
            
            new sap.ui.layout.form.FormContainer({
                title: oBundle.getText("Slots_Capacity"),
                formElements: [
                    new sap.ui.layout.form.FormElement({ label: "Slot 8:00 - 9:00", fields: [oFieldLoc8] }),
                    new sap.ui.layout.form.FormElement({ label: "Slot 9:01 - 10:00", fields: [oFieldLoc9] }),
                    new sap.ui.layout.form.FormElement({ label: "Slot 10:01 - 11:00", fields: [oFieldLoc10] }),
                    new sap.ui.layout.form.FormElement({ label: "Slot 11:01 - 12:00", fields: [oFieldLoc11] }),
                    // new sap.ui.layout.form.FormElement({ label: "Slot 12 - 13", fields: [oFieldLoc12] }),
                    new sap.ui.layout.form.FormElement({ label: "Slot 13:01 - 14:00", fields: [oFieldLoc13] }),
                    new sap.ui.layout.form.FormElement({ label: "Slot 14:01 - 15:00", fields: [oFieldLoc14] }),
                    new sap.ui.layout.form.FormElement({ label: "Slot 15:01 - 16:00", fields: [oFieldLoc15] }),
                    new sap.ui.layout.form.FormElement({ label: "Slot 16:01 - 17:00", fields: [oFieldLoc16] }),
                    new sap.ui.layout.form.FormElement({ label: "Slot 17:01 - 18:00", fields: [oFieldLoc17] }),
                    new sap.ui.layout.form.FormElement({ label: "Total Capacity", fields: [oFieldLoc18] }),
                ]
            })
        ]
    });
    

    var updateBtn = new sap.m.Button({
        text: oBundle.getText("Update"),
        type: "Emphasized",
        press: function () {
            var location_id = oFieldLoc1.getValue();
            var location_name = oFieldLoc2.getValue();
            var location_type = oFieldLoc3.getValue();
            var city_id = oFieldLoc4.getValue();
            var city_name = oFieldLoc5.getValue();
            var checkpoint = oFieldLoc6.getSelectedKey(); // Assuming ComboBox, use getSelectedKey
            
            var status = oFieldLoc7.getSelectedKey();     // Assuming Select, use getSelectedKey
            var notes = oFieldLoc0.getValue();     // Assuming the Notes field is a simple Input

            var slot_8_9 = parseInt(oFieldLoc8.getValue()) || 0;
            var slot_9_10 = parseInt(oFieldLoc9.getValue()) || 0;
            var slot_10_11 = parseInt(oFieldLoc10.getValue()) || 0;
            var slot_11_12 = parseInt(oFieldLoc11.getValue()) || 0;
            var slot_12_13 = 0;
            var slot_13_14 = parseInt(oFieldLoc13.getValue()) || 0;
            var slot_14_15 = parseInt(oFieldLoc14.getValue()) || 0;
            var slot_15_16 = parseInt(oFieldLoc15.getValue()) || 0;
            var slot_16_17 = parseInt(oFieldLoc16.getValue()) || 0;
            var slot_17_18 = parseInt(oFieldLoc17.getValue()) || 0;
            var total_capacity = parseInt(oFieldLoc18.getValue()) || 0;

            // Calculate total of all slot values
            var total_slot_value = slot_8_9 + slot_9_10 + slot_10_11 + slot_11_12 + slot_12_13 +
                                slot_13_14 + slot_14_15 + slot_15_16 + slot_16_17 + slot_17_18;

            // Check if the total slot value exceeds the total capacity
            if (total_slot_value > total_capacity) {
                sap.m.MessageBox.error(oBundle.getText("Total_slot_value_should_not_exceed_total_capacity"));
                return;
            }
            var updated_date = getIndonesianTime();
            var updateItems = {
                row_id: obj['id'], capacity: total_capacity,
                status: status, notes: notes, checkpoint: Boolean(parseInt(checkpoint)),
                slot8_9: slot_8_9, slot9_10: slot_9_10, slot10_11: slot_10_11,
                slot11_12: slot_11_12, slot12_13: slot_12_13, slot13_14: slot_13_14,
                slot14_15: slot_14_15, slot15_16: slot_15_16, slot16_17: slot_16_17,
                slot17_18: slot_17_18, updated_by: operatedID, updated_date: updated_date
            };
            
            // console.log(updateItems)
            updateLocationData(updateItems,oCreateDialog);
           
            
        }
    });

    // Create the dialog
    const oCreateDialog = new sap.m.Dialog({
        title: oBundle.getText("Update_Location"),
        contentWidth: "70%",
        contentHeight: "70%",
        resizable: true,
        draggable: true,
        content: [oFormCreateLocation],
        buttons: [
            updateBtn,
            new sap.m.Button({
                text: oBundle.getText("Cancel"),
                press: function () {
                    oCreateDialog.close();
                }
            })
        ],
        afterClose: function () {
            oCreateDialog.destroy();
        }
    }).open();


    if(src == "1"){
        oFieldLoc0.setValue(obj['notes']);
        oFieldLoc1.setValue(obj['location_id']);
        oFieldLoc2.setValue(obj['location_name']);
        oFieldLoc3.setValue(obj['type']);
        oFieldLoc4.setValue(obj['city_id']);
        oFieldLoc5.setValue(obj['city_name']);
        oFieldLoc6.setSelectedKey(obj['checkpoint'] == "True" ? 1 : 0); // Assuming 'Yes'/'No' text
        oFieldLoc7.setSelectedKey(obj['status']);
        oFieldLoc8.setValue(obj['slot8_9']);
        oFieldLoc9.setValue(obj['slot9_10']);
        oFieldLoc10.setValue(obj['slot10_11']);
        oFieldLoc11.setValue(obj['slot11_12']);
        oFieldLoc12.setValue(0);
        oFieldLoc13.setValue(obj['slot13_14']);
        oFieldLoc14.setValue(obj['slot14_15']);
        oFieldLoc15.setValue(obj['slot15_16']);
        oFieldLoc16.setValue(obj['slot16_17']);
        oFieldLoc17.setValue(obj['slot17_18']);
        oFieldLoc18.setValue(obj['capacity']);

    }
};
function displayMenu4WLocation(event,obj){
    var oMenu = new sap.m.Menu({
        items: [
            new sap.m.MenuItem({icon: "sap-icon://edit",text: oBundle.getText("Update"),key: "0"}),
        ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "0"){
                openCreateLocationDialog(1,obj);//Update Slot Capacity
            }
        }
    });
    
   
    oMenu.openBy(event.getSource());
};

var holidayCalenderFilterByLocation = new sap.m.Select({
    // placeholder: "Select Location",
    items: [
        new sap.ui.core.Item({ key: "Select Location", text: "Select Location" }) // Empty default option
    ],
    change: function () {
        if(holidayCalenderFilterByLocation.getSelectedKey() != 'Select Location'){
            getHolidayDataByLocation(holidayCalenderFilterByLocation.getSelectedKey());
        };
    }
});
//Location
var oTable4WLocation = new sap.m.Table({
    growing: true,
    noDataText:oBundle.getText("No_Data"),
    growingTriggerText:oBundle.getText("More"),
    sticky:[sap.m.Sticky.ColumnHeaders,sap.m.Sticky.HeaderToolbar,sap.m.Sticky.InfoToolbar],
    growingThreshold: 25,
    growingScrollToLoad : false,
    columns: [
            new sap.m.Column({width:"100px",header: new sap.m.Label({text: oBundle.getText("Action"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Location_Detail"),design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Type"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true,  text: oBundle.getText("City_Detail"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Capacity"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Checkpoint"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Note"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
    ],
    headerToolbar:new sap.m.OverflowToolbar({
        content: [   
            // new sap.m.Button({ 
            //     id:"createHolidayBtnID",
            //     text: oBundle.getText(""), 
            //     type:sap.m.ButtonType.Emphasized,
            //     icon: sap.ui.core.IconPool.getIconURI("add"), 
            //     press: function(){ addUpdate4WHolidayCal(1); } 
            // }),
            new sap.m.ToolbarSpacer(),
            new sap.m.SearchField({
                placeholder: oBundle.getText("Search"),
                width: "300px",
                liveChange: function (event) {
                    var oBinding = oTable4WLocation.getBinding("items");
                    var searchStr = this.getValue();
                    if (oBinding) {
                        var oFilters = [
                            new sap.ui.model.Filter("location_id", sap.ui.model.FilterOperator.Contains, searchStr),
                            new sap.ui.model.Filter("location_name", sap.ui.model.FilterOperator.Contains, searchStr),
                            new sap.ui.model.Filter("type", sap.ui.model.FilterOperator.Contains, searchStr),
                            new sap.ui.model.Filter("city_id", sap.ui.model.FilterOperator.Contains, searchStr),
                            new sap.ui.model.Filter("city_name", sap.ui.model.FilterOperator.Contains, searchStr),
                            new sap.ui.model.Filter("notes", sap.ui.model.FilterOperator.Contains, searchStr),
                            new sap.ui.model.Filter("capacity", sap.ui.model.FilterOperator.Contains, searchStr),
                        ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
            }),
            new sap.m.Button({
                icon: "sap-icon://filter",
                type: "Transparent",
                press: function() {
                    clearLocationFilters();
                    populateLocationFilterDropdowns();
                    LocationFilterDialog.open();
                }
            })
        ]
    })
});
var location4WTemplate = new sap.m.ColumnListItem({
    cells: [
        new sap.m.Button({
            type: "Emphasized",
            icon: "sap-icon://action",
            text: oBundle.getText("Action"),
            press: function (event) {
                var model = this.getModel();
                var path = event.getSource().getBindingContext().getPath();
                var obj = model.getProperty(path);
                displayMenu4WLocation(event,obj);
            
            }
        }),
        new sap.m.VBox({
            items:[new sap.m.Label({ wrapping: true, text: "{location_id}" }),
                    new sap.m.Label({ wrapping: true, text: "{location_name}" }).addStyleClass("sapUiTinyMarginTop"),
            ]
        }).addStyleClass("sapUiTinyMargin"),
        new sap.m.Label({wrapping:true,text: "{type}"}),
        new sap.m.VBox({
            items:[new sap.m.Label({ wrapping: true, text: "{city_id}" }),
                    new sap.m.Label({ wrapping: true, text: "{city_name}" }).addStyleClass("sapUiTinyMarginTop"),
            ]
        }).addStyleClass("sapUiTinyMargin"),
        new sap.m.Label({wrapping:true,text: "{capacity}"}),
        // new sap.m.Label({
        //     wrapping: true,
        //     text: {
        //       path: "checkpoint",
        //       formatter: function (value) {
        //         if(value == 'True' || value == 'true'){
        //             return "Yes";
        //         }else{
        //             return "No";
        //         }
        //       }
        //     }
        //   }),       

        new sap.tnt.InfoLabel({
            text: {
                path: "checkpoint",
                formatter: function (value) {
                    return (value === 'True' || value === "true") ? "Yes" : "No";
                }
            },
            colorScheme: {
                path: "checkpoint",
                formatter: function (value) {
                    if (value === 'True' || value === "true") {
                        return 8; // Orange = Critical
                    } else {
                        return 1; // Gray = None / Neutral
                    }
                }
            }
        }),        
        new sap.m.ObjectStatus({
            text: "{status}",
            state: {
                path: "status",
                formatter: function (value) {
                    if (value == "Active") {
                        return "Success"; // green
                    } else if (value == "Inactive") {
                        return "Error"; // red
                    } else {
                        return "None";
                    }
                }
            }
        }),
        new sap.m.Label({wrapping:true,text: "{notes}"})
    ]
});




var LocationFilterDialog = new sap.m.Dialog({
    title: "Multi Filter Location",
    contentWidth: "40%",
    content: [
        new sap.m.VBox({
            width: "100%",
            items: [
                new sap.m.Label({ text: "Location:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Location"
                }),
                
                new sap.m.Label({ text: "City:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select City"
                }),
                
                new sap.m.Label({ text: "Checkpoint:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Checkpoint"
                }),
                
                new sap.m.Label({ text: "Status:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Status"
                }),
                new sap.m.Label({ text: "Type:", design: "Bold", required: false }),
                new sap.m.ComboBox({ 
                    width: "94%",
                    placeholder: "Select Type"
                }),
            ]
        }).addStyleClass("sapUiSmallMargin")
    ],
    buttons: [
        new sap.m.Button({
            icon: "sap-icon://clear-filter",
            text: "Clear Filter",
            press: function() {
                clearLocationFilters();
            }
        }),
        new sap.m.Button({
            icon: "sap-icon://decline",
            text: "Cancel",
            press: function() {
                LocationFilterDialog.close();
            }
        }),
        new sap.m.Button({
            icon: "sap-icon://filter",
            text: "Apply Filter",
            type: "Emphasized",
            press: function() {
                var aFilters = [];
                
                // Get ComboBoxes (only first two fields now)
                var aComboBoxes = LocationFilterDialog.getContent()[0].getItems().filter(function(item) {
                    return item instanceof sap.m.ComboBox;
                });
                
                // Add filters for ComboBox fields (Workshop Group and License Number)
                var comboBoxFields = ["location_name", "city_name","checkpoint","status","type"];
                aComboBoxes.forEach(function(oComboBox, index) {
                    var sValue = oComboBox.getSelectedKey();
                    if (sValue) {
                        aFilters.push(new sap.ui.model.Filter(
                            comboBoxFields[index],
                            sap.ui.model.FilterOperator.EQ,
                            sValue
                        ));
                    }
                });
            
                
                var oBinding = oTable4WLocation.getBinding("items");
                if (oBinding) {
                    if (aFilters.length > 0) {
                        var oCombinedFilter = new sap.ui.model.Filter({
                            filters: aFilters,
                            and: true
                        });
                        oBinding.filter(oCombinedFilter);
                    } else {
                        oBinding.filter([]);
                    }
                }
                
                LocationFilterDialog.close();
            }
        })
    ]
}).addStyleClass("sapUiSizeCompact");


function clearLocationFilters() {
    var aComboBoxes = LocationFilterDialog.getContent()[0].getItems().filter(function(item) {
        return item instanceof sap.m.ComboBox;
    });
    
    // Clear ComboBoxes
    aComboBoxes.forEach(function(oComboBox) {
        oComboBox.setSelectedKey("");
    });
    
    
    // Clear table filters
    var oBinding = oTable4WLocation.getBinding("items");
    if (oBinding) {
        oBinding.filter([]);
    }
}
    
function populateLocationFilterDropdowns() {
    try {
        var oModel = oTable4WLocation.getModel();
        if (!oModel) return;
        
        var aData = oModel.getProperty("/modelData");
        if (!aData) return;

        // Get unique workshop groups
        var uniqueLocationGroups = [...new Set(aData
            .map(item => item.location_name)
            .filter(item => item && item.trim() !== "")
        )].sort();
        var uniqueCityGroups = [...new Set(aData
            .map(item => item.city_name)
            .filter(item => item && item.trim() !== "")
        )].sort();
        var uniqueCheckpointGroups = [...new Set(aData
            .map(item => item.checkpoint)
            .filter(item => item && item.trim() !== "")
        )].sort();
        var uniqueStatusGroups = [...new Set(aData
            .map(item => item.status)
            .filter(item => item && item.trim() !== "")
        )].sort();
        var uniqueTypeGroups = [...new Set(aData
            .map(item => item.type)
            .filter(item => item && item.trim() !== "")
        )].sort();
        

    var comboBoxes = LocationFilterDialog.getContent()[0].getItems()
    .filter(item => item instanceof sap.m.ComboBox);
    
    var oMakeGroupComboBox = comboBoxes[0];
    var oModelComboBox = comboBoxes[1];
    var oTransmissionComboBox = comboBoxes[2];
    var oCityNameComboBox = comboBoxes[3];
    var oStatusComboBox = comboBoxes[4];

    // Clear existing items
    oMakeGroupComboBox.removeAllItems();
    oModelComboBox.removeAllItems();
    oTransmissionComboBox.removeAllItems();
    oCityNameComboBox.removeAllItems();
    oStatusComboBox.removeAllItems();

    // Add items to Make Group ComboBox
    uniqueLocationGroups.forEach(function(group) {
        oMakeGroupComboBox.addItem(new sap.ui.core.Item({
            key: group,
            text: group
        }));
    });
    uniqueCityGroups.forEach(function(group) {
        oModelComboBox.addItem(new sap.ui.core.Item({
            key: group,
            text: group
        }));
    });
    uniqueCheckpointGroups.forEach(function(group) {
        oTransmissionComboBox.addItem(new sap.ui.core.Item({
            key: group,
            text: group
        }));
    });
    uniqueStatusGroups.forEach(function(group) {
        oCityNameComboBox.addItem(new sap.ui.core.Item({
            key: group,
            text: group
        }));
    });
    uniqueTypeGroups.forEach(function(group) {
        oStatusComboBox.addItem(new sap.ui.core.Item({
            key: group,
            text: group
        }));
    });

 

    } catch (error) {
        console.error("Error populating filter dropdowns:", error);
    }
}



//-----------------------------------------HOLIDAY-----------------------------------------
//Holiday Calender
var oTable4WHolidayCal = new sap.m.Table({
    growing: true,
    noDataText:oBundle.getText("No_Data"),
    growingTriggerText:oBundle.getText("More"),
    sticky:[sap.m.Sticky.ColumnHeaders,sap.m.Sticky.HeaderToolbar,sap.m.Sticky.InfoToolbar],
    growingThreshold: 25,
    growingScrollToLoad : false,
    columns: [
            new sap.m.Column({width:"100px",header: new sap.m.Label({text: oBundle.getText("Action"),design: sap.m.LabelDesign.Bold})}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Location"),design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Tablet", popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Date"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
            new sap.m.Column({header: new sap.m.Label({wrapping:true,  text: oBundle.getText("Notes"), design: sap.m.LabelDesign.Bold}),
            minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
    ],
    headerToolbar:new sap.m.OverflowToolbar({
        content: [   
            new sap.m.Button({ 
                id:"createHolidayBtnID",
                text: oBundle.getText("Create_Holiday"), 
                type:sap.m.ButtonType.Emphasized,
                icon: sap.ui.core.IconPool.getIconURI("add"), 
                press: function(){ addUpdate4WHolidayCal(1); } 
            }),
            new sap.m.ToolbarSpacer(),
            holidayCalenderFilterByLocation,
            new sap.m.SearchField({
                placeholder: oBundle.getText("Search"),
                width: "300px",
                liveChange: function (event) {
                    var oBinding = oTable4WHolidayCal.getBinding("items");
                    var searchStr = this.getValue();
                    if (oBinding) {
                        var oFilters = [
                        new sap.ui.model.Filter("location_id", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("holiday_date", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("note", sap.ui.model.FilterOperator.Contains, searchStr)
                        ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
        
            }),
        ]
    })
});
var holidayCal4WTemplate = new sap.m.ColumnListItem({
    cells: [
        new sap.m.Button({
            type: "Emphasized",
            icon: "sap-icon://action",
            text: oBundle.getText("Action"),
            press: function (event) {
                var model = this.getModel();
                var path = event.getSource().getBindingContext().getPath();
                var obj = model.getProperty(path);
                displayMenu4WHolidayCal(event,obj);
            
            }
        }),
        // new sap.m.VBox({ alignItems: "Center", 
        //     items:[
        //         new sap.m.Label({ wrapping: true, text: "{jaya_location_id}" }),
        //         new sap.m.Label({ wrapping: true, text: "{jaya_location_name}" }).addStyleClass("sapUiTinyMarginTop"),
        //     ]
        // }).addStyleClass("sapUiTinyMargin"),
        new sap.m.Label({wrapping:true,
            text: {
                path: "location_id",
                formatter: function (location_id) {
                    var fitlerData = locationMasterJSONArray.filter(a=>a.id == location_id);
                    
                    if(fitlerData.length > 0 ){
                        return fitlerData[0]['location_name']
                    }
                }
            },
        }),
        new sap.m.Label({wrapping:true,text: "{holiday_date}"}),
        new sap.m.Label({wrapping:true,text: "{notes}"})
    ]
});
//Display Action 
function displayMenu4WHolidayCal(event,obj){

    var oMenu = new sap.m.Menu({
        items: [],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "2"){
                var oDialog = new sap.m.Dialog({
                    title: oBundle.getText("Alert"),
                    state: sap.ui.core.ValueState.Error,
                    content: [new sap.m.Label({ text: oBundle.getText("Sure_You_want_to_delete") })],
                    buttons: [
                                new sap.m.Button({text: oBundle.getText("Delete"),icon: "sap-icon://delete",
                                    press: function () {
                                        deleteHolidayCalendar(obj['id'],oDialog);
                                    }
                                }),
                                new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
                                    press: function () {
                                        oDialog.close();
                                    }
                                })
                            ]
                }).open();
            }
        }
    });
    
    // //Delete
    // if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('delete_supplier') != -1)){
        getDeleteMenu(oMenu,"2");
    // };
    oMenu.openBy(event.getSource());
};
//Add Update View
function addUpdate4WHolidayCal(src, obj){

    var reqLbl = new sap.m.Label({ required: true });
    var oLbl = new sap.m.Label({ });

    var o4WHolidayField1 = new sap.m.DatePicker({width:"100%",displayFormat: "yyyy-MM-dd",valueFormat: "yyyy-MM-dd"});
    var o4WHolidayField2 = new sap.m.Input({});
    o4WHolidayField1.attachBrowserEvent("keydown", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });

    var o4WHolidayField3 = new sap.m.Select({
        items: {
            path: "/levels", // Path in the model
            template: new sap.ui.core.Item({
                key: "{location_id}",
                text: "{location_name}"
            })
        }
    });

    var oHolidayForm4w =  new sap.ui.layout.form.Form({
        editable: true,
        layout: new sap.ui.layout.form.ResponsiveGridLayout(),
        formContainers: [
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Location")),fields: [o4WHolidayField3]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Date")),fields: [o4WHolidayField1]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Note")),fields: [o4WHolidayField2]})
                    
                ]
            }),
        ]
    });


    var add4WHolidayBtn = new sap.m.Button({ 
        text: oBundle.getText("Create"), 
        icon: "sap-icon://add",
        press: function(){
            let holiday_date = o4WHolidayField1.getValue();
            let note = o4WHolidayField2.getValue();
            let location_id = o4WHolidayField3.getSelectedKey();

            if(location_id == "Select Location"){
                if (validation( "", oBundle.getText("Location_Id"))) { return; }
            }
            if (validation( location_id, oBundle.getText("Location_Id"))) { return; }
            if (validation( holiday_date, oBundle.getText("Holiday_Date"))) { return; }
            // if (validation( note, oBundle.getText("Note"))) { return; }
           
            createHolidayCalendar(location_id,holiday_date,note,oDialog);
        }
    });


    let oDialog = new sap.m.Dialog({ contentWidth: "30%", contentHeight: "40%", draggable: true, resizable: true,
        title: oBundle.getText("Add_Holiday"),
        content: [oHolidayForm4w],
        buttons: [add4WHolidayBtn,
			new sap.m.Button({ text: oBundle.getText("Close"), icon: "sap-icon://decline",press: function () { oDialog.close();}})
		]
    }).open();

    if(src == 1){

        var approvalLevelModel = new sap.ui.model.json.JSONModel();
        approvalLevelModel.setData({ levels: locationMasterActiveJSONArray });
        approvalLevelModel.setSizeLimit(locationMasterActiveJSONArray.length);
        o4WHolidayField3.setModel(approvalLevelModel);

    }else if(src == 2){
        // update4WSupplierBtn.setVisible(true);
        // add4WSupplierBtn.setVisible(false);

        // oDialog.setTitle("Update Supplier");
        // o4WHolidayField1.setValue(obj["supplier_number"]);
        // o4WHolidayField1.setEnabled(false);
        // o4WHolidayField2.setValue(obj["supplier_name"]);
        // o4WHolidayField3.setValue(obj["city"]);

    }
}


// //Create Holday
// function openHolidayDialog() {
//     var oDialogModel = new sap.ui.model.json.JSONModel({
//         holidayName: "",
//         holidayDate: null,
//         selectedLocations: [], // array of full location objects
//     });

//     // List to show selected locations
//     var oSelectedLocationList = new sap.m.List({
//         items: {
//             path: "/selectedLocations",
//             template: new sap.m.StandardListItem({
//                 title: "{location_name}",
//                 description: "{city_name}",
//                 info: "{location_id}"
//             })
//         }
//     });
//     oSelectedLocationList.setModel(oDialogModel);

//     // Search field to filter selected locations
//     var oSearchField = new sap.m.SearchField({
//         placeholder: "Search selected locations...",
//         liveChange: function (oEvent) {
//             var sQuery = oEvent.getParameter("newValue").toLowerCase();
//             var aAllSelected = oDialogModel.getProperty("/selectedLocations") || [];

//             var aFiltered = aAllSelected.filter(function (loc) {
//                 return loc.location_name.toLowerCase().includes(sQuery) ||
//                     loc.city_name.toLowerCase().includes(sQuery) ||
//                     String(loc.location_id).toLowerCase().includes(sQuery);
//             });

//             // Set filtered data temporarily to the list
//             oSelectedLocationList.setModel(new sap.ui.model.json.JSONModel({
//                 selectedLocations: aFiltered
//             }));
//         }
//     });

//     var oListScrollContainer = new sap.m.ScrollContainer({
//         height: "200px",
//         vertical: true,
//         horizontal: false,
//         content: [oSelectedLocationList]
//     });

//     var o4WHolidayField1 = new sap.m.DatePicker({ valueHelpOnly:true,value: "{/holidayDate}", displayFormat: "yyyy-MM-dd",valueFormat: "yyyy-MM-dd" });
//     o4WHolidayField1.attachBrowserEvent("keydown", function (oEvent) {
//         oEvent.preventDefault(); // Prevent manual typing
//     });
//     // Main Dialog
//     var oDialog = new sap.m.Dialog({
//         title: "Create Holiday",
//         contentWidth: "40%",
//         content: [
//             new sap.m.Label({ text: "Holiday Name" }),
//             new sap.m.Input({ value: "{/holidayName}" }),

//             new sap.m.Label({ text: "Holiday Date" }),
//             o4WHolidayField1,
//             new sap.m.Label({ text: "Selected Locations" }),
//             new sap.m.Button({
//                 text: "Select Locations",
//                 press: function () {
//                     openLocationDialog(oDialogModel);
//                 }
//             }),
//             oSearchField,
//             oListScrollContainer,

//         ],
//         beginButton: new sap.m.Button({
//             text: "Save",
//             press: function () {
//                 var data = oDialogModel.getData();

//                 var holidayName = data.holidayName;
//                 var holidayDate = data.holidayDate;
//                 // var selectedLocationIDs = (data.selectedLocations); // this is an array of IDs
//                 // var selectedLocationIDs = data.selectedLocations; // this is an array of IDs
               
//                 var aItems = oSelectedLocationList.getItems();
//                 var sLocationIds = aItems.map(function(oItem) {
//                     var oData = oItem.getBindingContext().getObject();
//                     return oData.location_id;
//                 }).join("^");

//                 console.log("Location IDs (separated by ^):", sLocationIds);

//                 console.log(selectedLocationIDs)
//                 console.log(selectedLocationIDs.join("^"))
//                 if(sLocationIds.length < 1){
//                     sap.m.MessageBox.error(oBundle.getText("Select_Location"));
//                     return;
//                 }

//                 // ✅ You now have all required values
//                 console.log("Holiday Name:", holidayName);
//                 console.log("Holiday Date:", holidayDate);
//                 console.log("Selected Location IDs:", selectedLocationIDs);
        
//                 // You can now use them (e.g., send to backend, save to DB, etc.)
        
//                 oDialog.close();
//                 oDialog.destroy();
//             }
//         }),
//         endButton: new sap.m.Button({
//             text: "Cancel",
//             press: function () {
               
//                 oDialog.close();
//                 oDialog.destroy();
//             }
//         })
//     });

//     oDialog.setModel(oDialogModel);
//     oDialog.open();
// }
// //Select Location Dialogue
// function openLocationDialog(oDialogModel) {
//     // Location model
//     var oLocationModel = new sap.ui.model.json.JSONModel({ locations: locationMasterJSONArray });

//     // Table to display all locations
//     var oTableLocationData = new sap.m.Table({
//         mode: "MultiSelect",
//         growing: true,
//         growingScrollToLoad: true,
//         columns: [
//             new sap.m.Column({ header: new sap.m.Label({ text: "Location ID" }) }),
//             new sap.m.Column({ header: new sap.m.Label({ text: "Location Name" }) }),
//             new sap.m.Column({ header: new sap.m.Label({ text: "City ID" }) }),
//             new sap.m.Column({ header: new sap.m.Label({ text: "City Name" }) }),
//         ],
//         items: {
//             path: "/locations",
//             template: new sap.m.ColumnListItem({
//                 cells: [
//                     new sap.m.Text({ text: "{location_id}" }),
//                     new sap.m.Text({ text: "{location_name}" }),
//                     new sap.m.Text({ text: "{city_id}" }),
//                     new sap.m.Text({ text: "{city_name}" }),
//                 ]
//             })
//         }
//     });
//     oTableLocationData.setModel(oLocationModel);
//     var oSelectedModel = new sap.ui.model.json.JSONModel([]);

//     // Dialog with both full table and selected list area
//     var oLocationDialog = new sap.m.Dialog({
//         title: "Select Locations",
//         contentWidth: "600px",
//         contentHeight: "600px",
//         content: [
//             new sap.m.Label({ text: "All Locations", design: "Bold" }),
//             oTableLocationData,
//             // new sap.m.ToolbarSeparator(),
//             // oSelectedArea
//         ],
//         beginButton: new sap.m.Button({
//             text: "OK",
//             press: function () {
//                 var selectedItems = oTableLocationData.getSelectedItems();
//                 var selectedObjects = selectedItems.map(function (item) {
//                     return item.getBindingContext().getObject();
//                 });
            
//                 // Extract names (for comma-separated preview, optional)
//                 var selectedNames = selectedObjects.map(function (obj) {
//                     return obj.location_name;
//                 });
            
//                 // Store full objects for binding in scrollable list
//                 oDialogModel.setProperty("/selectedLocations", selectedObjects);
//                 oDialogModel.setProperty("/selectedLocationNames", selectedNames.join(", "));
            
//                 oLocationDialog.close();
//                 oLocationDialog.destroy();
//             }
            
//         }),
//         endButton: new sap.m.Button({
//             text: "Cancel",
//             press: function () {
//                 oLocationDialog.close();
//                 oLocationDialog.destroy();
//             }
//         })
//     });

//     // Restore previous selections
//     var previouslySelected = oDialogModel.getProperty("/selectedLocations") || [];
//     console.log(previouslySelected)
//     oTableLocationData.attachEventOnce("updateFinished", function () {
//         var items = oTableLocationData.getItems();
//         console.log(items)
//         items.forEach(function (item) {
//             // console.log(item)
//             console.log(data)
//             var data = item.getBindingContext().getObject();
//             if (previouslySelected.includes(data.location_id)) {
//                 console.log(item)
//                 item.setSelected(true);
//             }
//         });

//         // Populate the selected preview list
//         var selectedObjects = locationMasterJSONArray.filter(loc =>
//             previouslySelected.includes(loc.location_id)
//         );
//         oSelectedModel.setData(selectedObjects);
//     });

//     oLocationDialog.open();
// }





  

var slotMainLayout = new sap.uxap.ObjectPageLayout({ headerContentPinnable: true, 
    preserveHeaderStateOnScroll: true, useIconTabBar: true, toggleHeaderOnTitleClick: false,showHeaderContent:false,
    // headerContent:[ customDateWOD1, customDateWOD2, customDateWODButton],
    toggleHeaderOnTitleClick:false,
    sections: [
        new sap.uxap.ObjectPageSection({id:"SLM0", showTitle: true, title: oBundle.getText("Location"),
            subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTable4WLocation]})
        }),
        new sap.uxap.ObjectPageSection({id:"SLM1", showTitle: true, title: oBundle.getText("Holiday"),
            subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTable4WHolidayCal]})
        }),
        // new sap.uxap.ObjectPageSection({id:"SLM1", showTitle: true, title: oBundle.getText("Slot_Daily"),
        //     subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTable4WSlotsDaily]})
        // }),
        // new sap.uxap.ObjectPageSection({id:"SLM2", showTitle: true, title: oBundle.getText("Slot_Master"),
        //     subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTable4WSlots]})
        // }),
        
    ],
    navigate: function (event) {
        var mID = event.getParameter('section').getId();
        if(mID == 'SLM0'){
            // getAllLocationData();
        }
        // var buttonSegmentNumber = oSegmentedGroupWorkorderDashboard.getSelectedButton();
        // // console.log(mID)
        // // console.log(buttonSegmentNumber)
        // // console.log(mainDashboard)
        // if(buttonSegmentNumber == "WODsegment1" && mainDashboard ){
        //     funWODashboard(new Date(getCurrentDate()),new Date(getCurrentDate()));
        //     console.log("Dashboard Funtion")
        // }

    }
});

var locationHolidayPage4W = new sap.m.Page("location_holiday_page_4w", {
    title:oBundle.getText("Location_&_Holiday"),
    showHeader:true,
    enableScrolling:true,
    content : [slotMainLayout] 
}); 
