//Staging
var api_url_name_main = 'https://grab-api-stg.azurewebsites.net';
var jaya_api_url_name = 'https://partner-api.grab.com'
var jrs_go_api_url_name_main = 'https://grab-api-stg.oxmaint.com'
var jrs_go_api_url_name1_main = 'https://grab-prime-api-stg.azurewebsites.net'
var jrs_go_api_key = '175f8336cd40276b457300cbbe28bdbefc6024ad1d557ac99931510a1856a38b';
var jrs_go_api_key1 = '5b815e54c05f7268ea2ac29437b517a8114f55b1b8e9fe761bf90179433127d5';



//Production
if(client.applicationUrl == 'https://grab-taxi-prod.azurewebsites.net/'){
    api_url_name_main = 'https://grab-api-prod.azurewebsites.net';
    jaya_api_url_name = 'https://partner-api.grab.com';
    jrs_go_api_url_name_main = 'https://prime-api.oxmaint.com';
    jrs_go_api_url_name1_main = 'https://grab-prime-api-prod.azurewebsites.net'
    jrs_go_api_key = 'e253dc138711a9f27802e602f97931e720956c3a89aea0bba1280f21d87dfa4d';
    jrs_go_api_key1 = '5b815e54c05f7268ea2ac29437b517a8114f55b1b8e9fe761bf90179433127d5';
    driverReminderDays = {
        6: "1 time in 28 calendar days",
        8: "1 time in 14 calendar days",
        9: "1 time in 14 calendar days",
        10: "5 times in a week",
        17: "1 time in 14 calendar days",
        25: "1 times in a week",
        26: "1 time in 28 calendar days",
        27: "1 times in a week",
        28: "5 times in a week",
        29: "1 time in 14 calendar days",
        30: "1 time in 14 calendar days",
        31: "1 time in 14 calendar days",
        32: "1 times in a week",
        33: "1 times in a week",
        34: "1 times in a week"
    };
    
    driverTypeArray = {
        "6": "Gold",
        "8": "Greenline",
        "9": "Sahabat Rental",
        "10": "EV",
        "17": "Sahabat Sejati",
        "25": "Sahabat Rental HVR",
        "26": "Emoto",
        "27": "Premium EV",
        "28": "Premium Non EV",
        "29": "Sahabat Rental Airport",
        "30": "Sahabat Rental HVR ICE Airport",
        "31": "Sahabat Rental Plus",
        "32": "Sahabat Rental HVR EV",
        "33": "Sahabat Rental HVR EV Airport",
        "34": "Sahabat Rental HVR ICE"
      }

};









var api_url_name = `${api_url_name_main}/V01`;
var  jrs_go_api_url_name = `${jrs_go_api_url_name_main}/api/v1`;
var  jrs_go_api_url_name1 = `${jrs_go_api_url_name1_main}/api/v1`;

//ALl Table Define
var Grab_Checklist1 = client.getTable('Grab_Checklist1');
var Grab_Checklist2 = client.getTable('Grab_Checklist2');
var Grab_Checklist3 = client.getTable('Grab_Checklist3');

var Approval_Master = client.getTable('Approval_Master');
var Car_Driver_Master = client.getTable('Car_Driver_Master');

var Car_Inspection = client.getTable('Car_Inspection');
var Car_Inspection_Item = client.getTable('Car_Inspection_Item');

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

var Car_Vehicle_Master =  client.getTable('Car_Vehicle_Master');
var Car_User_Master =  client.getTable('Car_User_Master');
var Part_Master =  client.getTable('Part_Master');
var Car_Schedule = client.getTable("Car_Schedule");
var Supplier_Master = client.getTable('Supplier_Master');
var Car_Insurance_Renewal =  client.getTable('Car_Insurance_Renewal');

var Car_Workshop = client.getTable('Car_Workshop');
var Car_Workshop_Master = client.getTable('Car_Workshop_Master');

var Car_Workorder = client.getTable("Car_Workorder");
var Car_Workorder_Status = client.getTable("Car_Workorder_Status");
var Car_Workorder_Part = client.getTable("Car_Workorder_Part");
var Car_Workorder_Remark = client.getTable("Car_Workorder_Remark");
var Car_Workorder_Attachment = client.getTable("Car_Workorder_Attachment");


if(portal_type_flag == "2W"){


    api_url_name = `${api_url_name_main}/Bike_V01`;
    jrs_go_api_url_name = `${jrs_go_api_url_name_main}/api/v1/bike`;
    jrs_go_api_url_name1 = `${jrs_go_api_url_name1_main}/api/v1/bike`;
    /*
    Approval_Master = client.getTable('Approval_Master');
    Supplier_Master = client.getTable('Supplier_Master');
    Car_Insurance_Renewal =  client.getTable('Car_Insurance_Renewal');
    */
   
   
    Part_Master =  client.getTable('Bike_Part_Master');
    Grab_Checklist1 = client.getTable('Bike_Checklist1');
    Grab_Checklist2 = client.getTable('Bike_Checklist2');
    Grab_Checklist3 = client.getTable('Bike_Checklist3');

    Car_Driver_Master = client.getTable('Bike_Driver_Master');
    
    Car_Inspection = client.getTable('Bike_Inspection');
    Car_Inspection_Item = client.getTable('Bike_Inspection_Item');
    
    Car_Invoice =  client.getTable('Bike_Invoice');
    Car_Invoice_Item =  client.getTable('Bike_Invoice_Item');
    Car_Schedule = client.getTable('Bike_Schedule');
    
    Car_User_Master =  client.getTable('Bike_User_Master');
    Car_Vehicle_Master =  client.getTable('Bike_Vehicle_Master');

    Car_Workshop = client.getTable('Bike_Workshop');
    Car_Workshop_Master = client.getTable('Bike_Workshop_Group');

    Car_Workorder = client.getTable('Bike_Workorder');
    Car_Workorder_Status = client.getTable('Bike_Workorder_Status');
    Car_Workorder_Part = client.getTable('Bike_Workorder_Part');
    Car_Workorder_Remark = client.getTable('Bike_Workorder_Remark');
    Car_Workorder_Attachment = client.getTable('Bike_Workorder_Attachment');
    
}


//Get Index numbers
function getWOIndex(input){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_index.asmx/get_grab_index`,
        data: {
            "master_email": emailUser
        },
        success: function (data) { 
            
            
           
           var index = "000000"+(parseInt(data[0]['wo_number'])+1);

           var index1 = index.substr(-6);

           var newNumber = (portal_type_flag+getIndexDate()+index1)
            input.setText(newNumber);
            // workorderID = (newNumber);

            //4W-YY-MM-DD-000001 (e.g., 4W250123 000001).
        }
    });

}
//Get Part ID
function getPartsIdAPIParts(latestPartId){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_index.asmx/get_grab_index`,
        data: {
            "master_email": emailUser
        },
        success: function (data) { 
            latestPartId.setValue(parseInt(data[0]['part_id']) + 1);
           
        }
    });
}
function getPartsIdAPI(latestPartId){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_index.asmx/get_grab_index`,
        data: {
            "master_email": emailUser
        },
        success: function (data) { 
            latestPartId = data[0]['part_id'];
            
            uploadDialogPartsExcel(parseInt(latestPartId) + 1);
           
        }
    });
}
//Update Bulk Part ID
function updateBulkPartsIdAPI(latestPartId){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_index.asmx/get_and_update_part_index_bulk`,
        data: {
            "master_email": emailUser,
            "count":latestPartId
        },
        success: function (data) { 
           
        }
    });
}
//Get Workshop Number
function getWorkshopIndex(input){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_index.asmx/get_grab_index`,
        data: {
            "master_email": emailUser
        },
        success: function (data) { 
            
            input.seValue(data[0]['workshop_number']);
           
        }
    });
}
//Get Workshop Group Number
function getWorkshopGroupIndex(input){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_index.asmx/get_grab_index`,
        data: {
            "master_email": emailUser
        },
        success: function (data) { 
            
            input.seValue(data[0]['ws_group_number']);
           
        }
    });
}
//Get Supplier Number
function getSupplierIndex(input){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_index.asmx/get_grab_index`,
        data: {
            "master_email": emailUser
        },
        success: function (data) { 

            input.seValue(data[0]['supplier_number']);
           
        }
    });
}




function getFinalWorkorderNumber(){
    $.ajax({
        type: "POST",
        url:  `${api_url_name}/Grab_index.asmx/get_and_update_wo_index`,
        data: {
            "master_email": emailUser
        },
        success: function (data) { 
            
        
           var index = "000000"+(parseInt(data['wo_number']));
           var index1 = index.substr(-6);
    
            var wo_number = portal_type_flag+getIndexDate()+index1;
    

            // workorderID = wo_number;
            createWorkOrderSubmit(wo_number);
           
        }, error: function (xhr, status, error) {
            oBusyDialogWO.close();
            sap.m.MessageBox.error("Operation failed -index error");
        }
    }); 
}

function getAccessToken() {

// avd
    $.ajax({
            type: 'POST',
            // url: "https://partner-api.grab.com/grabid/v1/oauth2/token",
            url: `${api_url_name}/grabid/v1/oauth2/token`,
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify({
                "client_id": "client_id",
                "client_secret": "client_secret",
                "grant_type": "client_credentials",
                "scope": "jaya.jrs_integration"
            }),
            success: function (data) {
                

                // {
                //      "access_token": "eyJhbGc...",
                //      "token_type": "Bearer",
                //      "expires_in": 7199
                //      }
            },
            error: function (xhr, status, error) {
                console.error("Error:", status, error);
            }
        });

}

function funVehicleUpdate(vehicleId,licenseNo,locationId,locationName,locationType,vehicleStatus,lastUpdatedAt) {

    $.ajax({
        type: 'PUT',
        // url: "https://partner-api.grab.com/jaya/partner/dax/v1/vehicle",
        url: `${api_url_name}/jaya/partner/dax/v1/vehicle`,
        headers: {Authorization: "Bearer token"},
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({
            "vehicleId": vehicleId,
            "licenseNo": licenseNo,
            "locationId": locationId,
            "locationName": locationName,
            "locationType": locationType,
            "vehicleStatus": vehicleStatus,
            "lastUpdatedAt": lastUpdatedAt, //"2025-01-14T04:05:27Z",
            
                
        }),
        success: function (data) {

        },
        error: function (xhr, status, error) {
            console.error("Error:", status, error);
        }
    });

}


//After Workorder create Update Attachent, Remark, parts
function updateWoPartsNumber(workorderID,wo_number){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/update_wo_number_in_part_remark_attachment`,
        data: {
            "master_email": emailUser,
            "wo_id":workorderID+"",
            "wo_number":wo_number
        },
        success: function (data) { 
            
        }, error: function (xhr, status, error) {
            console.log(error)
        }
    });    
};

//Get all vehicle data
function getAllVehicleData(){
    
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Vehicle.asmx/get_vehicle_all`,
        data: {
            // "master_email": "admin@grab.com"//emailUser,
            "master_email": emailUser,
        },
        success: function (data) { 

            vehicle4WJSONData = data
          
            var assignVehicleValues = data;
            // let oxmaint_role = sessionStorage.getItem('oxmaint_role');
            // if(!allowedRoles.includes(oxmaint_role)){
            //     assignVehicleValues = filterGrabVehicle(assignVehicleValues);
            // }

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

            var oBinding = oTableFourWheeler.getBinding("items");
            oBinding.filter(aVehicleFilters);

            oTFWOV1.setModel(oModel);
            oTFWOV1.bindAggregation("suggestionItems", "/modelData", new sap.ui.core.ListItem({
                key:"{license_number}",text: "{license_number}", additionalText:"{chassis_number}"}));


            // oTablePickVehicle.setModel(oModel);
            // oTablePickVehicle.bindItems({ path: "/modelData", template: PickVehicleTemplate });

            for (var i = 0; i < vehicle4WJSONData.length; i++) {
                var vehicle = vehicle4WJSONData[i]['license_number'];
                vehicle4WArray = vehicle4WArray.concat(vehicle);

            }
            busyDialog.close();
        }, error: function (xhr, status, error) {
            busyDialog.close();
            console.log(error)
        }
    });    
};

//get Assigned Vehicle Data
function getAssignedVehicleData(){
    
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Vehicle.asmx/get_assigned_vehicle`,
        data: {
            "master_email": emailUser,
            "vehicle_list": hvi_assign_vehicle
        },
        success: function (data) { 

            vehicle4WJSONData = data
          
            var assignVehicleValues = data;
            // let oxmaint_role = sessionStorage.getItem('oxmaint_role');
            // if(!allowedRoles.includes(oxmaint_role)){
            //     assignVehicleValues = filterGrabVehicle(assignVehicleValues);
            // }

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

            var oBinding = oTableFourWheeler.getBinding("items");
            oBinding.filter(aVehicleFilters);

            oTFWOV1.setModel(oModel);
            oTFWOV1.bindAggregation("suggestionItems", "/modelData", new sap.ui.core.ListItem({
                key:"{license_number}",text: "{license_number}", additionalText:"{chassis_number}"}));


            // oTablePickVehicle.setModel(oModel);
            // oTablePickVehicle.bindItems({ path: "/modelData", template: PickVehicleTemplate });

            for (var i = 0; i < vehicle4WJSONData.length; i++) {
                var vehicle = vehicle4WJSONData[i]['license_number'];
                vehicle4WArray = vehicle4WArray.concat(vehicle);

            }
            busyDialog.close();
        }, error: function (xhr, status, error) {
            busyDialog.close();
            oTableFourWheeler.setBusy(false);
            console.log(error)
        }
    });    
}

