
// var Car_Inspection = client.getTable('Car_Inspection');
// var Car_Inspection_Item = client.getTable('Car_Inspection_Item');
var aInspectionAllFilters = [];
var historySearch = new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px",
        selectOnFocus: false,
        layoutData: new sap.ui.layout.GridData({span: "L4 M6 S12"}),
        search: function (event) {
            if (event.getParameter("clearButtonPressed")) {
                historySearch.setValue("");
            }
        },
        liveChange: function (event) {
            var oBinding = oTableInspection.getBinding("items");
            var searchStr = this.getValue();
            if (oBinding) {
                var oFilters = [ 
                    new sap.ui.model.Filter("report_number", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("inspection_date", 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_model", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("location", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("inspector_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("vehicle_status", sap.ui.model.FilterOperator.Contains, searchStr),
                    new sap.ui.model.Filter("group_name", sap.ui.model.FilterOperator.Contains, searchStr),
                   
                ];
                var filterObj = new sap.ui.model.Filter(oFilters, false);
                oBinding.filter(filterObj);

                aInspectionAllFilters = [filterObj];
                
                // Additional logic for external call
                if(searchStr.startsWith("INSP") && searchStr.length > 16) {
                    setTimeout(function () {
                        var items = oTableInspection.getItems(); //For All table
                        var visibleItems = items.filter(function (item) {
                            return item.getVisible(); // Only visible items
                        });
                        // console.log("hello")
                        if (visibleItems.length === 0) {
                            busyDialog.open();
                            sap.m.MessageToast.show('Getting Data From DB.');
                            funGetInspectionDetailsFromDb(searchStr, '0');//grabGrnWOJSONArray, oTable4WGrnWO, workorderTemplate,
                        }
                    }, 300); // Small delay to let filtering apply
                }



            } else {
                oBinding.filter([]);
            }
        }
    });

var oTableInspection = 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("Report_No"),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({wrapping:true, text: oBundle.getText("Vehicle_Details"), design: sap.m.LabelDesign.Bold}),
                minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true}),
               
                new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Location"), design: sap.m.LabelDesign.Bold}),
                minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),
                new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Inspector"), design: sap.m.LabelDesign.Bold}),
                minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),

                new sap.m.Column({header: new sap.m.Label({ text: oBundle.getText("Fault"), design: sap.m.LabelDesign.Bold}),
                minScreenWidth : "Tablet",popinDisplay : "Inline",demandPopin : true,hAlign: "Center"}),
                new sap.m.Column({header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Linked_Wo"), design: sap.m.LabelDesign.Bold}),
                minScreenWidth : "Desktop",popinDisplay : "Inline",demandPopin : true,hAlign: "Left"}),
                new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Note")),
                minScreenWidth : "2500px",popinDisplay : "Inline",demandPopin : true}),
          ]
    });

var inspectionTemplate = 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);
                        displayMenuInspection(event, obj);
                    }
                }),
                new sap.m.VBox({
                    items:[new sap.m.Label({wrapping:true,text: "{report_number}"}),
                           new sap.tnt.InfoLabel({colorScheme:3,
                            text: { path: "vehicle_status",
                            formatter: function (vehicle_status) {
                                if (vehicle_status != null &&  vehicle_status != "") {
                                    if(vehicle_status=="Breakdown") {
                                        this.setVisible(true);
                                    }else{
                                        this.setVisible(false);
                                    }
                                }else{
                                    this.setVisible(false);
                                }
                                return oBundle.getText("Breakdown");
                            }
                        }
                        }).addStyleClass("sapUiTinyMarginTop"),
               ]}).addStyleClass("sapUiTinyMargin"),
                new sap.m.Label({ wrapping: true, text: "{inspection_date}" }),
                new sap.m.VBox({
                    items:[new sap.m.Label({ wrapping: true, text: "{license_number}" }),
                           new sap.m.Label({ wrapping: true, text: "{chassis_number}" }).addStyleClass("sapUiTinyMarginTop"),
                    ]}).addStyleClass("sapUiTinyMargin"),
                new sap.m.Label({ wrapping: true, text: "{location}" }),
                new sap.m.Label({ wrapping: true, text: "{inspector_name}" }),
                new sap.m.Button({
                    icon: "sap-icon://message-warning",
                    type: sap.m.ButtonType.Reject,
                    text: {
                        parts: [{ path: "repair", type: new sap.ui.model.type.String() },
                                { path: "replace", type: new sap.ui.model.type.String()}],
                        formatter: function (repair, replace) {
                            var repairArray = [];
                            var replaceArray = [];
                            if (repair != null) {
                                var repairArray = repair.split("^");
                            }
                            if (replace != null) {
                                var replaceArray = replace.split("^");
                            }

                            if (repairArray.length > 1 || replaceArray.length > 1) {
                                this.setVisible(true);
                                return (repairArray.length - 1) + (replaceArray.length - 1);
                            } else {
                                this.setVisible(false);
                            }
                        }
                    },
                    press: function (event) {
                        var model = this.getModel();
                        var path = event.getSource().getBindingContext().getPath();
                        var obj = model.getProperty(path);
                        viewDefect(obj['repair'], obj['replace'],obj['id']);
                    }
                }),
                // new sap.tnt.InfoLabel({
                //     text: {
                //         parts: [{ path: "id", type: new sap.ui.model.type.String() },
                //                 { path: "action_source", type: new sap.ui.model.type.String() },
                //                 { path: "corrective_action", type: new sap.ui.model.type.String() },
                //                 { path: "repair", type: new sap.ui.model.type.String() },
                //                 { path: "replace", type: new sap.ui.model.type.String()}],
                //         formatter: function (mid, action_source, action, repair, replace) {
                //             if (action_source == null) {

                //                 var repairArray = [];
                //                 var replaceArray = [];
                //                 if (repair != null) {
                //                     var repairArray = repair.split("^");
                //                 }
                //                 if (replace != null) {
                //                     var replaceArray = replace.split("^");
                //                 }

                //                 if (repairArray.length > 1 || replaceArray.length > 1) {
                //                     if (action == null || action=="" ) {
                //                         this.setColorScheme(3);
                //                         return oBundle.getText("Not_Taken");
                //                     }else if (action == "1") {
                //                         this.setColorScheme(8);
                //                         return oBundle.getText("Taken");
                //                     } else if (action == "2") {
                //                         this.setColorScheme(1);
                //                         return oBundle.getText("Partially");
                //                     } else if (action == "3") {
                //                         this.setColorScheme(9);
                //                         return oBundle.getText("NA");
                //                     } else {
                //                         this.setColorScheme(3);
                //                         return oBundle.getText("Not_Taken");
                //                     }
                //                 } else {
                //                     this.setColorScheme(9);
                //                     return oBundle.getText("NA");
                //                 }
                //             } else {

                //                 var taskItems = inspectionFaultJSONArray.filter(function (obj, index) {
                //                     return (obj.inspection_id === mid);
                //                 });

                //                 if (taskItems.length > 0) {
                //                     var fixed = 0;
                //                     var notFixed = 0;
                //                     for (var i = 0; i < taskItems.length; i++) {
                //                         var status = taskItems[i]['task_status'];
                //                         if (status == "4" || status == "7") {
                //                             fixed = fixed + 1;
                //                         } else {
                //                             notFixed = notFixed + 1;
                //                         }
                //                     }

                //                     if (taskItems.length == fixed) {
                //                         this.setColorScheme(8);
                //                         return oBundle.getText("Taken");
                //                     } else if (taskItems.length == notFixed) {
                //                         this.setColorScheme(3);
                //                         return oBundle.getText("Not_Taken");
                //                     } else {
                //                         this.setColorScheme(1);
                //                         return oBundle.getText("Partially");
                //                     }
                //                 } else { 
                //                        this.setColorScheme(8);
                //                        return oBundle.getText("Taken");
                //                 }
                //             }
                //         }
                //     }
                // }),
                new sap.m.Link({ emphasized: true,
                    text: {
                        path: "workorder",
                        formatter: function (ref_workorder) {
                            var refArray = [];
                            if (ref_workorder != null) {
                                refArray = ref_workorder.split("^");
                                if (refArray.length == 1) {
                                    return refArray[0];
                                } else {
                                    return refArray[0]+"/...";
                                }
                            }
                        }
                    },
                    press: function (event) {
                        var model = this.getModel();
                        var path = event.getSource().getBindingContext().getPath();
                        var obj = model.getProperty(path);

                        var ref_workorder = obj['workorder']
                        var refArray = [];
                        if (ref_workorder != null) {
                            refArray = ref_workorder.split("^");
                        }
                        refrenceWorkorder(refArray, obj['license_number']);
                    }
                }),
                new sap.m.HBox({
                    items:[ new sap.m.Label({wrapping:true,text: "{group_name}"}).addStyleClass("sapUiTinyMarginEnd sapUiTinyMarginTop"),
                        //    new sap.tnt.InfoLabel({ colorScheme:8,
                        //     text: { path: "root_cause",
                        //             formatter: function (root_cause) {
                        //                 if (root_cause != null &&  root_cause != "") {
                        //                     this.setVisible(true);
                        //                 }else{
                        //                     this.setVisible(false);
                        //                 }
                        //                 return oBundle.getText("RCA");
                        //             }
                        //     }}),
                            new sap.m.Button({
                                icon: "sap-icon://pdf-attachment",
                                type: sap.m.ButtonType.Transparent,
                                text: { path: "uploaded",
                                    formatter: function (uploaded) {
                                        if (uploaded != null && uploaded =="") {
                                            this.setVisible(false);
                                        } else {
                                            this.setVisible(true);
                                        }
                                }},
                                press: function (e) {
                                    var model = this.getModel();
                                    var path = e.getSource().getBindingContext().getPath();
                                    var obj = model.getProperty(path);
                                    var blob_path = obj['pdf_url'];
            
                                    window.open(blob_path, "_blank");
                                }
                            })
                ]}),
                new sap.m.Label({
                    text: {
                    parts: [{ path: "remark", type: new sap.ui.model.type.String() },
                            { path: "repair_note", type: new sap.ui.model.type.String() },
                            { path: "replace_note", type: new sap.ui.model.type.String()}],
                    formatter: function (remark, repair_note, replace_note) {
                        var allNote ="";
                        if (remark != null && remark != "") {
                            allNote = remark+", ";
                        }
                        if (repair_note != null && repair_note != "") {
                            allNote = allNote + repair_note+", ";
                        }
                        if (replace_note != null && replace_note != "") {
                            allNote = allNote + replace_note;
                        }

                        return allNote.replace(/\^/g, ", ");
                    }}
                }) 

            ],
          highlight: {
              path: "inspection_date",
              formatter: function (createdDate) {
                  if (createdDate != null && createdDate != "") {
                      if (getDate() == createdDate.split(" ")[0]) { return "Success"; }
                      return "None";
                  }
              }
          }
      });

