// var Car_Invoice =  client.getTable('Car_Invoice');
// var Car_Invoice_Item =  client.getTable('Car_Invoice_Item');


//Open Invoice
var oTable4WInvoiceOpen = 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}),
        // 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 = 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 invoice4WTemplate = 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);
                    displayMenu4WInvoice(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}"}),
         
         ]
});

//Review Invoice
var oTable4WInvoiceReview = 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),
                        ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
        
            }),
        ]
      })
});
var invoice4WTemplateReview =  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);
                displayMenu4WInvoice(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}"}),
         
         ]
});


//Complete Invoice
var oTable4WInvoiceCompleted = 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("GRN_Number"), design: sap.m.LabelDesign.Bold}),
        // minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
        // new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("GRN_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 = oTable4WWorkshop.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),
                        ];
                        var filterObj = new sap.ui.model.Filter(oFilters, false);
                        oBinding.filter(filterObj);
                    } else {
                        oBinding.filter([]);
                    }
                }
        
            }),
        ]
      })
});
var invoice4WTemplateCompleted =  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);
                    displayMenu4WInvoice(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}"}),
        //   new sap.m.Label({wrapping:true,text: "{grn_number}"}),
        //   new sap.m.Label({wrapping:true,
        //     // text: "{grn_date}"
        //     text: { path: "grn_date",
        //         formatter: function (grn_date) {
        //             if(nullCheckAll(grn_date)){
        //                return formatDateToDDMMMYYYY(grn_date);
        //             }
        //         }}
        //     }),
         
         ]
});

// oTable4WInvoiceCompleted.destroyHeaderToolbar(); 

//Reopen Invoice
// var oTable4WInvoiceReopen = oTable4WInvoiceReview.clone();



//Archive Invoice
// var oTable4WInvoiceArchive = oTable4WInvoiceOpen.clone();
// oTable4WInvoiceArchive.destroyHeaderToolbar(); 
// var invoice4WTemplateArchive = invoice4WTemplate.clone();


//Invoice GRN Workorder
var oTable4WAllInvoiceGRN = oTableWorkorder.clone();
var oTable4WAllInvoiceGRNTemplate = workorderTemplate.clone();
// oTable4WAllInvoiceGRN.removeColumn(0);
oTable4WAllInvoiceGRNTemplate.removeCell(0); 
oTable4WAllInvoiceGRNTemplate.insertCell(new sap.m.Button({
    type: "Emphasized",
    icon: "sap-icon://action",
    text: "",
    press: function (event) {
        var model = this.getModel();
        var path = event.getSource().getBindingContext().getPath();
        var obj = model.getProperty(path);
        displayMenuWorkOrderViewOnly(event, obj);
    }
}), 0);

// oTable4WAllWO.removeColumn(0);
// oTable4WAllWOTemplate.removeCell(0);

