//Open Invoice
var oTableSupplierOpenInvoice = 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("Invoice_Number"),design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Workshop_Estimate"),design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Date"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),       
    ],
    headerToolbar:new sap.m.OverflowToolbar({
        content: [   
            new sap.m.Button({
                // id:"createSupplierInvID",
                type: "Emphasized",
                icon: "sap-icon://action",
                text: oBundle.getText("Create_Invoice"),
                press: function (event) {
                    createSuppInvHeader(1);
                }
            }),
            new sap.m.ToolbarSpacer(),
            new sap.m.SearchField({
                placeholder: oBundle.getText("Search"),
                width: "300px",
                liveChange: function (event) {
                    var oBinding = oTable4WInvoiceOpen.getBinding("items");
                    var searchStr = this.getValue();
                    if (oBinding) {
                        var oFilters = [
                        new sap.ui.model.Filter("invoice_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("created_date", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("workshop_estimate", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("wo_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
        
            }),
        ]
      })
});
var invoiceSupOpen4WTemplate = 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);
                    displayMenu4WSuppInvoice(event,obj);
              }
          }),
          new sap.m.Label({wrapping:true,text: "{invoice_number}"}),
          new sap.m.Label({wrapping:true,text: "{workshop_estimate}"}),
          new sap.m.Label({wrapping:true,text: "{invoice_date}"}),
            //   new sap.m.Label({wrapping:true,text: "{status}"}),
         ]
});


var oTableSupplierReviewInvoice = 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("Invoice_Number"),design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Workshop_Estimate"),design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Total_Cost"),design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Date"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        // new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold}),
        // minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
       
    ],
    headerToolbar:new sap.m.OverflowToolbar({
        content: [   
            new sap.m.ToolbarSpacer(),
            new sap.m.SearchField({
                placeholder: oBundle.getText("Search"),
                width: "300px",
                liveChange: function (event) {
                    var oBinding = oTable4WInvoiceReview.getBinding("items");
                    var searchStr = this.getValue();
                    if (oBinding) {
                        var oFilters = [
                        new sap.ui.model.Filter("invoice_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("created_date", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("total_cost", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("workshop_estimate", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("wo_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
        
            }),
        ]
      })
});
var invoiceSupp4WTemplateReview =  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);
                displayMenu4WSuppInvoice(event,obj);
            }
        }),
        new sap.m.Label({wrapping:true,text: "{invoice_number}"}),
        new sap.m.Label({wrapping:true,text: "{workshop_estimate}"}),
        //   new sap.m.Label({wrapping:true,text: "{total_cost}"}),
        new sap.m.Label({
            wrapping: true,
            text: {
                path: "total_cost",
                formatter: function (value) {
                    if (value) {
                        return value.toLocaleString(); // Formats the number with commas (e.g., 7,315,423)
                    }
                    return value; // Fallback for null or undefined
                }
            }
        }),
        new sap.m.Label({wrapping:true,text: "{invoice_date}"}),
        //   new sap.m.Label({wrapping:true,text: "{status}"}),
         
         ]
});

var oTableSupplierCompletedInvoice = 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("Invoice_Number"),design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Workshop_Estimate"),design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Total_Cost"),design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Date"), design: sap.m.LabelDesign.Bold}),
        minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
       
    ],
    headerToolbar:new sap.m.OverflowToolbar({
        content: [   
            new sap.m.ToolbarSpacer(),
            new sap.m.SearchField({
                placeholder: oBundle.getText("Search"),
                width: "300px",
                liveChange: function (event) {
                    var oBinding = oTableSupplierCompletedInvoice.getBinding("items");
                    var searchStr = this.getValue();
                    if (oBinding) {
                        var oFilters = [
                        new sap.ui.model.Filter("invoice_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("created_date", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("workshop_estimate", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("total_cost", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("wo_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
        
            }),
        ]
      })
});
var supplier4WTemplateCompleted =  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);
                    displayMenu4WSuppInvoice(event,obj);
              }
          }),
          new sap.m.Label({wrapping:true,text: "{invoice_number}"}),
          new sap.m.Label({wrapping:true,text: "{workshop_estimate}"}),
          new sap.m.Label({wrapping:true,text: "{total_cost}"}),
          new sap.m.Label({wrapping:true,text: "{invoice_date}"}),
         
         ]
});



var totalMaterialCostInvoiceSupp = new sap.m.Input({ enabled: false, value: "0.00" });
var totalMaterialDiscountInvoiceSupp = new sap.m.Input({ enabled: false, value: "0.00" })
var totalLaborCostInvoiceSupp = new sap.m.Input({ enabled: false, value: "0.00" });
var totalLaborDiscountInvoiceSupp = new sap.m.Input({ enabled: false, value: "0.00" });
var totalOtherCostInvoiceSupp = new sap.m.Input({ enabled: false, value: "0.00" });
var totalOtherDiscountInvoiceSupp = new sap.m.Input({ enabled: false, value: "0.00" });
var totalTaxValueInvoiceSupp = new sap.m.Input({ enabled: false, value: "0.00" });
var grandTotalInvoiceSupp = new sap.m.Input({ enabled: false, value: "0.00" });
// var selectedWOInvoice = [];



//Invoice Parts Details
var oTableSuppPartsInvoice = 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:"70px", 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("Workorder_Number"), design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Part_Name"), design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Date"), design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Material_Cost"), design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Material_Disc_%"), design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Labour_Cost"), design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Labor_Disc_%"), design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Other_Cost"), design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Other_Disc_%"), design: sap.m.LabelDesign.Bold})}),        
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Tax_Value"), design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Total"), design: sap.m.LabelDesign.Bold})})
    ],
    headerToolbar: new sap.m.Toolbar({
        content: [
            new sap.m.Title({
                text: "Invoice Parts", // Title text
                level: sap.ui.core.TitleLevel.H2, // Optional: Title level,
                customData: [
                    new sap.ui.core.CustomData({
                        key: "style",
                        value: "background-color:rgb(47, 79, 143); color: #333; padding: 10px; border-bottom: 1px solid #ccc;"
                    })
                ]
            })
        ],
     
    })
});
oTableSuppPartsInvoice.getHeaderToolbar().addStyleClass("customHeaderToolbarInvoice");
var suppPartsInvoiceTemplate = new sap.m.ColumnListItem({
    cells: [
        // Action Button
        // new sap.m.Button({
        //     text: oBundle.getText(""),
        //     type: "Emphasized",
        //     icon: "sap-icon://action",
        //     press: function(oEvent) {
        //         var oItem = oEvent.getSource().getBindingContext().getObject();
        //         // Handle action button press
        //     }
        // }),
        // Type (Text)
        new sap.m.Text({
            text: "{wo_number}"
        }),
        // Description (Text)
        new sap.m.Text({
            text: "{part_name}"
        }),
        // // Date (Text)
        // new sap.m.Text({
        //     text: "{added_date}"
        // }),
        // Material Cost (Input)
        new sap.m.Input({
            enabled:false,
            type: "Number",
            value: "{total_parts_cost}",
            maxLength:99999999999,
            // change: function(oEvent) {
                
            //     var sValue = oEvent.getParameter("value");
            //     if (sValue > 99999999999) {
            //         sap.m.MessageToast.show("Maximum character limit " + 99999999999 + " reached.");
            //     }
            //     calculateSuppRowTotal(oEvent);
            // }
        }),
        // Material Disc % (Input)
        // new sap.m.Input({
        //     enabled:false,
        //     type: "Number",
        //     value: "{material_disc}",
        //     maxLength:100,
        //     change: function(oEvent) {
                
        //         var sValue = oEvent.getParameter("value");
        //         if (sValue > 100) {
        //             this.setValue(0)
        //             sap.m.MessageBox.error(oBundle.getText("The_discount_value_cannot_exceed_100_Please_enter_a_valid_discount_percentage_and_try_again"));
        //         }
        //         calculateSuppRowTotal(oEvent);
        //     }
        // }),
        // Labour Cost (Input)
        new sap.m.Input({
            enabled:false,
            type: "Number",
            value: "{labor_item_cost}",
            maxLength:99999999999,
            // change: function(oEvent) {
                
            //     var sValue = oEvent.getParameter("value");
            //     if (sValue > 99999999999) {
            //         sap.m.MessageToast.show("Maximum character limit " + 99999999999 + " reached.");
            //     }
            //     calculateSuppRowTotal(oEvent);
            // }
        }),
        // Labor Disc % (Input)
        // new sap.m.Input({
        //     enabled:false,
        //     type: "Number",
        //     value: "{labor_disc}",
        //     maxLength:100,
        //     change: function(oEvent) {
                
        //         var sValue = oEvent.getParameter("value");
        //         if (sValue > 100) {
        //             this.setValue(0)
        //             sap.m.MessageBox.error(oBundle.getText("The_discount_value_cannot_exceed_100_Please_enter_a_valid_discount_percentage_and_try_again"));
        //         }
        //         calculateSuppRowTotal(oEvent);
        //     }
        // }),
        // Other Cost (Input)
        // new sap.m.Input({
        //     enabled:false,
        //     type: "Number",
        //     value: "{other_cost}",
        //     maxLength:99999999999,
        //     change: function(oEvent) {
                
        //         var sValue = oEvent.getParameter("value");
        //         if (sValue > 99999999999) {
        //             sap.m.MessageToast.show("Maximum character limit " + 99999999999 + " reached.");
        //         }
        //         calculateSuppRowTotal(oEvent);
        //     }
        // }),
        // // Other Disc % (Input)
        // new sap.m.Input({
        //     enabled:false,
        //     type: "Number",
        //     value: "{other_disc}",
        //     maxLength:100,
        //     change: function(oEvent) {
        //         var sValue = oEvent.getParameter("value");
        //         if (sValue > 100) {
        //             this.setValue(0)
        //             sap.m.MessageBox.error(oBundle.getText("The_discount_value_cannot_exceed_100_Please_enter_a_valid_discount_percentage_and_try_again"));
        //         }
        //         calculateSuppRowTotal(oEvent);
        //     }
        // }),
        new sap.m.Text({
            text: "{tax_value}"
        }),
        // Total (Text - calculated)
        new sap.m.Text({
            text: "{total_cost}"
        })
    ]
});
var suppPartsInvoiceViewTemplate = new sap.m.ColumnListItem({
    cells: [
        // Action Button
        // new sap.m.Button({
        //     enabled:false,
        //     text: oBundle.getText(""),
        //     type: "Emphasized",
        //     icon: "sap-icon://action",
        //     press: function(oEvent) {
        //         var oItem = oEvent.getSource().getBindingContext().getObject();
        //     }
        // }),

        new sap.m.Text({ text: "{wo_number}" }),
        new sap.m.Text({ text: "{part_name}" }),
        // new sap.m.Text({ text: "{added_date}" }),
        
        new sap.m.Text({ text: "{item_material_cost}" }),
        // new sap.m.Text({ text: "{item_material_discount}" }),
        new sap.m.Text({ text: "{item_labor_cost}" }),
        // new sap.m.Text({ text: "{item_labor_discount}" }),
        // new sap.m.Text({ text: "{item_other_cost}" }),
        // new sap.m.Text({ text: "{item_other_discount}" }),
        new sap.m.Text({ text: "{item_tax_value}" }),
        new sap.m.Text({ text: "{item_total_cost}" }),
    ]
});