//Get All Parts
function getPartsDetails(){
    oTable4WPartMaster.setBusy(true);
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_part_master`,
        data: {
            "master_email": emailUser,
        },
        success: function (data) { 
            // results =  "";
            // let oxmaint_role = sessionStorage.getItem('oxmaint_role');

            // if(allowedRoles.includes(oxmaint_role) ){
            //     results = data;
            // }else{
            //     results = data.filter(function(val,ind){
            //         return val.workshop_number == oxmaint_workshop_number;
            //     })
            // }
            partMaster4WJSONData = data;  

            data.sort((a, b) => {
                let dateA = new Date(a.created_date.replace(/(\d{2})-([A-Za-z]+)-(\d{4}) (.*)/, '$1 $2 $3 $4'));
                let dateB = new Date(b.created_date.replace(/(\d{2})-([A-Za-z]+)-(\d{4}) (.*)/, '$1 $2 $3 $4'));
                return dateB - dateA; // Ascending order
            });

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

        }, error: function (xhr, status, error) {
            oTable4WPartMaster.setBusy(false);
            console.log(error)
        }
    }); 
};
//Get Workshop Parts
function getPartsDetailsWorkshop(workshop_number){
    
    oTable4WPartMaster.setBusy(true);
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_part_master_by_workshop_number`,
        data: {
            "master_email": emailUser,
            "workshop_number":workshop_number
        },
        success: function (data) { 
            
            partMaster4WJSONData = data;            
            data.sort((a, b) => {
                let dateA = new Date(a.created_date.replace(/(\d{2})-([A-Za-z]+)-(\d{4}) (.*)/, '$1 $2 $3 $4'));
                let dateB = new Date(b.created_date.replace(/(\d{2})-([A-Za-z]+)-(\d{4}) (.*)/, '$1 $2 $3 $4'));
                return dateB - dateA; // Ascending order
            });

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

        }, error: function (xhr, status, error) {
            oTable4WPartMaster.setBusy(false);
            console.log(error)
        }
    }); 
};
//Get Workorder Filtered Parts
function getWOrkorderFilteredParts(workshop_number,make,model,transmission){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_workorder_filtered_parts`,
        data: {
            "master_email": emailUser,
            "workshop_number":workshop_number,
            "make":make,
            "model":model,
            "transmission":transmission
        },
        success: function (data) { 

            workorderPartJSONArray = data;
            
            var oModel12 = new sap.ui.model.json.JSONModel();
            oModel12.setData({ modelData: data }); // results is an array of suggestion data
            oInputPartField1.setModel(oModel12);

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

};


//GET Workorder detail report Workshop
function workorderDetailAPi(startDate,endDate) {
    busyDialog.open();
    // Format dates correctly
    var requestBody = {
        "master_email": emailUser,
        "start_date": startDate,  // Match Swagger format
        "end_date": endDate,    // Match Swagger format
        "page": 0,
        "page_size": 0
    };

    
 
    // Make API call
    $.ajax({
        url: `${jrs_go_api_url_name}/work_order/get_wo_part_inv_details`,
        method: 'POST',
        headers: {
            //  'X-API-Key': 'e253dc138711a9f27802e602f97931e720956c3a89aea0bba1280f21d87dfa4d',
             'X-API-Key': jrs_go_api_key,
            'Content-Type': 'application/json'
        },
        data: JSON.stringify(requestBody),
        success: function(response) {
            
            let dataValues = response['data']['data'];
            console.log(dataValues)
            if(dataValues == 'No data for current filters'){
                sap.m.MessageBox.information(oBundle.getText("No_record_found"));
                busyDialog.close();
            }else{

                let oxmaint_role = sessionStorage.getItem('oxmaint_role');
                if(allowedRoles.includes(oxmaint_role) ){
                    
                }else if(oxmaint_role == 'Workshop Group Admin'){
                    dataValues = dataValues.filter(a => a.ws_group_number == oxmaint_ws_group_number);
                }else{
                    dataValues = dataValues.filter(a => a.workshop_number == oxmaint_workshop_number);
                };

                if(dataValues.length < 1){
                    sap.m.MessageBox.information(oBundle.getText("No_record_found"));
                    busyDialog.close();
                    return; 
                }

                dataValues.sort((a, b) => {
                    let dateA = new Date(a.created_date.replace(/(\d{2})-([A-Za-z]+)-(\d{4}) (.*)/, '$1 $2 $3 $4'));
                    let dateB = new Date(b.created_date.replace(/(\d{2})-([A-Za-z]+)-(\d{4}) (.*)/, '$1 $2 $3 $4'));
                    return dateA - dateB; // Ascending order
                });
                reportGrabWODetail(dataValues)
                busyDialog.close();
            }
          
        },
        error: function(xhr, status, error) {
            busyDialog.close();
            
            console.error("=== API Error Details ===");
            console.error("Request Body:", requestBody);
            console.error("Status:", status);
            console.error("Error:", error);
            console.error("Status Code:", xhr.status);
            console.error("Status Text:", xhr.statusText);
            console.error("Response Text:", xhr.responseText);
            
            try {
                var errorResponse = JSON.parse(xhr.responseText);
                console.error("Parsed Error:", errorResponse);
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "Message: " + (errorResponse.message || error)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "Message: " + xhr.responseText
                );
            }
        }
    });
};

//GET Workorder detail report Supplier
function workorderDetailSupplierAPi(startDate,endDate) {
    busyDialog.open();
    // Format dates correctly
    var requestBody = {
        "master_email": emailUser,
        "start_date": startDate,  // Match Swagger format
        "end_date": endDate,    // Match Swagger format
        "page": 0,
        "page_size": 0
    };

    
 
    // Make API call
    $.ajax({
        url: `${jrs_go_api_url_name}/work_order/get_supplier_wo_part_inv_details`,
        method: 'POST',
        headers: {
            //  'X-API-Key': 'e253dc138711a9f27802e602f97931e720956c3a89aea0bba1280f21d87dfa4d',
             'X-API-Key': jrs_go_api_key,
            'Content-Type': 'application/json'
        },
        data: JSON.stringify(requestBody),
        success: function(response) {
            
            let dataValues = response['data']['data'];
            console.log(response)
            console.log(dataValues)
            if(dataValues == 'No data for current filters'){
                sap.m.MessageBox.information(oBundle.getText("No_record_found"));
                busyDialog.close();
            }else{

                let oxmaint_role = sessionStorage.getItem('oxmaint_role');
                if(allowedRoles.includes(oxmaint_role) || oxmaint_role == 'Supplier'){
                    
                }else if(oxmaint_role == 'Workshop Group Admin'){
                    dataValues = dataValues.filter(a => a.ws_group_number == oxmaint_ws_group_number);
                }else{
                    dataValues = dataValues.filter(a => a.workshop_number == oxmaint_workshop_number);
                };

                if(dataValues.length < 1){
                    sap.m.MessageBox.information(oBundle.getText("No_record_found"));
                    busyDialog.close();
                    return; 
                }

                dataValues.sort((a, b) => {
                    let dateA = new Date(a.created_date.replace(/(\d{2})-([A-Za-z]+)-(\d{4}) (.*)/, '$1 $2 $3 $4'));
                    let dateB = new Date(b.created_date.replace(/(\d{2})-([A-Za-z]+)-(\d{4}) (.*)/, '$1 $2 $3 $4'));
                    return dateA - dateB; // Ascending order
                });
                reportGrabSupplierWODetail(dataValues)
                busyDialog.close();
            }
          
        },
        error: function(xhr, status, error) {
            busyDialog.close();
            
            console.error("=== API Error Details ===");
            console.error("Request Body:", requestBody);
            console.error("Status:", status);
            console.error("Error:", error);
            console.error("Status Code:", xhr.status);
            console.error("Status Text:", xhr.statusText);
            console.error("Response Text:", xhr.responseText);
            
            try {
                var errorResponse = JSON.parse(xhr.responseText);
                console.error("Parsed Error:", errorResponse);
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "Message: " + (errorResponse.message || error)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "Message: " + xhr.responseText
                );
            }
        }
    });
};



//Filter Particular Vehicle With Search in select vehicle
function getVehicleByLicenseNumber(value){
    oTablePickVehicle.setBusy(true);
    
    if(value.length > 7){
        $.ajax({
            type: "POST",
            url: `${api_url_name}/Vehicle.asmx/get_vehicle_by_license_number`,
            data: {
                "master_email": emailUser,
                "license_number":value
            },
            success: function (data) { 

                if(data.length > 0){

                    var oModel = new sap.ui.model.json.JSONModel();
                    oModel.setData({ modelData: data });
                    oTablePickVehicle.setModel(oModel);
                    oTablePickVehicle.bindItems({ path: "/modelData", template: PickVehicleTemplate });   
                    oTablePickVehicle.setBusy(false);
                }else{
                    sap.m.MessageBox.error("No Vehicle Found");
                    oTablePickVehicle.setBusy(false);
                    return ;
                }
            },
            error: function(xhr, status, error) {
                oTablePickVehicle.setBusy(false);

            }
        });
    } else{
        sap.m.MessageBox.alert("Enter at least 8 characters to search for a vehicle");
        oTablePickVehicle.setBusy(false);
    }   

};


//Workorder get API
function getWorkorderByStatus(status,variableJSONArray,tableName){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_workorder_by_status`,
        data: {
            "master_email": emailUser,
            "wo_status":status
        },
        success: function (data) { 
     
            // if(data.length > 0 ){
                // var results = filterGrabVehicle(data);
                var results = data;
        
                if(status == 'Pending Approval'){ grabPendingWOJSONArray = results;
                }else if(status == 'Reject'){ grabRejectWOJSONArray = results;
                }else if(status == 'Open'){ grabOpenWOJSONArray = results;
                }else if(status == 'Completed'){ grabCompletedWOJSONArray = results;
                }else if(status == 'Closed'){ grabClosedWOJSONArray = results;
                }else if(status == 'GRN'){ 
                    grabGrnWOJSONArray = results;

                    //Invoice GRN
                    var oModel = new sap.ui.model.json.JSONModel();
                    oModel.setData({ modelData: results });
                    oTable4WAllInvoiceGRN.setModel(oModel);
                
                    oTable4WAllInvoiceGRN.bindItems({ path: "/modelData", template : oTable4WAllInvoiceGRNTemplate});
                    oTable4WAllInvoiceGRN.setBusy(false);
                }else if(status == 'Cancelled'){ grabCancelledWOJSONArray = results;
                }else if(status == 'Need Verification'){
                    grabVerificationWOJSONArray = results;
                }

                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: results });
                tableName.setModel(oModel);
            
                tableName.bindItems({ path: "/modelData", template : workorderTemplate});
                tableName.setBusy(false);
            
                var oBinding = tableName.getBinding("items");
                if(status == 'Pending Approval'){ oBinding.filter(aPendingFilters);
                }else if(status == 'Reject'){ oBinding.filter(aRejectFilters);
                }else if(status == 'Open'){ oBinding.filter(aOpenFilters);
                }else if(status == 'Completed'){ oBinding.filter(aCompletedFilters);
                }else if(status == 'Closed'){ oBinding.filter(aClosedFilters);
                }else if(status == 'GRN'){ oBinding.filter(aGRNFilters);
                }else if(status == 'Cancelled'){ oBinding.filter(aCancelledFilters);
                }else if(status == 'Need Verification'){ oBinding.filter(aNeedVerifyFilters);
                }


            // };
        },
        error: function(xhr, status, error) {
            tableName.setBusy(false);
        }
    });

};
function getWorkorderByStatusAndWorkshop(status,variableJSONArray,tableName){
    
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_workorder_by_status_and_workshop`,
        data: {
            "master_email": emailUser,
            "wo_status":status,
            "workshop_number":oxmaint_workshop_number
        },
        success: function (data) { 
            
            // if(data.length > 0 ){
                // var results = filterGrabVehicle(data);
                var results = data;                
                
                if(status == 'Pending Approval'){ grabPendingWOJSONArray = results;
                }else if(status == 'Reject'){ grabRejectWOJSONArray = results;
                }else if(status == 'Open'){ grabOpenWOJSONArray = results;
                }else if(status == 'Completed'){ grabCompletedWOJSONArray = results;
                }else if(status == 'Closed'){ grabClosedWOJSONArray = results;
                }else if(status == 'GRN'){ 
                    grabGrnWOJSONArray = results;

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

                }else if(status == 'Cancelled'){ grabCancelledWOJSONArray = results;
                }else if(status == 'Need verification'){
                    grabVerificationWOJSONArray = results;
                }

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


                var oBinding = tableName.getBinding("items");
                if(status == 'Pending Approval'){ oBinding.filter(aPendingFilters);
                }else if(status == 'Reject'){ oBinding.filter(aRejectFilters);
                }else if(status == 'Open'){ oBinding.filter(aOpenFilters);
                }else if(status == 'Completed'){ oBinding.filter(aCompletedFilters);
                }else if(status == 'Closed'){ oBinding.filter(aClosedFilters);
                }else if(status == 'GRN'){ oBinding.filter(aGRNFilters);
                }else if(status == 'Cancelled'){ oBinding.filter(aCancelledFilters);
                }else if(status == 'Need Verification'){ oBinding.filter(aNeedVerifyFilters);
                }

            // };
            // tableName.setBusy(false);
        },
        error: function(xhr, status, error) {
            tableName.setBusy(false);
        }
    });
    
};
function getWorkorderByStatusAndWorkshopGroup(status,variableJSONArray,tableName){
    
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_workorder_by_status_and_workshop_group`,
        data: {
            "master_email": emailUser,
            "wo_status":status,
            "ws_group_number":oxmaint_ws_group_number
        },
        success: function (data) { 
            
            // if(data.length > 0 ){
                // var results = filterGrabVehicle(data);
                var results = data;                
                
                if(status == 'Pending Approval'){ grabPendingWOJSONArray = results;
                }else if(status == 'Reject'){ grabRejectWOJSONArray = results;
                }else if(status == 'Open'){ grabOpenWOJSONArray = results;
                }else if(status == 'Completed'){ grabCompletedWOJSONArray = results;
                }else if(status == 'Closed'){ grabClosedWOJSONArray = results;
                }else if(status == 'GRN'){ 
                    grabGrnWOJSONArray = results;
                    
                    
                    //Invoice GRN
                    var oModel = new sap.ui.model.json.JSONModel();
                    oModel.setData({ modelData: results });
                    oTable4WAllInvoiceGRN.setModel(oModel);
                
                    oTable4WAllInvoiceGRN.bindItems({ path: "/modelData", template : oTable4WAllInvoiceGRNTemplate});
                    oTable4WAllInvoiceGRN.setBusy(false);
                    
                }else if(status == 'Cancelled'){ grabCancelledWOJSONArray = results;
                }else if(status == 'Need verification'){
                    grabVerificationWOJSONArray = results;
                }

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


                var oBinding = tableName.getBinding("items");
                if(status == 'Pending Approval'){ oBinding.filter(aPendingFilters);
                }else if(status == 'Reject'){ oBinding.filter(aRejectFilters);
                }else if(status == 'Open'){ oBinding.filter(aOpenFilters);
                }else if(status == 'Completed'){ oBinding.filter(aCompletedFilters);
                }else if(status == 'Closed'){ oBinding.filter(aClosedFilters);
                }else if(status == 'GRN'){ oBinding.filter(aGRNFilters);
                }else if(status == 'Cancelled'){ oBinding.filter(aCancelledFilters);
                }else if(status == 'Need Verification'){ oBinding.filter(aNeedVerifyFilters);
                }


            // };
            // tableName.setBusy(false);
        },
        error: function(xhr, status, error) {
            tableName.setBusy(false);
        }
    });
    
};