oTable4WAllInvoiceGRN.destroyHeaderToolbar();
oTable4WAllInvoiceGRN.setHeaderToolbar(
  new sap.m.Toolbar({
    content: [
      new sap.m.ToolbarSpacer(),
      new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px",
        liveChange: function (event) {
          var oBinding = oTable4WAllInvoiceGRN.getBinding("items");
          var searchStr = this.getValue();
          if (oBinding) {
            var oFilters = [
              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),
              new sap.ui.model.Filter("wo_memo",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("city",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("license_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("chassis_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("engine_number",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("model",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("make",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("vehicle_color",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("rental_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("leasing_company_name",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_id",sap.ui.model.FilterOperator.Contains,searchStr),
              new sap.ui.model.Filter("assigned_name",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("ws_group_number",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),
            ];
            var filterObj = new sap.ui.model.Filter(oFilters, false);
            oBinding.filter(filterObj);

            //  Additional logic for external call
            if((searchStr.startsWith("4W2") || searchStr.startsWith("2W2")) && searchStr.length > 13) {

                setTimeout(function () {
                    var items = oTable4WAllInvoiceGRN.getItems(); //For All table
                    var visibleItems = items.filter(function (item) {
                        return item.getVisible(); // Only visible items
                    });

                    if (visibleItems.length === 0) {
                        busyDialog.open();
                        sap.m.MessageToast.show('Getting Data From DB.');
                        funGetWorkorderDetailsFromDb(searchStr, 'INVOICEGRNCOMPARE');//grabGrnWOJSONArray, oTable4WGrnWO, workorderTemplate,
                    }
                }, 300); // Small delay to let filtering apply
            }
          } else {
            oBinding.filter([]);
          }
        },
      }),
      new sap.m.Button({
        icon: "sap-icon://filter",
        press: function () {
          funMultiFilterOpenWO(
            2,

            grabGrnWOJSONArray,
            oTable4WAllInvoiceGRN,
            oTable4WAllInvoiceGRNTemplate
          );
        },
      }),
      
    ],
  })
);




function displayMenu4WInvoice(event,obj){
    var oMenu = new sap.m.Menu({
        items: [
            new sap.m.MenuItem({icon: "sap-icon://show",text: oBundle.getText("View"),key: "0"}),
            // new sap.m.MenuItem({icon: "sap-icon://edit",text: oBundle.getText("Update"),key: "1"}),
            // new sap.m.MenuItem({icon: "sap-icon://add-activity",text: oBundle.getText("Add Invoice Item"),key: "3"}),
        ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "0") { 
                if(obj['status'] == "Open"){
                    createGrabInvoiceHeader(3,obj);//View Invoice header
                }else{
                    createGrabInvoice(2,obj); //View Invoice Part Items 
                }
            } else if (oItem == "1") {
                createGrabInvoiceHeader(2,obj); //Update Invoice header
            } else if (oItem == "2") {
                var oDialog = new sap.m.Dialog({
                    title: oBundle.getText("Alert"),
                    state: sap.ui.core.ValueState.Error,
                    content: [new sap.m.Label({ text: oBundle.getText("Sure_You_want_to_delete") })],
                    buttons: [
                                new sap.m.Button({text: oBundle.getText("Delete"),icon: "sap-icon://delete",
                                    press: function () {
                                        busyDialog.open();
                                        Car_Invoice.del({ id: obj['id'] }).done(function () {
                                            if(obj['status'] == "Open"){
                                                get4WOpenInvoice();
                                            // }else if(obj['status'] == "Under Review"){
                                            //     get4WReviewInvoice();
                                            // }else if(obj['status'] == "Reopen"){
                                            //     get4WReopenInvoice();
                                            }else if(obj['status'] == "Completed"){
                                                get4WCompletedInvoice();
                                            }
                                            oDialog.close();
                                            busyDialog.close();
                                        });
                                    }
                                }),
                                new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
                                    press: function () {
                                        oDialog.close();
                                    }
                                })
                            ]
                }).open();
            
            } else if (oItem == "3") {
                createGrabInvoice(1,obj); // Add Invoice Items
            } 
            /*else if (oItem == "4"){
                markCompleteInvoice(obj);
                
            } else if (oItem == "5"){
                var oDialog = new sap.m.Dialog({
                    title: oBundle.getText("Alert"),
                    state: sap.ui.core.ValueState.Error,
                    content: [new sap.m.Label({ text: oBundle.getText("Do_you_want_to_Reopen_this_Invoice") +" : "+ obj['invoice_number'] })],
                    buttons: [
                                new sap.m.Button({text: oBundle.getText("Reopen"),icon: "sap-icon://future",
                                    press: function () {
                                        busyDialog.open();
                                        Car_Invoice.update({ id: obj['id'],status:"Reopen" }).done(function () {
                                            get4WReviewInvoice();
                                            get4WReopenInvoice();

                                            oDialog.close();
                                            busyDialog.close();
                                        });
                                    }
                                }),
                                new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
                                    press: function () {
                                        oDialog.close();
                                    }
                                })
                            ]
                }).open();
            }else if (oItem == "6"){
                updateGrabInvoice(1,obj);
            }*/
        }
    });

    // if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('delete_master_data_part_and_labour') != -1)){
        // }else{
            //     sap.m.MessageToast.show("Delete Access not provided.");
            // }
            
    // if(obj['status'] != "Under Review" || obj['status'] != "Completed"){
        // oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://edit",text: oBundle.getText("Update"),key: "1"}));
        // }
    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"}));
    }
    /*
    else if(obj['status'] == "Under Review"){
        oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://complete",text: oBundle.getText("Reopen"),key: "5"}));
        oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://future",text: oBundle.getText("Mark_As_Complete"),key: "4"}));
    }else if(obj['status'] == "Reopen"){
        oMenu.addItem(new sap.m.MenuItem({icon: "sap-icon://add-activity",text: oBundle.getText("Update_Invoice_Item"),key: "6"}));
    }*/

    // getDeleteMenu(oMenu,"2");
    oMenu.openBy(event.getSource());
}


/*
function markCompleteInvoice(obj){

    var grn_number = new sap.m.Input({});
    var grn_date = new sap.m.DatePicker({width:"100%",displayFormat: "dd-MMM-yyyy",valueFormat:"dd-MMM-yyyy"}).attachBrowserEvent("keydown", function (oEvent) {
        oEvent.preventDefault(); 
    });
    grn_date.setMinDate(new Date());
    var grn_note = new sap.m.Input({});

    var oFormInvoiceComplete =  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: new sap.m.Label({required:true,text:oBundle.getText("GRN_Number")}),fields: [grn_number]}),
                    new sap.ui.layout.form.FormElement({label: new sap.m.Label({required:true,text:oBundle.getText("GRN_Date")}),fields: [grn_date]}),
                    new sap.ui.layout.form.FormElement({label: new sap.m.Label({required:true,text:oBundle.getText("Note")}),fields: [grn_note]}),
                    
            ]})
        ]});

    var addCompleteBtn = new sap.m.Button({text: oBundle.getText("Complete_Invoice"),
        press: function (oEvent) {
            let partsSplitWO = obj['wo_number'].split("^");
            let grn_number_value = grn_number.getValue();
            let grn_date_value = grn_date.getValue();
            let grn_note_value = grn_note.getValue();

            if(!nullCheckAll(grn_number_value)){
                sap.m.MessageBox.error(oBundle.getText("Enter_GRN_Number"));
                busyDialog.close();
                return;
            };
            if(!nullCheckAll(grn_date_value)){
                sap.m.MessageBox.error(oBundle.getText("Enter_GRN_Date"));
                busyDialog.close();
                return;
            };
            
            
            busyDialog.open();
            let updated_date = getIndonesianTime();
            partsSplitWO.forEach((item, index) => {
                Car_Workorder.update({ id:item, wo_status: "GRN" }).done(() => {
                    Car_Workorder_Status.insert({ master_email:emailUser, wo_number:item, wo_id: item, wo_status: "GRN",
                        changed_date: updated_date, changed_by: operatedID
                    }).done(function () { });

                    if (index === partsSplitWO.length) {
                        Car_Invoice.update({id:obj['id'],status:"Completed",grn_number:grn_number_value,grn_date:grn_date_value,grn_note:grn_note_value}).done(function () {
                            getClosedWorkorder();
                            getGrnWorkorder();
                            get4WReviewInvoice();
                            get4WCompletedInvoice
                            busyDialog.close();
                            oDialog12.close();
                        }, failure);
                    }
                });
            });
            
        }
    });
        
    
    var oDialog12 = new sap.m.Dialog({
        title: oBundle.getText("Complete_Invoice") + " - " + obj['invoice_number'],
        content: [oFormInvoiceComplete],
        buttons: [
            addCompleteBtn,
                new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",
                    press: function () {
                        oDialog12.close();
                    }
                })
            ]
    }).open();
}*/

var totalMaterialCostInvoice = new sap.m.Input({ enabled: false, value: "0.00" });
// var totalMaterialDiscountInvoice = new sap.m.Input({ enabled: false, value: "0.00" })
var totalLaborCostInvoice = new sap.m.Input({ enabled: false, value: "0.00" });
// var totalLaborDiscountInvoice = new sap.m.Input({ enabled: false, value: "0.00" });
var totalTaxValueInvoice = new sap.m.Input({ enabled: false, value: "0.00" });
var grandTotalInvoice = new sap.m.Input({ enabled: false, value: "0.00" });
// var selectedWOInvoice = [];




//Invoice Parts Details
var oTablepartsInvoice = 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("Labour_Cost"), 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({wrapping:true, text: oBundle.getText("Final_Material_Cost"), design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Final_Labor_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("Final_Total_Cost"), 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
            })
        ],
     
    })
});
oTablepartsInvoice.getHeaderToolbar().addStyleClass("customHeaderToolbarInvoice");
var partsInvoiceTemplate = new sap.m.ColumnListItem({
    cells: [
       

        new sap.m.Text({ text: "{wo_number}" }),
        new sap.m.Text({ text: "{part_name}" }),
        new sap.m.Input({ enabled:false, type: "Number", value: "{total_parts_cost}"}),
        new sap.m.Input({ enabled:false, type: "Number", value: "{labor_item_cost}"}),
        new sap.m.Input({ enabled:false, type: "Number", value: "{total_cost}"}),
      
        // Labour Cost (Input)
        new sap.m.Input({
            type: "Number",
            value: "{final_material_cost}",
            maxLength:99999999999,
            change: function(oEvent) {
                
                var sValue = oEvent.getParameter("value");
                if (sValue > 99999999999) {
                    sap.m.MessageToast.show("Maximum character limit " + 99999999999 + " reached.");
                }
                let roundedValue = roundToInt(sValue);
                oEvent.getSource().setValue(roundedValue);
                calculateRowTotal(oEvent);
            }
        }),
        new sap.m.Input({
            type: "Number",
            value: "{final_labor_cost}",
            maxLength:99999999999,
            change: function(oEvent) {
                
                var sValue = oEvent.getParameter("value");
                if (sValue > 99999999999) {
                    sap.m.MessageToast.show("Maximum character limit " + 99999999999 + " reached.");
                }
                let roundedValue = roundToInt(sValue);
                oEvent.getSource().setValue(roundedValue);
                calculateRowTotal(oEvent);
            }
        }),
    

        new sap.m.Text({ text: "{tax_value}" }),
        // Total (Text - calculated)
        new sap.m.Text({ text: "{final_total_cost}" })
    ]
});
var partsInvoiceViewTemplate = new sap.m.ColumnListItem({
    cells: [

        new sap.m.Text({ text: "{wo_number}" }),
        new sap.m.Text({ text: "{part_name}" }),
        
        new sap.m.Text({ text: "{item_material_cost}" }),
        new sap.m.Text({ text: "{item_labor_cost}" }),
        new sap.m.Text({ text: "{item_total_cost}" }),
        new sap.m.Text({ text: "{item_final_material_cost}" }),
        new sap.m.Text({ text: "{item_total_labor_cost}" }),
        new sap.m.Text({ text: "{item_tax_value}" }),
        new sap.m.Text({ text: "{item_final_total_cost}" }),

    ]
});
var partsInvoiceUpdateTemplate = new sap.m.ColumnListItem({
    cells: [

        new sap.m.Text({ text: "{wo_number}" }),
        new sap.m.Text({ text: "{part_name}" }),
        new sap.m.Input({ enabled:false, type: "Number", value: "{item_material_cost}"}),
        new sap.m.Input({ enabled:false, type: "Number", value: "{item_labor_cost}"}),
        new sap.m.Input({ enabled:false, type: "Number", value: "{item_total_cost}"}),
      
        // Labour Cost (Input)
        new sap.m.Input({
            type: "Number",
            value: "{item_final_material_cost}",
            maxLength:99999999999,
            change: function(oEvent) {
                
                var sValue = oEvent.getParameter("value");
                if (sValue > 99999999999) {
                    sap.m.MessageToast.show("Maximum character limit " + 99999999999 + " reached.");
                }
                let roundedValue = roundToInt(sValue);
                oEvent.getSource().setValue(roundedValue);
                calculateUpdateRowTotal(oEvent);
            }
        }),
        new sap.m.Input({
            type: "Number",
            value: "{item_total_labor_cost}",
            maxLength:99999999999,
            change: function(oEvent) {
                
                var sValue = oEvent.getParameter("value");
                if (sValue > 99999999999) {
                    sap.m.MessageToast.show("Maximum character limit " + 99999999999 + " reached.");
                }
                let roundedValue = roundToInt(sValue);
                oEvent.getSource().setValue(roundedValue);
                calculateUpdateRowTotal(oEvent);
            }
        }),
    

        new sap.m.Text({ text: "{item_tax_value}" }),
        // Total (Text - calculated)
        new sap.m.Text({ text: "{item_final_total_cost}" })

    ]
});