var VSDInspection = new sap.m.ViewSettingsDialog({
          sortDescending: true,
          confirm: function (oEvent) {
              var p = oEvent.getParameters();
              var oSorter = null;
              if (p.sortItem) {
                  oSorter = p.sortItem.getCustomData()[0].getValue();
                  var key = p.sortItem.getCustomData()[0].getKey();

                  var sortType = sap.ui.core.SortOrder.Descending;
                  if (this.getSortDescending()) {
                      sortType = sap.ui.core.SortOrder.Descending;
                  } else {
                      sortType = sap.ui.core.SortOrder.Ascending;
                  }

                  oTableInspection.getColumns()[1].setSortIndicator(sap.ui.core.SortOrder.None);
                  oTableInspection.getColumns()[2].setSortIndicator(sap.ui.core.SortOrder.None);
                  oTableInspection.getColumns()[3].setSortIndicator(sap.ui.core.SortOrder.None);
                  oTableInspection.getColumns()[4].setSortIndicator(sap.ui.core.SortOrder.None);
                  oTableInspection.getColumns()[5].setSortIndicator(sap.ui.core.SortOrder.None);
                  oTableInspection.getColumns()[6].setSortIndicator(sap.ui.core.SortOrder.None);
                 

                  if (key == "1") {
                      oTableInspection.getColumns()[1].setSortIndicator(sortType);
                  } else if (key == "2") {
                      oTableInspection.getColumns()[2].setSortIndicator(sortType);
                  } else if (key == "3") {
                      oTableInspection.getColumns()[3].setSortIndicator(sortType);
                  } else if (key == "4") {
                      oTableInspection.getColumns()[4].setSortIndicator(sortType);
                  } else if (key == "5") {
                      oTableInspection.getColumns()[5].setSortIndicator(sortType);
                  } else if (key == "6") {
                      oTableInspection.getColumns()[6].setSortIndicator(sortType);
                  }

                  if (oSorter) {
                      oSorter.bDescending = p.sortDescending;

                      if (key === "2") {
                          oSorter.fnCompare = function (a, b) {

                              var strDate1 = a;
                              var strDate2 = b;

                              var aDate = new Date(strDate1);
                              var bDate = new Date(strDate2);

                              if (bDate == null) { return -1; }
                              if (aDate == null) { return 1; }
                              if (aDate < bDate) { return -1; }
                              if (aDate > bDate) { return 1; }
                              return 0;
                          };
                      }
                      oTableInspection.getBinding("items").sort(oSorter);
                  }
              }
          }
      });
VSDInspection.setTitle(oBundle.getText("Sort"));

VSDInspection.addSortItem(new sap.m.ViewSettingsItem({ text: oBundle.getText("Report_No"),
    customData: new sap.ui.core.CustomData({
        key:"1",value: new sap.ui.model.Sorter("report_number", false)
    })
}));
VSDInspection.addSortItem(new sap.m.ViewSettingsItem({ text: oBundle.getText("Inspection_Date" ),
    selected: true, customData: new sap.ui.core.CustomData({ key:"2", value: new sap.ui.model.Sorter("inspection_date", false) })
}));
VSDInspection.addSortItem(new sap.m.ViewSettingsItem({ text: oBundle.getText("License_Number"),
    customData: new sap.ui.core.CustomData({ key:"3", value: new sap.ui.model.Sorter("license_number", false) })
}));
VSDInspection.addSortItem(new sap.m.ViewSettingsItem({ text: oBundle.getText("Vehicle_Model"),
    customData: new sap.ui.core.CustomData({ key:"4", value: new sap.ui.model.Sorter("vehicle_model", false) })
}));
VSDInspection.addSortItem(new sap.m.ViewSettingsItem({text: oBundle.getText("Location"),
    customData: new sap.ui.core.CustomData({ key:"5", value: new sap.ui.model.Sorter("location", false) })
}));
VSDInspection.addSortItem(new sap.m.ViewSettingsItem({ text: oBundle.getText("Inspector"),
    customData: new sap.ui.core.CustomData({ key:"6", value: new sap.ui.model.Sorter("inspector", false) })
}));

var oInputInspVehicleNumber = new sap.m.Input({
    placeholder: "Search Vehicle Number"
  });

  // Create Button
  var oButtonSearchVehicleInsp = new sap.m.Button({
    text: "GO",
    type: "Emphasized", // You can change to "Transparent" for smaller style
    press: function () {
      var inputValue = oInputInspVehicleNumber.getValue();
      console.log("Input value:", inputValue);
      funGetInspectionDetailsFromDb(inputValue,'0')
    }
  });

  // Horizontal Layout to hold input and button side by side
  var oHBoxVehicleSearchInsp = new sap.m.HBox({
    items: [oInputInspVehicleNumber, oButtonSearchVehicleInsp],
    alignItems: "Center",
    justifyContent: "Start"
  });

oTableInspection.setHeaderToolbar(new sap.m.Toolbar({
    content: [
            new sap.m.Button({ 
                visible:false,
                type:sap.m.ButtonType.Emphasized,
                icon: "sap-icon://inspection",
                text: oBundle.getText("Start_New_Inspection"),
                press: function () {
                    // getInspectionIndex();
                    oAppInspection.to("create_inspection"); 
                }
            }),
            new sap.m.Button({
                text: "Compare Inspection",
                type: sap.m.ButtonType.Emphasized,
                visible:true,
                icon: "sap-icon://detail-view",
                press: function (e) {
                    showSelectionDialog();
                }
            }),
            oHBoxVehicleSearchInsp,
            new sap.m.ToolbarSpacer(),
            historySearch,
            new sap.m.Button({icon: "sap-icon://sort",press: function () {
                    VSDInspection.open();
                }
            }),
            new sap.m.MenuButton({
                icon: "sap-icon://menu",
                menu: new sap.m.Menu({
                    itemSelected: function(oEvent) {
                        var key = oEvent.getParameter("item").getKey();
                        if(key == "1"){
                            oAppInspection.to("inspection_archive_page");
                            funGetArchiveInspection();
                        }else if(key == "2"){
                            inspectionExcelExport();
                        }else if(key == "3"){
                            oTableInspection.setGrowingThreshold(500);
                            funGetAllInspection();
                        }
                    },
                    items: [
                            new sap.m.MenuItem({
                            text: oBundle.getText("Archive_Inspection"),
                            icon: "sap-icon://sap-box",
                            key: "1"
                        }),
                        // new sap.m.MenuItem({
                        //     text: oBundle.getText("Excel_Export"),
                        //     icon: "sap-icon://excel-attachment",
                        //     visible:false,
                        //     key: "2"
                        // }),
                        // new sap.m.MenuItem({
                        //     text: oBundle.getText("All_Reports"),
                        //     visible:false,
                        //     icon: "sap-icon://pdf-attachment",
                        //     key: "3"
                        // }),
                                
                    ]
                })
            })  
        ]
}));

function openDialogMapInspection() {

      /*  var oHBox = new sap.m.HBox({height: "400px",width: "100%"});
        var oBlockLayoutCell = new sap.ui.layout.BlockLayoutCell({content: [oHBox]});
    
        var oDialog = new sap.m.Dialog({ title: "Map",
            draggable:true, resizable: true,
            contentWidth: "60%",
            content: [oBlockLayoutCell],
            beginButton: new sap.m.Button({text: "Close",
                press: function(oEvent){
                oDialog.close();
             }
            })
        });
    
        oDialog.open();
    
        var script = document.createElement("script");
        script.onload = function () {
            setMapDataInspection(oHBox);
        };
        script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyCKyhW2JqLM_CsXIjMGuu6vwxuUJq7XBmc";
        document.body.appendChild(script);*/
      
}
      
function setMapDataInspection(oHBox) {
    
 /*   var latlongCenter = new google.maps.LatLng(39.291035900000004, -84.320976);

     var tableItem = oTableInspection.getItems();
        for(var i=0;i<tableItem.length;i++){
            var item = tableItem[i].getBindingContext().getObject().lat_long;
            if(item!=null){
                if(item!="" ){
                var splitArray = item.split(",");
                latlongCenter = new google.maps.LatLng(parseFloat(splitArray[0]), parseFloat(splitArray[1]));
             }
            }
          }
        
        var mapProperty = {
            center: latlongCenter,
            zoom: 12,
            scrollwheel: true,
            draggable: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
    
        var map = new google.maps.Map(oHBox.getDomRef(), mapProperty);
    
        var tableItem = oTableInspection.getItems();
        for(var i=0;i<tableItem.length;i++){
            var item = tableItem[i].getBindingContext().getObject().lat_long;
            var vehicle_Number = tableItem[i].getBindingContext().getObject().license_number;
           
            if(item!=null ){
                if(item!="" ){
                var splitArray = item.split(",");
                var latlong = new google.maps.LatLng(parseFloat(splitArray[0]), parseFloat(splitArray[1]));

                var marker = new google.maps.Marker({position: latlong , title: vehicle_Number,});

                var infowindow = new google.maps.InfoWindow({content: vehicle_Number, maxWidth: 200});

                marker.addListener('click', function() {

                    //alert(vehicleJSONArray);

                    var getVehicle = vehicleJSONArray.filter(function(obj, index){
                        return (obj.license_number === vehicle_Number);
                    });

                    var startDate = "01-Jan-2015";
                    var endDate = "01-Jan-2025"+" "+"11:59 PM";
                    vehicleOverviewDialog(getVehicle[0],startDate,endDate);
                    
                    infowindow.open(map, marker);
                 });
                 
                 infowindow.open(map, marker);

                marker.setMap(map);
            }
          }
        }
   
        window.map = map;*/
}