//Inspection get API
function getAllInspection(src,archiveStatus){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_Inspection.asmx/get_all_inspection`,
        data: {
            "master_email": emailUser,
            "archive":archiveStatus
        },
        success: function (data) { 
     
            if(data.length > 0 ){
                if(src == 'unarchived'){
                    var results = filterGrabVehicle(data);
                    //  var results = result;
                    inspectionJSONArray = results;
                    var oModel = new sap.ui.model.json.JSONModel();
                    oModel.setData({ modelData: results });
        
                    oTableInspection.setModel(oModel);
                    oModel.setSizeLimit(results.length);
                    oTableInspection.bindItems({path: "/modelData",template: inspectionTemplate});
                    oTableInspection.setBusy(false);
            
                    var oBinding = oTableInspection.getBinding("items");
                    oBinding.filter(aInspectionAllFilters);

                    var inspectionCount = 0;
                    var goodInspectionCount = 0;
                    var faultyInspectionCount = 0;
            
                    //  refWoArray = [];
            
                    for (var i = 0; i < results.length; i++) {
        
                        var inspection_date = results[i]['inspection_date'];
        
                        var oDate = new Date(inspection_date.split(" ")[0]);
                        if (segmentedDate1 <= oDate && oDate <= segmentedDate2) {
        
                            inspectionCount = inspectionCount + 1;
        
                            var vehicle_number = results[i]['license_number'];
                            var repair = results[i]['repair'];
                            var replace = results[i]['replace'];
                            if (repair == null) { repair = ""; }
                            if (replace == null) { replace = ""; }
                        
                            var repair1 = repair.split("^");
                            var replace1 = replace.split("^");
        
                            allInspectionJSONArray.push(results[i]);
        
                            if (repair1.length > 1 || replace1.length > 1) {
        
                                faultyInspectionCount = faultyInspectionCount + 1;
                                faultyInspectionJSONArray.push(results[i]);
        
                            } else {
                                goodInspectionCount = goodInspectionCount + 1;
                                goodInspectionJSONArray.push(results[i]);
                            
                            }  
                        }
                    }
            
                    homeListGrabInspectionItem1.setInfo(inspectionCount);
                    homeListGrabInspectionItem2.setInfo(goodInspectionCount);
                    homeListGrabInspectionItem3.setInfo(faultyInspectionCount);
            
                    var oDataInspectionCountChart = [];
                    oDataInspectionCountChart.push({ item: oBundle.getText("Good"), count: goodInspectionCount });
                    oDataInspectionCountChart.push({ item: oBundle.getText("Faulty"), count: faultyInspectionCount });
        
                    var oModelInspectionCountChart = new sap.ui.model.json.JSONModel();
                    oModelInspectionCountChart.setData({ modelData: oDataInspectionCountChart });
                    oPieChartGrabInspectionCount.setModel(oModelInspectionCountChart);
        
                
                    busyDialog.close();
                }else{

                    var results = filterGrabVehicle(data);


                    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);
                }
            }
         
            if(src == "unarchived"){
                oTableInspection.setBusy(false);
            }else{
                ArchiveInspectionTable.setBusy(false);
            }
            busyDialog.close();
        },
        error: function(xhr, status, error) {
            if(src == "unarchived"){
                oTableInspection.setBusy(false);
            }else{
                ArchiveInspectionTable.setBusy(false);
            }
            busyDialog.close();
        }
    });

};
function getAllInspectionWorkshop(src,archiveStatus){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_Inspection.asmx/get_all_inspection_by_workshop`,
        data: {
            "master_email": emailUser,
            "workshop_number":oxmaint_workshop_number,
            "archive":archiveStatus
        },
        success: function (data) { 
     
           
            if(data.length > 0 ){
                if(src == 'unarchived'){
                    var results = filterGrabVehicle(data);
                    //  var results = result;
                    inspectionJSONArray = results;
                    var oModel = new sap.ui.model.json.JSONModel();
                    oModel.setData({ modelData: results });
        
                    oTableInspection.setModel(oModel);
                    oModel.setSizeLimit(results.length);
                    oTableInspection.bindItems({path: "/modelData",template: inspectionTemplate});
                    oTableInspection.setBusy(false);
        
                    var oBinding = oTableInspection.getBinding("items");
                    oBinding.filter(aInspectionAllFilters);

                    var inspectionCount = 0;
                    var goodInspectionCount = 0;
                    var faultyInspectionCount = 0;
            
                    
                    for (var i = 0; i < results.length; i++) {
        
                        var inspection_date = results[i]['inspection_date'];
        
                        var oDate = new Date(inspection_date.split(" ")[0]);
                        if (segmentedDate1 <= oDate && oDate <= segmentedDate2) {
        
                            inspectionCount = inspectionCount + 1;
        
                            var vehicle_number = results[i]['license_number'];
                            var repair = results[i]['repair'];
                            var replace = results[i]['replace'];
                            if (repair == null) { repair = ""; }
                            if (replace == null) { replace = ""; }
                        
                            var repair1 = repair.split("^");
                            var replace1 = replace.split("^");
        
                            allInspectionJSONArray.push(results[i]);
        
                            if (repair1.length > 1 || replace1.length > 1) {
        
                                faultyInspectionCount = faultyInspectionCount + 1;
                                faultyInspectionJSONArray.push(results[i]);
        
                            } else {
                                goodInspectionCount = goodInspectionCount + 1;
                                goodInspectionJSONArray.push(results[i]);
                            
                            }  
                        }
                    }
            
                    homeListGrabInspectionItem1.setInfo(inspectionCount);
                    homeListGrabInspectionItem2.setInfo(goodInspectionCount);
                    homeListGrabInspectionItem3.setInfo(faultyInspectionCount);
            
                    var oDataInspectionCountChart = [];
                    oDataInspectionCountChart.push({ item: oBundle.getText("Good"), count: goodInspectionCount });
                    oDataInspectionCountChart.push({ item: oBundle.getText("Faulty"), count: faultyInspectionCount });
        
                    var oModelInspectionCountChart = new sap.ui.model.json.JSONModel();
                    oModelInspectionCountChart.setData({ modelData: oDataInspectionCountChart });
                    oPieChartGrabInspectionCount.setModel(oModelInspectionCountChart);
        
                
                    busyDialog.close();
                }else{
                    var results = filterGrabVehicle(data);


                    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);
                }
            }
         
            if(src == "unarchived"){
                oTableInspection.setBusy(false);
            }else{
                ArchiveInspectionTable.setBusy(false);
            }
            busyDialog.close();
        },
        error: function(xhr, status, error) {
            if(src == "unarchived"){
                oTableInspection.setBusy(false);
            }else{
                ArchiveInspectionTable.setBusy(false);
            }
            busyDialog.close();
        }
    });

};
function getAllInspectionByWorkshopGroup(src,archiveStatus){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_Inspection.asmx/get_all_inspection_by_workshop_group`,
        data: {
            "master_email": emailUser,
            "ws_group_number":oxmaint_ws_group_number,
            "archive":archiveStatus
        },
        success: function (data) { 
     
            if(data.length > 0 ){
                if(src == 'unarchived'){
                    var results = filterGrabVehicle(data);
                    //  var results = result;
                    inspectionJSONArray = results;
                    var oModel = new sap.ui.model.json.JSONModel();
                    oModel.setData({ modelData: results });
        
                    oTableInspection.setModel(oModel);
                    oModel.setSizeLimit(results.length);
                    oTableInspection.bindItems({path: "/modelData",template: inspectionTemplate});
                    oTableInspection.setBusy(false);
        
                    var oBinding = oTableInspection.getBinding("items");
                    oBinding.filter(aInspectionAllFilters);

                    var inspectionCount = 0;
                    var goodInspectionCount = 0;
                    var faultyInspectionCount = 0;
            
                    //  refWoArray = [];
            
                    for (var i = 0; i < results.length; i++) {
        
                        var inspection_date = results[i]['inspection_date'];
        
                        var oDate = new Date(inspection_date.split(" ")[0]);
                        if (segmentedDate1 <= oDate && oDate <= segmentedDate2) {
        
                            inspectionCount = inspectionCount + 1;
        
                            var vehicle_number = results[i]['license_number'];
                            var repair = results[i]['repair'];
                            var replace = results[i]['replace'];
                            if (repair == null) { repair = ""; }
                            if (replace == null) { replace = ""; }
                        
                            var repair1 = repair.split("^");
                            var replace1 = replace.split("^");
        
                            allInspectionJSONArray.push(results[i]);
        
                            if (repair1.length > 1 || replace1.length > 1) {
        
                                faultyInspectionCount = faultyInspectionCount + 1;
                                faultyInspectionJSONArray.push(results[i]);
        
                            } else {
                                goodInspectionCount = goodInspectionCount + 1;
                                goodInspectionJSONArray.push(results[i]);
                            
                            }  
                        }
                    }
            
                    homeListGrabInspectionItem1.setInfo(inspectionCount);
                    homeListGrabInspectionItem2.setInfo(goodInspectionCount);
                    homeListGrabInspectionItem3.setInfo(faultyInspectionCount);
            
                    var oDataInspectionCountChart = [];
                    oDataInspectionCountChart.push({ item: oBundle.getText("Good"), count: goodInspectionCount });
                    oDataInspectionCountChart.push({ item: oBundle.getText("Faulty"), count: faultyInspectionCount });
        
                    var oModelInspectionCountChart = new sap.ui.model.json.JSONModel();
                    oModelInspectionCountChart.setData({ modelData: oDataInspectionCountChart });
                    oPieChartGrabInspectionCount.setModel(oModelInspectionCountChart);
        
                 
                    busyDialog.close();
                }else{
                    var results = filterGrabVehicle(data);


                    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);
                }
            }
         
            if(src == "unarchived"){
                oTableInspection.setBusy(false);
            }else{
                ArchiveInspectionTable.setBusy(false);
            }
            busyDialog.close();
        },
        error: function(xhr, status, error) {
            if(src == "unarchived"){
                oTableInspection.setBusy(false);
            }else{
                ArchiveInspectionTable.setBusy(false);
            }
            busyDialog.close();
        }
    });

};




//Workshop Invoice APi
function getAllOpenInvoice(invoice_type,tableName){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_Invoice.asmx/get_all_open_invoice`,
        data: {
            "master_email": emailUser,
            "invoice_type":invoice_type
        },
        success: function (results) { 
     
            if(invoice_type == 'Workshop'){
                invoiceOpen4WJSONData = results;            
    
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: results });
                tableName.setModel(oModel);
                tableName.bindItems({ path: "/modelData", template : invoice4WTemplate });
                tableName.setBusy(false);
            }else{
                invoiceSuppOpen4WJSONData = results;            

                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: results });
                tableName.setModel(oModel);
                tableName.bindItems({ path: "/modelData", template : invoiceSupOpen4WTemplate });
                tableName.setBusy(false);
            }
            tableName.setBusy(false);
        },
        error: function(xhr, status, error) {
            tableName.setBusy(false);
        }
    });
};
function getAllOpenInvoiceBydWorkshopGroup(invoice_type,tableName){
 $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_Invoice.asmx/get_all_open_invoice_by_workshop_group`,
        data: {
            "master_email": emailUser,
            "invoice_type":invoice_type,
            "ws_group_number":oxmaint_ws_group_number
        },
        success: function (results) { 
     
            if(invoice_type == 'Workshop'){
                invoiceOpen4WJSONData = results;            
    
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: results });
                tableName.setModel(oModel);
                tableName.bindItems({ path: "/modelData", template : invoice4WTemplate });
                tableName.setBusy(false);
            }else{
                
            }
        },
        error: function(xhr, status, error) {
            tableName.setBusy(false);
        }
    });
};
function getAllOpenInvoiceByWorkshop(invoice_type,tableName){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_Invoice.asmx/get_all_open_invoice_by_workshop`,
        data: {
            "master_email": emailUser,
            "invoice_type":invoice_type,
            "workshop_number":oxmaint_workshop_number
        },
        success: function (results) { 
     
            if(invoice_type == 'Workshop'){
                invoiceOpen4WJSONData = results;            
    
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: results });
                tableName.setModel(oModel);
                tableName.bindItems({ path: "/modelData", template : invoice4WTemplate });
                tableName.setBusy(false);
            }else{
                
            }
        },
        error: function(xhr, status, error) {
            tableName.setBusy(false);
        }
    });
}