//Workorder price Overview
var invoicePriceWoOverview = 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("Total"), design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Final_Material_Cost"), design: sap.m.LabelDesign.Bold})}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Final_Labor_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("Final_Total_Cost"), 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 invoicePriceWoOverviewTemplate = 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: "{total_cost}"}),
        new sap.m.Text({ text: "{final_material_cost}"}),
        new sap.m.Text({ text: "{final_labor_cost}"}),
        new sap.m.Text({ text: "{tax_value}"}),
        new sap.m.Text({ text: "{final_total_cost}"}),
    ]
});


//Add Update Invoice Header
function createGrabInvoiceHeader(src,obj){
    let reqLbl = new sap.m.Label({ required: true });
    let oLbl = new sap.m.Label({});

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

    var oIFInvoice3 = new sap.m.Input({value:"0",type:'Number',enabled:false}); // Workshop Estimate
    var oIFInvoice4 = new sap.m.DatePicker({
        width: "100%",
        minDate: new Date(),
        displayFormat: "dd-MMM-yyyy",
        valueFormat: "dd-MMM-yyyy",
        enabled:false,
        change: function (oEvent) {
            // Validate if the date is valid; otherwise, clear it
            if (!oEvent.getParameter("valid")) {
                oIFInvoice4.setValue(""); // Clear invalid input
                sap.m.MessageToast.show("Please select a valid date from the calendar.");
            }
        }
    }).attachBrowserEvent("keydown", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });
    oIFInvoice4.setDateValue(new Date());
    var oIFInvoice5 = new sap.m.Input({visible:true,enabled:false});
    var workorderInvoiceDB = new sap.m.MultiInput({ showSuggestion: true, fieldWidth: "100%",
        showValueHelp: true,valueHelpOnly: true,
        valueHelpRequest: function () { selectWorkorderInvoice(workorderInvoiceDB,oIFInvoice3, oIFInvoice5); },
        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){
                    logCurrentTokens(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 (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("^");
        
                    if (src != 1) {
                        removedTokens.forEach(token => {
                            Car_Workorder.update({ id: token.getKey(), wo_status: "Completed" }).done(() => {
                                Car_Workorder_Status.insert({
                                    master_email: emailUser,
                                    wo_number: token.getText(),
                                    wo_id: token.getKey(),
                                    wo_status: "Completed",
                                    changed_date: updated_date,
                                    changed_by: operatedID
                                }).done(() => {
                                    let getWOCost = [...grabCompletedWOJSONArray, ...grabClosedWOJSONArray].filter(a => a.id === token.getKey());
                                    if (getWOCost.length > 0) {
                                        var updatedEstimateCost = roundToInt(oIFInvoice3.getValue()) - roundToInt(getWOCost[0]['workshop_cost']);
                                        oIFInvoice3.setValue(updatedEstimateCost);
                                        sap.m.MessageBox.success(oBundle.getText("Workorder_Moved_to_Completed_status"));
                                        busyDialog.close();
                                        Car_Invoice.update({
                                            id: obj['id'],
                                            wo_number: remainingTexts,
                                            wo_id: remainingKeys,
                                            workshop_estimate: updatedEstimateCost
                                        }).done(() => {
                                            get4WOpenInvoice();
                                            getCompletedWorkorder();
                                            getClosedWorkorder();
                                        });

                                    }
                                   
                                });
                            });
                        });
                    } else {
                        busyDialog.close();
                        removedTokens.forEach(token => {
                            let getWOCost = [...grabCompletedWOJSONArray, ...grabClosedWOJSONArray].filter(a => a.id === token.getKey());
                            if (getWOCost.length > 0) {
                                var updatedEstimateCost = roundToInt(oIFInvoice3.getValue()) - roundToInt(getWOCost[0]['workshop_cost']);
                                oIFInvoice3.setValue(updatedEstimateCost);
                            }
                        });
                    }
                }, 0);
            }
        }
        
    
    });


    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: [oIFInvoice1]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: reqLbl.clone().setText(oBundle.getText("Workorder_Number")),
                        // fields: [oIFInvoice2]
                        fields: [workorderInvoiceDB]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Workshop_Estimate")),
                        fields: [oIFInvoice3]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: reqLbl.clone().setText(oBundle.getText("Invoice_Date")),
                        fields: [oIFInvoice4]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: reqLbl.clone().setText(oBundle.getText("Tax")),
                        fields: [oIFInvoice5]
                    }),
                ]
            })
        ]
    });


    let addInvoceBtn = new sap.m.Button({ 
        text: oBundle.getText("Add"), 
        icon: "sap-icon://add",
        press: function() {
            
            let invoice_number = oIFInvoice1.getValue();
            let workshop_estimate = oIFInvoice3.getValue();
            let invoice_date = oIFInvoice4.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(workshop_estimate)){ sap.m.MessageBox.error(oBundle.getText("Enter Workshop Estimate.")); 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:"Workshop",
                            labor_discount:"", total_cost:"",tax:oIFInvoice5.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);

                        // Car_Invoice.insert(insertItems).done(function () {
                        //     get4WOpenInvoice();
                            
                        //     const partsSplitWO = wo_id.split("^");
                        //     const partsSplitWONumber = wo_number.split("^");

                        //     partsSplitWO.forEach((item, index) => {
                        //         console.log(index)
                        //         console.log( partsSplitWO.length)
                        //         Car_Workorder.update({ id:item, wo_status: "Closed" }).done(() => {
                        //             Car_Workorder_Status.insert({ master_email:emailUser, wo_number:partsSplitWONumber[index], wo_id: item, wo_status: "Closed",
                        //                 changed_date: created_date, changed_by: operatedID
                        //             }).done(function () { });
                        //             if (index == partsSplitWO.length - 1) {
                        //                 getCompletedWorkorder();
                        //                 getClosedWorkorder();
                        //                 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,invoice_type:"Workshop",
                        workshop_estimate:workshop_estimate, invoice_date:invoice_date,
                        material_cost:"", material_discount:"", labor_cost:"",
                        labor_discount:"",tax:oIFInvoice5.getValue(),
                        updated_date:created_date,updated_by:operatedID
                    };
                    updateInvoiceHeaderApi(updateItems,oDialog,obj);
                    // Car_Invoice.update(updateItems).done(function () {
                    //     if(obj['status'] == "Open"){
                    //         get4WOpenInvoice();
                    //     };
                    //     const partsSplitWO = wo_id.split("^");
                    //     const partsSplitWONumber = wo_number.split("^");
                    
                    //     partsSplitWO.forEach((item, index) => {

                    //         Car_Workorder.update({ id:item, wo_status: "Closed" }).done(() => {
                    //             Car_Workorder_Status.insert({ master_email:emailUser, wo_number:partsSplitWONumber[index], wo_id: item, wo_status: "Closed",
                    //                 changed_date: created_date, changed_by: operatedID
                    //             }).done(function () { });
                    //             if (index === partsSplitWO.length - 1) {
                    //                 getCompletedWorkorder();
                    //                 getClosedWorkorder();
                    //                 busyDialog.close();
                    //                 oDialog.close();
                    //             }
                    //         });
                    //     });
                       
                    // }, failure);
                }
                /*else{
                    Car_Invoice.update({
                        id:obj['id'],
                        wo_number:wo_number, invoice_number:invoice_number,
                        workshop_estimate:workshop_estimate, invoice_date:invoice_date,
                        material_cost:"", material_discount:"", labor_cost:"",
                        labor_discount:"", other_cost:"", other_discount:"",
                        updated_date:created_date,updated_by:operatedID
                    }).done(function () {
                        
                        Car_Invoice_Item.where({master_email:emailUser,invoice_id:obj['id']}).skip(skipRowVehicle4w).take(200).orderByDescending("createdAt").read().done(function (results) {
                            if(results.length > 0){
                                results.forEach((item, index) => {
                                    Car_Workorder_Status.update({ id:item.id,invoice_number:invoice_number,
                                        updated_date: created_date, updated_by: operatedID
                                    }).done(function () { });
                                    if (index === results.length - 1) {
                                        if(obj['status'] == "Reopen"){
                                            get4WReopenInvoice();
                                        }else if(obj['status'] == "Under Review"){
                                            get4WReviewInvoice();
                                        };
                                        busyDialog.close();
                                        oDialog.close();
                                    }
                                })
                            }
                        });
                        // const partsSplitWO = wo_number.split("^");
                        // console.log(partsSplitWO);
                        // partsSplitWO.forEach((item, index) => {
                        //     console.log(item)
                        //     Car_Workorder.update({ id:item, wo_status: "Closed" }).done(() => {
                        //         Car_Workorder_Status.insert({ master_email:emailUser, wo_number:item, wo_id: item, wo_status: "Closed",
                        //             changed_date: created_date, changed_by: operatedID
                        //         }).done(function () { });
                        //         if (index === partsSplitWO.length - 1) {
                        //             getCompletedWorkorder();
                        //             getClosedWorkorder();
                        //             busyDialog.close();
                        //             oDialog.close();
                        //         }
                        //     });
                        // });
                       
                    }, failure);
                }*/
            }

        }
    });

    

    let oDialog = new sap.m.Dialog({ 
        contentWidth: "80%", 
        contentHeight: "30%", 
        draggable: true, 
        resizable: true,
        title: oBundle.getText("Create_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
        
        // Car_Invoice.where({master_email:emailUser}).take(1).orderByDescending("createdAt").read().done(function (results) {
        //     if(results){
        //         console.log(results)
        //         let latestNumber = results[0]['invoice_number'];
        //         let numericPart = roundToInt(latestNumber.slice(3));  // Extract the numeric part and convert to an integer
        //         let newInvoiceNumber = numericPart + 1;          // Add 1 to the numeric part
        //         oIFInvoice1.setValue("INV" + newInvoiceNumber);
        //     }    
        // });
    }else if(src == 2){
        oDialog.setTitle(oBundle.getText("Update_Invoice_Header"));
        addInvoceBtn.setText("Update");
        oIFInvoice1.setValue(obj['invoice_number']);
        oIFInvoice3.setValue(obj['workshop_estimate']);
        oIFInvoice4.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);
        }
        oIFInvoice5.setValue(obj['tax'])


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

        if (nullCheckAll(obj['wo_number'])) {
            var wo_number = obj['wo_number'].split("^");
            for (var i = 0; i < wo_number.length; i++) {//
                workorderInvoiceDB.addToken(new sap.m.Token({key:wo_number[i], text: wo_number[i] }));
            };
        };
        oIFInvoice1.setEnabled(false);
        oIFInvoice3.setEnabled(false);
        oIFInvoice4.setEnabled(false);
        oIFInvoice5.setValue(obj['tax']);
        workorderInvoiceDB.setEnabled(false);
    }
} 