function displayMenuInspection(event,obj){

    var oMenu = new sap.m.Menu({
        items: [
            new sap.m.MenuItem({icon: "sap-icon://show",text: oBundle.getText("View"),key: "1"}),
            new sap.m.MenuItem({visible:false,icon: "sap-icon://share-2",text: oBundle.getText("Share"),key: "2"}),
            new sap.m.MenuItem({icon: "sap-icon://add-equipment",text: oBundle.getText("Create_Workorder_4"),key: "3"}),
            // new sap.m.MenuItem({icon: "sap-icon://complete",text: oBundle.getText("Corrective_Action"),key: "7"}),
            // new sap.m.MenuItem({icon: "sap-icon://cause",text: oBundle.getText("Root_Cause_Analysis"),key: "8"})
        ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
            if (oItem == "1") {
                historyView(obj);
            }else if (oItem == "7") {
                fun_corrective_action(obj);
            } else if (oItem == "2") {
                var license_number = obj['license_number'];
                var vehicle_model = obj['vehicle_model'];
                var reportNo = obj['report_number'];
                var reportLink = obj['pdf_url'];

                var inspection_date = obj['inspection_date'];
                var inspector = obj['inspector_name'];
                var maintenance_required = obj['maintenance_required'];
                var overall_condition = obj['overall_condition'];
                var repairItem = obj['repair'].replace("^", "");
                var replaceItem = obj['replace'].replace("^", "");

                if (maintenance_required == "1" || maintenance_required == oBundle.getText("Yes")) {
                    maintenance_required = oBundle.getText("Yes");
                } else if (maintenance_required == "2" || maintenance_required == oBundle.getText("No")) {
                    maintenance_required = oBundle.getText("No");
                }

                var defectiveItem = repairItem.split("^").toString() + ", " + replaceItem.split("^").toString();

                var subject = oBundle.getText("Sharing_HVI_Inspection_Report") + " #" + " " + reportNo;
                var message = oBundle.getText("Vehicle_Number") + " : " + license_number + "<br>" +
                              oBundle.getText("Vehicle_Model") + " : " + vehicle_model + "<br>" +
                              oBundle.getText("Inspection_Date") + " : " + inspection_date + "<br>" +
                              oBundle.getText("Inspector") + " : " + inspector + "<br>" +
                              oBundle.getText("Maintenance_Required") + " : " + maintenance_required + "<br>" +
                              oBundle.getText("Overall_Condition") + " : " + overall_condition + "<br>" +
                              oBundle.getText("Faulty_Item") + " : " + defectiveItem + "<br>" +
                              oBundle.getText("Report_Link") + " : " + reportLink;

                var dialogTitle = oBundle.getText("Share_Report_with_Team_Member");
                var layoutHeader = oBundle.getText("Report") + "# " + reportNo;

                shareDialog(subject, message, dialogTitle, layoutHeader);
                
            } else if (oItem == "4") {
                archiveInspection(obj['id'], "archive");
            } else if (oItem == "5") {
                archiveInspection(obj['id'], "unarchive");
            } else if (oItem == "3") {

                if(vehicleTemp){
                    sap.m.MessageBox.error(oBundle.getText("Please Wait while vehicles get loaded."));
                    get4WVehicle();
                    vehicleTemp = false;
                    return;
                };

                var repairItem = obj['repair'];
                var replaceItem = obj['replace'];
                var workorder = obj['workorder'];

                if ((repairItem == null && repairItem == null) || (repairItem =="" && replaceItem =="")) {
                    sap.m.MessageBox.error(oBundle.getText("No_defective_item_in_inspection"), { title: oBundle.getText("Alert") });
                    return;
                }
                if (workorder != null && workorder != "") {
                    sap.m.MessageBox.error("#"+workorder+" "+oBundle.getText("Workorder_already_created"), { title: oBundle.getText("Alert") });
                    return;
                };


                var filterVehicleStatus = vehicle4WJSONData.filter(a=>a.license_number == obj['license_number']);
                if(filterVehicleStatus.length > 0 && 
                    ['sold', 'total_loss', 'loss_in_rent', 'removed', 'total_loss_accident', 'total_loss'].includes(filterVehicleStatus[0]["vehicle_status"])
                ){
                    sap.m.MessageBox.error(oBundle.getText("This vehicle cannot be selected due to its current status :" + filterVehicleStatus[0]["vehicle_status"]), { title: oBundle.getText("Alert") });
                    return;
                }
                
                // if (hvi_user_access != null && hvi_user_access.indexOf('5') == -1) {
                //     sap.m.MessageBox.error(oBundle.getText("Not_authorised_to_create_workorder"), { title: oBundle.getText("Alert") });
                // } else {

                    sideNavigation.setSelectedKey("grab_workorder");
                    navContainer.to("grab_workorder");
                    // oLayoutVehicle.to("vehicle_page");

                    addPageSrc = "1";
                    // oAppWoRequest.removePage(addWOPage);
                    oAppWorkOrder.addPage(addWOPage);
                    oAppWorkOrder.to("add_wo_page");
                    addWOPage.setTitle(oBundle.getText("Maintenance_Workorder"));
                    iniWorkOrder("Dashboard", obj);
                    btnWO1.setText(oBundle.getText("Create_WorkOrder"));
                // }
            } else if (oItem == "6") {
                deleteInspection(obj['id']);
            }
        }
    });

    var menuItem =  oMenu.getItems();

    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('create_work_order') == -1)){
        oMenu.getItems()[2].setVisible(false);
    };

    if(hvi_login_type == "1"  || (hvi_login_type == "2" && hvi_account_access_value.indexOf('archive_inspection_transaction') != -1)){
        if(obj['archive'] == "1"){
            menuItem[2].setVisible(false);
            oMenu.addItem(new sap.m.MenuItem({ icon: "sap-icon://sap-box",text: oBundle.getText("Unarchive"),key: "5"}));
        }else{
            oMenu.addItem(new sap.m.MenuItem({ icon: "sap-icon://sap-box",text: oBundle.getText("Archive"),key: "4"}));
        }
    };
    
    

    // menuItem[1].setVisible(false);
    // getDeleteMenu(oMenu,"6");
    oMenu.openBy(event.getSource());
}

function archiveInspection(inspID,type) {
 
    var dialogMsg = new sap.m.Label({ text: oBundle.getText("Do_you_want_to_archive")+"?" });
    var btn = new sap.m.Button({
            text: oBundle.getText("Archive"),
            icon: "sap-icon://sap-box",
            press: function () {
                busyDialog.open();
                Car_Inspection.update({ id: inspID,archive:archive }).done(function () {
                    busyDialog.close();
                    oDialog.close();
                    funGetInspection();
                    if(type != "archive"){
                        funGetArchiveInspection();
                    }
                }, failure);
            }
        });
    var archive = "0";

     if(type=="archive"){
        archive = "1";
        dialogMsg.setText(oBundle.getText("Do_you_want_to_archive")+"?");
        btn.setText(oBundle.getText("Archive"));
    }else{
        archive = "0";
        dialogMsg.setText(oBundle.getText("Do_you_want_to_unarchive")+"?");
        btn.setText(oBundle.getText("Unarchive"));
    }

     var oDialog = new sap.m.Dialog({
        title: oBundle.getText("Information"),
        state: sap.ui.core.ValueState.Information,
        content: [dialogMsg],
        buttons: [ btn,
					new sap.m.Button({
					    text: oBundle.getText("Cancel"),
					    icon: "sap-icon://decline",
					    press: function () {
					        oDialog.close();
					    }
					})
				]
    }).open();
}