//Supplier Workorder pick
function get_closed_workorder_supplier_invoice(){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_closed_workorder_supplier_invoice`,
        data: {
            "master_email": emailUser,
            "supplier_id":oxmaint_supplier_id
        },
        success: function (results) { 
     
            grabSuppInvoiceAllWOJSONArray = results;
            grabSuppInvoiceWOJSONArray = results.filter(a=>a.supplier_inv_pick != 'Done');

        },
        error: function(xhr, status, error) {
        
        }
    });
}


//Workshop Invoice Comparision Dashboard Workorders
var invoiceCompareJSONArray = [];
function getAllInvoiceCompClosedWOAPI(status,tableName){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_workorder_by_status`,
        data: {
            "master_email": emailUser,
            "wo_status":status
        },
        success: function (results) { 
            if(results.length > 0 ){
                var filteredResults = results.filter(function(item) {
                    return (item.ws_group_name !== null &&
                           item.ws_group_name !== undefined &&
                           item.ws_group_name !== "") &&
                           (item.wo_status !== "GRN") &&
                          !nullCheckAll(item.grn_number) &&
                            nullCheckAll(item.invoice_number);
                });
                invoiceCompareJSONArray = filteredResults;
                // Store all workorder numbers
                var allWorkorderNumbers = filteredResults.map(function(item) {
                    return item.wo_number;
                });
        
         
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: filteredResults });
                tableName.setModel(oModel);
                tableName.bindItems({ path: "/modelData", template : invoiceComparisonTemplate });
                
                // Get toolbar content
                var oToolbar = tableName.getHeaderToolbar();
                
                // Find the Workshop Name ComboBox
                var oComboBox = null;
                oToolbar.getContent().forEach(function(control) {
                    if (control instanceof sap.m.ComboBox) {
                        oComboBox = control;
                    }
                });
                
                if (oComboBox) {
                    // Clear existing items and add "All Workshop Names"
                    oComboBox.removeAllItems();
                    // oComboBox.addItem(new sap.ui.core.Item({ key: "all", text: "All Workshop Names" }));
                    
                    // Get unique workshop names
                    var uniqueNames = new Set();
                    filteredResults.forEach(function(item) {
                        if (item.workshop_name) {
                            uniqueNames.add(item.workshop_name);
                        }
                    });
                    
                    // Add workshop names to ComboBox
                    Array.from(uniqueNames).sort().forEach(function(name) {
                        oComboBox.addItem(new sap.ui.core.Item({ 
                            key: name, 
                            text: name 
                        }));
                    });
                }
                
                updateScoreCards(filteredResults);
                tableName.setBusy(false);
            }else{
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: [] });
                tableName.setModel(oModel);
                tableName.bindItems({ path: "/modelData", template : invoiceComparisonTemplate });
                
            };
            tableName.setBusy(false);
        },
        error: function(xhr, status, error) {
            tableName.setBusy(false);
        }
    });
}
function getAllInvoiceCompClosedWOByWorkshopAPI(status,tableName){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_workorder_by_status_and_workshop`,
        data: {
            "master_email": emailUser,
            "wo_status":status,
            "workshop_number":oxmaint_workshop_number
        },
        success: function (data) { 
     
            if(data.length > 0 ){
                var filteredResults = data.filter(function(item) {
                    return (item.ws_group_name !== null &&
                           item.ws_group_name !== undefined &&
                           item.ws_group_name !== "") &&
                           (item.wo_status !== "GRN") &&
                          !nullCheckAll(item.grn_number) &&
                            nullCheckAll(item.invoice_number);
                });
                
                // Store all workorder numbers
                var allWorkorderNumbers = filteredResults.map(function(item) {
                    return item.wo_number;
                });
                invoiceCompareJSONArray = filteredResults;
              
                
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: filteredResults });
                tableName.setModel(oModel);
                tableName.bindItems({ path: "/modelData", template : invoiceComparisonTemplate });
                
                // Get toolbar content
                var oToolbar = tableName.getHeaderToolbar();
                
                // Find the Workshop Name ComboBox
                var oComboBox = null;
                oToolbar.getContent().forEach(function(control) {
                    if (control instanceof sap.m.ComboBox) {
                        oComboBox = control;
                    }
                });
                
                if (oComboBox) {
                    // Clear existing items and add "All Workshop Names"
                    oComboBox.removeAllItems();
                    // oComboBox.addItem(new sap.ui.core.Item({ key: "all", text: "All Workshop Names" }));
                    
                    // Get unique workshop names
                    var uniqueNames = new Set();
                    filteredResults.forEach(function(item) {
                        if (item.workshop_name) {
                            uniqueNames.add(item.workshop_name);
                        }
                    });
                    
                    // Add workshop names to ComboBox
                    Array.from(uniqueNames).sort().forEach(function(name) {
                        oComboBox.addItem(new sap.ui.core.Item({ 
                            key: name, 
                            text: name 
                        }));
                    });
                }
                
                updateScoreCards(filteredResults);
                tableName.setBusy(false);
            }else{
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: [] });
                tableName.setModel(oModel);
                tableName.bindItems({ path: "/modelData", template : invoiceComparisonTemplate });
                
            };
            tableName.setBusy(false);
        },
        error: function(xhr, status, error) {
            tableName.setBusy(false);
        }
    });
}
function getAllInvoiceCompClosedWOByWorkshopGroupAPI(status,tableName){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_workorder_by_status_and_workshop_group`,
        data: {
            "master_email": emailUser,
            "wo_status":status,
            "ws_group_number":oxmaint_ws_group_number
        },
        success: function (data) { 
     
            if(data.length > 0 ){
                var filteredResults = data.filter(function(item) {
                    return (item.ws_group_name !== null &&
                           item.ws_group_name !== undefined &&
                           item.ws_group_name !== "") &&
                           (item.wo_status !== "GRN") &&
                          !nullCheckAll(item.grn_number) &&
                            nullCheckAll(item.invoice_number);
                });
                invoiceCompareJSONArray = filteredResults;
                // Store all workorder numbers
                var allWorkorderNumbers = filteredResults.map(function(item) {
                    return item.wo_number;
                });
        
                
                
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: filteredResults });
                tableName.setModel(oModel);
                tableName.bindItems({ path: "/modelData", template : invoiceComparisonTemplate });
                
                // Get toolbar content
                var oToolbar = tableName.getHeaderToolbar();
                
                // Find the Workshop Name ComboBox
                var oComboBox = null;
                oToolbar.getContent().forEach(function(control) {
                    if (control instanceof sap.m.ComboBox) {
                        oComboBox = control;
                    }
                });
                
                if (oComboBox) {
                    // Clear existing items and add "All Workshop Names"
                    oComboBox.removeAllItems();
                    // oComboBox.addItem(new sap.ui.core.Item({ key: "all", text: "All Workshop Names" }));
                    
                    // Get unique workshop names
                    var uniqueNames = new Set();
                    filteredResults.forEach(function(item) {
                        if (item.workshop_name) {
                            uniqueNames.add(item.workshop_name);
                        }
                    });
                    
                    // Add workshop names to ComboBox
                    Array.from(uniqueNames).sort().forEach(function(name) {
                        oComboBox.addItem(new sap.ui.core.Item({ 
                            key: name, 
                            text: name 
                        }));
                    });
                }
                
                updateScoreCards(filteredResults);
                tableName.setBusy(false);
            }else{
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: [] });
                tableName.setModel(oModel);
                tableName.bindItems({ path: "/modelData", template : invoiceComparisonTemplate });
                
            };
            tableName.setBusy(false);
        },
        error: function(xhr, status, error) {
            tableName.setBusy(false);
        }
    });
}

//Supplier Invoice Comparision Dashboard Workorder
function getSupplierInvoiceComparisionWO(){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_supplier_workorder`,
        data: {
            "master_email": emailUser
        },
        success: function (results) { 
            if(results.length > 0 ){
                // results = results.filter(function(item) {
                //     return !nullCheckAll(item.supplier_grn_number) && nullCheckAll(item.supplier_invoice_number);
                // });
                // Store all workorder numbers
                var allSupplierWorkorders = results.map(function(item) {
                    return item.wo_number;
                });
                
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: results });
                oTableSupplierInvoice.setModel(oModel);
                
                // Populate Workshop Name dropdown
                var uniqueWorkshops = [...new Set(results
                    .map(item => item.workshop_name)
                    .filter(item => item && item.trim() !== "")
                )].sort();

                var oWorkshopComboBox = oTableSupplierInvoice.getHeaderToolbar().getContent()
                    .find(control => control instanceof sap.m.ComboBox);

                if (oWorkshopComboBox) {
                    oWorkshopComboBox.removeAllItems();
                    oWorkshopComboBox.addItem(new sap.ui.core.Item({
                        key: "",
                        text: "All Workshops"
                    }));
                    uniqueWorkshops.forEach(function(workshop) {
                        oWorkshopComboBox.addItem(new sap.ui.core.Item({
                            key: workshop,
                            text: workshop
                        }));
                    });
                }

                // Update score cards with the results
                updateSupplierScoreCards(results);

                populateSuppFilterDropdowns();
                
                // Bind table items
                oTableSupplierInvoice.bindItems({
                    path: "/modelData",
                    template: new sap.m.ColumnListItem({
                        cells: [
                            new sap.m.CheckBox(),
                            new sap.m.Text({ text: "{ws_group_name}" }),
                            new sap.m.Text({ text: "{workshop_name}" }),
                            new sap.m.Text({ text: "{wo_number}" }),
                            new sap.m.Text({ text: "{license_number}" }),
                            new sap.m.Text({ 
                                text: {
                                    path: "supplier_cost",
                                    formatter: function(value) {
                                        return value ? "Rp " + value : "Rp 0";
                                    }
                                }
                            }),
                            new sap.m.Text({ text: "{supplier_invoice_number}" }),
                            new sap.m.Text({ text: "{created_date}" })
                        ]
                    })
                });
                
                oTableSupplierInvoice.setBusy(false);
            }else{
                oTableSupplierInvoice.setBusy(false);
                 var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: [] });
                oTableSupplierInvoice.setModel(oModel);
                
                oTableSupplierInvoice.setBusy(false);
            }
           
        },
        error: function(xhr, status, error) {
            oTableSupplierInvoice.setBusy(false);
        }
    });
};


//Workshop Master
function getLatestWorkshopMaster(ws_number){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Vehicle.asmx/get_workshop_by_id`,
        data: {
            "master_email": emailUser,
            "ws_group_number":ws_number
        },
        success: function (results) { 

            if(results.length > 0 ){
                addUpdate4WWSMaster(2, results[0])
            }

            // tableName.setBusy(false);
        },
        error: function(xhr, status, error) {
            // tableName.setBusy(false);
        }
    });
}
function getInvoiceWorkorderPartById(part_type, wo_id){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_invoice_workorder_part_by_wo_ids`,
        data: {
            "master_email": emailUser,
            "part_type":part_type,
            "wo_ids":wo_id
        },
        success: function (results) { 

            if(results.length > 0 ){
                if(part_type == 'Workshop'){
                    let filterParts = results;
    
                    filterParts = filterParts.map(function (item) {
                        item.final_material_cost = item.total_parts_cost; 
                        item.final_labor_cost = item.labor_item_cost; 
                        item.final_total_cost = item.total_cost;
                        return item;
                    });
    
    
                    var oModel = new sap.ui.model.json.JSONModel();
                    oModel.setData({ modelData: filterParts });
                    oTablepartsInvoice.setModel(oModel);
                    oTablepartsInvoice.bindItems({ 
                        path: "/modelData", 
                        template: partsInvoiceTemplate 
                    });
                    oTablepartsInvoice.setBusy(false);
                    calculateRowTotal1(oTablepartsInvoice);
    
                    woPartInvoiceJSONArrary = filterParts;
                }else{
                    let filterParts = results;
                    var oModel = new sap.ui.model.json.JSONModel();
                    oModel.setData({ modelData: filterParts });
                    oTableSuppPartsInvoice.setModel(oModel);
                    oTableSuppPartsInvoice.bindItems({ 
                        path: "/modelData", 
                        template: suppPartsInvoiceTemplate 
                    });
                    calculateSuppRowTotal1(oTableSuppPartsInvoice);
            
                    woPartSuppInvoiceJSONArrary = filterParts;
                }
            }else{
                oTablepartsInvoice.setBusy(false);
            }
        },
        error: function(xhr, status, error) {
            oTablepartsInvoice.setBusy(false);
        }
    });
}



//All Workorder Status
function getWorkorderAllStatus(){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_workorder`,
        data: {
            "master_email": emailUser
        },
        success: function (results) { 

            if(results.length > 0){
                grab4WAllWoJSONArray = results;
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: results });
                oTable4WAllWO.setModel(oModel);
                oTable4WAllWO.bindItems({ path: "/modelData", template : oTable4WAllWOTemplate});
                oTable4WAllWO.setBusy(false);
           
       
                var oBinding = oTable4WAllWO.getBinding("items");
                oBinding.filter(aAllFilters);
               
            }else{
                oTable4WAllWO.setBusy(false);
                oPieChartGrabWorkorderStatus.setBusy(false);
            }
            
        },
        error: function(xhr, status, error) {
            oTable4WAllWO.setBusy(false);
            oPieChartGrabWorkorderStatus.setBusy(false);
        }
    });
}
function getWorkorderAllStatusAndWorkshopGroup(){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_workorder_by_workshop_group`,
        data: {
            "master_email": emailUser,
            'ws_group_number':oxmaint_ws_group_number
        },
        success: function (results) { 

            if(results.length > 0){
                grab4WAllWoJSONArray = results;
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: results });
                oTable4WAllWO.setModel(oModel);
                oTable4WAllWO.bindItems({ path: "/modelData", template : oTable4WAllWOTemplate});
                oTable4WAllWO.setBusy(false);
           
                var oBinding = oTable4WAllWO.getBinding("items");
                oBinding.filter(aAllFilters);
               
            }else{
                oTable4WAllWO.setBusy(false);
                oPieChartGrabWorkorderStatus.setBusy(false);
            }
            
        },
        error: function(xhr, status, error) {
            oTable4WAllWO.setBusy(false);
            oPieChartGrabWorkorderStatus.setBusy(false);
        }
    });
}
function getWorkorderAllStatusAndWorkshop(){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_workorder_by_workshop`,
        data: {
            "master_email": emailUser,
            "workshop_number":oxmaint_workshop_number
        },
        success: function (results) { 

            if(results.length > 0){
                grab4WAllWoJSONArray = results;
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: results });
                oTable4WAllWO.setModel(oModel);
                oTable4WAllWO.bindItems({ path: "/modelData", template : oTable4WAllWOTemplate});
                oTable4WAllWO.setBusy(false);
                
                var oBinding = oTable4WAllWO.getBinding("items");
                oBinding.filter(aAllFilters);
               
            }else{
                oTable4WAllWO.setBusy(false);
                oPieChartGrabWorkorderStatus.setBusy(false);
            }
            
        },
        error: function(xhr, status, error) {
            oTable4WAllWO.setBusy(false);
            oPieChartGrabWorkorderStatus.setBusy(false);
        }
    });
}