//Attach Invoice Part
var invoice_tax_value;
function createGrabInvoice(src,obj) {
    let reqLbl = new sap.m.Label({ required: true });
    let oLbl = new sap.m.Label({});
    totalMaterialCostInvoice.setValue("0.00");
    totalLaborCostInvoice.setValue("0.00");
    totalTaxValueInvoice.setValue("0.00");
    grandTotalInvoice.setValue("0.00");
 


    var oPageInvoiceLayout =  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("^",", ")})]}),
                    
                ]
            })
            
        ]
    })
    
    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")}),
                            totalMaterialCostInvoice,
                            new sap.m.Label({text: oBundle.getText("Total_Labor_Cost")}),
                            totalLaborCostInvoice,
                            new sap.m.Label({text: oBundle.getText("Tax")}),
                            totalTaxValueInvoice
                           
                        ]
                    })
                ]
            }),
            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"
                            // })
                            grandTotalInvoice
                        ]
                    })
                ]
            })
        ]
    });

    var horizontalBar = new sap.m.HBox({
        width: "100%",
        items: [
            invoicePriceWoOverview,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 = oTablepartsInvoice.getItems();
            var alltableItemdata = oTablepartsInvoice.getModel().getData();
            var tableItem = alltableItemdata['modelData']

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

            var completedRequests = 0;
            var totalInvoiceCost = 0; 
            var invoice_item_json = [];
            // var tableItems = invoicePriceWoOverview.getItems();
            if(tableItem.length <= 0){
                sap.m.MessageBox.error(oBundle.getText("NO_Invoice_item_Available_to_add"));
                busyDialog.close();
                return;
            }

            

            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 total_cost = item.total_cost;
                let final_part_cost = item.final_material_cost;
                let total_item_cost = item.final_labor_cost;
                let tax_value = item.tax_value;
                let final_total_cost = item.final_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);
                total_cost = isNaN(total_cost) || total_cost === "" ? 0 : roundToInt(total_cost);
                tax_value = isNaN(tax_value) || tax_value === "" ? 0 : roundToInt(tax_value);
                final_part_cost = isNaN(final_part_cost) || final_part_cost === "" ? 0 : roundToInt(final_part_cost);
                total_item_cost = isNaN(total_item_cost) || total_item_cost === "" ? 0 : roundToInt(total_item_cost);
                final_total_cost = isNaN(final_total_cost) || final_total_cost === "" ? 0 : roundToInt(final_total_cost);


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

                var itemsData = {
                    master_email:emailUser,

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

                    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:final_part_cost+"",
                    item_total_labor_cost:total_item_cost+"",
                    item_final_total_cost:final_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 () {
                            
                //             updateWorkorderAmount(obj['invoice_number'],
                //                 function () {
                //                     get4WOpenInvoice();
                //                     // get4WReviewInvoice();
                //                     fetchInvoiceComparision();
                //                     busyDialog.close();
                //                     oDialog.close();
                //                 }
                //             );
                //         });
                        
                //     }
                // }, failure);
                
            }

            var total_invoice_cost = roundToInt(totalInvoiceCost);
            insertInvoiceItemsApi(invoice_item_json,tableItem1,total_invoice_cost,obj['id'],obj['invoice_number'],'Workshop',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: [oPageInvoiceLayout,new sap.ui.core.HTML({ content: "<hr />" }), oTablepartsInvoice,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){
        // getWoInvoicePartsData();
    }else if(src == 2){
        oDialog.setTitle("View Invoice Parts")
       
        // workorderInvoiceDB.setEnabled(false);
        
        getInvoiceItemsData(obj,partsInvoiceViewTemplate);
    }else if(src == 1){
        updateinvoiceBtn.setVisible(true);
        oDialog.setTitle("Add Invoice Parts")

        var oModel = new sap.ui.model.json.JSONModel();
        oModel.setData({ modelData: [] });
        oTablepartsInvoice.setModel(oModel);
        oTablepartsInvoice.bindItems({ 
            path: "/modelData", 
            template: partsInvoiceTemplate 
        });
        calculateRowTotal1(oTablepartsInvoice);

        // getWoInvoicePartsData(obj['wo_id']);
        getInvoiceWorkorderPartById('Workshop',obj['wo_id']);
    }
};


function updateWorkorderAmount(invoiceNumber, callback) {
    // Get all items from the `invoicePriceWoOverview` table
    var alltableItemdata1 = invoicePriceWoOverview.getModel().getData();
    var tableItems = Object.values(alltableItemdata1['modelData']);

    var completedUpdates = 0; // Counter for completed updates

    if (!tableItems || tableItems.length === 0) {
        console.warn("No items in the invoicePriceWoOverview 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 item = tableItems[i]; 
        var wo_number = item.wo_number;
        var wo_id = item.wo_id;
        var invoice_amount = roundToInt(item.final_total_cost);
        // Perform the update for each work order
        Car_Workorder.update({ id:wo_id,invoice_number:invoiceNumber, invoice_amount:invoice_amount
        }).done(function () {
            completedUpdates++; 

            if (completedUpdates === tableItems.length) {
                if (typeof callback === "function") {
                    callback(); // Execute the callback after all updates
                }
            }
        }),function (error) {
            console.error("Error updating work order:", error);
            completedUpdates++;
            if (completedUpdates === tableItems.length) {
                if (typeof callback === "function") {
                    callback();
                }
            }
        };
    }
}


//Update Reopne Invoice
function updateGrabInvoice(src,obj) {

    totalMaterialCostInvoice.setValue("0.00");
    totalLaborCostInvoice.setValue("0.00");
    grandTotalInvoice.setValue("0.00");
    totalTaxValueInvoice.setValue("0.00");
 
    var oPageInvoiceLayout =  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("Workorder")),fields: [new sap.m.Text({text: obj['wo_number'].replaceAll("^",", ")})]}),
                ]
            })
            
        ]
    })
    
    invoice_tax_value = obj['tax']
    // 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")}),
                            totalMaterialCostInvoice,
                            new sap.m.Label({text: oBundle.getText("Total_Labor_Cost")}),
                            totalLaborCostInvoice,
                            new sap.m.Label({text: oBundle.getText("Tax")}),
                            totalTaxValueInvoice
                        ]
                    })
                ]
            }),
            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"}),
                            grandTotalInvoice
                        ]
                    })
                ]
            })
        ]
    });

    var horizontalBar = new sap.m.HBox({
        width: "100%",
        items: [
            invoicePriceWoOverview,oSummaryForm
        ]
    })


    var updateinvoiceBtn = new sap.m.Button({ 
        text: oBundle.getText("Update"), 
        visible: true,
        icon: "sap-icon://edit",
        press: function() {
            busyDialog.open();

            var updated_date = getIndonesianTime();

            // var tableItem = oTablepartsInvoice.getItems();
            var alltableItemdata = oTablepartsInvoice.getModel().getData();
            var tableItem = alltableItemdata['modelData']
            let completedRequests = 0;
            let totalInvoiceCost = 0; 
            
            for(var i=0;i<tableItem.length;i++){
                // var item = tableItem[i].getBindingContext().getObject();
                var item = tableItem[i];


                let total_parts_cost = item.item_material_cost;
                let labor_item_cost = item.item_labor_cost;
                let tax_value = item.item_tax_value;
                let total_cost = item.item_total_cost;
                let final_part_cost = item.item_final_material_cost;
                let total_item_cost = item.item_total_labor_cost;
                let final_total_cost = item.item_final_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);
                total_cost = isNaN(total_cost) || total_cost === "" ? 0 : roundToInt(total_cost);
                tax_value = isNaN(tax_value) || tax_value === "" ? 0 : roundToInt(tax_value);
                final_part_cost = isNaN(final_part_cost) || final_part_cost === "" ? 0 : roundToInt(final_part_cost);
                total_item_cost = isNaN(total_item_cost) || total_item_cost === "" ? 0 : roundToInt(total_item_cost);
                final_total_cost = isNaN(final_total_cost) || final_total_cost === "" ? 0 : roundToInt(final_total_cost);
                
                // Accumulate the total cost and round to 2 decimals
                totalInvoiceCost = totalInvoiceCost + final_total_cost;

                var itemsData = {
                    id:item.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:final_part_cost,
                    item_total_labor_cost:total_item_cost,
                    item_final_total_cost:final_total_cost,


                    updated_by:operatedID,
                    updated_date:updated_date

                };

                Car_Invoice_Item.update(itemsData).done(function () {
                   completedRequests++;
    
                    if (completedRequests === tableItem.length) {
                        var total_invoice_cost = roundToInt(totalInvoiceCost);
                        Car_Workorder.update({id:obj['id'],invoice_amount:total_invoice_cost}).done(function () {
                            // fetchInvoiceComparision();
                            refreshCurrentWorkshopInvoiceData();
                            getClosedWorkorder();
                        });
                        busyDialog.close();
                        oDialog.close();
                    }
                }, failure);
                
            }

            if(tableItem.length < 1){
                busyDialog.close();
            }
        }
    });

    // Create and open dialog
    var oDialog = new sap.m.Dialog({ 
        contentWidth: "100%", 
        contentHeight: "80%", 
        draggable: true, 
        resizable: true,
        title: oBundle.getText("Update_Reopen_Invoice_Items"),
        content: [oPageInvoiceLayout,new sap.ui.core.HTML({ content: "<hr />" }), oTablepartsInvoice,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 == 1){
        getInvoiceItemsPartsData(obj,partsInvoiceUpdateTemplate);
    }else{
        oDialog.setTitle("View Invoice Item")
        updateinvoiceBtn.setVisible(false);
        getInvoiceItemsPartsData(obj,partsInvoiceViewTemplate);
    }
}


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

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

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

// Function to calculate row total
function calculateRowTotal(oEvent) {
    var oItem = oEvent.getSource().getBindingContext().getObject();
    var oInput = oEvent.getSource();


    var actualMaterialCost = roundToInt(oItem.total_parts_cost || 0);
    var actualLaborCost = roundToInt(oItem.labor_item_cost || 0);
    var actualTotalCost = roundToInt(oItem.total_cost || 0);
    var finalMaterialCost = roundToInt(oItem.final_material_cost || 0);
    var finalLaborCost = roundToInt(oItem.final_labor_cost || 0);
    var finalTotalCost = roundToInt(oItem.final_total_cost || 0);

    if(actualMaterialCost < finalMaterialCost){
        sap.m.MessageBox.error("Material cost cannot exceed the actual material cost."); 
        oInput.setValue(oItem.total_parts_cost);
        finalMaterialCost = actualMaterialCost;
    }
    
    if(actualLaborCost < finalLaborCost){ 
        sap.m.MessageBox.error("Labor cost cannot be exceed the actual labor cost"); 
        oInput.setValue(oItem.labor_item_cost);
        finalLaborCost = actualLaborCost;
    }

    if(actualTotalCost < finalTotalCost){ 
        sap.m.MessageBox.error("Total cost cannot be exceed the actual Total cost"); 
        return;
    };

    var total = finalMaterialCost + finalLaborCost;
    var tax_value = roundToInt((total * invoice_tax_value)/100);
    
    var oModel = oEvent.getSource().getModel();
    var path = oEvent.getSource().getBindingContext().getPath();
    oModel.setProperty(path + "/final_total_cost", total + tax_value);
    oModel.setProperty(path + "/tax_value", tax_value);

    var allData = oModel.getData().modelData;
    var allData = oModel.getData().modelData;
    
    var totalMaterialCost = 0;
    var totalLaborCost = 0;
    var totalTaxCost = 0;
    
    allData.forEach(function(item) {
        // Material calculations
        var materialCost = roundToInt(item.final_material_cost || 0);
        var laborCost = roundToInt(item.final_labor_cost || 0);
        totalMaterialCost += materialCost;
        totalLaborCost += laborCost;
        
        totalTaxCost += roundToInt(item.tax_value || 0);
    });
    
     //Tax
    //  var totalTaxCost = roundToInt(((totalMaterialCost + totalLaborCost)*invoice_tax_value)/100);
    

    // Update summary fields
    totalMaterialCostInvoice.setValue(roundToInt(totalMaterialCost));
    totalLaborCostInvoice.setValue(roundToInt(totalLaborCost));
    totalTaxValueInvoice.setValue(roundToInt(totalTaxCost));
    

    // Calculate and update grand total
    var grandTotal = (totalMaterialCost + totalLaborCost + totalTaxCost);
    grandTotalInvoice.setValue(roundToInt(grandTotal));
 
    updateInvoiceWOOverview(allData);
};

function calculateRowTotal1(oTablepartsInvoice) {

    var oModel = oTablepartsInvoice.getModel();
    var aTableData =  oTablepartsInvoice.getBinding("items").getPath();
    var allData = oModel.getProperty(aTableData);

    var totalMaterialCost = 0;
    var totalLaborCost = 0;
    var totalTaxCost = 0;
    allData.forEach(function(item) {
        // Material calculations
        var materialCost = roundToInt(item.final_material_cost || 0);
        var laborCost = roundToInt(item.labor_item_cost || 0);
        totalMaterialCost += materialCost;
        totalLaborCost += laborCost;
        
        totalTaxCost += roundToInt(item.tax_value || 0);
    });
    
     //Tax
    //  var totalTaxCost = roundToInt(((totalMaterialCost + totalLaborCost)*invoice_tax_value)/100);
     

    // Update summary fields
    totalMaterialCostInvoice.setValue(roundToInt(totalMaterialCost));
    totalLaborCostInvoice.setValue(roundToInt(totalLaborCost));
    totalTaxValueInvoice.setValue(roundToInt(totalTaxCost));
    

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

    let totalMaterial = 0;
    let totalLabor = 0;
    let totaltax = 0;
    let grabTotal = 0;
    // 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,
                total_cost: 0,
                final_material_cost: 0,
                final_labor_cost: 0,
                tax_value:0,
                final_total_cost: 0,
            };
        }

        // Aggregate the values
        groupedData[woNumber].total_parts_cost += roundToInt(item.total_parts_cost || 0);
        groupedData[woNumber].labor_item_cost += roundToInt(item.labor_item_cost || 0, 10);
        groupedData[woNumber].total_cost += roundToInt(item.total_cost || 0);
        groupedData[woNumber].final_material_cost += roundToInt(item.final_material_cost || 0, 10);
        groupedData[woNumber].final_labor_cost += roundToInt(item.final_labor_cost || 0, 10);
        groupedData[woNumber].tax_value += roundToInt(item.tax_value || 0, 10);
        groupedData[woNumber].final_total_cost += roundToInt(item.final_total_cost || 0, 10);
        totalMaterial += roundToInt(item.final_material_cost || 0);
        totalLabor += roundToInt(item.final_labor_cost || 0);
        totaltax += roundToInt(item.tax_value || 0, 10);
        grabTotal += roundToInt(item.final_total_cost || 0);
    });

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