//Workorder price Overview
var invoiceSuppPriceWoOverview = new sap.m.Table({
    width:"90%",
    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({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Workorder_Number"), design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Material_Cost"), design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Labour_Cost"), design: sap.m.LabelDesign.Bold})}),
        // new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Other_Cost"), design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Tax_Value"), design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Total"), design: sap.m.LabelDesign.Bold})})
    ],
    headerToolbar: new sap.m.Toolbar({
        content: [
            new sap.m.Title({
                text: "Workorders Cost Detail", // Title text
                level: sap.ui.core.TitleLevel.H2 // Optional: Title level
            })
        ]
    })
});
var invoiceSuppPriceWoOverviewTemplate = new sap.m.ColumnListItem({
    cells: [
        new sap.m.Text({ text: "{wo_number}" }),
        new sap.m.Text({ text: "{total_parts_cost}" }),
        new sap.m.Text({ text: "{labor_item_cost}"}),
        // new sap.m.Text({ text: "{other_cost}"}),
        new sap.m.Text({ text: "{tax_value}"}),
        new sap.m.Text({ text: "{total_cost}"}),
    ]
});



function displayMenu4WSuppInvoice(event,obj){
    var oMenu = new sap.m.Menu({
        items: [
            new sap.m.MenuItem({icon: "sap-icon://show",text: oBundle.getText("View"),key: "0"}),
        ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "0") { 
                if(obj['status'] == "Open"){
                    createSuppInvHeader(3,obj);//View Invoice header
                }else{
                    createGrabSuppInvoice(2,obj); //View Invoice Part Items 
                }
            } else if (oItem == "1") {
                createSuppInvHeader(2,obj); //Update Invoice header
            } else if (oItem == "3") {
                createGrabSuppInvoice(1,obj); // Add Invoice Items
            } 
        }
    });

            
    // if(obj['status'] != "Under Review" || obj['status'] != "Completed" ){
    // }
    if(obj['status'] == "Open"){
        oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://edit",text: oBundle.getText("Update"),key: "1"}));
        oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://add-activity",text: oBundle.getText("Add_Invoice_Item"),key: "3"}));
    }
   
    oMenu.openBy(event.getSource());
}