//Bulk Upload Parts 
function bulkUploadParts() {
    var fileUploader = new sap.ui.unified.FileUploader({
        name: "file",
        uploadUrl: `${jrs_go_api_url_name}/upload/bulk_upload_part_master`,
        sendXHR: true,
        useMultipart: true,
        fileType: ["xlsx", "xls"],
        change: function(oEvent) {
            var file = oEvent.getParameter("files")[0];
            if (!file) {
                return;
            }

            var reader = new FileReader();
            reader.onload = function(e) {
                try {
                    
                    // Confirm before proceeding
                    sap.m.MessageBox.confirm(
                        "Do you want to upload the part master?",
                        {
                            onClose: function(oAction) {
                                if (oAction === sap.m.MessageBox.Action.OK) {
                                    // Show busy dialog
                                    var busyDialog = new sap.m.BusyDialog({
                                        title: "Processing",
                                        text: "Please wait..."
                                    });
                                    busyDialog.open();

                                    // Make API call
                                    var formData = new FormData();
                                    formData.append("master_name", operatedID);
                                    formData.append("file", file);
                                    formData.append("master_email", emailUser);

                                    $.ajax({
                                        url: `${jrs_go_api_url_name}/upload/bulk_upload_part_master`,
                                        method: 'POST',
                                        data: formData,
                                        processData: false,
                                        contentType: false,
                                        headers: {
                                            'X-API-Key': jrs_go_api_key,
                                            'accept': 'application/json'
                                        },
                                        success: function(response) {
                                            busyDialog.close();
                                            sap.m.MessageToast.show("File uploaded successfully!");
                                            oDialog.close();

                                            var workshop_number = ""
                                            let workshopTokenList = partFilterWOrkshopData.getTokens();
                                            // console.log(workshopTokenList)
                                            for (var j = 0; j < workshopTokenList.length; j++) {
                                                // console.log(workshopTokenList[j].getKey())
                                                if (workshop_number == "") {
                                                    getPartsDetailsWorkshop(workshopTokenList[j].getKey())
                                                }
                                            };
                                        },
                                        error: function(xhr, status, error) {
                                            busyDialog.close();
                                            console.error("Upload failed:", xhr.responseJSON.status);
                                            sap.m.MessageBox.error("Upload failed: " + xhr.responseJSON.status);
                                        }
                                    });
                                }
                            }
                        }
                    );

                } catch (error) {
                    console.error("Error processing file:", error);
                    sap.m.MessageBox.error("Error processing file. Please ensure you're uploading a valid Excel file.");
                }
            };
            
            reader.readAsBinaryString(file);
        }
    });

    var oDialog = new sap.m.Dialog({
        title: "Bulk Upload Part Master",
        contentWidth: "50%",
        content: [
            new sap.m.VBox({
                items: [
                    new sap.m.Text({
                        text: "Select Excel file to upload"
                    }).addStyleClass("sapUiSmallMarginBottom"),
                    fileUploader
                ]
            }).addStyleClass("sapUiSmallMargin")
        ],
        buttons: [
            new sap.m.Button({
                text: "Cancel",
                press: function() {
                    oDialog.close();
                }
            })
        ],
        afterClose: function() {
            oDialog.destroy();
        }
    });

    oDialog.open();
}
//Bulk Upload Update Parts 
function bulkUploadUpdateParts() {
    var fileUploader = new sap.ui.unified.FileUploader({
        name: "file",
        uploadUrl: `${jrs_go_api_url_name}/upload/bulk_update_part_master`,
        sendXHR: true,
        useMultipart: true,
        fileType: ["xlsx", "xls"],
        change: function(oEvent) {
            var file = oEvent.getParameter("files")[0];
            if (!file) {
                return;
            }

            var reader = new FileReader();
            reader.onload = function(e) {
                try {
                    
                    // Confirm before proceeding
                    sap.m.MessageBox.confirm(
                        "Do you want to upload the part master for update?",
                        {
                            onClose: function(oAction) {
                                if (oAction === sap.m.MessageBox.Action.OK) {
                                    // Show busy dialog
                                    var busyDialog = new sap.m.BusyDialog({
                                        title: "Processing",
                                        text: "Please wait..."
                                    });
                                    busyDialog.open();

                                    // Make API call
                                    var formData = new FormData();
                                    formData.append("master_name", operatedID);
                                    formData.append("file", file);
                                    formData.append("master_email", emailUser);

                                    $.ajax({
                                        url: `${jrs_go_api_url_name}/upload/bulk_update_part_master`,
                                        method: 'POST',
                                        data: formData,
                                        processData: false,
                                        contentType: false,
                                        headers: {
                                            'X-API-Key': jrs_go_api_key,
                                            'accept': 'application/json'
                                        },
                                        success: function(response) {
                                            busyDialog.close();
                                            sap.m.MessageToast.show("File uploaded successfully!");
                                            oDialog.close();
                                        
                                            var workshop_number = ""
                                            let workshopTokenList = partFilterWOrkshopData.getTokens();
                                            // console.log(workshopTokenList)
                                            for (var j = 0; j < workshopTokenList.length; j++) {
                                                // console.log(workshopTokenList[j].getKey())
                                                if (workshop_number == "") {
                                                    getPartsDetailsWorkshop(workshopTokenList[j].getKey())
                                                }
                                            };


                                        },
                                        error: function(xhr, status, error) {
                                            busyDialog.close();
                                            console.error("Upload failed:", xhr.responseJSON.status);
                                            sap.m.MessageBox.error("Upload failed: " + xhr.responseJSON.status);
                                        }
                                    });
                                }
                            }
                        }
                    );

                } catch (error) {
                    console.error("Error processing file:", error);
                    sap.m.MessageBox.error("Error processing file. Please ensure you're uploading a valid Excel file.");
                }
            };
            
            reader.readAsBinaryString(file);
        }
    });

    var oDialog = new sap.m.Dialog({
        title: "Bulk Upload Part Master",
        contentWidth: "50%",
        content: [
            new sap.m.VBox({
                items: [
                    new sap.m.Text({
                        text: "Select Excel file to upload"
                    }).addStyleClass("sapUiSmallMarginBottom"),
                    fileUploader
                ]
            }).addStyleClass("sapUiSmallMargin")
        ],
        buttons: [
            new sap.m.Button({
                text: "Cancel",
                press: function() {
                    oDialog.close();
                }
            })
        ],
        afterClose: function() {
            oDialog.destroy();
        }
    });

    oDialog.open();
}


//Get vehicle data for workorder
function getVehicleByLicenseNumberWO(value){
   
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Vehicle.asmx/get_vehicle_by_license_number`,
        data: {
            "master_email": emailUser,
            "license_number":value
        },
        success: function (data) { 
            if(data.length > 0){
                console.log(data)
                oTFWOV0.setValue(data[0]["id"]);
                oTFWOV1.setValue(data[0]["license_number"]);
                oTFWOV3.setValue(data[0]["model"]);
                oTFWOV8.setValue(data[0]["chassis_number"]);
                oTFWOV9.setValue(data[0]["engine_number"]);
                oTFWOV10.setValue(data[0]["make"]);
                oTFWOV11.setValue(data[0]["vehicle_color"]);
                oTFWOV12.setValue(data[0]["rental_company_name"]);
                oTFWOV13.setValue(data[0]["leasing_company_name"]);
                oTFWOV14.setValue(data[0]["transmission"]);

                let workshop_number = "";
                let workshopWoTokenList = oTFWOV7.getTokens();

                for (var j = 0; j < workshopWoTokenList.length; j++) {
                    if (workshop_number == "") {
                    workshop_number = workshopWoTokenList[j].getKey();
                    }
                }
                
                if(nullCheckAll(workshop_number)){
                    getWOrkorderFilteredParts(workshop_number,data[0]["make"],data[0]["model"],data[0]["transmission"]);
                  }else{
                    workorderPartJSONArray = [];
                  
                    var oModel12 = new sap.ui.model.json.JSONModel();
                    oModel12.setData({ modelData: workorderPartJSONArray }); // results is an array of suggestion data
                    oInputPartField1.setModel(oModel12);
                  
                    var oModel = new sap.ui.model.json.JSONModel();
                    oModel.setData({ modelData: workorderPartJSONArray });
                    oTablePickPartWO.setModel(oModel);
                    oTablePickPartWO.bindItems({ path: "/modelData", template : oTablePickPartTemplate });
                    oTablePickPartWO.setBusy(false);
                  }
                
            }else{
                sap.m.MessageBox.error("No Vehicle Found");
                oTablePickVehicle.setBusy(false);
                return ;
            }
        },
        error: function(xhr, status, error) {
            oTablePickVehicle.setBusy(false);

        }
    });

};



//UPDATE Workshop Master
function updateWOrkshopMaster(updateItems,dialogClose,obj){

    let id = updateItems['id'];
    let assignVehicle = updateItems['assign_vehicle'];
    let ws_group_name = updateItems['ws_group_name'];
    let updated_date = updateItems['updated_date'];
    let updated_by = operatedID;
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/update_assign_vehicle_workshop_group`,
        data: {
            "id":id,
            "assign_vehicle":assignVehicle,
            "ws_group_name":ws_group_name,
            "updated_date":updated_date,
            "updated_by":updated_by
        },
        success: function (results) { 

                getWorkshopMaster();
                var blankAssignVehicle = [];
                oModelAssignVehicle.setData({ modelData: blankAssignVehicle });
                oTableAssignVehicle.setModel(oModelAssignVehicle);
                oTableAssignVehicle.bindRows("/modelData");

                sap.m.MessageToast.show("Workshop Group Updated Successfully.");
                addHistoryTableData(updateItems['ws_group_number'],"Update","Workshop Group",obj,updateItems);
                busyDialog.close();
                dialogClose.close();

           
        },
        error: function(xhr, status, error) {
                getWorkshopMaster();
                var blankAssignVehicle = [];
                oModelAssignVehicle.setData({ modelData: blankAssignVehicle });
                oTableAssignVehicle.setModel(oModelAssignVehicle);
                oTableAssignVehicle.bindRows("/modelData");

                sap.m.MessageToast.show("Workshop Group Updated Failed.");
                busyDialog.close();
                dialogClose.close();
        }
    });
}