//Invoice View/Update Functions
function calculateUpdateRowTotal(oEvent) {
    var oItem = oEvent.getSource().getBindingContext().getObject();
    var oInput = oEvent.getSource();


    var actualMaterialCost = roundToInt(oItem.item_material_cost || 0);
    var actualLaborCost = roundToInt(oItem.item_labor_cost || 0);
    var actualTotalCost = roundToInt(oItem.item_total_cost || 0);
    var finalMaterialCost = roundToInt(oItem.item_final_material_cost || 0);
    var finalLaborCost = roundToInt(oItem.item_total_labor_cost || 0);
    var finalTotalCost = roundToInt(oItem.item_final_total_cost || 0);

    if(actualMaterialCost < finalMaterialCost){
        sap.m.MessageBox.error("Material cost cannot exceed the actual material cost."); 
        oInput.setValue(oItem.item_material_cost);
        finalMaterialCost = actualMaterialCost;
    }
    
    if(actualLaborCost < finalLaborCost){
        sap.m.MessageBox.error("Labor cost cannot be exceed the actual labor cost"); 
        oInput.setValue(oItem.item_labor_cost);
        finalLaborCost = actualLaborCost;
    }

    if(actualTotalCost < finalTotalCost){ 
        sap.m.MessageBox.error("Total cost cannot be exceed the actual Total cost"); 
        return;
    };


    var total = finalMaterialCost + finalLaborCost;
    var tax_value = roundToInt((total * invoice_tax_value)/100);

    var oModel = oEvent.getSource().getModel();
    var path = oEvent.getSource().getBindingContext().getPath();
    oModel.setProperty(path + "/item_final_total_cost", total + tax_value);
    oModel.setProperty(path + "/item_tax_value", tax_value);


    var allData = oModel.getData().modelData;
    
    var totalMaterialCost = 0;
    var totalLaborCost = 0;
    var totalTaxCost = 0;
    
    allData.forEach(function(item) {
        // Material calculations
        var materialCost = roundToInt(item.item_final_material_cost || 0);
        var laborCost = roundToInt(item.item_total_labor_cost || 0);
        totalMaterialCost += materialCost;
        totalLaborCost += laborCost;
        
        totalTaxCost += roundToInt(item.item_tax_value || 0);
    });
    
     //Tax
    //  var totalTaxCost = roundToInt(((totalMaterialCost + totalLaborCost)*invoice_tax_value)/100);
     

    // Update summary fields
    totalMaterialCostInvoice.setValue(roundToInt(totalMaterialCost));
    totalLaborCostInvoice.setValue(roundToInt(totalLaborCost));
    totalTaxValueInvoice.setValue(roundToInt(totalTaxCost));
    

    // Calculate and update grand total
    var grandTotal = (totalMaterialCost + totalLaborCost + totalTaxCost);
    grandTotalInvoice.setValue(roundToInt(grandTotal));
    viewInvoiceWOOverview(allData)
};
function calculateRowTotalView(oTablepartsInvoice) {

    var oModel = oTablepartsInvoice.getModel();
    var aTableData =  oTablepartsInvoice.getBinding("items").getPath();
    var allData = oModel.getProperty(aTableData);

    var totalMaterialCost = 0;
    var totalLaborCost = 0;
    var totalTaxCost = 0;
  
    allData.forEach(function(item) {
        
        materialCost = roundToInt(item.item_final_material_cost || 0);
        laborCost = roundToInt(item.item_total_labor_cost || 0);
        totalMaterialCost += materialCost;
        totalLaborCost += laborCost;

        totalTaxCost += roundToInt(item.item_tax_value || 0);
    });
    
    // var totalTaxCost = roundToInt(((totalMaterialCost + totalLaborCost)*invoice_tax_value)/100);
    
    // Update summary fields
    totalMaterialCostInvoice.setValue(roundToInt(totalMaterialCost));
    totalLaborCostInvoice.setValue(roundToInt(totalLaborCost));
    totalTaxValueInvoice.setValue(roundToInt(totalTaxCost));
    
    // Calculate and update grand total
    var grandTotal = (totalMaterialCost + totalLaborCost + totalTaxCost);
    grandTotalInvoice.setValue(roundToInt(grandTotal));
    viewInvoiceWOOverview(allData);
};