function createSuppInvHeader(src,obj){
    let reqLbl = new sap.m.Label({ required: true });
    let oLbl = new sap.m.Label({});

    // Input fields
    var oIFSuppInvoice1 = new sap.m.Input({enabled:true}); // Invoice Number

    var oIFSuppInvoice3 = new sap.m.Input({value:"0",type:'Number',enabled:false}); // Workshop Estimate
    var oIFSuppInvoice4 = new sap.m.DatePicker({
        width: "100%",
        minDate: new Date(),
        displayFormat: "dd-MMM-yyyy",
        valueFormat: "dd-MMM-yyyy",
        enabled:false,
        change: function (oEvent) {
            if (!oEvent.getParameter("valid")) {
                oIFSuppInvoice4.setValue(""); 
                sap.m.MessageToast.show("Please select a valid date from the calendar.");
            }
        }
    }).attachBrowserEvent("keydown", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });
    oIFSuppInvoice4.setDateValue(new Date());
    
    var oIFSuppInvoice5 = new sap.m.Input({editable:false});
    var workorderInvoiceDB = new sap.m.MultiInput({ showSuggestion: true, fieldWidth: "100%",
        showValueHelp: true,valueHelpOnly: true,
        valueHelpRequest: function () { selectSuppWorkorderInvoice(workorderInvoiceDB,oIFSuppInvoice3,oIFSuppInvoice5); },
        suggestionItemSelected: function (oEvent) {
            var selectedItem = oEvent.getParameter("selectedItem");
            if (selectedItem) {
                // Add token when a suggestion is selected
                var newToken = new sap.m.Token({
                    text: selectedItem.getText(),
                    key: selectedItem.getKey() || selectedItem.getText()
                });
                this.addToken(newToken);
    
                // Log the current token list
                if(src == 1){
                    logSuppCurrentTokens(this);
                }
            }
        },
        tokenUpdate: function (oEvent) {
            let updated_date = getIndonesianTime();
            
            if (oEvent.getParameter("type") === "removed") {
                var removedTokens = oEvent.getParameter("removedTokens");
                var that = this;  // Reference to the MultiInput control
                
                setTimeout(() => {
                    busyDialog.open();
                    var remainingTokens = that.getTokens();
                    
                    // 🚫 Prevent removing the last token
                    if(src != 1){
                        if (remainingTokens.length === 0 && removedTokens.length === 1) {
                            // Re-add the removed token
                            var tokenToRestore = removedTokens[0];
                            that.addToken(new sap.m.Token({
                                key: tokenToRestore.getKey(),
                                text: tokenToRestore.getText()
                            }));
                            
                            sap.m.MessageBox.warning(oBundle.getText("Cannot_Remove_Last_Item"));
                            busyDialog.close();
                            return;  // Stop further processing
                        }
                    }
        
                    var remainingKeys = remainingTokens.map(token => token.getKey()).join("^");
                    var remainingTexts = remainingTokens.map(token => token.getText()).join("^");
                    busyDialog.open()
                    if (src != 1) {
                        removedTokens.forEach(token => {
                            Car_Workorder.update({ id: token.getKey(), supplier_inv_pick:""  }).done(() => {
                              
                                    let getWOCost = [...grabSuppInvoiceAllWOJSONArray].filter(a => a.id === token.getKey());
                                    if (getWOCost.length > 0) {
                                        var updatedEstimateCost = roundToInt(oIFSuppInvoice3.getValue()) - roundToInt(getWOCost[0]['supplier_cost']);
                                        oIFSuppInvoice3.setValue(updatedEstimateCost);
                                        busyDialog.close();
                                        Car_Invoice.update({ id: obj['id'], wo_number: remainingTexts, wo_id: remainingKeys,workshop_estimate:updatedEstimateCost}).done(() => {
                                            busyDialog.close();
                                            get4WSuppOpenInvoice();
                                            getSupplierClosedWorkorder();
                                        });
                        
                                    }
                                    busyDialog.close();
        
                            });
                        });
                    } else {
                        removedTokens.forEach(token => {
                            let getWOCost = [...grabSuppInvoiceAllWOJSONArray].filter(a => a.id === token.getKey());
                            if (getWOCost.length > 0) {
                                var updatedEstimateCost = roundToInt(oIFSuppInvoice3.getValue()) - roundToInt(getWOCost[0]['supplier_cost']);
                                oIFSuppInvoice3.setValue(updatedEstimateCost);
                            }
                            busyDialog.close();
                        });
                    }
                }, 0);
            }
        }
        
        // tokenUpdate: function (oEvent) {
        //     let updated_date = getIndonesianTime();;
        //     // Check if the operation is "removed"
        //     if (oEvent.getParameter("type") === "removed") {
        //         var remainingTokens = this.getTokens();
        //         var remainingKeys = remainingTokens.map(function (token) {
        //             return token.getKey();
        //         }).join("^");
        //         var remainingTexts = remainingTokens.map(function (token) {
        //             return token.getText();
        //         }).join("^");

                
        //         var removedTokens = oEvent.getParameter("removedTokens");
        //         if(src != 1){
        //             removedTokens.forEach(function (token) {
        //                 Car_Workorder.update({ id:token.getKey(), supplier_inv_pick:"" }).done(() => {

        //                     let getWOCost = [...grabSuppInvoiceWOJSONArray].filter(a=>a.id ==token.getKey());
        //                     if(getWOCost.length > 0){
        //                         var updatedEstimateCost = roundToInt(oIFSuppInvoice3.getValue()) - roundToInt(getWOCost[0]['supplier_cost']);
        //                         oIFSuppInvoice3.setValue(updatedEstimateCost);
        //                     }

        //                     Car_Invoice.update({id:obj['id'],wo_number:remainingTexts, wo_id:remainingKeys}).done(() => {});
        //                     getSupplierClosedWorkorder();
        //                 });
        //             });
        //         }else{
        //             removedTokens.forEach(function (token) {
        //                 let getWOCost = [...grabSuppInvoiceWOJSONArray].filter(a=>a.id ==token.getKey());
        //                 if(getWOCost.length > 0){
        //                     var updatedEstimateCost = roundToInt(oIFSuppInvoice3.getValue()) - roundToInt(getWOCost[0]['supplier_cost']);
        //                     oIFSuppInvoice3.setValue(updatedEstimateCost);
        //                 }
        //             })
        //         }

        //     }
        // }
    });


    var oInvoiceHeader = 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("Invoice_Number")),
                        fields: [oIFSuppInvoice1]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: reqLbl.clone().setText(oBundle.getText("Workorder_Number")),
                        fields: [workorderInvoiceDB]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Workshop_Estimate")),
                        fields: [oIFSuppInvoice3]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: reqLbl.clone().setText(oBundle.getText("Invoice_Date")),
                        fields: [oIFSuppInvoice4]
                    }),
                    // new sap.ui.layout.form.FormElement({
                    //     label: reqLbl.clone().setText(oBundle.getText("Tax")),
                    //     fields: [oIFSuppInvoice5]
                    // }),
                ]
            })
        ]
    });


    let addInvoceBtn = new sap.m.Button({ 
        text: oBundle.getText("Add"), 
        icon: "sap-icon://add",
        press: function() {
            
            let invoice_number = oIFSuppInvoice1.getValue();
            let workshop_estimate = oIFSuppInvoice3.getValue();
            let invoice_date = oIFSuppInvoice4.getValue();

            let wo_id = "";
            let wo_number = "";
            let workorderTokensList = workorderInvoiceDB.getTokens();            
            for (var j = 0; j < workorderTokensList.length; j++) {
                if (wo_number == "") {
                    wo_id = workorderTokensList[j].getKey();
                    wo_number = workorderTokensList[j].getText();
                }else{
                    wo_id = wo_id + "^" + workorderTokensList[j].getKey();
                    wo_number = wo_number + "^" + workorderTokensList[j].getText();
                }
            };

            if(!nullCheckAll(invoice_number)){ sap.m.MessageBox.error(oBundle.getText("Invoice_Number_cannot_be_empty")); return; };
            if(!nullCheckAll(wo_number)){ sap.m.MessageBox.error(oBundle.getText("Select_at_least_one_workorder")); return; };
            if(!nullCheckAll(invoice_date)){ sap.m.MessageBox.error(oBundle.getText("Select_Invoice_Date")); return; };
            if (validation(invoice_number, oBundle.getText("Invoice_Number_cannot_be_empty"))) { return; }
            if (validation(wo_number, oBundle.getText("Select_at_least_one_workorder"))) { return; }
            
            var created_date = getIndonesianTime();


            if(src == 1){
                busyDialog.open();
                
                Car_Invoice.where({master_email:emailUser,invoice_number:invoice_number}).
                take(10).read().done(function (result) {

                    if(result.length > 0){
                        sap.m.MessageBox.error(oBundle.getText("The_invoice_number_you_entered_already_exists_Please_enter_a_unique_invoice_number_to_proceed")); 
                        busyDialog.close();
                        return;
                    }else{
                        let insertItems = {
                            master_email:emailUser, invoice_number:invoice_number, wo_number:wo_number, wo_id:wo_id,
                            workshop_estimate:workshop_estimate, invoice_date:invoice_date, status:"Open",
                            material_cost:"", material_discount:"", labor_cost:"",invoice_type:"Supplier",
                            labor_discount:"", total_cost:"",tax:oIFSuppInvoice5.getValue(),
                            created_date:created_date,created_by:operatedID,
                            ws_group_number: oxmaint_ws_group_number, ws_group_name: oxmaint_ws_group_name,
                            workshop_name: oxmaint_workshop_name, workshop_number: oxmaint_workshop_number,
                        };
            

                        insertInvoiceHeaderApi(insertItems,oDialog);
                        // supplierInsertInvoiceHeader(insertItems,oDialog);
                        // Car_Invoice.insert(insertItems).done(function () {                            
                        //     const partsSplitWO = wo_id.split("^");
                        //     const partsSplitWONumber = wo_number.split("^");
                            
                        //     partsSplitWO.forEach((item, index) => {

                        //         Car_Workorder.update({ id:item, supplier_inv_pick:"Done" }).done(() => {
                        //             if (index === partsSplitWO.length - 1) {
                        //                 getSupplierClosedWorkorder();
                        //                 get4WSuppOpenInvoice();
                        //                 busyDialog.close();
                        //                 oDialog.close();
                        //             }
                        //         });
                        //     });
                            
                        // }, failure);
                    }
                });
                
                
            }else{
                busyDialog.open();

                if(obj['status'] == "Open"){
                    var updateItems = {
                        id:obj['id'],
                        master_email:emailUser,
                        wo_number:wo_number, invoice_number:invoice_number,wo_id,wo_id,
                        workshop_estimate:workshop_estimate, invoice_date:invoice_date,
                        material_cost:"", material_discount:"", labor_cost:"",invoice_type:"Supplier",
                        labor_discount:"", tax:oIFSuppInvoice5.getValue(),
                        updated_date:created_date,updated_by:operatedID
                    };

                    updateInvoiceHeaderApi(updateItems,oDialog,obj);
                    // supplierUpdateInvoiceHeader(updateItems,oDialog);
                    // Car_Invoice.update(updateItems).done(function () {
                    //     const partsSplitWO = wo_id.split("^");
                    //     const partsSplitWONumber = wo_number.split("^");
                        
                    //     partsSplitWO.forEach((item, index) => {

                    //         Car_Workorder.update({ id:item, supplier_inv_pick:"Done" }).done(() => {
                    //             if (index === partsSplitWO.length - 1) {
                    //                 getSupplierClosedWorkorder();
                    //                 if(obj['status'] == "Open"){
                    //                     get4WSuppOpenInvoice();
                    //                 // }else if(obj['status'] == "Under Review"){
                    //                 //     get4WSuppReviewInvoice();
                    //                 };
                    //                 busyDialog.close();
                    //                 oDialog.close();
                    //             }
                    //         });
                    //     });
                                               
                    // }, failure);
                }
                
            }

        }
    });

    

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

    if(src == 1){ // Create Header
    }else if(src == 2){ // Update
        oDialog.setTitle(oBundle.getText("Update_Invoice_Header"));
        addInvoceBtn.setText("Update");
        oIFSuppInvoice1.setValue(obj['invoice_number']);
        oIFSuppInvoice3.setValue(obj['workshop_estimate']);
        oIFSuppInvoice4.setValue(formatDateToDDMMMYYYY(obj['invoice_date']));

        if (nullCheckAll(obj['wo_number'])) {
            var wo_number = obj['wo_number'].split("^");
            var wo_id = obj['wo_id'].split("^");
            for (var i = 0; i < wo_number.length; i++) {//
                workorderInvoiceDB.addToken(new sap.m.Token({key:wo_id[i], text: wo_number[i] }));
            };
        };
        if(obj['status'] == "Completed" || obj['status'] == "Under Review" || obj['status'] == "Reopen"){
            workorderInvoiceDB.setEnabled(false);
        }

        oIFSuppInvoice5.setValue(obj['tax'])

    }else if(src == 3){ // View
        addInvoceBtn.setVisible(false);
        oDialog.setTitle("View Invoice Header");
        oIFSuppInvoice1.setValue(obj['invoice_number']);
        oIFSuppInvoice3.setValue(obj['workshop_estimate']);
        oIFSuppInvoice4.setValue(formatDateToDDMMMYYYY(obj['invoice_date']));

        if (nullCheckAll(obj['wo_number'])) {
            var wo_number = obj['wo_number'].split("^");
            var wo_id = obj['wo_id'].split("^");
            for (var i = 0; i < wo_number.length; i++) {//
                workorderInvoiceDB.addToken(new sap.m.Token({key:wo_id[i], text: wo_number[i] }));
            };
        };
        oIFSuppInvoice1.setEnabled(false);
        oIFSuppInvoice3.setEnabled(false);
        oIFSuppInvoice4.setEnabled(false);
        oIFSuppInvoice5.setValue(obj['tax'])
        workorderInvoiceDB.setEnabled(false);
    }
};
var supplier_invoice_tax_value;
function createGrabSuppInvoice(src,obj){
    let reqLbl = new sap.m.Label({ required: true });
    let oLbl = new sap.m.Label({});

    totalMaterialCostInvoiceSupp.setValue("0.00");
    totalMaterialDiscountInvoiceSupp.setValue("0.00");
    totalLaborCostInvoiceSupp.setValue("0.00");
    totalLaborDiscountInvoiceSupp.setValue("0.00");
    totalOtherCostInvoiceSupp.setValue("0.00");
    totalOtherDiscountInvoiceSupp.setValue("0.00");
    totalTaxValueInvoiceSupp.setValue("0.00");
    grandTotalInvoiceSupp.setValue("0.00");
 

    var oPageInvoiceLayoutSupp =  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: oLbl.clone().setText(oBundle.getText("Invoice_Number")),fields: [new sap.m.Text({text: obj['invoice_number']})]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Invoice_Date")),fields: [new sap.m.Text({text: obj['invoice_date']})]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Workshop_Estimate")),fields: [new sap.m.Text({text: obj['workshop_estimate']})]}),
                    new sap.ui.layout.form.FormElement({label: oLbl.clone().setText(oBundle.getText("Workorder")),fields: [new sap.m.Text({text: obj['wo_number'].replaceAll("^",", ")})]}),
                    
                ]
            })
            
        ]
    })

    supplier_invoice_tax_value = obj['tax'] || 0;

    // Create summary form below table
    var oSummaryForm = new sap.ui.layout.form.SimpleForm({
        // width:"50%",
        layout: sap.ui.layout.form.SimpleFormLayout.ResponsiveGridLayout,
        editable: true,
        content: [
            new sap.m.Label({text: oBundle.getText("Summary"), design: "Bold"}),
            new sap.m.VBox({
                items: [
                    new sap.m.VBox({
                        width: "300px",
                        items: [
                            new sap.m.Label({text: oBundle.getText("Total_Material_Cost")}),
                            totalMaterialCostInvoiceSupp,
                            // new sap.m.Label({text: oBundle.getText("Total_Material_Discount")}),
                            // totalMaterialDiscountInvoiceSupp
                        ]
                    }),
                    new sap.m.VBox({
                        width: "300px",
                        items: [
                            new sap.m.Label({text: oBundle.getText("Total_Labor_Cost")}),
                            totalLaborCostInvoiceSupp,
                            // new sap.m.Label({text: oBundle.getText("Total_Labor_Discount")}),
                            // totalLaborDiscountInvoiceSupp
                        ]
                    }),
                    new sap.m.VBox({
                        width: "300px",
                        items: [
                            // new sap.m.Label({text: oBundle.getText("Total_Other_Cost")}),
                            // totalOtherCostInvoiceSupp,
                            // new sap.m.Label({text: oBundle.getText("Total_Other_Discount")}),
                            // totalOtherDiscountInvoiceSupp,
                            new sap.m.Label({text: oBundle.getText("Tax")}),
                            totalTaxValueInvoiceSupp
                        ]
                    })
                ]
            }),
            new sap.m.HBox({
                justifyContent: "End",
                items: [
                    new sap.m.VBox({
                        width: "300px",
                        items: [
                            new sap.m.Label({text: oBundle.getText("Grand_Total"), design: "Bold"}),
                            // new sap.m.Input({
                            //     id: "grandTotal",
                            //     enabled: false,
                            //     value: "0.00"
                            // })
                            grandTotalInvoiceSupp
                        ]
                    })
                ]
            })
        ]
    });

    var horizontalBar = new sap.m.HBox({
        width: "100%",
        items: [
            invoiceSuppPriceWoOverview,oSummaryForm
        ]
    })
   
    var updateinvoiceBtn = new sap.m.Button({ 
        text: oBundle.getText("Update"), 
        visible: false,
        icon: "sap-icon://edit",
        press: function() {
            busyDialog.open();
            var created_date = getIndonesianTime();
            // var tableItem = oTableSuppPartsInvoice.getItems();
            var alltableItemdata = oTableSuppPartsInvoice.getModel().getData();
            var tableItem = alltableItemdata['modelData'];


            var alltableItemdata1 = invoiceSuppPriceWoOverview.getModel().getData(); 
            var tableItem1 = Object.values(alltableItemdata1['modelData']);

            if(tableItem.length <= 0){
                sap.m.MessageBox.error(oBundle.getText("NO_Invoice_item_Available_to_add"));
                busyDialog.close();
                return;
            }


            var completedRequests = 0;
            var totalInvoiceCost = 0; 
            var invoice_item_json = [];

            for(var i=0;i<tableItem.length;i++){
                // var item = tableItem[i].getBindingContext().getObject();
                var item = tableItem[i];
               
                
                let total_parts_cost = item.total_parts_cost;
                let labor_item_cost = item.labor_item_cost;
                let tax_value = item.tax_value;
                let total_cost = item.total_cost;

                total_parts_cost = isNaN(total_parts_cost) || total_parts_cost === "" ? 0 : roundToInt(total_parts_cost);
                labor_item_cost = isNaN(labor_item_cost) || labor_item_cost === "" ? 0 : roundToInt(labor_item_cost);               
                tax_value = isNaN(tax_value) || tax_value === "" ? 0 : roundToInt(tax_value);
                total_cost = isNaN(total_cost) || total_cost === "" ? 0 : roundToInt(total_cost);


                // Accumulate the total cost and round to 2 decimals
                totalInvoiceCost = totalInvoiceCost + total_cost

                var itemsData = {
                    master_email:emailUser,

                    invoice_id:obj['id'],
                    invoice_number:obj['invoice_number'],
                    invoice_type:"Supplier",

                    wo_id:item.wo_id,
                    wo_number:item.wo_number,
                    part_name:item.part_name,
                    
                    item_material_cost:total_parts_cost+"",
                    item_labor_cost:labor_item_cost+"",
                    item_total_cost:total_cost+"",
                    item_tax_value:tax_value+"",
                    item_final_material_cost:total_parts_cost+"",
                    item_total_labor_cost:labor_item_cost+"",
                    item_final_total_cost:total_cost+"",

                    created_by:operatedID,
                    created_date:created_date

                };
                invoice_item_json.push(itemsData)
                // Car_Invoice_Item.insert(itemsData).done(function () {

                //    completedRequests++;
    
                //     if (completedRequests === tableItem.length) {
                //         var total_invoice_cost = roundToInt(totalInvoiceCost);
                //         Car_Invoice.update({id:obj['id'],status:"Under Review",total_cost: total_invoice_cost+""}).done(function () {
                            
                //             updateSuppWorkorderAmount(obj['invoice_number'],
                //                 function () {
                //                     get4WSuppOpenInvoice();
                //                     // get4WSuppReviewInvoice();
                //                     fetchSupplierInvoice();
                //                     busyDialog.close();
                //                     oDialog.close();
                //                 }
                //             );
                //         });
                        
                //     }
                // }, failure);
                
            }
            var total_invoice_cost = roundToInt(totalInvoiceCost);
            insertInvoiceItemsApi(invoice_item_json,tableItem1,total_invoice_cost,obj['id'],obj['invoice_number'],'Supplier',oDialog)

        }
    });

    // Create and open dialog
    var oDialog = new sap.m.Dialog({ 
        contentWidth: "100%", 
        contentHeight: "80%", 
        draggable: true, 
        resizable: true,
        title: oBundle.getText("Create_Invoice"),
        content: [oPageInvoiceLayoutSupp,new sap.ui.core.HTML({ content: "<hr />" }), oTableSuppPartsInvoice,new sap.ui.core.HTML({ content: "<hr />" }),horizontalBar],
        buttons: [
            updateinvoiceBtn,
            new sap.m.Button({ 
                text: oBundle.getText("Close"), 
                icon: "sap-icon://decline",
                press: function () { 
                    oDialog.close();
                }
            })
        ]
    }).open();


    if(src == 3){
    }else if(src == 2){
        oDialog.setTitle("View Invoice Parts");        
        getSuppInvoiceItemsData(obj,suppPartsInvoiceViewTemplate);
    }else if(src == 1){
        updateinvoiceBtn.setVisible(true);
        // addInvoceBtn.setVisile(false);
        oDialog.setTitle("Add Supplier Invoice Parts")
        // getWoSuppInvoicePartsData(obj['wo_id'].split("^"));
        getInvoiceWorkorderPartById('Supplier',obj['wo_id'])
    }
};
function selectSuppWorkorderInvoice(input, workshop_estimate_input,tax_input) {
    var oTableInvoiceWo = 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,
        mode: sap.m.ListMode.MultiSelect, // Enable MultiSelect mode
        columns: [
            // new sap.m.Column({ wrapping: true, width: "100px", header: new sap.m.Label({ text: oBundle.getText("Select"), design: sap.m.LabelDesign.Bold }) }),
            new sap.m.Column({ width: "120px", header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Workorder_Number"), design: sap.m.LabelDesign.Bold }), sortIndicator: "Descending" }),
            new sap.m.Column({ width: "130px", header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Workorder_Title"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Desktop", popinDisplay: "Inline", demandPopin: true }),
            new sap.m.Column({ width: "130px", header: new sap.m.Label({ wrapping: true, text: oBundle.getText("License_Number"), 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("Workshop_Number"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left", width: "120px" }),
            new sap.m.Column({ header: new sap.m.Label({wrapping: true, text: oBundle.getText("Workshop_Name"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left", width: "120px" }),
            new sap.m.Column({ header: new sap.m.Label({wrapping: true, text: oBundle.getText("Workshop_Group_Number"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left", width: "120px" }),
            new sap.m.Column({ header: new sap.m.Label({wrapping: true, text: oBundle.getText("Workshop_Group_Name"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left", width: "120px" }),
        ],
        headerToolbar: new sap.m.OverflowToolbar({
            content: [
                new sap.m.ToolbarSpacer(),
                new sap.m.SearchField({
                    placeholder: oBundle.getText("Search"),
                    width: "300px",
                    liveChange: function (event) {
                        var oBinding = oTableInvoiceWo.getBinding("items");
                        var searchStr = this.getValue();
                        if (oBinding) {
                            var oFilters = [
                                new sap.ui.model.Filter("ws_group_number", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("ws_group_name", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("workshop_name", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("workshop_number", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("wo_number", sap.ui.model.FilterOperator.Contains, searchStr),
                                new sap.ui.model.Filter("wo_title", 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",press: function () {
                //     funMultiFilterOpenWO(2,resultTokenList, oTableInvoiceWo,oItemWoPickInvoice);
                // }})
                new sap.m.Button({
                    icon: "sap-icon://filter",
                    type: "Transparent",
                    press: function() {
                        clearFiltersSupplierInv();
                        populateSuppInvFilterDropdowns();
                        oSupplierInvFilterDialog.open();
                    }
                })

            ],
        }),
    });

    var oItemWoPickInvoice = new sap.m.ColumnListItem({
        cells: [
            new sap.m.Text({ wrapping: true, text: "{wo_number}" }),
            new sap.m.Text({ wrapping: true, text: "{wo_title}" }),
            new sap.m.Text({ wrapping: true, text: "{license_number}" }),
            new sap.m.Text({ wrapping: true, text: "{workshop_number}" }),
            new sap.m.Text({ wrapping: true, text: "{workshop_name}" }),
            new sap.m.Text({ wrapping: true, text: "{ws_group_number}" }),
            new sap.m.Text({ wrapping: true, text: "{ws_group_name}" }),
        ],
    });


    var oSupplierInvFilterDialog = new sap.m.Dialog({
        title: "Multi Filter Workorder",
        contentWidth: "40%",
        content: [
            new sap.m.VBox({
                width: "100%",
                items: [
                    new sap.m.Label({ text: "Workshop Group:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select Workshop Group"
                    }),
                    
                    new sap.m.Label({ text: "Workshop:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select Workshop Group"
                    }),
                    
                    new sap.m.Label({ text: "License Number:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select License Number"
                    }),
                    
                    new sap.m.Label({ text: "City:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select City"
                    }),
                    
                    new sap.m.Label({ text: "Rental Company:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select Rental Company"
                    }),
                    
                    new sap.m.Label({ text: "Leasing Company:", design: "Bold", required: false }),
                    new sap.m.ComboBox({ 
                        width: "94%",
                        placeholder: "Select Leasing Company"
                    }),
                ]
            }).addStyleClass("sapUiSmallMargin")
        ],
        buttons: [
            new sap.m.Button({
                icon: "sap-icon://clear-filter",
                text: "Clear Filter",
                press: function() {
                    clearFiltersSupplierInv();
                }
            }),
            new sap.m.Button({
                icon: "sap-icon://decline",
                text: "Cancel",
                press: function() {
                    oSupplierInvFilterDialog.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 = oSupplierInvFilterDialog.getContent()[0].getItems().filter(function(item) {
                        return item instanceof sap.m.ComboBox;
                    });
                    
                    
                    // Add filters for ComboBox fields (Workshop Group and License Number)
                    var comboBoxFields = ["ws_group_name","workshop_name", "license_number","city","rental_company_name","leasing_company_name"];
                    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 = oTableInvoiceWo.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([]);
                        }
                    }
                    
                    oSupplierInvFilterDialog.close();
                }
            })
        ]
    }).addStyleClass("sapUiSizeCompact");
    // Add this function to populate filter dropdowns
    function populateSuppInvFilterDropdowns() {
        try {
            var oModel = oTableInvoiceWo.getModel();
            if (!oModel) return;
            
            var aData = oModel.getProperty("/modelData");
            if (!aData) return;

            // Get unique workshop groups
            var uniqueWorkshopGroups = [...new Set(aData
                .map(item => item.ws_group_name)
                .filter(item => item && item.trim() !== "")
            )].sort();
            
            // Get unique workshop Name
            var uniqueWorkshopName = [...new Set(aData
                .map(item => item.workshop_name)
                .filter(item => item && item.trim() !== "")
            )].sort();

            // Get unique license plates
            var uniqueLicensePlates = [...new Set(aData
                .map(item => item.license_number)
                .filter(item => item && item.trim() !== "")
            )].sort();
        
            // Get unique City
            var uniqueCityName = [...new Set(aData
                .map(item => item.city)
                .filter(item => item && item.trim() !== "")
            )].sort();
             
            // Get unique Rental COmpany Name
            var uniqueRenatalCompany = [...new Set(aData
                .map(item => item.rental_company_name)
                .filter(item => item && item.trim() !== "")
            )].sort();
        
            // Get unique  leasing COmpany Name
            var uniqueLeasingCompany = [...new Set(aData
                .map(item => item.leasing_company_name)
                .filter(item => item && item.trim() !== "")
            )].sort();
        
            // Get unique Supplier invoice number
            // var uniqueSupplierInvoiceNumber = [...new Set(aData
            //     .map(item => item.supplier_invoice_number)
            //     .filter(item => item && item.trim() !== "")
            // )].sort();

            // Get the ComboBoxes
            var comboBoxes = oSupplierInvFilterDialog.getContent()[0].getItems()
                .filter(item => item instanceof sap.m.ComboBox);
            
            var oWorkshopGroupComboBox = comboBoxes[0];
            var oWorkshopComboBox = comboBoxes[1];
            var oLicensePlateComboBox = comboBoxes[2];
            // var oInvoiceNumberComboBox = comboBoxes[3];
            var oCityComboBox = comboBoxes[3];
            var oRentalComboBox = comboBoxes[4];
            var oLeasingComboBox = comboBoxes[5];

            // Clear existing items
            oWorkshopGroupComboBox.removeAllItems();
            oWorkshopComboBox.removeAllItems();
            oLicensePlateComboBox.removeAllItems();
            // oInvoiceNumberComboBox.removeAllItems();
            oCityComboBox.removeAllItems();
            oRentalComboBox.removeAllItems();
            oLeasingComboBox.removeAllItems();


            // Add items to Workshop Group ComboBox
            uniqueWorkshopGroups.forEach(function(group) {
                oWorkshopGroupComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });
           
            uniqueWorkshopName.forEach(function(group) {
                oWorkshopComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });

            // Add items to License Plate ComboBox
            uniqueLicensePlates.forEach(function(group) {
                oLicensePlateComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });
            
            uniqueCityName.forEach(function(group) {
                oCityComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });
            uniqueRenatalCompany.forEach(function(group) {
                oRentalComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });
            uniqueLeasingCompany.forEach(function(group) {
                oLeasingComboBox.addItem(new sap.ui.core.Item({
                    key: group,
                    text: group
                }));
            });
        


        } catch (error) {
            console.error("Error populating filter dropdowns:", error);
        }
    };
    // Add this function to clear filters
    function clearFiltersSupplierInv() {
        try {
            var aComboBoxes = oSupplierInvFilterDialog.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 = oTableInvoiceWo.getBinding("items");
            if (oBinding) {
                oBinding.filter([]);
            }
            sap.m.MessageToast.show("All filters have been cleared");
        } catch (error) {
            console.error("Error clearing filters:", error);
            sap.m.MessageBox.error("Error clearing filters. Please try again.");
        }
    }
        


    let oDialog1 = new sap.m.Dialog({
        contentWidth: "100%",
        contentHeight: "50%",
        draggable: true,
        resizable: true,
        title: oBundle.getText("Select_Workorder"),
        content: [oTableInvoiceWo],
        buttons: [
            new sap.m.Button({
                text: oBundle.getText("Add"), // Add button
                type: "Emphasized",
                press: function () {
                    var selectedItems = oTableInvoiceWo.getSelectedItems(); // Get selected items
                    var existingTokens = input.getTokens();
                    var selectedKeys = existingTokens.map(token => token.getKey());
                    var total_cost = roundToInt(workshop_estimate_input.getValue());
                    var tax;
                    selectedItems.forEach(function (item) {
                        let context = item.getBindingContext();
                        let data = context.getProperty("");
                        tax = data.tax;
                        let wo_amount = parseInt(data.supplier_cost) || 0;
                        
                        if (!selectedKeys.includes(data.wo_number)) {
                            total_cost += wo_amount;
                            input.addToken(new sap.m.Token({
                                key: data.id,
                                text: data.wo_number
                            }));
                        }
                    });

                    workshop_estimate_input.setValue(roundToInt(total_cost));
                    tax_input.setValue(tax)
                    oDialog1.close(); // Close the dialog after adding
                }
            }),
            new sap.m.Button({
                text: oBundle.getText("Close"),
                icon: "sap-icon://decline",
                press: function () {
                    oDialog1.close();
                }
            }),
        ],
    }).open();

    let tokenList = input.getTokens();
    let resultTokenList = grabSuppInvoiceWOJSONArray.filter(function (obj) {
        return !tokenList.some(token => token.getText() === obj.wo_number);
    });

    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: resultTokenList });
    oTableInvoiceWo.setModel(oModel);
    oTableInvoiceWo.bindItems({ path: "/modelData", template: oItemWoPickInvoice });
}




function updateSuppWorkorderAmount(invoiceNumber, callback) {
    // Get all items from the `invoiceSuppPriceWoOverview` table
    // var tableItems = invoiceSuppPriceWoOverview.getItems();
    var alltableItemdata1 = invoiceSuppPriceWoOverview.getModel().getData();
    var tableItems = alltableItemdata1['modelData']
    var completedUpdates = 0; // Counter for completed updates

    if (!tableItems || tableItems.length === 0) {
        console.warn("No items in the invoiceSuppPriceWoOverview table.");
        if (typeof callback === "function") {
            callback(); // Proceed with callback even if there's no data
        }
        return;
    }

    for (var i = 0; i < tableItems.length; i++) {
        var item = tableItems[i].getBindingContext().getObject(); 
        var wo_number = item.wo_number;
        var wo_id = item.wo_id;
        var invoice_amount = roundToInt(item.total_cost);
        // Perform the update for each work order
        Car_Workorder.update({ id:wo_id,supplier_invoice_number:invoiceNumber, supplier_invoice_amount:invoice_amount
        }).done(function () {
            completedUpdates++; // Increment the counter for successful updates

            // Check if all updates are complete
            if (completedUpdates === tableItems.length) {
                console.log("All work orders updated successfully.");
                if (typeof callback === "function") {
                    callback(); // Execute the callback after all updates
                }
            }
        }),function (error) {
            console.error("Error updating work order:", error);

            // Ensure callback is invoked even if updates fail
            completedUpdates++;
            if (completedUpdates === tableItems.length) {
                if (typeof callback === "function") {
                    callback();
                }
            }
        };
    }
}

function logSuppCurrentTokens(input) {
    var tokens = input.getTokens();
    var tokenValues = tokens.map(function (token) {
        return token.getKey()
    });

    var filterparts = woPartSuppInvoiceJSONArrary.filter(function(val,ind){
        return tokenValues.includes(val.wo_number)
    }  );
    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: filterparts });
    oTableSuppPartsInvoice.setModel(oModel);
    oTableSuppPartsInvoice.bindItems({ 
        path: "/modelData", 
        template: suppPartsInvoiceTemplate 
    });
    calculateSuppRowTotal1(oTableSuppPartsInvoice);

    // return tokenValues; // Optional: return the token values for further processing
};

// Function to calculate row total
/*
function calculateSuppRowTotal(oEvent) {
    var oItem = oEvent.getSource().getBindingContext().getObject();
    var materialCost = parseFloat(oItem.total_parts_cost || 0);
    var labourCost = parseFloat(oItem.labor_item_cost || 0);

    // Calculate total after discounts
    var materialTotal = materialCost //* (1 - materialDisc/100);
    var labourTotal = labourCost //* (1 - laborDisc/100);
    // var otherTotal = otherCost * (1 - otherDisc/100);

    var total = roundToInt(materialTotal + labourTotal)// + otherTotal);
    var tax_value = roundToInt((total * supplier_invoice_tax_value)/100);


    // Update the model
    var oModel = oEvent.getSource().getModel();
    var path = oEvent.getSource().getBindingContext().getPath();
    oModel.setProperty(path + "/total_cost", total + tax_value);
    oModel.setProperty(path + "/tax_value", tax_value);

    // Calculate totals across all rows
    var allData = oModel.getData().modelData;
    
    var totalMaterialCost = 0;
    var totalLaborCost = 0;
    
    allData.forEach(function(item) {
        // Material calculations
        var materialCost = parseFloat(item.total_parts_cost || 0);
        totalMaterialCost += materialCost;
        
        // Labor calculations
        var laborCost = parseFloat(item.labor_item_cost || 0);
        totalLaborCost += laborCost;
    });
    
    //Tax
    var totalTaxCost = roundToInt(((totalMaterialCost + totalLaborCost)*supplier_invoice_tax_value)/100);
    

    // Update summary fields
    totalMaterialCostInvoiceSupp.setValue(roundToInt(totalMaterialCost));
    totalLaborCostInvoiceSupp.setValue(roundToInt(totalLaborCost));
    totalTaxValueInvoiceSupp.setValue(roundToInt(totalTaxCost));
 
    // Calculate and update grand total
    var grandTotal = totalMaterialCost  + totalLaborCost  + totalTaxCost;
    grandTotalInvoiceSupp.setValue(roundToInt(grandTotal));
    updateSuppInvoiceWOOverview(allData);

};*/
function calculateSuppRowTotal1(oTableSuppPartsInvoice) {

    var oModel = oTableSuppPartsInvoice.getModel();
    var aTableData =  oTableSuppPartsInvoice.getBinding("items").getPath();
    var allData = oModel.getProperty(aTableData);
    console.log(allData)
    var totalMaterialCost = 0;
    var totalLaborCost = 0;
    var totalTaxCost = 0;

    
    allData.forEach(function(item) {
        // Material calculations
        var materialCost = parseFloat(item.total_parts_cost || 0);
        totalMaterialCost += materialCost;
        
        // Labor calculations
        var laborCost = parseFloat(item.labor_item_cost || 0);
        totalLaborCost += laborCost;
       
        //Tax
        totalTaxCost += roundToInt(item.tax_value);

    });
    
    //Tax
    // var totalTaxCost = roundToInt(((totalMaterialCost + totalLaborCost)*supplier_invoice_tax_value)/100);


    // Update summary fields
    totalMaterialCostInvoiceSupp.setValue(roundToInt(totalMaterialCost));
    totalLaborCostInvoiceSupp.setValue(roundToInt(totalLaborCost));
    totalTaxValueInvoiceSupp.setValue(roundToInt(totalTaxCost));
   
    
    // Calculate and update grand total
    var grandTotal = totalMaterialCost + totalLaborCost + totalTaxCost;
    grandTotalInvoiceSupp.setValue(roundToInt(grandTotal));
    updateSuppInvoiceWOOverview(allData);
    
};
function updateSuppInvoiceWOOverview(partsData){
    const groupedData = {};

    // Iterate over each item in the data
    partsData.forEach(item => {
        const woNumber = item.wo_number;
        const woIdInvoice = item.wo_id;

        // Initialize the group if it doesn't exist
        if (!groupedData[woNumber]) {
            groupedData[woNumber] = {
                wo_id:woIdInvoice,
                wo_number: woNumber,
                total_parts_cost: 0,
                labor_item_cost: 0,
                // other_cost: 0,
                tax_value:0,
                total_cost: 0,
                final_total_cost:0
            };
        }

        // Aggregate the values
        groupedData[woNumber].total_parts_cost += parseInt(item.total_parts_cost || 0);
        groupedData[woNumber].labor_item_cost += parseInt(item.labor_item_cost || 0, 10);
        // groupedData[woNumber].other_cost += parseInt(item.other_cost || 0, 10);
        groupedData[woNumber].tax_value += parseInt(item.tax_value || 0, 10);
        groupedData[woNumber].total_cost += parseFloat(item.total_cost || 0);
        groupedData[woNumber].final_total_cost += parseFloat(item.total_cost || 0);
    });

    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: groupedData });
    invoiceSuppPriceWoOverview.setModel(oModel);
    invoiceSuppPriceWoOverview.bindItems({ 
        path: "/modelData", 
        template: invoiceSuppPriceWoOverviewTemplate 
    });


    // // Convert the grouped object into an array
    // return Object.values(groupedData);
    // console.log(partsData)
};

function calculateSuppRowTotalView(oTableSuppPartsInvoice) {

    var oModel = oTableSuppPartsInvoice.getModel();
    var aTableData =  oTableSuppPartsInvoice.getBinding("items").getPath();
    var allData = oModel.getProperty(aTableData);
    console.log(allData)
    var totalMaterialCost = 0;
    var totalLaborCost = 0;
    var taxableValue = 0
    
    allData.forEach(function(item) {
        // Material calculations
        var materialCost = parseFloat(item.item_material_cost || 0);
        totalMaterialCost += materialCost;
        // Labor calculations
        var laborCost = parseFloat(item.item_labor_cost || 0);
        totalLaborCost += laborCost;

        var tax = roundToInt(item.item_labor_cost)
        
    
    });
    
    var totalTaxCost = roundToInt(((totalMaterialCost + totalLaborCost)*supplier_invoice_tax_value)/100);


    // Update summary fields
    totalMaterialCostInvoiceSupp.setValue(totalMaterialCost.toFixed(2));
    // totalMaterialDiscountInvoiceSupp.setValue(totalMaterialDiscount.toFixed(2));
    totalLaborCostInvoiceSupp.setValue(totalLaborCost.toFixed(2));
    // totalLaborDiscountInvoiceSupp.setValue(totalLaborDiscount.toFixed(2));
    // totalOtherCostInvoiceSupp.setValue(totalOtherCost.toFixed(2));
    // totalOtherDiscountInvoiceSupp.setValue(totalOtherDiscount.toFixed(2));
    totalTaxValueInvoiceSupp.setValue(roundToInt(totalTaxCost));

    // Calculate and update grand total
    var grandTotal = totalMaterialCost + totalLaborCost  + totalTaxCost;
    grandTotalInvoiceSupp.setValue(roundToInt(grandTotal));
    viewSuppInvoiceWOOverview(allData);
};
function viewSuppInvoiceWOOverview(partsData){
    const groupedData = {};

    // Iterate over each item in the data
    partsData.forEach(item => {
        const woNumber = item.wo_number;
        const woIdInvoice = item.wo_id;

        // Initialize the group if it doesn't exist
        if (!groupedData[woNumber]) {
            groupedData[woNumber] = {
                wo_id:woIdInvoice,
                wo_number: woNumber,
                total_parts_cost: 0,
                labor_item_cost: 0,
                // other_cost: 0,
                tax_value:0,
                total_cost: 0,
                final_total_cost:0
            };
        }

        // Aggregate the values
        groupedData[woNumber].total_parts_cost += parseInt(item.item_material_cost || 0);
        groupedData[woNumber].labor_item_cost += parseInt(item.item_labor_cost || 0, 10);
        // groupedData[woNumber].other_cost += parseInt(item.item_other_cost || 0, 10);
        groupedData[woNumber].tax_value += parseInt(item.tax_value || 0, 10);
        groupedData[woNumber].total_cost += parseFloat(item.item_total_cost || 0);
        groupedData[woNumber].final_total_cost += parseFloat(item.item_total_cost || 0);
    });

    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({ modelData: groupedData });
    invoiceSuppPriceWoOverview.setModel(oModel);
    invoiceSuppPriceWoOverview.bindItems({ 
        path: "/modelData", 
        template: invoiceSuppPriceWoOverviewTemplate 
    });


    // // Convert the grouped object into an array
    // return Object.values(groupedData);
    // console.log(partsData)
}

// function selectWorkorderInvoice(input, workshop_estimate_input) {
//     var oTableInvoiceWo = 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,
//         mode: sap.m.ListMode.MultiSelect, // Enable MultiSelect mode
//         columns: [
//             new sap.m.Column({ wrapping: true, width: "100px", header: new sap.m.Label({ text: oBundle.getText("Select"), design: sap.m.LabelDesign.Bold }) }),
//             new sap.m.Column({ wrapping: true, width: "120px", header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Workorder_Number"), design: sap.m.LabelDesign.Bold }), sortIndicator: "Descending" }),
//             new sap.m.Column({ wrapping: true, width: "130px", header: new sap.m.Label({ text: oBundle.getText("Workorder_Title"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Desktop", popinDisplay: "Inline", demandPopin: true }),
//             new sap.m.Column({ wrapping: true, width: "130px", header: new sap.m.Label({ text: oBundle.getText("License_Number"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Desktop", popinDisplay: "Inline", demandPopin: true }),
//             new sap.m.Column({ wrapping: true, header: new sap.m.Label({ text: oBundle.getText("Workshop_Number"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left", width: "120px" }),
//             new sap.m.Column({ wrapping: true, header: new sap.m.Label({ text: oBundle.getText("Workshop_Name"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left", width: "120px" }),
//             new sap.m.Column({ wrapping: true, header: new sap.m.Label({ text: oBundle.getText("Workshop_Group_Number"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left", width: "120px" }),
//             new sap.m.Column({ wrapping: true, header: new sap.m.Label({ text: oBundle.getText("Workshop_Group_Name"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left", width: "120px" }),
//         ],
//         headerToolbar: new sap.m.OverflowToolbar({
//             content: [
//                 new sap.m.ToolbarSpacer(),
//                 new sap.m.SearchField({
//                     placeholder: oBundle.getText("Search"),
//                     width: "300px",
//                     liveChange: function (event) {
//                         var oBinding = oTableInvoiceWo.getBinding("items");
//                         var searchStr = this.getValue();
//                         if (oBinding) {
//                             var oFilters = [
//                                 new sap.ui.model.Filter("ws_group_number", sap.ui.model.FilterOperator.Contains, searchStr),
//                                 new sap.ui.model.Filter("ws_group_name", sap.ui.model.FilterOperator.Contains, searchStr),
//                                 new sap.ui.model.Filter("workshop_name", sap.ui.model.FilterOperator.Contains, searchStr),
//                                 new sap.ui.model.Filter("workshop_number", sap.ui.model.FilterOperator.Contains, searchStr),
//                                 new sap.ui.model.Filter("wo_number", sap.ui.model.FilterOperator.Contains, searchStr),
//                                 new sap.ui.model.Filter("wo_title", 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",press: function () {
//                     funMultiFilterOpenWO(2,resultTokenList, oTableInvoiceWo,oItemWoPickInvoice);
//                 }})
//             ],
//         }),
//     });

//     var oItemWoPickInvoice = new sap.m.ColumnListItem({
//         cells: [
//             new sap.m.Text({ wrapping: true, text: "{wo_number}" }),
//             new sap.m.Text({ wrapping: true, text: "{wo_title}" }),
//             new sap.m.Text({ wrapping: true, text: "{license_number}" }),
//             new sap.m.Text({ wrapping: true, text: "{workshop_number}" }),
//             new sap.m.Text({ wrapping: true, text: "{workshop_name}" }),
//             new sap.m.Text({ wrapping: true, text: "{ws_group_number}" }),
//             new sap.m.Text({ wrapping: true, text: "{ws_group_name}" }),
//         ],
//     });

//     let oDialog1 = new sap.m.Dialog({
//         contentWidth: "100%",
//         contentHeight: "50%",
//         draggable: true,
//         resizable: true,
//         title: oBundle.getText("Select_Workorder"),
//         content: [oTableInvoiceWo],
//         buttons: [
//             new sap.m.Button({
//                 text: oBundle.getText("Add"), // Add button
//                 type: "Emphasized",
//                 press: function () {
//                     var selectedItems = oTableInvoiceWo.getSelectedItems(); // Get selected items
//                     var existingTokens = input.getTokens();
//                     var selectedKeys = existingTokens.map(token => token.getKey());
//                     var total_cost = 0;
//                     selectedItems.forEach(function (item) {
//                         let context = item.getBindingContext();
//                         let data = context.getProperty("");
                        
//                         let wo_amount = parseInt(data.workshop_cost) || 0;
//                         if (!selectedKeys.includes(data.wo_number)) {
//                             total_cost += wo_amount;
//                             input.addToken(new sap.m.Token({
//                                 key: data.id,
//                                 text: data.wo_number
//                             }));
//                         }
//                     });
//                     workshop_estimate_input.setValue(roundToInt(total_cost));
//                     oDialog1.close(); // Close the dialog after adding
//                 }
//             }),
//             new sap.m.Button({
//                 text: oBundle.getText("Close"),
//                 icon: "sap-icon://decline",
//                 press: function () {
//                     oDialog1.close();
//                 }
//             }),
//         ],
//     }).open();

//     let tokenList = input.getTokens();
//     let resultTokenList = grabCompletedWOJSONArray.filter(function (obj) {
//         return !tokenList.some(token => token.getText() === obj.wo_number);
//     });

//     var oModel = new sap.ui.model.json.JSONModel();
//     oModel.setData({ modelData: resultTokenList });
//     oTableInvoiceWo.setModel(oModel);
//     oTableInvoiceWo.bindItems({ path: "/modelData", template: oItemWoPickInvoice });
// }





var oAppSupplierInvoicePage =  new sap.uxap.ObjectPageLayout({id:'supplier_inv_page', headerContentPinnable: false, 
    preserveHeaderStateOnScroll: true, useIconTabBar: true, toggleHeaderOnTitleClick: true,
    headerTitle: new sap.uxap.ObjectPageDynamicHeaderTitle({
        heading: [new sap.m.Title({ text: oBundle.getText("Supplier_Attach_Invoice"), level: "H1", titleStyle: "H2" })] }),
    sections: [
        new sap.uxap.ObjectPageSection({id:"SUPP1", showTitle: true, title: oBundle.getText("Open"),
            subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTableSupplierOpenInvoice]})
        }),      
        new sap.uxap.ObjectPageSection({id:"SUPP2", showTitle: true, title: oBundle.getText("Under_Review"),
            subSections: new sap.uxap.ObjectPageSubSection({ blocks: [supplierInvoiceCompare]})
        }),
        // new sap.uxap.ObjectPageSection({id:"SUPP3", showTitle: true, title: oBundle.getText("Completed"),
        //     subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTableSupplierCompletedInvoice]})
        // }),
    ],
    
    navigate: function (event) {
        var mID = event.getParameter('section').getId();
       
        // funGetSupplierWoParts();
        // if(mID == "SINV1"){
        //     get4WCompletedInvoice();
        // }else if (mID == "SINV2"){
        //     get4WReviewInvoice();
        // }else if (mID == "SINV3"){
        //     get4WCompletedSuppInvoice();
        // }

    }

});






var woPartSuppInvoiceJSONArrary = [];
/*
function getWoSuppInvoicePartsData(woArray){

    var wo_list = woArray;
    const workorderFilter = wo_list.map(num => `wo_id eq '${num}'`).join(" or ");
    const filterQuery = `master_email eq '${emailUser}' and part_type eq 'Supplier' and (${workorderFilter})`;
    
    Car_Workorder_Part
        .where(filterQuery)
        .take(1000)
        .read()
        .done(function (results) {

            let filterParts = results;
            var oModel = new sap.ui.model.json.JSONModel();
            oModel.setData({ modelData: filterParts });
            oTableSuppPartsInvoice.setModel(oModel);
            oTableSuppPartsInvoice.bindItems({ 
                path: "/modelData", 
                template: suppPartsInvoiceTemplate 
            });
            calculateSuppRowTotal1(oTableSuppPartsInvoice);
    
            woPartSuppInvoiceJSONArrary = filterParts;

        }
    )

    // Car_Workorder_Part.where({master_email:emailUser,part_type:"Supplier"}).take(2000).orderByDescending("createdAt").read().done(function (result) {
    //     // console.log(result)
        
    //     let filterParts = result.filter(a=> woArray.includes(a.wo_number));
    //     var oModel = new sap.ui.model.json.JSONModel();
    //     oModel.setData({ modelData: filterParts });
    //     oTableSuppPartsInvoice.setModel(oModel);
    //     oTableSuppPartsInvoice.bindItems({ 
    //         path: "/modelData", 
    //         template: suppPartsInvoiceTemplate 
    //     });
    //     calculateSuppRowTotal1(oTableSuppPartsInvoice);

    //     woPartSuppInvoiceJSONArrary = filterParts;

    // })
};*/

function getSuppInvoiceItemsData(objData,tableTemplate){

    Car_Invoice_Item.where({master_email:emailUser,invoice_id:objData['id']}).take(1000).orderByDescending("createdAt").read().done(function (results) {
        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oTableSuppPartsInvoice.setModel(oModel);
        oTableSuppPartsInvoice.bindItems({ 
            path: "/modelData", 
            template: tableTemplate 
        });
        calculateSuppRowTotalView(oTableSuppPartsInvoice);
    })
}


var invoiceSuppOpen4WJSONData = [];
function get4WSuppOpenInvoice(){
    oTableSupplierOpenInvoice.setBusy(true);

    getAllOpenInvoice("Supplier",oTableSupplierOpenInvoice);
    // Car_Invoice.where({master_email:emailUser,status:"Open",invoice_type:"Supplier"}).take(1000).orderByDescending("createdAt").read().done(function (results) {
    //     // console.log(results)
    //     invoiceSuppOpen4WJSONData = results;            

    //     var oModel = new sap.ui.model.json.JSONModel();
    //     oModel.setData({ modelData: results });
    //     oTableSupplierOpenInvoice.setModel(oModel);
    //     oTableSupplierOpenInvoice.bindItems({ path: "/modelData", template : invoiceSupOpen4WTemplate });
    //     oTableSupplierOpenInvoice.setBusy(false);
    // })    
};
/*
var invoiceSuppReview4WJSONData = [];
function get4WSuppReviewInvoice(){
    oTableSupplierReviewInvoice.setBusy(true);
    Car_Invoice.where({master_email:emailUser,status:"Under Review",invoice_type:"Supplier"}).take(1000).orderByDescending("createdAt").read().done(function (results) {
        // console.log(results)
        invoiceSuppOpen4WJSONData = results;            

        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: results });
        oTableSupplierReviewInvoice.setModel(oModel);
        oTableSupplierReviewInvoice.bindItems({ path: "/modelData", template : invoiceSupp4WTemplateReview });
        oTableSupplierReviewInvoice.setBusy(false);
    })
};*/

var grabSuppInvoiceAllWOJSONArray = [];
var grabSuppInvoiceWOJSONArray = [];
function getSupplierClosedWorkorder(){

    get_closed_workorder_supplier_invoice();
    // Car_Workorder.where({master_email:emailUser,status:"Closed",supplier_wo_flag:"Supplier",supplier_id:oxmaint_supplier_id}).take(1000).orderByDescending("createdAt").read().done(function (results) {
    // Car_Workorder.where(filterQueryGrabSuppInvWO,"Closed").take(2000).orderByDescending("createdAt").read().done(function (results) {
    //     result = results.filter(a=>a.supplier_inv_pick != 'Done');
    //     console.log(result)
    //     grabSuppInvoiceWOJSONArray = result; 
    // })
}


var invoiceSuppCompleted4WJSONData = [];
function get4WCompletedSuppInvoice(){
    invoiceSuppCompleted4WJSONData = [];
    oTableSupplierCompletedInvoice.setBusy(true);
    Car_Workorder.where({master_email:emailUser,wo_status:"GRN",supplier_wo_flag:"Supplier"}).take(2000).orderByDescending("createdAt").read().done(function (woresults) {

        if(woresults.length > 0){
            woresults = woresults.map(item => item.wo_number);
            Car_Invoice.where({master_email:emailUser,status:"Under Review",invoice_type:"Supplier"}).take(2000).orderByDescending("createdAt").read().done(function (results) {

                results.forEach(invoice => {
                    // Extract wo_number array from invoice
                    const invoiceWorkOrders = invoice.wo_number.split('^'); // Assuming this is an array
               
                    // Check if all workorders in this invoice exist in woresults
                    const allWorkOrdersExist = invoiceWorkOrders.every(wo => woresults.includes(wo));
                
                    if (allWorkOrdersExist) {
                        invoiceSuppCompleted4WJSONData.push(invoice);
                    } 
                });            
            

                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: invoiceSuppCompleted4WJSONData });
                oTableSupplierCompletedInvoice.setModel(oModel);
                oTableSupplierCompletedInvoice.bindItems({ path: "/modelData", template : supplier4WTemplateCompleted });
                oTableSupplierCompletedInvoice.setBusy(false);
            })    
        }else{
            oTableSupplierCompletedInvoice.setBusy(false);
        }
    })
        
   
};