var ArchiveInspectionTable = oTableInspection.clone();

 var inspectionArchiveSearch = new sap.m.SearchField({
        placeholder: oBundle.getText("Search"),
        width: "300px",
        selectOnFocus: false,
        layoutData: new sap.ui.layout.GridData({span: "L4 M6 S12"}),
        search: function (event) {
            if (event.getParameter("clearButtonPressed")) {
                inspectionArchiveSearch.setValue("");
            }
        },
        liveChange: function (event) {
            var oBinding = ArchiveInspectionTable.getBinding("items");
            var searchStr = this.getValue();
            if (oBinding) {
                var oFilters = [ new sap.ui.model.Filter("report_number", sap.ui.model.FilterOperator.Contains, searchStr),
                                 new sap.ui.model.Filter("inspection_date", 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_model", sap.ui.model.FilterOperator.Contains, searchStr),
                                 new sap.ui.model.Filter("location", sap.ui.model.FilterOperator.Contains, searchStr),
                                 new sap.ui.model.Filter("inspector", sap.ui.model.FilterOperator.Contains, searchStr),
                                 new sap.ui.model.Filter("vehicle_status", sap.ui.model.FilterOperator.Contains, searchStr)
                                 ];
                var filterObj = new sap.ui.model.Filter(oFilters, false);
                oBinding.filter(filterObj);
            } else {
                oBinding.filter([]);
            }
        }

    });

 ArchiveInspectionTable.setHeaderToolbar(new sap.m.Toolbar({
    content: [
            new sap.m.Label({text: oBundle.getText("Archive_Inspection")}),
            new sap.m.ToolbarSpacer(),
            inspectionArchiveSearch
        ]
    }));

 var inspection_history_page = new sap.m.Page("inspection_history",{
        title:oBundle.getText("Inspection_Reports"),
        showHeader:true,
        enableScrolling:true,
        content : [oTableInspection]
    });

var inspectionArchivePage = new sap.m.Page("inspection_archive_page", {
        title:oBundle.getText("Archive_Inspection"),
        showHeader:true,
        enableScrolling:true,
        showNavButton: true,
        navButtonPress: function(){ oAppInspection.backToTop(); },
        content : [ArchiveInspectionTable]
    });

 
 function inspectionExcelExport(){
   

        var xlsHeader = [oBundle.getText("Report_No"), 
                         oBundle.getText("Inspection_Date"),

                         oBundle.getText("Vehicle_Number"),
                         oBundle.getText("Vehicle_Model"),
                         oBundle.getText("VIN_Number"),
                         oBundle.getText("Model"),
                         oBundle.getText("Meter_Reading"),
                         oBundle.getText("Location"),
                         oBundle.getText("Inspector"),

                         oBundle.getText("Overall_Condition"),
                         oBundle.getText("Vehicle_Safe_to_Use"),
                         oBundle.getText("Maintenance_Required"),
                         oBundle.getText("Link_Workorder"),
                         oBundle.getText("Additional_Note"),

                         oBundle.getText("Faults_Count"),
                         oBundle.getText("Faults_Repair"),
                         oBundle.getText("Faults_Replace"),
                         oBundle.getText("Corrective_Action"),
                    ];
 
        var dataObject = [];
        var tableItem = oTableInspection.getItems();
        for(var i=0;i<tableItem.length;i++){

            var fault_count = tableItem[i].getCells()[6].getText();
            var CorrectiveAction = tableItem[i].getCells()[7].getText();



            var item = tableItem[i].getBindingContext().getObject();

            var maintenance_required = item.maintenance_required;
                if (maintenance_required == "1" || maintenance_required == oBundle.getText("Yes")) {
                        maintenance_required = oBundle.getText("Yes");
                } else if (maintenance_required == "2" || maintenance_required == oBundle.getText("No")) { 
                        maintenance_required = oBundle.getText("No");
                }

            var repair = item.repair;
            var replace = item.replace;

            var faultRepair = "";
            var faultReplace = "";

            if (repair != null) {
                faultRepair = repair.replace(/\^/g, ", ");
            }
            if (replace != null) {
                faultReplace = replace.replace(/\^/g, ", ");
            }
            
           dataObject.push({"1":item.report_number,
                            "2":item.inspection_date,

                            "3":item.license_number,
                            "4":item.vehicle_model,
                            "5":item.vehicle_vin,
                            "6":item.vehicle_model,
                            "7":item.meter_reading,
                            "8":item.location,
                            "9":item.inspector,

                            "10":item.overall_condition,
                            "11":item.safe_to_use,
                            "12":maintenance_required,
                            "13":item.workorder,
                            "14":item.remark,
                                 
                            "15":fault_count,
                            "16":faultRepair,
                            "17":faultReplace,
                            "18":CorrectiveAction
                });
        }

       var createXLSLFormatObj = [];

        createXLSLFormatObj.push(xlsHeader);
        $.each(dataObject, function(index, value) {
            var innerRowData = [];
            $.each(value, function(ind, val) {
                innerRowData.push(val);
            });
            createXLSLFormatObj.push(innerRowData);
        });

        var filename = "InspectionExport.xlsx";
        var sheet_name = "Data";

        var wb = XLSX.utils.book_new();
        var ws = XLSX.utils.aoa_to_sheet(createXLSLFormatObj);

        XLSX.utils.book_append_sheet(wb, ws, sheet_name);
        XLSX.writeFile(wb, filename);
}

function inspectionPDFExport(){

       var aCols = [
            {title: oBundle.getText("Report_No"),key: 'report_number'},
            {title: oBundle.getText("Date"),key: 'inspection_date'},
            {title: oBundle.getText("Vehicle_Number"),key: 'license_number'},
            {title: oBundle.getText("Vehicle Model"),key: 'vehicle_model'},
            {title: oBundle.getText("Location"),key: 'location'},
            {title: oBundle.getText("Inspector"),key: 'inspector'},
            {title: oBundle.getText("Attention"),key: 'maintenance_required'}
        ];

    if(customJSONArray.length>0){

        var inspection_flag1 = customJSONArray[0]['inspection_flag1'];
        var inspection_flag2 = customJSONArray[0]['inspection_flag2'];
        var inspection_flag3 = customJSONArray[0]['inspection_flag3'];
        var inspection_flag4 = customJSONArray[0]['inspection_flag4'];
        var inspection_flag5 = customJSONArray[0]['inspection_flag5'];
       
        if(inspection_flag1!=null && inspection_flag1=="1"){
            aCols.push({title: customJSONArray[0]['inspection_field1'],key: 'field1'});
        }
       if(inspection_flag2!=null && inspection_flag2=="1"){
            aCols.push({title: customJSONArray[0]['inspection_field2'],key: 'field2'});
        }
       if(inspection_flag3!=null && inspection_flag3=="1"){
            aCols.push({title: customJSONArray[0]['inspection_field3'],key: 'field3'});
        }
        if(inspection_flag4!=null && inspection_flag4=="1"){
            aCols.push({title: customJSONArray[0]['inspection_field4'],key: 'field4'});
        }
        if(inspection_flag5!=null && inspection_flag5=="1"){
            aCols.push({title: customJSONArray[0]['inspection_field5'],key: 'field5'});
        }

    }

    var aData = (oTableInspection.getItems() || []).map(function(oItem){
            return oItem.getBindingContext().getObject();
        });

    var doc = new jsPDF('l', 'pt'); 
	doc.setFontSize(12);
	doc.autoTable(aCols, aData, 
    //{styles: { overflow: 'linebreak', columnWidth: 'wrap' }},
    {columnStyles: {2: {columnWidth: 'auto'}}}
    
    );
	doc.save("InspectionExport.pdf");
}

function viewDefect(repair,replace,inspectionID){
    
    var oTableRepair = new sap.ui.table.Table({
        editable : false, 
        width : "100%",
        visibleRowCount :5	   
    });
        
    oTableRepair.setSelectionMode(sap.ui.table.SelectionMode.Single);
    oTableRepair.setSelectionBehavior(sap.ui.table.SelectionBehavior.RowOnly);

    oTableRepair.addColumn(new sap.ui.table.Column({
        label: new sap.ui.commons.Label({ text: "SN" }),
        template: new sap.ui.commons.TextView({
            text: {
                path: "",
                formatter: function () {
                    var path = this.getBindingContext()?.getPath();
                    if (path) {
                        var index = parseInt(path.split("/").pop());
                        return index + 1;
                    }
                    return "";
                }
            }
        }),
        width: "30px"
    }));
    
    oTableRepair.addColumn(new sap.ui.table.Column({
        label: new sap.ui.commons.Label({text:oBundle.getText("Repair_Item")}),
        template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "task_name"),
        width:"100%"
    }));
    oTableRepair.addColumn(new sap.ui.table.Column({
        label: new sap.ui.commons.Label({text:oBundle.getText("Workorder")}),
        template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "link_workorder"),
        width:"100%"
    }));

    var oTableReplace = new sap.ui.table.Table({
        editable : false, 
        width:"100%",
        visibleRowCount :5   
    });
        
    oTableReplace.setSelectionMode(sap.ui.table.SelectionMode.Single);
    oTableReplace.setSelectionBehavior(sap.ui.table.SelectionBehavior.RowOnly);

    oTableReplace.addColumn(new sap.ui.table.Column({
        label: new sap.ui.commons.Label({ text: "SN" }),
        template: new sap.ui.commons.TextView({
            text: {
                path: "",
                formatter: function () {
                    var path = this.getBindingContext()?.getPath();
                    if (path) {
                        var index = parseInt(path.split("/").pop());
                        return index + 1;
                    }
                    return "";
                }
            }
        }),
        width: "30px"
    }));
    oTableReplace.addColumn(new sap.ui.table.Column({
        label: new sap.ui.commons.Label({text:oBundle.getText("Replace_Item")}),
        template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "task_name"),
        width:"100%"
    }));
    oTableReplace.addColumn(new sap.ui.table.Column({
        label: new sap.ui.commons.Label({text:oBundle.getText("Workorder")}),
        template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "link_workorder"),
        width:"100%"
    }));

    var aDataRepair =[];
    var aDataReplace =[];

    if (repair == null) {repair = "";} 
    if (replace == null) {replace = "";} 
    console.log(inspectionID)
    Car_Inspection_Item.where({master_email:emailUser,inspection_id:inspectionID}).read()
    .done(function (results) {

        aDataRepair = results.filter(a=>a.task_type == 'Repair');
        aDataReplace = results.filter(a=>a.task_type == 'Replace');
       
        var oModelRepair = new sap.ui.model.json.JSONModel();
        oModelRepair.setData({ modelData: aDataRepair });
        oTableRepair.setModel(oModelRepair);
        oTableRepair.bindRows("/modelData");

        var oModelReplace = new sap.ui.model.json.JSONModel();
        oModelReplace.setData({ modelData: aDataReplace });
        oTableReplace.setModel(oModelReplace);
        oTableReplace.bindRows("/modelData");
    });
   
    // var repairArray = repair.split("^");
    // var replaceArray = replace.split("^");

    // if (repair != "") {
    //     for (var i = 1; i < repairArray.length; i++) {
    //         aDataRepair.push({ repair: repairArray[i]});
    //     }
    // }
    // if (replace != "") {
    //     for (var i = 1; i < replaceArray.length; i++) {
    //         aDataReplace.push({ replace: replaceArray[i]});
    //     }
    // }
    
    
    var oDialog = new sap.m.Dialog({
        draggable: true,
        icon: "sap-icon://alert",
        title: oBundle.getText("Defect_Item"),
        state: sap.ui.core.ValueState.Error,
        content: [oTableRepair,new sap.m.Label({ text: "" }),oTableReplace],
        buttons: [
            new sap.m.Button({
                text: oBundle.getText("Close"),
                icon: "sap-icon://decline",
                press: function () {
                    oDialog.close();
                }
            })
        ]
    }).open();

}

function deleteInspection(inspection_id) {

    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 () {
					        oDialog.close();
					        Car_Inspection.del({ id: inspection_id }).done(function () {
					            funGetInspection();
					        });
					    }
					}),
					new sap.m.Button({
					    text: oBundle.getText("Cancel"),
					    icon: "sap-icon://decline",
					    press: function () {
					        oDialog.close();
					    }
					})
				]
    }).open();

}

// var refWoArray = [];
var inspectionJSONArray = [];
// var inspectionFaultJSONArray = [];

var allInspectionJSONArray = [];
var goodInspectionJSONArray = [];
var faultyInspectionJSONArray = [];

function funGetInspection() {

    allInspectionJSONArray = [];
    goodInspectionJSONArray = [];
    faultyInspectionJSONArray = [];

    busyDialog.open();
    oTableInspection.setBusy(true);
    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getAllInspection("unarchived","0");
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getAllInspectionByWorkshopGroup("unarchived","0");
    }else{
        getAllInspectionWorkshop("unarchived","0");
    };

 }


function funGetArchiveInspection() {

    ArchiveInspectionTable.setBusy(true);


    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        getAllInspection("archived","1");
    }else if(oxmaint_role == 'Workshop Group Admin'){
        getAllInspectionByWorkshopGroup("archived","1");
    }else{
        getAllInspectionWorkshop("archived","1");
    };


    // Car_Inspection.where(filterQueryGrabInspection(2)).take(1000).orderByDescending("createdAt").read().done(function (result) {
        
    //     var results = filterGrabVehicle(result);

    //     // var results =result;
           
    //     for (var i = 0; i < results.length; i++) {
    //         results[i]['SerialNo'] = parseInt(i + 1);
    //     }
    
    //     var oModel = new sap.ui.model.json.JSONModel();
    //     oModel.setData({ modelData: results });
    //     oModel.setSizeLimit(results.length);
       
    //     ArchiveInspectionTable.setModel(oModel);
    //     ArchiveInspectionTable.bindItems({ path: "/modelData", template : inspectionTemplate});
    //     ArchiveInspectionTable.setBusy(false);

    // });
}