function viewInvoiceWOOverview(partsData){
    const groupedData = {};

    // Iterate over each item in the data
    let totalMaterial;
    let totalLabor;
    let totaltax;
    let grabTotal;
    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,
                total_cost: 0,
                final_material_cost: 0,
                final_labor_cost: 0,
                tax_value:0,
                final_total_cost: 0,
            };
        }

        // Aggregate the values
        groupedData[woNumber].total_parts_cost += roundToInt(item.item_material_cost || 0);
        groupedData[woNumber].labor_item_cost += roundToInt(item.item_labor_cost || 0, 10);
        groupedData[woNumber].tax_value += roundToInt(item.item_tax_value || 0, 10);
        groupedData[woNumber].total_cost += roundToInt(item.item_total_cost || 0);
        groupedData[woNumber].final_material_cost += roundToInt(item.item_final_material_cost || 0);
        groupedData[woNumber].final_labor_cost += roundToInt(item.item_total_labor_cost || 0);
        totalMaterial += roundToInt(item.item_final_material_cost || 0);
        totalLabor += roundToInt(item.item_total_labor_cost || 0);
        totaltax += roundToInt(item.item_tax_value || 0, 10);
        grabTotal += roundToInt(item.item_final_total_cost || 0);
        groupedData[woNumber].final_total_cost += roundToInt(item.item_final_total_cost || 0);
    });


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

}