//Insert Workshop Invoice Header
function insertInvoiceHeaderApi(addItems,dialogClose){


    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/insert_invoice_header`,
        data: {
           "insertData":JSON.stringify(addItems)
        },
        success: function (results) { 
           
            if(addItems['invoice_type'] == 'Workshop'){
                getCompletedWorkorder();
                getClosedWorkorder();
                addHistoryTableData(addItems['invoice_number'],"Insert","Workshop Invoice");
            }else{
                getSupplierClosedWorkorder();
                get4WSuppOpenInvoice();
                addHistoryTableData(addItems['invoice_number'],"Insert","Supplier Invoice");
            }

            busyDialog.close();
            dialogClose.close();
        },
        error: function(xhr, status, error) {

            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
              
        }
    });
}
//Update Workshop Invoice Header
function updateInvoiceHeaderApi(updateItems,dialogClose,obj){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/update_invoice_header`,
        data: {
           "updateData":JSON.stringify(updateItems)
        },
        success: function (results) { 
           
            if(updateItems['invoice_type'] == 'Workshop'){
                get4WOpenInvoice();
                getCompletedWorkorder();
                getClosedWorkorder();
                addHistoryTableData(updateItems['invoice_number'],"Update","Workshop Invoice",obj,updateItems);
            }else{
                getSupplierClosedWorkorder();
                get4WSuppOpenInvoice();
                addHistoryTableData(updateItems['invoice_number'],"Update","Supplier Invoice",obj,updateItems);
            }
            busyDialog.close();
            dialogClose.close();
        },
        error: function(xhr, status, error, response) {
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
              
        }
    });
}

/*
//Insert Supplier Invoice Header
function supplierInsertInvoiceHeader(addItems,dialogClose){


    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/insert_supplier_invoice_header`,
        data: {
           "insertData":JSON.stringify(addItems)
        },
        success: function (results) { 
           
            getSupplierClosedWorkorder();
            get4WSuppOpenInvoice();
            busyDialog.close();
            dialogClose.close();
        },
        error: function(xhr, status, error, response) {
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            sap.m.MessageBox.error(("Supplier Invoice Insert Failed"));
            busyDialog.close();
              
        }
    });
}
//Update Supplier Invoice Header
function supplierUpdateInvoiceHeader(updateItems,dialogClose){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/update_supplier__invoice_header`,
        data: {
           "updateData":JSON.stringify(updateItems)
        },
        success: function (results) { 
           
            getSupplierClosedWorkorder();
            get4WSuppOpenInvoice();
            busyDialog.close();
            dialogClose.close();
        },
        error: function(xhr, status, error, response) {
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            sap.m.MessageBox.error(("Supplier Invoice Update Failed"));
            busyDialog.close();
              
        }
    });
}
*/


//Workshop Add Invoice items
function insertInvoiceItemsApi(invoicePartsItems,woItems,totalCost,invoiceId,invoiceNumber,invoiceType,dialogClose){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/insert_invoice_items_update_workorder`,
        data: {
           "invoicePartsItems":JSON.stringify(invoicePartsItems),
           "woData":JSON.stringify(woItems),
           "totalCost":totalCost,
           "invoiceId":invoiceId,
           "invoiceNumber":invoiceNumber,
           "invoiceType":invoiceType
        },
        success: function (results) { 

            if(invoiceType == 'Workshop'){
                get4WOpenInvoice();
                // fetchInvoiceComparision();

            }else{
                get4WSuppOpenInvoice();
                fetchSupplierInvoice();
            }
            busyDialog.close();
            dialogClose.close();
        },
        error: function(xhr, status, error) {

            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
              
        }
    });
}


//Workorder History Data 
function getWorkorderHistoryByLicenseNumber(license_number,oTableWorkorderGrabView,grabViewWoTemplate){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_workorder_part_history_by_license_number`,
        data: {
           "master_email":emailUser,
           "license_number":license_number
        },
        success: function (results) { 
            // return results

            var oModel = new sap.ui.model.json.JSONModel();
            oModel.setData({ workorders: results });
            oTableWorkorderGrabView.setModel(oModel);
            oTableWorkorderGrabView.bindItems({
                path: "/workorders",
                template: grabViewWoTemplate
            });


            // var result = results;

            // if(result.lenght <= 0){
            //     result = [];
            // }
            // var oModel = new sap.ui.model.json.JSONModel();
            // oModel.setData({ modelData: result });
            // oTableName.setModel(oModel);
            // oTableName.bindItems({ path: "/modelData",template: oTableTeemplate});
            // oTableName.setBusy(false);

        }, error: function(xhr, status, error, response) {
            oTableName.setBusy(false);
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
              
        }
    })
}


//Dashboard KPI Main
function dashboardWorkorderInspectionCount(date1,date2){

    var filter_value = "";
    var filter_type = "";
    let oxmaint_role = sessionStorage.getItem('oxmaint_role');
    if(allowedRoles.includes(oxmaint_role) ){
        filter_value = "";
        filter_type = "";
    }else if(oxmaint_role == 'Workshop Group Admin'){
        filter_value = oxmaint_ws_group_number;
        filter_type = "group";
    }else{
        filter_value = oxmaint_workshop_number;
        filter_type = "workshop";
    };



    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/getDashboardKPIMain`,
        data: {
           "master_email":emailUser,
           "from_date":date1,
           "to_date":date2,
           "filter_value":filter_value,
           "filter_type":filter_type
        },
        success: function (results) { 
           
            //Workorder
            woGrabStatuslistItem1.setInfo(results['Total_Work_Order'] || 0);
            woGrabStatuslistItem2.setInfo(results['Completed'] || 0);
            woGrabStatuslistItem3.setInfo(results['Open1'] || 0);
            woGrabStatuslistItem4.setInfo(results['Reject'] || 0);
            woGrabStatuslistItem5.setInfo(results['Pending_Approval'] || 0);
            woGrabStatuslistItem6.setInfo(results['Closed'] || 0);
            woGrabStatuslistItem7.setInfo(results['GRN'] || 0);
            woGrabStatuslistItem8.setInfo(results['Cancelled'] || 0);
            woGrabStatuslistItem9.setInfo(results['Need_Verification'] || 0);
            //Workorder chart
            let oDataGrabWoStatus = [];
            oDataGrabWoStatus.push({ status: oBundle.getText("Open"), count: results['Open1']  || 0});
            oDataGrabWoStatus.push({ status: oBundle.getText("Completed"), count: results['Completed'] || 0});
            oDataGrabWoStatus.push({ status: oBundle.getText("Closed"), count: results['Closed'] || 0});
            oDataGrabWoStatus.push({ status: oBundle.getText("Cancelled"), count: results['Cancelled'] || 0});
            oDataGrabWoStatus.push({ status: oBundle.getText("GRN"), count: results['GRN'] || 0});
            oDataGrabWoStatus.push({ status: oBundle.getText("Reject"), count: results['Reject'] || 0});
            oDataGrabWoStatus.push({ status: oBundle.getText("Pending_Approval"), count: results['Pending_Approval'] || 0});
            oDataGrabWoStatus.push({ status: oBundle.getText("Need_Verification"), count: results['Need_Verification'] || 0});

            var oModelPieChartWoStatus = new sap.ui.model.json.JSONModel();
            oModelPieChartWoStatus.setData({ modelData: oDataGrabWoStatus });
            oPieChartGrabWorkorderStatus.setModel(oModelPieChartWoStatus);
            oPieChartGrabWorkorderStatus.setBusy(false);

            //Inspection
            homeListGrabInspectionItem1.setInfo(results['Total_Inspection'] || 0);
            homeListGrabInspectionItem2.setInfo(results['Good_Inspection'] || 0);
            homeListGrabInspectionItem3.setInfo(results['Faulty_Inspection'] || 0);
            //Inspection Chart
            var oDataInspectionCountChart = [];
            oDataInspectionCountChart.push({ item: oBundle.getText("Good"), count: results['Good_Inspection'] || 0 });
            oDataInspectionCountChart.push({ item: oBundle.getText("Faulty"), count: results['Faulty_Inspection'] || 0 });

            var oModelInspectionCountChart = new sap.ui.model.json.JSONModel();
            oModelInspectionCountChart.setData({ modelData: oDataInspectionCountChart });
            oPieChartGrabInspectionCount.setModel(oModelInspectionCountChart);


        }, error: function(xhr, status, error, response) {

            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
              
        }
    })

};


//Create Holiday Calendar
function createHolidayCalendar(location_id,holiday_date,note,dialog){
    location_id = locationMasterActiveJSONArray.filter(a=> a.location_id == location_id);
    if(location_id.length > 0){
        location_id = location_id[0]['id']
    }

    $.ajax({
        url: `${api_url_name}/Grab_Inspection.asmx/create_holiday`,
        type: 'POST',
        data:{
            "master_email":emailUser,
            "holiday_date":holiday_date,
            // "location_id":Number(location_id),
            "location_id":location_id,
            "notes":note,
        },
        success: function (results) {
            
            if(results.status == 'success'){
                if(holidayCalenderFilterByLocation.getSelectedKey() != 'Select Location'){
                    getHolidayDataByLocation(holidayCalenderFilterByLocation.getSelectedKey());
                };
            }else{
                sap.m.MessageBox.error(results.message);
            }
            
            dialog.close();
        }, error: function(xhr, status, error, response) {
            sap.m.MessageBox.error(("Create Holiday Failed"));

              
        }
    })
}

//Get Holiday Data By Location 
function getHolidayDataByLocation(location_id){
    location_id = locationMasterActiveJSONArray.filter(a=> a.location_id == location_id);
    if(location_id.length > 0){
        location_id = location_id[0]['id']
    }
    $.ajax({
        url: `${api_url_name}/Grab_Inspection.asmx/get_holiday_by_location_id`,
        type: 'POST',
        data:{
            "master_email":emailUser,
            "location_id":location_id
        },
        success: function (results) { 
        
                holidayJSONArray = results;
                if(nullCheckAll(holidayJSONArray)){           
                    var oModel = new sap.ui.model.json.JSONModel();
                    oModel.setData({ modelData: holidayJSONArray });
                    oTable4WHolidayCal.setModel(oModel);
                    oTable4WHolidayCal.bindItems({ path: "/modelData", template : holidayCal4WTemplate });
                    oTable4WHolidayCal.setBusy(false);
                }else{
                    sap.m.MessageBox.warning(
                        "Message: " + "No Data Present"
                    );
                    var oModel = new sap.ui.model.json.JSONModel();
                    oModel.setData({ modelData: [] });
                    oTable4WHolidayCal.setModel(oModel);
                    oTable4WHolidayCal.bindItems({ path: "/modelData", template : holidayCal4WTemplate });
                    oTable4WHolidayCal.setBusy(false);
                }
          
            // dialog.close();

        }, error: function(xhr, status, error, response) {

            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
              
        }
    })
};

//Delete Holiday Data
function deleteHolidayCalendar(row_id,oDialog){

    // locationId = locationMasterJSONArray.filter(a=> a.id == row_id);

    // if(locationId.length > 0){
    //     locationId = locationId[0]['id']
    // }
    $.ajax({
        url: `${api_url_name}/Grab_Inspection.asmx/delete_holiday`,
        type: 'POST',
        data:{
            row_id:row_id
        },
        success: function (results) { 
           
            if(holidayCalenderFilterByLocation.getSelectedKey() != 'Select Location'){
                getHolidayDataByLocation(holidayCalenderFilterByLocation.getSelectedKey());
            };
            oDialog.close();

        }, error: function(xhr, status, error, response) {
            
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
              
        }
    })
};

//Location New GET Data
var locationMasterJSONArray = [];
var locationMasterActiveJSONArray = [];
function getAllLocationData(){
    oTable4WLocation.setBusy(true);
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_Inspection.asmx/get_all_location_master`,
        data: {
            "master_email": emailUser
        },
        success: function (data) { 
        
            if(data.length > 0 ){
                locationMasterJSONArray = data;
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: data });
                oTable4WLocation.setModel(oModel);
                oTable4WLocation.bindAggregation("items", "/modelData", location4WTemplate);
                oTable4WLocation.setBusy(false);



                locationMasterActiveJSONArray = [...locationMasterJSONArray.filter(a=>a.checkpoint == 'True' && a.status == 'Active')];
                // Sort alphabetically by jaya_location_name (case-insensitive)
                locationMasterActiveJSONArray.sort(function(a, b) {
                    return a.location_name.localeCompare(b.location_name, undefined, { sensitivity: 'base' });
                });
                locationMasterActiveJSONArray.unshift({ location_id: "Select Location", location_name: "Select Location" });
                
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ levels: locationMasterActiveJSONArray });
                oModel.setSizeLimit(locationMasterActiveJSONArray.length);
                holidayCalenderFilterByLocation.setModel(oModel);

                holidayCalenderFilterByLocation.bindItems({
                    path: "/levels", template: new sap.ui.core.Item({ key: "{location_id}", text: "{location_name}" })
                });
            

            }else{
                locationMasterJSONArray = data;
                locationMasterActiveJSONArray = [...locationMasterJSONArray]
                locationMasterActiveJSONArray.unshift({ location_id: "Select Location", location_name: "Select Location" });
                // console.log(locationMasterActiveJSONArray)
            }
            oTable4WLocation.setBusy(false);
        },
        error: function(xhr, status, error) {
            locationMasterJSONArray = [];
                locationMasterActiveJSONArray = [...locationMasterJSONArray]
                locationMasterActiveJSONArray.unshift({ location_id: "Select Location", location_name: "Select Location" });
                // console.log(locationMasterActiveJSONArray)
            oTable4WLocation.setBusy(false);
        }
    });
};
//Update Location and slots.
function updateLocationData(updateItems,oDialog){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_Inspection.asmx/update_location_master`,
        data: updateItems,
        success: function (data) { 
            
            if(data.status == 'success' ){
                // var oModel = new sap.ui.model.json.JSONModel();
                // oModel.setData({ modelData: data });
                // oTable4WLocation.setModel(oModel);
                // oTable4WLocation.bindAggregation("items", "/modelData", location4WTemplate);
                // oTable4WLocation.setBusy(false);
                sap.m.MessageToast.show("Updated successfully");
                getAllLocationData();
                addHistoryTableData(updateItems['row_id'],"Update","Location");
            }else{
            }
            oTable4WLocation.setBusy(false);
            oDialog.close();
        },
        error: function(xhr, status, error) {
            oTable4WLocation.setBusy(false);
            oDialog.close();
        }
    });
};



function updateTeamApprovalPriceAPI(approvalLevel,updatedPrice) {

    busyDialog.open();
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Login.asmx/update_approval_amount`,
        data: {
            "master_email": emailUser,
            "approval_level": approvalLevel,
            "approval_amount": updatedPrice

        },
        success: function (data) {
            busyDialog.close();
            sap.m.MessageBox.success(oBundle.getText("Approval_Amount_Updated")
            ,{title: oBundle.getText("Success")});
        },
        error: function(xhr, status, error) {
            busyDialog.close();
        }
    });

}