function historyView(obj) {

   

    // HVI_WO_Task.where({ master_email: emailUser, inspection_id: obj['id'] }).read().done(function (results) {
    //     var oModel = new sap.ui.model.json.JSONModel();
    //     oModel.setData({ modelData: results });
    //     oTableCorrectiveAction.setModel(oModel);
    //     oTableCorrectiveAction.bindItems({ path: "/modelData",template: correctiveTemplate});
    // });

    var oTableRepair = new sap.ui.table.Table({
        width : "100%",
        visibleRowCount :4
    });     

    oTableRepair.setSelectionMode(sap.ui.table.SelectionMode.Single);
    oTableRepair.setSelectionBehavior(sap.ui.table.SelectionBehavior.RowOnly);
    oTableRepair.addColumn(new sap.ui.table.Column({
        label: new sap.ui.commons.Label({ text: oBundle.getText("Repair_Item")}),
        template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "item")
    }));
          
    var  oTableReplace = new sap.ui.table.Table({
        width : "100%",
        visibleRowCount :4
    });
         
    oTableReplace.setSelectionMode(sap.ui.table.SelectionMode.Single);
    oTableReplace.setSelectionBehavior(sap.ui.table.SelectionBehavior.RowOnly);

    oTableReplace.addColumn(new sap.ui.table.Column({
        label: new sap.ui.commons.Label({ text: oBundle.getText("Replace_Item")}),
        template: new sap.ui.commons.TextView({wrapping:true}).bindProperty("text", "item")
    }));
  
 
    var aDataReplace =[];
    var aDataRepair =[];
    var oModelRepair = new sap.ui.model.json.JSONModel();
    var oModelReplace = new sap.ui.model.json.JSONModel(); 
    /////////////////////////////////////////////

    var replace = obj['replace'];
    var repair = obj['repair'];

    if (replace == null) {
        replace = "";
    }
    if (repair == null) {
        repair = "";
    }

    replace = replace.substring(1);
    repair = repair.substring(1);

    var replace1 = replace.split("^");
    var repair1 = repair.split("^");

    var repairCount = 0;
    var replaceCount = 0;
    
    if (repair1 != "") {
        repairCount = repair1.length;
        for (var i = 0; i < repair1.length; i++) {
            aDataRepair.push({ item: repair1[i] });
        }
    }

    if (replace1 != "") {
        replaceCount = replace1.length;
        for (var i = 0; i < replace1.length; i++) {
            aDataReplace.push({ item: replace1[i]});
        }
    }
    /////////////////////////////////////////////

    oModelRepair.setData({ modelData: aDataRepair });
    oTableRepair.setModel(oModelRepair);
    oTableRepair.bindRows("/modelData");

    oModelReplace.setData({ modelData: aDataReplace });
    oTableReplace.setModel(oModelReplace);
    oTableReplace.bindRows("/modelData");

    var id = obj['id'];
    var report_no = obj['report_number'];

    var license_number = obj['license_number'];
    var vehicle_model = obj['vehicle_model'];
    var chassis_number = obj['chassis_number'];
    var engine_number = obj['engine_number'];
    var vehicle_status = obj['vehicle_status'];
    var meter_reading = obj['meter_reading'];

    var inspection_date = obj['inspection_date'];
    var location = obj['location'];
    var inspector = obj['inspector_name'];


    var overall_condition = obj['overall_condition'];
    var safe_to_use = obj['safe_to_use'];
    var maintenance_required = obj['maintenance_required'];
    var maintenance_priority = obj['maintenance_priority'];

    var uploaded = obj['uploaded'];
    var ref_workorder = obj['workorder'];
    
    var overall_remark = obj['remark'];
    var pdf_url = obj['pdf_url'];
    
    if (pdf_url == null) { pdf_url = ""; }
    
    var pdfBtn = new sap.m.Button({
        width: "150px",
        text: oBundle.getText("Download"),
        type: sap.m.ButtonType.Emphasized,
        icon: "sap-icon://download",
        enabled: true,
        press: function (e) {

            if(uploaded =="0"){
                sap.m.MessageBox.error(oBundle.getText("Report_does_not_exist_on_cloud_First_upload_report_from_device"));
            }else{
                if (pdf_url.length > 15) {
                    //window.open("https://docs.google.com/viewer?url=" + custom1, "_blank");
                    window.open(pdf_url, "_blank");
                } else {
                    sap.m.MessageBox.error(oBundle.getText("Report_does_not_exist_on_cloud_First_upload_report_from_device"));
                }
            }
        }
    });
    if (pdf_url.length < 15) {
        pdfBtn.setEnabled(false);
    }
    
    var createWO = new sap.m.Button({ type: sap.m.ButtonType.Accept, text: oBundle.getText("Create_Workorder"), width: "150px",
        press: function () {

            var repairItem = obj['repair'];
            var replaceItem = obj['replace'];
            var workorder = obj['workorder'];

            if ((repairItem == null && repairItem == null) || (repairItem =="" && replaceItem =="")) {
                sap.m.MessageBox.error(oBundle.getText("No_defective_item_in_inspection"), { title: oBundle.getText("Alert") });
                return;
            }
            if (workorder != null && workorder != "") {
                sap.m.MessageBox.error("#"+workorder+" "+oBundle.getText("Workorder_already_created"), { title: oBundle.getText("Alert") });
                return;
            }

            if(hvi_user_access!=null && hvi_user_access.indexOf('5')==-1){
                sap.m.MessageBox.error(oBundle.getText("Not_authorised_to_create_workorder"),{title: oBundle.getText("Alert")});
            }else{
                oDialog.close();

                sideNavigation.setSelectedKey("p31");
                navContainer.to("p31");
                // oLayoutVehicle.to("vehicle_page");

                addPageSrc = "1";
                oAppWoRequest.removePage(addWOPage);
                oAppWorkOrder.addPage(addWOPage);
                oAppWorkOrder.to("add_wo_page");
                addWOPage.setTitle(oBundle.getText("Maintenance_Workorder"));
                iniWorkOrder("Dashboard", obj);
                btnWO1.setText(oBundle.getText("Create_WorkOrder"));

            
            }
        } 
    }); 
    /*
    var oCell1 = new sap.ui.commons.layout.MatrixLayoutCell({ colSpan: 2,rowSpan: 3 });
    oCell1.addContent(oTableRepair);
    var oCell2 = new sap.ui.commons.layout.MatrixLayoutCell({ colSpan: 2 ,rowSpan: 3});
    oCell2.addContent(oTableReplace);
    */
    var refArray = [];
    if(ref_workorder!=null){
        refArray = ref_workorder.split("^");
    }
    
    var woLink = new sap.m.Link({
        emphasized : true,
        press : function() {
            refrenceWorkorder(refArray,license_number);
        }
    });

    if(ref_workorder!=null){
        woLink.setText(oBundle.getText("Link"));
    }
    if(refArray.length==1){
            woLink.setText(refArray[0]);
    }
    
        var oInfoLabelSafeToUse = new sap.tnt.InfoLabel({text: "", width:"50px"});

    if (safe_to_use == "1" || safe_to_use == oBundle.getText("Yes")) {
        oInfoLabelSafeToUse.setColorScheme(8);
        oInfoLabelSafeToUse.setText(oBundle.getText("Yes"));
    } else if (safe_to_use == "2" || safe_to_use == oBundle.getText("No")) { 
        oInfoLabelSafeToUse.setColorScheme(3);
        oInfoLabelSafeToUse.setText(oBundle.getText("No"));
    }else if (safe_to_use == "3" || safe_to_use == oBundle.getText("NA")) { 
        oInfoLabelSafeToUse.setColorScheme(9);
        oInfoLabelSafeToUse.setText(oBundle.getText("NA"));
    }

    var oInfoLabelmaintenance_required = new sap.tnt.InfoLabel({text: maintenance_required,width:"50px"});

    if (maintenance_required == "1" || maintenance_required == oBundle.getText("Yes")) {
        oInfoLabelmaintenance_required.setColorScheme(3);
        oInfoLabelmaintenance_required.setText(oBundle.getText("Yes"));
    } else if (maintenance_required == "2" || maintenance_required == oBundle.getText("No")) { 
        oInfoLabelmaintenance_required.setColorScheme(8);
        oInfoLabelmaintenance_required.setText(oBundle.getText("No"));
    }

    // var action_source = obj['action_source'];
    // var corrective_date = obj['corrective_date'];
    // var corrective_action = obj['corrective_action'];
    // var corrective_vehicle_condition = obj['corrective_vehicle_condition'];
    // var mechanic_name = obj['mechanic_name'];
    // var operator_name = obj['operator_name'];

    // var oInfoLabelCorrect = new sap.tnt.InfoLabel({text: ""});

    /* if (corrective_action == "1" ) {
        oInfoLabelCorrect.setColorScheme(8);
        oInfoLabelCorrect.setText(oBundle.getText("Yes"));
    } else if (corrective_action == "2") { 
        oInfoLabelCorrect.setColorScheme(3);
        oInfoLabelCorrect.setText(oBundle.getText("No"));
    }else{
        oInfoLabelCorrect.setColorScheme(9);
        oInfoLabelCorrect.setText(oBundle.getText("NA"));
    }*/

   

    var customFieldMatrix = new sap.ui.commons.layout.MatrixLayout({
        columns: 2,
        width: "100%",
        widths: ["50%", "50%",]
    });
    
    
    var hvi_location_flag = sessionStorage.getItem('oxmaint_location_flag');
    // if(hvi_location_flag!=null && hvi_location_flag !="" && hvi_location_flag =="1"){

    // var coordinateLink =  new sap.m.Link({text:obj['lat_long'], emphasized : true,
    //     press : function() {
    //         var coordinates = this.getText();
    //         if(coordinates!=null && coordinates !=""){
    //             window.open("http://maps.google.com?q="+coordinates, "_blank");
    //         }else{
    //             sap.m.MessageBox.error(oBundle.getText("Coordinates_not_available"));
    //         } 
    //     }
    // });

    // customFieldMatrix.createRow(new sap.m.Label({ text: oBundle.getText("Coordinates")}), coordinateLink);
    // customFieldMatrix.createRow(new sap.m.Label({ text: oBundle.getText("Full_Location")}), new sap.m.Text({text: obj['full_location']}));



    let inspection_time_value = obj['inspection_time'] +" "+"Minutes";
    if(!nullCheckAll(inspection_time_value)){
        inspection_time_value = 0 +" "+"Minutes";
        // console.log(inspection_time_value)
    }

    customFieldMatrix.createRow(new sap.m.Label({ wrapping: true, text: oBundle.getText("Inspection_Time")}), 
    new sap.m.Label({ wrapping: true, text: inspection_time_value }) );



    // var dvirForm1 =  new sap.ui.layout.Grid({
    //                     hSpacing: 0,	
    //                     vSpacing: 0,
    //                     defaultSpan: "L4 M6 S12",
    //                     containerQuery: true,
    //                     content: [
    //                     new sap.ui.layout.Grid({
    //                         hSpacing: 0.5,	
    //                         vSpacing: 0.5,
    //                         defaultSpan: "L6 M6 S6",
    //                         content: [//new sap.m.Label({text: oBundle.getText("Report_Number")}),
    //                                 //new sap.m.Text({text: report_no}),
    //                                 new sap.m.Label({text: oBundle.getText("Inspection_Date")}),
    //                                 new sap.m.Text({text: inspection_date}),
    //                                 new sap.m.Label({ text: oBundle.getText("Location")}),
    //                                 new sap.m.Text({text: location}),
    //                                 new sap.m.Label({ text: oBundle.getText("Inspector_Name")}),
    //                                 new sap.m.Text({text: inspector}),
    //                                 new sap.m.Label({ text: oBundle.getText("Report_Download")}),
    //                                 pdfBtn,
    //                               //  new sap.m.Label({ text: oBundle.getText("WO_from_Inspection")}),
    //                                // createWO
    //                         ]}),

    //                     new sap.ui.layout.Grid({
    //                         hSpacing: 0.5,	
    //                         vSpacing: 0.5,
    //                         defaultSpan: "L6 M6 S6",
    //                         content: [new sap.m.Label({text: oBundle.getText("License_Number")}),
    //                                 new sap.m.Text({text: license_number}),
    //                                 new sap.m.Label({text: oBundle.getText("Vehicle_Model")}),
    //                                 new sap.m.Text({text: vehicle_model}),
    //                                 new sap.m.Label({ text: oBundle.getText("Chassis_Number")}),
    //                                 new sap.m.Text({text: chassis_number}),
    //                                 new sap.m.Label({ text: oBundle.getText("Engine_Number")}),
    //                                 new sap.m.Text({text: engine_number}),
    //                                 new sap.m.Label({ text: oBundle.getText("Odometer")}),
    //                                 new sap.m.Text({text: meter_reading}),
                                    
    //                         ]}),
    //                     new sap.ui.layout.Grid({
    //                         hSpacing: 0.5,	
    //                         vSpacing: 0.5,
    //                         defaultSpan: "L6 M6 S6",
    //                         content: [new sap.m.Label({text: oBundle.getText("Overall_Condition")}),
    //                                 new sap.m.Text({text: overall_condition}),
    //                                 new sap.m.Label({ text: oBundle.getText("Maintenance_Priority")}),
    //                                 new sap.m.Text({text: maintenance_priority}),
    //                                 new sap.m.Label({ text: oBundle.getText("Maintenance_Required")}),
    //                                 new sap.m.Text({text: maintenance_required}),
    //                                 new sap.m.Label({text: oBundle.getText("Vehicle_Safe_to_Use")}),
    //                                 oInfoLabelSafeToUse
    //                                 //oInfoLabelmaintenance_required     
    //                         ]}),

    //                     ]
    //     });

    
    var dvirForm1 = new sap.ui.layout.form.Form({
        editable: true,
        layout: new sap.ui.layout.form.ResponsiveGridLayout({
            labelSpanL: 4,  // Label span for large screens
            labelSpanM: 4,  // Label span for medium screens
            columnsL: 3,     // 3 columns for large screens
            columnsM: 2,     // 2 columns for medium screens
            singleContainerFullSize: false // Allows multiple containers in a row
        }),
        formContainers: [
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Inspection_Date")),
                        fields: [new sap.m.Text({ text: inspection_date })]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Location")),
                        fields: [new sap.m.Text({ text: location })]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Inspector_Name")),
                        fields: [new sap.m.Text({ text: inspector })]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Report_Download")),
                        fields: [pdfBtn]
                    })
                ]
            }),
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("License_Number")),
                        fields: [new sap.m.Text({ text: license_number })]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Vehicle_Model")),
                        fields: [new sap.m.Text({ text: vehicle_model })]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Chassis_Number")),
                        fields: [new sap.m.Text({ text: chassis_number })]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Engine_Number")),
                        fields: [new sap.m.Text({ text: engine_number })]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Odometer")),
                        fields: [new sap.m.Text({ text: meter_reading })]
                    })
                ]
            }),
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Overall_Condition")),
                        fields: [new sap.m.Text({ text: overall_condition })]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Maintenance_Priority")),
                        fields: [new sap.m.Text({ text: maintenance_priority })]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Maintenance_Required")),
                        fields: [new sap.m.Text({ text: maintenance_required })]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Battery")),
                        fields: [new sap.m.Text({ text: obj['battery_info'] })]
                    }),
                    new sap.ui.layout.form.FormElement({
                        label: oLbl.clone().setText(oBundle.getText("Tyre")),
                        fields: [new sap.m.Text({ text: obj['tyre_info'] })]
                    }),
                    // new sap.ui.layout.form.FormElement({
                    //     label: oLbl.clone().setText(oBundle.getText("Vehicle_Safe_to_Use")),
                    //     fields: [oInfoLabelSafeToUse]
                    // })
                ]
            })
        ]
    });
    
    
    var dvirForm2 =  new sap.ui.layout.Grid({
            hSpacing: 0,	
            vSpacing: 0,
            defaultSpan: "XL4 L4 M6 S12",
            containerQuery: true,
            content: [
            new sap.ui.layout.Grid({
                hSpacing: 0.5,	
                vSpacing: 0.5,
                defaultSpan: "L12 M12 S12",
                content: [oTableRepair]
                }),
                new sap.ui.layout.Grid({
                hSpacing: 0.5,	
                vSpacing: 0.5,
                defaultSpan: "L12 M12 S12",
                content: [oTableReplace]
                }),
                new sap.ui.layout.Grid({
                hSpacing: 0.5,	
                vSpacing: 0.5,
                defaultSpan: "L12 M12 S12",
                content: [customFieldMatrix]
                }),
                        
            ]
        });
   



    var oProcessFlowSC = new sap.suite.ui.commons.ProcessFlow({width:"100%",showLabels:true,scrollable: false, wheelZoomable: false });

    var resultWO = workorderJSONArray.filter(function (objwo, index) {
        return (objwo.wo_number == obj['workorder']);
    });
    

    if(resultWO.length>0){
        
        var woCreated_date  = resultWO[0]['created_date'];
        var woCompletion_date  = resultWO[0]['completion_date'];
        var woStatus = getStatusText(resultWO[0]['wo_status']);

        var statusDate1 = Date.parse(inspection_date)/1000;
        var statusDate2 = Date.parse(woCreated_date)/1000;
        var totalSec1 = statusDate2 - statusDate1;

        var totalSec2  = 0;
        if(woCompletion_date != null){
            var statusDate3 = Date.parse(woCompletion_date)/1000;
            totalSec2 = statusDate3 - statusDate2;
        }

        var inspectionTxt = "Inspection";
        if(vehicle_status=="Breakdown"){
            inspectionTxt = "Breakdown";
        }

        oProcessFlowSC.addLane(new sap.suite.ui.commons.ProcessFlowLaneHeader({laneId: 0,iconSrc: "sap-icon://inspection",
            text: inspectionTxt,position: 0
        }));

        var node1 =  new sap.suite.ui.commons.ProcessFlowNode({nodeId: 0,laneId: 0,
            title: inspection_date,
            state: sap.suite.ui.commons.ProcessFlowNodeState.Negative,
            texts: [oBundle.getText("Faults"),(repairCount + replaceCount)],
            children: [{
                nodeId: 1,
                connectionLabel: new sap.suite.ui.commons.ProcessFlowConnectionLabel({width:"100%",
                    text: secondsToHms(totalSec1)
                })
            }]
        });

        oProcessFlowSC.insertNode(node1);

        oProcessFlowSC.insertLane(new sap.suite.ui.commons.ProcessFlowLaneHeader({laneId: 1,iconSrc: "sap-icon://eam-work-order",
            text: "Work Order Created",position: 1
        }));

        var node2 =  new sap.suite.ui.commons.ProcessFlowNode({nodeId: 1,laneId: 1,
            title: woCreated_date,
            texts: [oBundle.getText("Status"),woStatus],
            state: sap.suite.ui.commons.ProcessFlowNodeState.Critical
        });

        oProcessFlowSC.insertNode(node2);

    
        if(woCompletion_date != null && woCompletion_date != ""){
        
            node2.setChildren([{nodeId: 2,
                connectionLabel: new sap.suite.ui.commons.ProcessFlowConnectionLabel({ text: secondsToHms(totalSec2)})
            }]);

            oProcessFlowSC.insertLane(new sap.suite.ui.commons.ProcessFlowLaneHeader({laneId: 2,iconSrc: "sap-icon://complete",
                text: "Work Order Completed",position: 2
            }));
        
            var node3 =  new sap.suite.ui.commons.ProcessFlowNode({nodeId: 2,laneId: 2,
                title: woCompletion_date,
                state: sap.suite.ui.commons.ProcessFlowNodeState.Positive
            });

            oProcessFlowSC.insertNode(node3);
        }

     }

     oProcessFlowSC.setZoomLevel(sap.suite.ui.commons.ProcessFlowZoomLevel.Two);

    var oDialog = new sap.m.Dialog({contentWidth:"100%",draggable:true, resizable: true,
        title: oBundle.getText("Report_Number")+" : " + report_no,
        content: [dvirForm1,dvirForm2,oProcessFlowSC],
        buttons: [
			   /* new sap.m.Button({text: oBundle.getText("Link_WO"),icon: "sap-icon://chain-link",
				    press: function () {
                        
                        linkInspectionToWO(id,license_number);
                    }
			    }),*/
                new sap.m.Button({text: oBundle.getText("Close"),icon: "sap-icon://decline",
				    press: function () {oDialog.close();}
			    })
	]}).open();


}