function selectWorkorderInvoice(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 }) }),
            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);
                }})
            ],
        }),
    });

    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 = 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.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));
                    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 = 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 oAppInvoicePageLayout = new sap.uxap.ObjectPageLayout({ headerContentPinnable: false, 
    preserveHeaderStateOnScroll: true, useIconTabBar: true, toggleHeaderOnTitleClick: true,
    headerTitle: new sap.uxap.ObjectPageDynamicHeaderTitle({
        heading: [new sap.m.Title({ text: oBundle.getText("Invoice"), level: "H1", titleStyle: "H2" })] }),
    sections: [        
        new sap.uxap.ObjectPageSection({id:"INV2", showTitle: true, title: oBundle.getText("Under_Review"),
            subSections: new sap.uxap.ObjectPageSubSection({ blocks: [invoiceCompare]})}),
                
        new sap.uxap.ObjectPageSection({id:"INV3", showTitle: true, title: oBundle.getText("Completed"),
            subSections: new sap.uxap.ObjectPageSubSection({ blocks: [oTable4WAllInvoiceGRN]})
        })
    ],

    navigate: function (event) {
        var mID = event.getParameter('section').getId();
       
        if(mID == "INV3"){
            // get4WCompletedInvoice();
            oTable4WAllInvoiceGRN.setBusy(true);
            getGrnWorkorder();
        }else if (mID == "INV2"){
            // get4WReviewInvoice();
            // fetchInvoiceComparision();
            refreshCurrentWorkshopInvoiceData();
        }

    }
});