//--------------------------------------------------------START REPORT SECION API------------------------------------------------------------------
function reportInspectionData(start_date,end_date){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_Inspection.asmx/get_inspection_detail`,
        data: {
            "master_email": emailUser,
            "from_date":start_date,
            "to_date":end_date
        },
        success: function (data) { 
            if(data.length > 0){
                grabInspectionDetail(data);
               
                busyDialogGetData.close();
            }else{
                busyDialogGetData.close();
                sap.m.MessageBox.error("No Data Found");
                return ;
            }
        },
        error: function(xhr, status, error) {
            busyDialogGetData.close();
        }
    });

};
function reportInspectionItemsData(start_date,end_date){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_Inspection.asmx/get_inspection_detail`,
        data: {
            "master_email": emailUser,
            "from_date":start_date,
            "to_date":end_date
        },
        success: function (data) { 
            if(data.length > 0){
                grabInspectionSummary(data);
                busyDialogGetData.close();
            }else{
                busyDialogGetData.close();
                sap.m.MessageBox.error("No Data Found");
                return ;
            }
        },
        error: function(xhr, status, error) {
            busyDialogGetData.close();
        }
    });


    // $.ajax({
    //     type: "POST",
    //     url: `${api_url_name}/Grab_Inspection.asmx/get_inspection_summary`,
    //     data: {
    //         "master_email": emailUser,
    //         "from_date":start_date,
    //         "to_date":end_date
    //     },
    //     success: function (data) { 
    //         if(data.length > 0){
    //             grabInspectionSummary(data);
               
    //             busyDialogGetData.close();
    //         }else{
    //             busyDialogGetData.close();
    //             sap.m.MessageBox.error("No Data Found");
    //             return ;
    //         }
    //     },
    //     error: function(xhr, status, error) {
    //         busyDialogGetData.close();
    //     }
    // });

};

function reportInspectionScheduleOld(start_date,end_date){
    start_date = start_date.split(" ")[0];
    end_date = end_date.split(" ")[0];
    $.ajax({
        url: `${jrs_go_api_url_name1}/reports/inspections_schedule_detail?master_email=${emailUser}&start_date=${start_date}&end_date=${end_date}`,
        method: 'GET',
        headers: {
            'X-API-Key': jrs_go_api_key1,
            'Content-Type': 'application/json'
        },
        success: function (results) { 
            var dataValues = results['data']['data'];

            if(dataValues == 'No data for current reqs'){
                sap.m.MessageBox.information(oBundle.getText("No_record_found"));
                busyDialogGetData.close();
            }else{
                grabInspectionScheduleDetail(dataValues);
            }
            busyDialogGetData.close();
        }, error: function(xhr, status, error, response) {
            
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseJSON.status)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseJSON.status)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialogGetData.close();
              
        }
    })
};
function reportInspectionSchedule(start_date,end_date){
    start_date = start_date.split(" ")[0];
    end_date = end_date.split(" ")[0];
    $.ajax({
        type: "POST",
        // url: `${api_url_name}/Grab_Inspection.asmx/cp_attendance_report`,
        url: `${api_url_name}/Grab_Inspection.asmx/inspection_reminder_report`,
        data: {
            "master_email": emailUser,
            "fromDate":start_date,
            "toDate":end_date
        },
        success: function (results) { 
            var dataValues = results;
            console.log(results)
            if(dataValues.length > 0){
                var filterrecordsCP = dataValues
                if(portal_type_flag == '2W'){
                    filterrecordsCP = dataValues.filter(a=> a.driver_type == 'Emoto');
                }else if(portal_type_flag == '4W'){
                    filterrecordsCP = dataValues.filter(a=> a.driver_type != 'Emoto');
                }
                grabInspectionScheduleDetail(filterrecordsCP);
            }else{
                sap.m.MessageBox.information(oBundle.getText("No_record_found"));
                busyDialogGetData.close();
            }
            busyDialogGetData.close();
        }, error: function(xhr, status, error, response) {
            
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseJSON.status)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseJSON.status)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialogGetData.close();
              
        }
    })
};
function reportWorkorderStatus(start_date,end_date){
    // start_date = '2025-01-01';
    // end_date = '2025-12-30';
    $.ajax({
        url: `${jrs_go_api_url_name1}/reports/wo_status?master_email=admin@grab.com&start_date=${start_date}&end_date=${end_date}`,
        method: 'GET',
        headers: {
            'X-API-Key': jrs_go_api_key1,
            'Content-Type': 'application/json'
        },
        success: function (results) { 
            var dataValues = results['data']['data'];

            if(dataValues == 'No data for current reqs'){
                sap.m.MessageBox.information(oBundle.getText("No_record_found"));
                busyDialog.close();
            }else{
                
                if (oTableDash1) {
                    dash1Page4W.removeContent(oTableDash1);
                    oTableDash1.destroy();
                }
                
                const dashboardData = transformDashboardData(dataValues);
                oTableDash1  = createDashboardTable(dashboardData);


                dash1Page4W.addContent(oTableDash1);
                oTableDash1.refresh()

            }

        }, error: function(xhr, status, error, response) {
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseJSON.status)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseJSON.status)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
              
        }
    })
};
//--------------------------------------------------------END REPORT SECION API------------------------------------------------------------------




function workorderBulkApproval(updatedItems,oDialog){
 
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/workorder_bulk_approval`,
        data: {
            "master_email": emailUser,
            "approved_by":operatedID,
            "approval_amount":updatedItems['amount_value'],
            "approvar_level":updatedItems['approval_value'],
            "jsonData":JSON.stringify(updatedItems['selectedWorkorders']),
            "note":updatedItems['approved_remark']
        },
        success: function (data) { 
            getPendingWorkorder();
           
            email = updatedItems['selectedApprovers'];
            if(nullCheckAll(email)){
                sendEmailToNextApprover(email,updatedItems['selectedWorkordersEmail']);
            }
            sap.m.MessageToast.show(`${updatedItems['selectedWorkorders'].length} workorders approved.`);
            oDialog.close();
        },
        error: function(xhr, status, error) {
            busyDialogGetData.close();
        }
    });
    
}


function getDifferenceMessages(obj1, obj2) {
    const messages = [];
  
   
    for (const key in obj2) {
      if (obj1.hasOwnProperty(key) && obj1[key] !== obj2[key]) {
        // console.log(`${key} column changed from ${obj1[key]} to ${obj2[key]}`)
        messages.push(`${key} column changed from ${obj1[key]} to ${obj2[key]}`);
      } else if (!obj1.hasOwnProperty(key)) {
        // console.log(`${key} column added with value ${obj2[key]}`)
        messages.push(`${key} column added with value ${obj2[key]}`);
      }
    }
    
    return messages;
};

function addHistoryTableData(record_id,action,section,originalValue,updatedValues){
  
    var differenceValue = "";
    if(action == 'Update'){
        const diffMessagesArray = getDifferenceMessages(originalValue,updatedValues);
        differenceValue = diffMessagesArray.join("; ");
    };

    var action_date = getIndonesianTime();
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/insert_history`,
        data: {
            "master_email": emailUser,
            "action_by":operatedID,
            "action_date":action_date,
            "record_id":record_id,
            "action":action,
            "section":section,
            "summary":differenceValue
        },
        success: function (data) { 
            // sap.m.MessageToast.show(`${updatedItems['selectedWorkorders'].length} workorders approved.`);
            
        },
        error: function(xhr, status, error) {
            console.log("xhr")
        }
    });
}



// function resetInvoiceAPIOld(invoice_id,invoice_number,dialog){
//     $.ajax({
//         type: "POST",
//         url: `${api_url_name}/Grab_Invoice.asmx/reset_invoice`,
//         data: {
//            "invoice_id":invoice_id,
//            "invoice_number":invoice_number,
//            "updated_by":operatedID
//         },
//         success: function (results) { 
//             dialog.close();
//             // fetchInvoiceComparision();
//             refreshCurrentWorkshopInvoiceData();
//             get4WOpenInvoice();
//         }, error: function(xhr, status, error, response) {
//             oTableName.setBusy(false);
//             try {
//                 sap.m.MessageBox.error(
//                     "API Error:\n" +
//                     "Status: " + xhr.status + "\n" +
//                     "StatusText: " + xhr.statusText + "\n" +
//                     "Message: " + (xhr.responseText)
//                 );
//             } catch(e) {
//                 sap.m.MessageBox.error(
//                     "API Error:\n" +
//                     "Status: " + xhr.status + "\n" +
//                     "StatusText: " + xhr.statusText + "\n" +
//                     "Message: " + (xhr.responseText)
//                 );
//             }
//             // sap.m.MessageBox.error(("Invoice Updated Failed"));
//             busyDialog.close();
              
//         }
//     })
// }

function resetInvoiceAPI(invoice_id,invoice_number,dialog,workorder){
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_Invoice.asmx/reset_invoice`,
        data: {
           "invoice_id":invoice_id,
           "invoice_number":invoice_number,
           "updated_by":operatedID,
           "workorder":workorder
        },
        success: function (results) { 
        
            if(results['success']){
                // fetchInvoiceComparision();
                refreshCurrentWorkshopInvoiceData();
                get4WOpenInvoice();
                dialog.close();
            }else{
                sap.m.MessageBox.error("This invoice cannot be reopened because not all associated work orders are in a closed status.");
            }
            busyDialog.close();
        }, error: function(xhr, status, error, response) {
            oTableName.setBusy(false);
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
              
        }
    })
}




function vehicle4WExcelExportAll(){
    
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Vehicle.asmx/get_vehicle_all_export`,
        data: {
            "master_email": emailUser,
        },
        success: function (data) { 
            if(data.length > 1){
                vehicle4WExcelExport('2', data)
            }
            busyDialog.close();
        }, error: function (xhr, status, error) {
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
         
        }
    });    
    
};