function linkInspectionToWO(id){

    var oField1 = new sap.m.Input({showValueHelp: true,valueHelpOnly: true,
        valueHelpRequest: function () {
            linkPOWorkorder(oField1);
        } 
    });

    var updateBtn = new sap.m.Button({
        text: oBundle.getText("Save"),
        icon: "sap-icon://save",
        press: function () {

            var link_wo = oField1.getValue();
           
            if (validation(link_wo, oBundle.getText("Field_Empty"))) {  return; }
            
            busyDialog.open();
            Car_Inspection.update({id:id, workorder: link_wo
                }).done(function () {
                    funGetInspection();
                    oDialog.close();
                    busyDialog.close();
            });
        }
    });

    var oDialog = new sap.m.Dialog({ contentWidth:"40%",
        title: oBundle.getText("Link_WO"),
        content: [oField1],
        buttons: [ updateBtn,
            new sap.m.Button({ text: oBundle.getText("Cancel"), icon: "sap-icon://decline",
                press: function () { oDialog.close();}
            })
    ]}).open();

}

function secondsToHms12(d) {

     if (d < 60) { return "0h 0m"; }

    d = Number(d);
    var days = 0;
    var h = Math.floor(d / 3600);


    if(h>24){
        days = h/24;
    }

    var m = Math.floor(d % 3600 / 60);
    var s = Math.floor(d % 3600 % 60);

    var hDisplay = h > 0 ? h + (h == 1 ? "h" : "h") : "0h";
    var mDisplay = m > 0 ? m + (m == 1 ? "m" : "m") : "0m";
    var sDisplay = s > 0 ? s + (s == 1 ? "s" : "s") : "";
    return hDisplay + mDisplay + sDisplay; 
}

function secondsToHms(seconds) {
    seconds = Number(seconds);
    var d = Math.floor(seconds / (3600*24));
    var h = Math.floor(seconds % (3600*24) / 3600);
    var m = Math.floor(seconds % 3600 / 60);
    var s = Math.floor(seconds % 60);
    
    var dDisplay = d > 0 ? d + (d == 1 ? "d" : "d") : "";
    var hDisplay = h > 0 ? h + (h == 1 ? "h" : "h") : "";
    var mDisplay = m > 0 ? m + (m == 1 ? "m" : "m") : "";

    return dDisplay + hDisplay + mDisplay ;
    }

function refrenceWorkorder(link_workorder){
    
    var oBread = new sap.m.Breadcrumbs();

    for(var i=0;i<link_workorder.length;i++){
    oBread.addLink(new sap.m.Link({text:link_workorder[i],
    press:function (event) {
        var wo_number = this.getText();
        // var allWOStatusData = [
        //     ...grabPendingWOJSONArray,...grabCancelledWOJSONArray,...grabGrnWOJSONArray,
        //     ...grabClosedWOJSONArray,...grabCompletedWOJSONArray,...grabOpenWOJSONArray,
        //     ...grabRejectWOJSONArray
        // ]
        // var result = allWOStatusData.filter(function (obj, index) {
        //     return (obj.wo_number == wo_number);
        // });
        getAttachedWorkorder(wo_number);
        // if(result.length>0){
        //     workorderViewGrab(result[0],"1");
        // }else{
        //     sap.m.MessageBox.error(oBundle.getText("Workorder_not_available_might_be_deleted"));
        // } 
    }
    }));
    }

     var oDialog = new sap.m.Dialog({
        title: oBundle.getText("Link_Workorder"),
        buttons: [new sap.m.Button({
					    text: oBundle.getText("Close"),
					    icon: "sap-icon://decline",
					    press: function () {
					        oDialog.close();
		}})]
    }).open();

   oDialog.addContent(oBread);
   
}