var woPartInvoiceJSONArrary = [];
/*function getWoInvoicePartsData(woArray){
    oTablepartsInvoice.setBusy(true);
    getInvoiceWorkorderPartById('Workshop',woArray)


    // var wo_list = woArray
    // const vehicleFilter = wo_list.map(num => `wo_id eq '${num}'`).join(" or ");
    // const filterQuery = `master_email eq '${emailUser}' and part_type eq 'Workshop' and (${vehicleFilter})`;

    // Car_Workorder_Part
    //     .where(filterQuery)
    //     .take(1000)
    //     .read()
    //     .done(function (results) {
    
    //     let filterParts = results;

    //     filterParts = filterParts.map(function (item) {
    //         item.final_material_cost = item.total_parts_cost; 
    //         item.final_labor_cost = item.labor_item_cost; 
    //         item.final_total_cost = item.total_cost;
    //         return item;
    //     });


    //     var oModel = new sap.ui.model.json.JSONModel();
    //     oModel.setData({ modelData: filterParts });
    //     oTablepartsInvoice.setModel(oModel);
    //     oTablepartsInvoice.bindItems({ 
    //         path: "/modelData", 
    //         template: partsInvoiceTemplate 
    //     });
    //     calculateRowTotal1(oTablepartsInvoice);

    //     woPartInvoiceJSONArrary = filterParts;

    // })
    // Car_Workorder_Part.where({master_email:emailUser,part_type:"Workshop"}).take(2000).orderByDescending("createdAt").read().done(function (result) {
        
    //     let filterParts = result.filter(a=> woArray.includes(a.wo_number));

    //     filterParts = filterParts.map(function (item) {
    //         item.final_material_cost = item.total_parts_cost; 
    //         item.final_labor_cost = item.labor_item_cost; 
    //         item.final_total_cost = item.total_cost;
    //         return item;
    //     });


    //     var oModel = new sap.ui.model.json.JSONModel();
    //     oModel.setData({ modelData: filterParts });
    //     oTablepartsInvoice.setModel(oModel);
    //     oTablepartsInvoice.bindItems({ 
    //         path: "/modelData", 
    //         template: partsInvoiceTemplate 
    //     });
    //     calculateRowTotal1(oTablepartsInvoice);

    //     woPartInvoiceJSONArrary = filterParts;

    // })
};*/

function getInvoiceItemsData(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 });
        oTablepartsInvoice.setModel(oModel);
        oTablepartsInvoice.bindItems({ 
            path: "/modelData", 
            template: tableTemplate 
        });
        calculateRowTotalView(oTablepartsInvoice);
    })
}

function getInvoiceItemsPartsData(objData,tableTemplate){
    Car_Invoice.where({master_email:emailUser,invoice_number:objData['invoice_number']}).take(10)
    .orderByDescending("createdAt").read().done(function (results) {
        if(results.length == 1){
            Car_Invoice_Item.where({master_email:emailUser,invoice_id:results[0]['id'],wo_number:objData['wo_number']}).take(100).orderByDescending("createdAt").read().done(function (results) {
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: results });
                oTablepartsInvoice.setModel(oModel);
                oTablepartsInvoice.bindItems({ 
                    path: "/modelData", 
                    template: tableTemplate 
                });
                calculateRowTotalView(oTablepartsInvoice);
            })
        }else if(results.length > 1){
            sap.m.MessageBox.error(oBundle.getText("Multiple Invoice number found!") + objData['invoice_number']);
        }else{
            sap.m.MessageBox.error(oBundle.getText("Invoice number not found!"));
        }
    })
   
}


var invoiceOpen4WJSONData = [];
function get4WOpenInvoice(){
    oTable4WInvoiceOpen.setBusy(true);
    
    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getAllOpenInvoice("Workshop",oTable4WInvoiceOpen);
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getAllOpenInvoiceBydWorkshopGroup("Workshop",oTable4WInvoiceOpen);
    }else{
        getAllOpenInvoiceByWorkshop("Workshop",oTable4WInvoiceOpen);
    }

    // Car_Invoice.where({master_email:emailUser,status:"Open",invoice_type:"Workshop"}).take(1000).orderByDescending("createdAt").read().done(function (results) {
        
    //     invoiceOpen4WJSONData = results;            

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


// var invoiceReview4WJSONData = [];
// function get4WReviewInvoice(){
//     oTable4WInvoiceReview.setBusy(true);
//     Car_Invoice.where({master_email:emailUser,status:"Under Review",invoice_type:"Workshop"}).take(1000).orderByDescending("createdAt").read().done(function (results) {
        
//         invoiceReview4WJSONData = results;            

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


// var invoiceCompleted4WJSONData = [];
function get4WCompletedInvoice(){
    // invoiceCompleted4WJSONData = [];
    // oTable4WInvoiceCompleted.setBusy(true);
    // Car_Workorder.where({master_email:emailUser,wo_status:"GRN"}).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:"Workshop"}).take(1000).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) {
    //                     invoiceCompleted4WJSONData.push(invoice)
    //                 } 
    //             });            
    //             var oModel = new sap.ui.model.json.JSONModel();
    //             oModel.setData({ modelData: invoiceCompleted4WJSONData });
    //             oTable4WInvoiceCompleted.setModel(oModel);
    //             oTable4WInvoiceCompleted.bindItems({ path: "/modelData", template : invoice4WTemplateCompleted });
    //             oTable4WInvoiceCompleted.setBusy(false);
    //         })    
    //     }else{
    //         oTable4WInvoiceCompleted.setBusy(false);
    //     }
    // })
        
   
};

// var invoiceReopen4WJSONData = [];
// function get4WReopenInvoice(){
    // oTable4WInvoiceReopen.setBusy(true);
    // Car_Invoice.where({master_email:emailUser,status:"Reopen"}).take(1000).orderByDescending("createdAt").read().done(function (results) {
        
    //     invoiceReopen4WJSONData = results;            

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