//Get Workorder from DB
function funGetWorkorderDetailsFromDb(searchedNumber,src){
    woSources = {
        "GRN": {
            array: grabGrnWOJSONArray,
            table: oTable4WGrnWO,
            template: workorderTemplate
        },
        "CLOSED": {
            array: grabClosedWOJSONArray,
            table: oTable4WClosedWO,
            template: workorderTemplate
        },
        "INVOICECOMPARE": {
            array: invoiceCompareJSONArray,
            table: oTableInvoiceComparison,
            template: invoiceComparisonTemplate
        },
        "INVOICEGRNCOMPARE": {
            array: grabGrnWOJSONArray,
            table: oTable4WAllInvoiceGRN,
            template: oTable4WAllInvoiceGRNTemplate
        },
        "ALLWO": {
            array: grab4WAllWoJSONArray,
            table: oTable4WAllWO,
            template: oTable4WAllWOTemplate
        }
    };
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_workorder_by_wo_number`,
        data: {
            "master_email":emailUser,
            "wo_number": searchedNumber
        },
        success: function (data) { 
     
            if(data.length >= 1){
                var newObj = data[0];
                
                if((src == 'GRN' || src == 'INVOICEGRNCOMPARE' ) && newObj.wo_status != 'GRN'){
                    sap.m.MessageBox.error(`This Workorder belongs to ${newObj.wo_status} status.`);
                    busyDialog.close();
                    return
                }else if(src == 'CLOSED' && newObj.wo_status != 'Closed'){
                    sap.m.MessageBox.error(`This Workorder belongs to ${newObj.wo_status} status.`);
                    busyDialog.close();
                    return
                }else if (src == 'INVOICECOMPARE') {
                    const isValidGroupName = newObj.ws_group_name !== null && newObj.ws_group_name !== undefined && newObj.ws_group_name !== "";
                    const isClosedStatus = newObj.wo_status === "Closed";
                    const hasGrnNumber = !nullCheckAll(newObj.grn_number);
                    const hasInvoiceNumber = nullCheckAll(newObj.invoice_number);
                
                    if (!(isValidGroupName && isClosedStatus && hasGrnNumber && hasInvoiceNumber)) {
                        sap.m.MessageBox.error("This workorder is not eligible for invoice.");
                        busyDialog.close();
                        return;
                    }
                };

                if(oxmaint_role == 'Workshop' && newObj.workshop_number != oxmaint_workshop_number){
                    sap.m.MessageBox.error(`This Workorder belongs to ${newObj.workshop_name} Workshop.`);
                    busyDialog.close();
                    return
                }else if(oxmaint_role == 'Workshop Group Admin' && newObj.ws_group_number != oxmaint_ws_group_number){
                    sap.m.MessageBox.error(`This Workorder belongs to ${newObj.ws_group_name} Workshop Group.`);
                    busyDialog.close();
                    return
                }

                const config = woSources[src] || woSources["ALLWO"];
                const dataArray = config.array;
                const oTable = config.table;
                const oTemplate = config.template;


                var exists = dataArray.some(function (item) {
                    return item.wo_number === newObj.wo_number;
                });
            
                if (!exists) {
                    dataArray.push(newObj);
                }
            
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: dataArray });
                oTable.setModel(oModel);
                oTable.bindItems({ path: "/modelData", template : oTemplate});
                oTable.setBusy(false);
            
                // Step 3: Filter the table to show the searched item
                var oBinding = oTable.getBinding("items");
                if (oBinding) {
                    var oFilter = new sap.ui.model.Filter("wo_number", sap.ui.model.FilterOperator.Contains, searchedNumber);
                    oBinding.filter([oFilter]);
                }


            }else{
                sap.m.MessageBox.error("No Workorder Found");
            }
            busyDialog.close();
        }, error: function (xhr, status, error) {
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
            console.log(error)
        }
    });    
};


//GET driver
//Common 4W and 2W
function getDriverData(){
    oTable4WGrabDriver.setBusy(true);

    $.ajax({
        type: "POST",
        url: `${api_url_name_main}/V01/Grab_Inspection_Booking.asmx/get_all_active_driver`,
        data: {
            "master_email": emailUser,
        },
        success: function (data) { 
        
            if(data.length >= 1){
                if(portal_type_flag == "2W" && client.applicationUrl == 'https://grab-taxi-prod.azurewebsites.net/'){
                    data = data.filter(a=>a.driver_type == '26');
                }else if(portal_type_flag == "2W" && client.applicationUrl == 'https://grab-taxi-stg.azurewebsites.net/'){
                    data = data.filter(a=>a.driver_type == '25');
                }

                driverJSONArray = data;
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: data });
        
                oTable4WGrabDriver.setModel(oModel);
                oModel.setSizeLimit(data.length);
                oTable4WGrabDriver.bindItems({path: "/modelData",template: driver4WGrabTemplate});
                

                // sap.m.MessageToast.show('Successfully updated driver details.');
            }else{
                sap.m.MessageBox.error(data);
            };

            oTable4WGrabDriver.setBusy(false);
            busyDialog.close();
        }, error: function (xhr, status, error) {
            oTable4WGrabDriver.setBusy(false);
            busyDialog.close();
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            
        }
    });  



};
//Sync Driver
//Common 4W and 2W
function syncJayaDriverData(driverObj,oDialog){
    $.ajax({
        type: "POST",
        // url: `${api_url_name_main}/V01/Grab_Inspection_Reminder.asmx/update_driver_from_jaya`,
        url: `${api_url_name_main}/V01/Grab_Inspection_Reminder.asmx/Jaya_Driver_Sync_Prime_Web_Portal`,
        data: {
            "jaya_driver_id": driverObj['jaya_driver_id'],
            "license_number":driverObj['license_number'],
            "last_checkout_date":driverObj['last_checkout_date']
        },
        success: function (data) { 

            if(data.length > 1 && data.startsWith('✅')){
                oDialog.close();
                getDriverData();
                sap.m.MessageBox.success(data);
                sap.m.MessageToast.show('Successfully updated driver details.');
            }else{
                sap.m.MessageBox.error(data);
            }
            busyDialog.close();
        }, error: function (xhr, status, error) {
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
            console.log(error)
        }
    });    

};
//Get Inspection Reminder 
//Common 4W and 2W
var inspectionReminderJSONArray = [];
function getInspectionReminder(){
    $.ajax({
        type: "POST",
        url: `${api_url_name_main}/V01/Grab_Inspection_Booking.asmx/get_all_reminder`,
        data: {
            "master_email":emailUser
        },
        success: function (results) { 

            if(results.length > 0 ){
                if(portal_type_flag == "2W" && client.applicationUrl == 'https://grab-taxi-prod.azurewebsites.net/'){
                    results = results.filter(a=>a.driver_type == '26');
                }else if(portal_type_flag == "2W" && client.applicationUrl == 'https://grab-taxi-stg.azurewebsites.net/'){
                    results = results.filter(a=>a.driver_type == '25');
                }

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

            }else{
            }
            oTable4WLocation.setBusy(false);

        },
        error: function(xhr, status, error) {
            oTable4WLocation.setBusy(false);
            oDialog.close();
        }
    });
};


//Get Invoice Comarision data by workshop number
function getInvoiceCompareData(selectedWS,tableName){
    console.log(selectedWS)
    let oxmaint_workshop_number = selectedWS;
    // let oxmaint_workshop_number_filter = workshop4WJSONData.filter(a=>a.workshop_name == selectedWS);
    // if(oxmaint_workshop_number_filter.length > 0){
    //     oxmaint_workshop_number = oxmaint_workshop_number_filter[0]['workshop_number'];
    // }
    // // console.log(oxmaint_workshop_number)
    // // return
    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_WO.asmx/get_all_workorder_by_status_and_workshop`,
        data: {
            "master_email": emailUser,
            "wo_status":'Closed',
            "workshop_number":oxmaint_workshop_number
        },
        success: function (data) { 

            if(data.length > 0 ){
                var filteredResults = data.filter(function(item) {
                    return nullCheckAll(item.ws_group_name) && (item.wo_status == "Closed") &&
                        !nullCheckAll(item.grn_number) && nullCheckAll(item.invoice_number);
                });
                
                invoiceCompareJSONArray = filteredResults;
            
                
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: filteredResults });
                tableName.setModel(oModel);
                tableName.bindItems({ path: "/modelData", template : invoiceComparisonTemplate });

                
                updateScoreCards(filteredResults);
                tableName.setBusy(false);
            }else{
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: [] });
                tableName.setModel(oModel);
                tableName.bindItems({ path: "/modelData", template : invoiceComparisonTemplate });
                updateScoreCards([]);
                
            };
            tableName.setBusy(false);
        },
        error: function(xhr, status, error) {
            tableName.setBusy(false);
        }
    });
};

//Get Inspection details from DB
function funGetInspectionDetailsFromDb(searchedNumber, archiveStatus,src,modelInput){

    $.ajax({
        type: "POST",
        url: `${api_url_name}/Grab_Inspection.asmx/get_inspection_by_number`,
        data: {
            "master_email":emailUser,
            "archive":archiveStatus,
            "number": searchedNumber
        },
        success: function (data) { 
            
            if(data.length >= 1 && searchedNumber.startsWith("INSP") && searchedNumber.length > 16){
                var newObj = data[0];
                
                if(oxmaint_role == 'Workshop' && newObj.workshop_number != oxmaint_workshop_number){
                    sap.m.MessageBox.error(`This Inspection belongs to ${newObj.workshop_name} Workshop.`);
                    busyDialog.close();
                    return
                }else if(oxmaint_role == 'Workshop Group Admin' && newObj.ws_group_number != oxmaint_ws_group_number){
                    sap.m.MessageBox.error(`This Inspection belongs to ${newObj.ws_group_name} Workshop Group.`);
                    busyDialog.close();
                    return
                }

               

                var exists = inspectionJSONArray.some(function (item) {
                    return item.wo_number === newObj.wo_number;
                });
            
                if (!exists) {
                    inspectionJSONArray.push(newObj);
                };
            
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: inspectionJSONArray });
                oTableInspection.setModel(oModel);
                oModel.setSizeLimit(inspectionJSONArray.length);
                oTableInspection.bindItems({path: "/modelData",template: inspectionTemplate});
                oTableInspection.setBusy(false);


                // Step 3: Filter the table to show the searched item
                var oBinding = oTableInspection.getBinding("items");
                if (oBinding) {
                    var oFilter = new sap.ui.model.Filter("report_number", sap.ui.model.FilterOperator.Contains, searchedNumber);
                    oBinding.filter([oFilter]);
                    aInspectionAllFilters = [oFilter];
                }


            }else if(data.length >= 1 && !searchedNumber.startsWith("INSP") && src != 'workorder'){
                var newObj = data;


                if(oxmaint_role == 'Workshop'){
                    newObj = data.filter(a=>a.workshop_number == oxmaint_workshop_number);
                }else if(oxmaint_role == 'Workshop Group Admin'){
                    newObj = data.filter(a=>a.ws_group_number == oxmaint_ws_group_number);
                }

                const inspectionReportNumbers = new Set(
                    inspectionJSONArray.map(item => item.report_number)
                  );
                  
                  // Step 2: Get full JSON objects from newObj where report_number is missing
                  const missingReports = newObj.filter(
                    item => !inspectionReportNumbers.has(item.report_number)
                  );


                // const missingReports = newObj.filter(
                //     item => !inspectionJSONArray.has(item.report_number)
                // );

                console.log(missingReports)
                if(missingReports.length > 0){
                    inspectionJSONArray.push(...missingReports);
                }
                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: inspectionJSONArray });
                oTableInspection.setModel(oModel);
                oModel.setSizeLimit(inspectionJSONArray.length);
                oTableInspection.bindItems({path: "/modelData",template: inspectionTemplate});
                oTableInspection.setBusy(false);


                var oBinding = oTableInspection.getBinding("items");
                if (oBinding) {
                    var oFilter = new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, searchedNumber);
                    oBinding.filter([oFilter]);
                    aInspectionAllFilters = [oFilter];
                }

                historySearch.setValue(searchedNumber)
            }else if(src == 'workorder'){
                filteredData = data.filter(obj =>
                  (nullCheckAll(obj["repair"]) || nullCheckAll(obj["replace"]))
                );

                modelInput.setData({ modelData: filteredData });                
            }else{
                sap.m.MessageBox.error("No Inspection Found");
            }
            busyDialog.close();
        }, error: function (xhr, status, error) {
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
            console.log(error)
        }
    });    
};



function funGetInspectionReminderDetailsFromDb(searchData){
    $.ajax({
        type: "POST",
        url: `${api_url_name_main}/V01/Grab_Inspection_Booking.asmx/get_all_reminder_filter`,
        data: {
            "master_email":emailUser,
            "value": searchData
        },
        success: function (data) { 
            
            console.log(data)
            if(data.length >= 1){
                oTable4WGrabInspReminder.setBusy(true);
                var newObj = data;

                var unmatchedRecords = newObj.filter(function(inputItem) {
                    return !inspectionReminderJSONArray.some(function(reminderItem) {
                        return reminderItem.license_number === inputItem.license_number &&
                               reminderItem.driver_email === inputItem.driver_email &&
                               reminderItem.booking_start_date === inputItem.booking_start_date &&
                               reminderItem.due_date === inputItem.due_date;
                    });
                });
                
                if(unmatchedRecords.length > 0){
                    inspectionReminderJSONArray.push(...unmatchedRecords);
                }

                var oModel = new sap.ui.model.json.JSONModel();
                oModel.setData({ modelData: inspectionReminderJSONArray });
                oTable4WGrabInspReminder.setModel(oModel);
                oModel.setSizeLimit(inspectionReminderJSONArray.length);
                oTable4WGrabInspReminder.bindItems({path: "/modelData",template: inspReminderTemplate});
                oTable4WGrabInspReminder.setBusy(false);


                var oBinding = oTable4WGrabInspReminder.getBinding("items");
                if (oBinding) {
                    var oFilter = new sap.ui.model.Filter({
                        filters: [
                            new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, searchData),
                            new sap.ui.model.Filter("driver_email", sap.ui.model.FilterOperator.Contains, searchData),
                            new sap.ui.model.Filter("jaya_driver_id", sap.ui.model.FilterOperator.Contains, searchData),
                            new sap.ui.model.Filter("booking_id", sap.ui.model.FilterOperator.Contains, searchData)
                        ],
                    });oBinding.filter([oFilter]);
                }

                inspReminderSearch.setValue(searchData)
            }
            busyDialog.close();
        }, error: function (xhr, status, error) {
            try {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            } catch(e) {
                sap.m.MessageBox.error(
                    "API Error:\n" +
                    "Status: " + xhr.status + "\n" +
                    "StatusText: " + xhr.statusText + "\n" +
                    "Message: " + (xhr.responseText)
                );
            }
            // sap.m.MessageBox.error(("Invoice Updated Failed"));
            busyDialog.close();
            console.log(error)
        }
    });  
}