function showInspection(inspection1,inspection2){
var compareDialog = new sap.m.Dialog({
    title: oBundle.getText("Inspection Comparision"),
    // state: sap.ui.core.ValueState.Error,
    content: [
        new sap.m.HBox({
            justifyContent: "SpaceAround",
            width: "100%",
            items: [
                createInspectionPanel(inspection1),
                createInspectionPanel(inspection2)
            ]
            })
    ],
    buttons: [
        new sap.m.Button({text: oBundle.getText("Compare PDF"),icon: "sap-icon://manager-insight",
            press: function () { 
                showPDFComparisonDialog(
                    inspection1['pdf_url'],
                    inspection2['pdf_url']
                  );
                }
        }),
        new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
            press: function () { compareDialog.close();}
        })
        
    ]
}).open();
}

//oPEN iNSPECTION WITHOUT lICENSE nUMBER FILTER
// function showSelectionDialog() {
//     const combo1 = new sap.m.ComboBox({
//         placeholder: "Select Inspection 1",
//         items: inspectionJSONArray.map(ins =>
//         new sap.ui.core.Item({ key: ins.id, text: ins.report_number })
//         )
//     });

//     const combo2 = new sap.m.ComboBox({
//         placeholder: "Select Inspection 2",
//         items: inspectionJSONArray.map(ins =>
//         new sap.ui.core.Item({ key: ins.id, text: ins.report_number })
//         )
//     });

//     const selectionDialog = new sap.m.Dialog({
//         title: "Compare Inspections",
//         content: [
//         new sap.m.VBox({
//             items: [
//             new sap.m.Label({ text: "Inspection 1" }), combo1,
//             new sap.m.Label({ text: "Inspection 2" }), combo2
//             ]
//         })
//         ],
//         beginButton: new sap.m.Button({
//         text: "Compare",
//         press: function () {
//             const selected1 = combo1.getSelectedKey();
//             const selected2 = combo2.getSelectedKey();

//             if (!selected1 || !selected2 || selected1 === selected2) {
//             sap.m.MessageToast.show("Please select two different inspections.");
//             return;
//             }

//             const ins1 = inspectionJSONArray.find(i => i.id === selected1);
//             const ins2 = inspectionJSONArray.find(i => i.id === selected2);

//             console.log(ins1)
//             console.log(ins2)
//             selectionDialog.close();
//             showInspection(ins1, ins2);
//         }
//         }),
//         endButton: new sap.m.Button({
//         text: "Cancel",
//         press: function () {
//             selectionDialog.close();
//         }
//         })
//     });

//     selectionDialog.open();
// }

// function createInspectionPanel(data) {
//     function labelRow(label, value) {
//         return new sap.m.HBox({
//           alignItems: "Center", // ✅ Vertically center items
//           items: [
//             new sap.m.Label({
//               text: label + ":",
//               width: "160px",
//               design: "Bold"
//             }),
//             new sap.m.Text({
//               text: value || "-"
//             }).addStyleClass("sapUiTinyMarginBottom")
//           ]
//         }).addStyleClass("sapUiTinyMarginBottom");
//       }
      
  
//     // 📌 Parse repair & replace strings into arrays
//     const repairs = data.repair ? data.repair.substring(1).split("^").filter(i => i.trim()) : [];
//     const replaces = data.replace ? data.replace.substring(1).split("^").filter(i => i.trim()) : [];
  
//     // 📌 Repair Table
//     const repairModel = new sap.ui.model.json.JSONModel({ items: repairs.map(item => ({ item })) });
//     const repairTable = new sap.m.Table({
//       columns: [new sap.m.Column({ header: new sap.m.Label({ text: "Repair Item" }) })],
//       items: {
//         path: "/items",
//         template: new sap.m.ColumnListItem({
//           cells: [new sap.m.Text({ text: "{item}" })]
//         })
//       }
//     });
//     repairTable.setModel(repairModel);
  
//     // 📌 Replace Table
//     const replaceModel = new sap.ui.model.json.JSONModel({ items: replaces.map(item => ({ item })) });
//     const replaceTable = new sap.m.Table({
//       columns: [new sap.m.Column({ header: new sap.m.Label({ text: "Replace Item" }) })],
//       items: {
//         path: "/items",
//         template: new sap.m.ColumnListItem({
//           cells: [new sap.m.Text({ text: "{item}" })]
//         })
//       }
//     });
//     replaceTable.setModel(replaceModel);
  
//     // 📌 Download Button
//     const downloadBtn = new sap.m.Button({
//       text: "Download PDF",
//       icon: "sap-icon://download",
//       enabled: data.pdf_url && data.pdf_url.length > 15,
//       press: function () {
//         if (data.uploaded === "0") {
//           sap.m.MessageBox.error("Report not uploaded yet.");
//         } else {
//           window.open(data.pdf_url, "_blank");
//         }
//       }
//     });
  
//     // 📦 Full VBox (Main Panel)
//     return new sap.m.VBox({
//       width: "48%",
//       items: [
//         new sap.m.Title({ text: "Report #: " + data.report_number, level: "H4" }),
        
//         labelRow("Inspection Date", data.inspection_date),
//         labelRow("Time Taken", data.inspection_time + " Minutes"),
//         labelRow("Inspector", data.inspector_name),
//         labelRow("Location", data.location),
//         labelRow("Full Location", data.full_location),
//         labelRow("Vehicle Status", data.vehicle_status),
//         labelRow("License Number", data.license_number),
//         labelRow("Vehicle Model", data.vehicle_model),
//         labelRow("Chassis Number", data.chassis_number),
//         labelRow("Engine Number", data.engine_number),
//         labelRow("Odometer", data.meter_reading),
//         labelRow("Overall Condition", data.overall_condition),
//         labelRow("Safe to Use", data.safe_to_use),
//         labelRow("Maintenance Required", data.maintenance_required),
//         labelRow("Maintenance Priority", data.maintenance_priority),
//         labelRow("Remark", data.remark),
//         labelRow("Group Name", data.group_name),
//         labelRow("Workshop", data.workshop_name),
//         labelRow("Workshop No.", data.workshop_number),
//         downloadBtn,
//         new sap.m.Label({ text: "Repair Items", design: "Bold", class: "sapUiTinyMarginTop" }),
//         repairTable,
//         new sap.m.Label({ text: "Replace Items", design: "Bold", class: "sapUiTinyMarginTop" }),
//         replaceTable
//       ]
//     });
// }
  
function showPDFComparisonDialog(pdfUrl1 = "https://primerentalstg.blob.core.windows.net/prime/INSP1743071362104_1743071395.pdf", pdfUrl2 = "https://primerentalstg.blob.core.windows.net/prime/INSP1741343498_1741343660.pdf") {
    // const iframeStyle = "width: 100%; height: 100%; border: none;";

    const dialog = new sap.m.Dialog({
        title: "Compare Inspection PDFs",
        contentWidth: "90%",
        contentHeight: "80%", // Adjust as needed
        stretch: sap.ui.Device.system.phone,
        resizable: true,
        draggable: true,
        content: [
            new sap.m.HBox({
                width: "100%",
                height: "100%",  // Important: ensure full vertical stretch
                fitContainer: true,
                justifyContent: "Start",
                items: [
                    new sap.ui.core.HTML({
                        content: `<iframe src="${pdfUrl1}" style="width:100%;height:100%;border:none;"></iframe>`,
                        layoutData: new sap.m.FlexItemData({ growFactor: 1 }),
                        width: "50%",
                        height: "100%"
                    }),
                    new sap.ui.core.HTML({
                        content: `<iframe src="${pdfUrl2}" style="width:100%;height:100%;border:none;"></iframe>`,
                        layoutData: new sap.m.FlexItemData({ growFactor: 1 }),
                        width: "50%",
                        height: "100%"
                    })
                ]
            })
        ],
        endButton: new sap.m.Button({
            text: "Close",
            press: function () {
                dialog.close();
            }
        })
    });
    
    dialog.open();
    
    
    
    

}
  
function createInspectionPanel(data) {
    // 📌 Title Row
    function titleRow(text) {
        return new sap.m.Title({
            text: text,
            level: "H6", // You can adjust the level based on the desired appearance
            width: "100%",
            class: "sapUiTinyMarginBottom"
        });
    }

    // 📌 Parse repair & replace strings into arrays
    const repairs = data.repair ? data.repair.substring(1).split("^").filter(i => i.trim()) : [];
    const replaces = data.replace ? data.replace.substring(1).split("^").filter(i => i.trim()) : [];

    // 📌 Repair Table
    const repairModel = new sap.ui.model.json.JSONModel({ items: repairs.map(item => ({ item })) });
    const repairTable = new sap.m.Table({
      columns: [new sap.m.Column({ header: new sap.m.Label({ text: "Repair Item" }) })],
      items: {
        path: "/items",
        template: new sap.m.ColumnListItem({
          cells: [new sap.m.Text({ text: "{item}" })]
        })
      },
      width: "100%" // Make sure the table takes full width
    });
    repairTable.setModel(repairModel);

    // 📌 Replace Table
    const replaceModel = new sap.ui.model.json.JSONModel({ items: replaces.map(item => ({ item })) });
    const replaceTable = new sap.m.Table({
      columns: [new sap.m.Column({ header: new sap.m.Label({ text: "Replace Item" }) })],
      items: {
        path: "/items",
        template: new sap.m.ColumnListItem({
          cells: [new sap.m.Text({ text: "{item}" })]
        })
      },
      width: "100%" // Make sure the table takes full width
    });
    replaceTable.setModel(replaceModel);

    // 📌 Download Button
    const downloadBtn = new sap.m.Button({
      text: "Download PDF",
      icon: "sap-icon://download",
      enabled: data.pdf_url && data.pdf_url.length > 15,
      press: function () {
        if (data.uploaded === "0") {
          sap.m.MessageBox.error("Report not uploaded yet.");
        } else {
          window.open(data.pdf_url, "_blank");
        }
      }
    });

    // 📦 Full VBox (Main Panel)
    return new sap.m.VBox({
      width: "48%",
      items: [
        new sap.m.Title({ text: "Report #: " + data.report_number, level: "H4" }),
        titleRow("Inspection Date: " + data.inspection_date),
        titleRow("Time Taken: " + data.inspection_time + " Minutes"),
        titleRow("Inspector: " + data.inspector_name),
        titleRow("Location: " + data.location),
        titleRow("Full Location: " + data.full_location),
        titleRow("Vehicle Status: " + data.vehicle_status),
        titleRow("License Number: " + data.license_number),
        titleRow("Vehicle Model: " + data.vehicle_model),
        titleRow("Chassis Number: " + data.chassis_number),
        titleRow("Engine Number: " + data.engine_number),
        titleRow("Odometer: " + data.meter_reading),
        titleRow("Overall Condition: " + data.overall_condition),
        titleRow("Safe to Use: " + data.safe_to_use),
        titleRow("Maintenance Required: " + data.maintenance_required),
        titleRow("Maintenance Priority: " + data.maintenance_priority),
        titleRow("Remark: " + data.remark),
        titleRow("Group Name: " + data.group_name),
        titleRow("Workshop: " + data.workshop_name),
        titleRow("Workshop No: " + data.workshop_number),
        titleRow("Battery Info: " + data.battery_info),
        titleRow("Tyre Info: " + data.tyre_info),
        downloadBtn,
        new sap.m.Label({ text: "Repair Items", design: "Bold", class: "sapUiTinyMarginTop" }),
        repairTable,
        new sap.m.Label({ text: "Replace Items", design: "Bold", class: "sapUiTinyMarginTop" }),
        replaceTable
      ],
      alignItems: "Stretch" // Ensure the elements stretch and fill the VBox properly
    });
}

function showSelectionDialog() {

    // const licenseComboBox = new sap.m.ComboBox({
    //     width:"90%",
    //     placeholder: "Select License Number",
    //     items: [],
    //     change:function(){
    //         const selectedLicense = licenseComboBox.getSelectedKey();
    //         if (selectedLicense) {
    //             combo1.setEnabled(true);  // Enable combo boxes when license is selected
    //             combo2.setEnabled(true);  // Enable combo boxes when license is selected
    //             filterInspectionsByLicense(selectedLicense);  // Filter inspections based on selected license
    //         }
    //     }

    // });

    const licenseInput = new sap.m.Input({
        placeholder:"Enter License Number",
        change:function(){
            var license_number = licenseInput.getValue();
            if (license_number) {
                combo1.setEnabled(true);  // Enable combo boxes when license is selected
                combo2.setEnabled(true);  // Enable combo boxes when license is selected
                filterInspectionsByLicense(license_number);  // Filter inspections based on selected license
            }
        }
    })

    // ComboBoxes for Inspection 1 and Inspection 2 (disabled initially)
    // const combo1 = new sap.m.ComboBox({
    //     width:"90%",
    //     placeholder: "Select Inspection 1",
    //     enabled: false,  // Initially disabled
    //     items: []
    // });

    // const combo2 = new sap.m.ComboBox({
    //     width:"90%",
    //     placeholder: "Select Inspection 2",
    //     enabled: false,  // Initially disabled
    //     items: []
    // });


    const combo1 = new sap.m.Input({
        width: "90%",
        placeholder: "Select Inspection 1",
        showValueHelp: true,
        enabled: false,
        valueHelpRequest: function () {
            openInspectionSelectionDialog("combo1",licenseInput,combo1);
        }
    });
    
    const combo2 = new sap.m.Input({
        width: "90%",
        placeholder: "Select Inspection 2",
        showValueHelp: true,
        enabled: false,
        valueHelpRequest: function () {
            openInspectionSelectionDialog("combo2",licenseInput,combo2);
        }
    });

    
    function filterInspectionsByLicense(licenseNumber) {

        combo1.setValue('');
        combo2.setValue('');
        
    }

    const selectionDialog = new sap.m.Dialog({
        title: "Compare Inspections",
        content: [
            new sap.m.VBox({
                items: [
                    new sap.m.Label({ text: "License Number" }), licenseInput,
                    new sap.m.Label({ text: "Inspection 1" }), combo1,
                    new sap.m.Label({ text: "Inspection 2" }), combo2
                ]
            })
        ],
        beginButton: new sap.m.Button({
            text: "Compare",
            press: function () {
                const selected1 = combo1.getValue();
                const selected2 = combo2.getValue();

                if (!selected1 || !selected2 || selected1 === selected2) {
                    sap.m.MessageToast.show("Please select two different inspections.");
                    return;
                }

                const ins1 = inspectionJSONArray.find(i => i.report_number === selected1);
                const ins2 = inspectionJSONArray.find(i => i.report_number === selected2);

                selectionDialog.close();
                showInspection(ins1, ins2);
            }
        }),
        endButton: new sap.m.Button({
            text: "Cancel",
            press: function () {
                selectionDialog.close();
            }
        })
    }).open();

    //Bind License Number
    // const uniqueLicenses = [...new Set(inspectionJSONArray.map(ins => ins.license_number))];  // Get unique license numbers
    // uniqueLicenses.map(license =>
    //     licenseComboBox.addItem(new sap.ui.core.Item({
    //         key: license,
    //         text: license
    //     }))
    // )

}

function openInspectionSelectionDialog(comboId, licenseInput, combo) {
    const selectedLicense = licenseInput.getValue();
    if (!selectedLicense) {
        sap.m.MessageToast.show("Please select a license number first.");
        return;
    }

    const filtered = inspectionJSONArray.filter(ins =>
        ins.license_number === selectedLicense //&&
        // (ins.repair?.trim() !== "" || ins.replace?.trim() !== "")
    );

    const selectionModel = new sap.ui.model.json.JSONModel({ items: filtered });

    const table = new sap.m.Table({
        mode: "SingleSelectLeft",
        columns: [
            new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Report_No"), 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({ wrapping: true, text: oBundle.getText("Vehicle_Details"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Desktop", popinDisplay: "Inline", demandPopin: true }),
            new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Location"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Left" }),
            new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Inspector"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Desktop", popinDisplay: "Inline", demandPopin: true, hAlign: "Left" }),
            new sap.m.Column({ header: new sap.m.Label({ text: oBundle.getText("Fault"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Tablet", popinDisplay: "Inline", demandPopin: true, hAlign: "Center" }),
            new sap.m.Column({ header: new sap.m.Label({ wrapping: true, text: oBundle.getText("Linked_Wo"), design: sap.m.LabelDesign.Bold }), minScreenWidth: "Desktop", popinDisplay: "Inline", demandPopin: true, hAlign: "Left" }),
            new sap.m.Column({ header: TableHeader.clone().setText(oBundle.getText("Note")), minScreenWidth: "2500px", popinDisplay: "Inline", demandPopin: true }),
        ],
        items: {
            path: "/items",
            template: new sap.m.ColumnListItem({
                cells: [
                    new sap.m.VBox({
                        items: [
                            new sap.m.Label({ wrapping: true, text: "{report_number}" }),
                            new sap.tnt.InfoLabel({
                                colorScheme: 3,
                                text: {
                                    path: "vehicle_status",
                                    formatter: function (vehicle_status) {
                                        if (vehicle_status === "Breakdown") {
                                            this.setVisible(true);
                                            return oBundle.getText("Breakdown");
                                        }
                                        this.setVisible(false);
                                        return "";
                                    }
                                }
                            }).addStyleClass("sapUiTinyMarginTop"),
                        ]
                    }).addStyleClass("sapUiTinyMargin"),
                    new sap.m.Label({ wrapping: true, text: "{inspection_date}" }),
                    new sap.m.VBox({
                        items: [
                            new sap.m.Label({ wrapping: true, text: "{license_number}" }),
                            new sap.m.Label({ wrapping: true, text: "{chassis_number}" }).addStyleClass("sapUiTinyMarginTop"),
                        ]
                    }).addStyleClass("sapUiTinyMargin"),
                    new sap.m.Label({ wrapping: true, text: "{location}" }),
                    new sap.m.Label({ wrapping: true, text: "{inspector_name}" }),
                    new sap.m.Button({
                        icon: "sap-icon://message-warning",
                        type: sap.m.ButtonType.Reject,
                        text: {
                            parts: ["repair", "replace"],
                            formatter: function (repair, replace) {
                                const repairCount = repair ? repair.split("^").length - 1 : 0;
                                const replaceCount = replace ? replace.split("^").length - 1 : 0;
                                const total = repairCount + replaceCount;
                                this.setVisible(total > 0);
                                return total;
                            }
                        },
                        press: function (event) {
                            const model = this.getModel();
                            const path = event.getSource().getBindingContext().getPath();
                            const obj = model.getProperty(path);
                            viewDefect(obj.repair, obj.replace,obj['id']);
                        }
                    }),
                    new sap.m.Link({
                        emphasized: true,
                        text: {
                            path: "workorder",
                            formatter: function (workorder) {
                                if (!workorder) return "";
                                const parts = workorder.split("^");
                                return parts.length === 1 ? parts[0] : `${parts[0]}/...`;
                            }
                        },
                        press: function (event) {
                            const model = this.getModel();
                            const path = event.getSource().getBindingContext().getPath();
                            const obj = model.getProperty(path);
                            const refArray = obj.workorder?.split("^") || [];
                            refrenceWorkorder(refArray, obj.license_number);
                        }
                    }),
                    new sap.m.HBox({
                        items: [
                            new sap.m.Label({ wrapping: true, text: "{group_name}" }).addStyleClass("sapUiTinyMarginEnd sapUiTinyMarginTop"),
                            new sap.m.Button({
                                icon: "sap-icon://pdf-attachment",
                                type: sap.m.ButtonType.Transparent,
                                text: {
                                    path: "uploaded",
                                    formatter: function (uploaded) {
                                        const visible = uploaded && uploaded !== "";
                                        this.setVisible(visible);
                                        return "";
                                    }
                                },
                                press: function (e) {
                                    const model = this.getModel();
                                    const path = e.getSource().getBindingContext().getPath();
                                    const obj = model.getProperty(path);
                                    window.open(obj.pdf_url, "_blank");
                                }
                            })
                        ]
                    }),
                    new sap.m.Label({
                        text: {
                            parts: ["remark", "repair_note", "replace_note"],
                            formatter: function (remark, repair_note, replace_note) {
                                return [remark, repair_note, replace_note]
                                    .filter(Boolean)
                                    .join(", ")
                                    .replace(/\^/g, ", ");
                            }
                        }
                    })
                ]
            })
        }
    });
    table.setModel(selectionModel);

    // Add SearchField
    const searchField = new sap.m.SearchField({
        width: "100%",
        placeholder: "Search by Report No, License No, or Group Name",
        liveChange: function (oEvent) {
            const query = oEvent.getParameter("newValue");
            const filters = [];

            if (query) {
                filters.push(new sap.ui.model.Filter({
                    filters: [
                        new sap.ui.model.Filter("report_number", sap.ui.model.FilterOperator.Contains, query),
                        new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, query),
                        new sap.ui.model.Filter("group_name", sap.ui.model.FilterOperator.Contains, query),
                        new sap.ui.model.Filter("inspection_date", sap.ui.model.FilterOperator.Contains, query),
                        new sap.ui.model.Filter("location", sap.ui.model.FilterOperator.Contains, query),
                        new sap.ui.model.Filter("inspector_name", sap.ui.model.FilterOperator.Contains, query),
                        new sap.ui.model.Filter("inspector_id", sap.ui.model.FilterOperator.Contains, query),
                    ],
                    and: false
                }));
            }

            table.getBinding("items").filter(filters, "Application");
        }
    });

    // Create and open dialog
    const dialog = new sap.m.Dialog({
        title: "Select Inspection",
        contentWidth: "70%",
        contentHeight: "80%",
        content: [searchField, table],
        beginButton: new sap.m.Button({
            text: "Select",
            press: function () {
                const selectedItem = table.getSelectedItem();
                if (selectedItem) {
                    const context = selectedItem.getBindingContext();
                    const selectedData = context.getObject();
                    combo.setValue(selectedData.report_number);
                    combo.data("selectedId", selectedData.id);
                    dialog.close();
                } else {
                    sap.m.MessageToast.show("Please select one inspection.");
                }
            }
        }),
        endButton: new sap.m.Button({
            text: "Cancel",
            press: function () {
                dialog.close();
            }
        })
    });

    dialog.open();
}




