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


//4W Grab Driver
var oTable4WGrabDriver = new sap.m.Table({growing: true,mode: "SingleSelectMaster",noDataText: oBundle.getText("No_Data"),
    growingTriggerText: oBundle.getText("More"),growingThreshold: 25,mode:"None",growingScrollToLoad: false,
    sticky: [sap.m.Sticky.ColumnHeaders, sap.m.Sticky.HeaderToolbar, sap.m.Sticky.InfoToolbar],
    columns: [
        new sap.m.Column({ width: "100px", header: new sap.m.Label({ text: oBundle.getText("Action"), design: sap.m.LabelDesign.Bold }) }),
        new sap.m.Column({ header: new sap.m.Label({ wrapping:true, text: oBundle.getText("Name"), design: sap.m.LabelDesign.Bold }),
        minScreenWidth: "Phone",demandPopin: true, popinDisplay: "Inline" }),
        new sap.m.Column({ header: new sap.m.Label({wrapping:true, text: oBundle.getText("License_Number"), design: sap.m.LabelDesign.Bold }),
        minScreenWidth: "Tablet", demandPopin: true, popinDisplay: "Inline" }),
        new sap.m.Column({ header: new sap.m.Label({wrapping:true, text: oBundle.getText("Email"), design: sap.m.LabelDesign.Bold }),
        minScreenWidth: "Desktop", demandPopin: true, popinDisplay: "Inline"}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Driver_Type"), design: sap.m.LabelDesign.Bold }),
        minScreenWidth: "Desktop", demandPopin: true, popinDisplay: "Inline"}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Handover_Date"), design: sap.m.LabelDesign.Bold }),
        minScreenWidth: "Tablet", demandPopin: true, popinDisplay: "Inline"}),
        new sap.m.Column({header: new sap.m.Label({wrapping:true, text: oBundle.getText("Status"), design: sap.m.LabelDesign.Bold }),
        minScreenWidth: "Desktop", demandPopin: true, popinDisplay: "Inline"}),
       
]});
oTable4WGrabDriver.setHeaderToolbar(new sap.m.Toolbar({
    content: [
        // new sap.m.Button({ 
        //     id:"createDriverID",
        //     text: oBundle.getText("Add_Driver"), 
        //     type:sap.m.ButtonType.Emphasized,
        //     icon: sap.ui.core.IconPool.getIconURI("add"), 
        //     press: function(){
        //         createUpdateDriver(1);
        //     } 
        // }),
        new sap.m.ToolbarSpacer(),
        new sap.m.SearchField({
            placeholder: oBundle.getText("Search"),
            width: "300px",
            liveChange: function (event) {
                var oBinding = oTable4WGrabDriver.getBinding("items");
                var searchStr = this.getValue();
                if (oBinding) {
                    var oFilters = [
                        new sap.ui.model.Filter("user_id", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("driver_email", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("handover_date", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("driver_type", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("license_number", sap.ui.model.FilterOperator.Contains, searchStr),
                        new sap.ui.model.Filter("driver_name", sap.ui.model.FilterOperator.Contains, searchStr),
                    ];
                    var filterObj = new sap.ui.model.Filter(oFilters, false);
                    oBinding.filter(filterObj);
                } else {
                    oBinding.filter([]);
                }
            }
    
        }),
       
    ]
}));
var driver4WGrabTemplate = new sap.m.ColumnListItem({
    cells: [
        new sap.m.Button({type: "Emphasized",icon: "sap-icon://action",text: oBundle.getText("Action"),
            press: function (event) {
                var model = this.getModel();
                var path = event.getSource().getBindingContext().getPath();
                var obj1 = model.getProperty(path);
                displayMenuGrabDriver(event, obj1);
            }
        }),
    
        new sap.m.Label({ wrapping:true, text: "{driver_name}"}),
        new sap.m.Label({ wrapping:true, text: "{license_number}"}),
        new sap.m.Label({ wrapping:true, text: "{driver_email}"}),
        // new sap.m.Label({ text: "{driver_type}"}),
        new sap.m.VBox({
            items:[
                new sap.m.Label({ wrapping: true, text: "{driver_type}" }),
                new sap.m.Label({
                    wrapping: true,
                    text: {
                      path: "driver_type",
                      formatter: function (driverTypeId) {
                        // const driverTypeMap = driverReminderDays;
                        const driverTypeMap = driverTypeArray;
                        return driverTypeMap[driverTypeId] || driverTypeId;
                      }
                    }
                  }).addStyleClass("sapUiTinyMarginTop")
            ]}).addStyleClass("sapUiTinyMargin"),
        new sap.m.Label({ wrapping:true, text: "{handover_date}"}),
        new sap.tnt.InfoLabel({colorScheme:6,
            text: { path: "status",
                formatter: function (status) {
                    if(status=="Inactive"){
                        this.setColorScheme(3);
                        return oBundle.getText("Inactive");
                    }else {
                        this.setColorScheme(8);
                        return oBundle.getText("Active");
                    }
                }
            }}),
    ],
});


function createUpdateDriver(src,obj){


    let o4WDriver1 =  new sap.m.Input({});
    // let o4WDriver2 =  new sap.m.Input({});
    let o4WDriver3 =  new sap.m.Input({placeholder:"Minimum 12 alphanumeric characters", type:"Password", value: "", width: "100%",
        liveChange : function(event) {
            var password = this.getValue();
            var specialCharRegex = /[!@#$%^&*(),.?":{}|<>]/; // Regex to check for special symbols
            var capitalLetterRegex = /[A-Z]/; // Regex to check for at least one capital letter

            if (password.length < 12) {
                this.setValueStateText(oBundle.getText("Minimum_12_alphanumeric_character"));
                this.setValueState(sap.ui.core.ValueState.Error);  // if the field is empty after change, it will go red
            }else if (!specialCharRegex.test(password)) {
                this.setValueStateText(oBundle.getText("Password_must_contain_at_least_one_special_symbol"));
                this.setValueState(sap.ui.core.ValueState.Error);
            } else if (!capitalLetterRegex.test(password)) {
                this.setValueStateText(oBundle.getText("Password_must_contain_at_least_one_capital_letter"));
                this.setValueState(sap.ui.core.ValueState.Error);
            }else {
                this.setValueStateText("");
                this.setValueState(sap.ui.core.ValueState.None); }
        } });
        //new sap.m.Input({});
    let o4WDriver4 =  new sap.m.Input({});
    let o4WDriver5 =  new sap.m.Input({});
    let o4WDriver6 =  new sap.m.DatePicker({width:"100%",displayFormat: "dd-MMM-yyyy" ,valueFormat: "dd-MMM-yyyy"});
    o4WDriver6.attachBrowserEvent("keydown", function (oEvent) {
        oEvent.preventDefault(); // Prevent manual typing
    });
    let o4WDriver7 =  new sap.m.Input({});

    var driverForm4w =  new sap.ui.layout.form.Form({
        editable: true,
        layout: new sap.ui.layout.form.ResponsiveGridLayout(),
        formContainers: [
            new sap.ui.layout.form.FormContainer({
                formElements: [
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Driver_Name")),fields: [o4WDriver1]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Email")),fields: [o4WDriver5]}),
                    // new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Driver_ID")),fields: [o4WDriver2]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Password")),fields: [o4WDriver3]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Driver_Type")),fields: [o4WDriver4]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("Handover_Date")),fields: [o4WDriver6]}),
                    new sap.ui.layout.form.FormElement({label: reqLbl.clone().setText(oBundle.getText("License_Number")),fields: [o4WDriver7]}),
                    
                ]
            }),
        ]
    });

    var add4WDriverBtn = new sap.m.Button({ 
        text: oBundle.getText("Create"), 
        icon: "sap-icon://add",
        press: function(){
            let driver_name = o4WDriver1.getValue();
            // let driver_id = o4WDriver2.getValue();
            let password = o4WDriver3.getValue();
            let driver_type = o4WDriver4.getValue();
            let email = o4WDriver5.getValue();
            let handover_date = o4WDriver6.getValue();
            let license_number = o4WDriver7.getValue()


            if (validation(driver_name , oBundle.getText("Driver_Name"))) { return; }
            if (validation(handover_date , oBundle.getText("Handover_Date"))) { return; }

            //Password
            const specialSymbolPattern = /[!@#$%^&*(),.?":{}|<>]/; // Special characters
            const numberPattern = /\d/; // At least one digit
            const uppercasePattern = /[A-Z]/; // At least one uppercase letter

            if (!specialSymbolPattern.test(password)) {
                 sap.m.MessageBox.error(oBundle.getText("Password_must_contain_at_least_one_special_symbol"));
                 return;
            }
            if (!numberPattern.test(password)) {
                 sap.m.MessageBox.error(oBundle.getText("Password_must_contain_at_least_one_number"));
                 return;
            }
            if (!uppercasePattern.test(password)) {
                 sap.m.MessageBox.error(oBundle.getText("Password_must_contain_at_least_one_uppercase_letter"));
                 return;
            }
            if (password.length < 12) {
                sap.m.MessageBox.error(oBundle.getText("Use_12_characters_or_more_for_Password"));
                return;
            }

            if (user_id.length < 3) {
                sap.m.MessageBox.error(oBundle.getText("User_ID_characters"));
                return;
            }

            //EMAIL
            if(hasWhiteSpace(email)){
                sap.m.MessageBox.error(oBundle.getText("Email")+" "+oBundle.getText("contain_space"));
                return;
            }
            if(email!=""){
                if (regEmail.test(email) == false) {
                    sap.m.MessageBox.error(oBundle.getText("Email_Invalid"));
                    return ;
                }
            }else{
                sap.m.MessageBox.error(oBundle.getText("Enter_Valid_Email"));
                return ;
            }

            Car_Driver_Master.where({master_email:emailUser,driver_email:email}).take(1000).orderByDescending("createdAt").read().done(function (results) {
                if(results.length > 0){
                    sap.m.MessageBox.error(oBundle.getText("Duplicate_Email_detected_Please_enter_a_different_Email"));
                    return ;
                }
            });


            busyDialog.open();
            var created_date = getIndonesianTime();
           
            let insertItems = {
               master_email:emailUser,
               driver_email:email,
               password:password,
               driver_name:driver_name,
               driver_type:driver_type,
               handover_date:handover_date,
               license_number:license_number,
               created_date:created_date,
               created_by:operatedID
            };
            console.log(insertItems)
            return
            Car_Driver_Master.insert(insertItems).done(function () {
                getDriverData();
                busyDialog.close();
                oDialog.close();
            }, failure);


        }
    });
    var update4WDriverBtn = new sap.m.Button({ 
        text: oBundle.getText("Create"), 
        icon: "sap-icon://add",
        press: function(){
            let driver_name = o4WDriver1.getValue();
            // let driver_id = o4WDriver2.getValue();
            let password = o4WDriver3.getValue();
            let driver_type = o4WDriver4.getValue();
            let email = o4WDriver5.getValue();
            let handover_date = o4WDriver6.getValue();
            let license_number = o4WDriver7.getValue()


            if (validation(driver_name , oBundle.getText("Driver_Name"))) { return; }
            if (validation(handover_date , oBundle.getText("Handover_Date"))) { return; }

            //Password
            const specialSymbolPattern = /[!@#$%^&*(),.?":{}|<>]/; // Special characters
            const numberPattern = /\d/; // At least one digit
            const uppercasePattern = /[A-Z]/; // At least one uppercase letter

            if (!specialSymbolPattern.test(password)) {
                 sap.m.MessageBox.error(oBundle.getText("Password_must_contain_at_least_one_special_symbol"));
                 return;
            }
            if (!numberPattern.test(password)) {
                 sap.m.MessageBox.error(oBundle.getText("Password_must_contain_at_least_one_number"));
                 return;
            }
            if (!uppercasePattern.test(password)) {
                 sap.m.MessageBox.error(oBundle.getText("Password_must_contain_at_least_one_uppercase_letter"));
                 return;
            }
            if (password.length < 12) {
                sap.m.MessageBox.error(oBundle.getText("Use_12_characters_or_more_for_Password"));
                return;
            }

            if (user_id.length < 3) {
                sap.m.MessageBox.error(oBundle.getText("User_ID_characters"));
                return;
            }

            //EMAIL
            if(hasWhiteSpace(email)){
                sap.m.MessageBox.error(oBundle.getText("Email")+" "+oBundle.getText("contain_space"));
                return;
            }
            if(email!=""){
                if (regEmail.test(email) == false) {
                    sap.m.MessageBox.error(oBundle.getText("Email_Invalid"));
                    return ;
                }
            }else{
                sap.m.MessageBox.error(oBundle.getText("Enter_Valid_Email"));
                return ;
            }

            Car_Driver_Master.where({master_email:emailUser,driver_email:email}).take(1000).orderByDescending("createdAt").read().done(function (results) {
                if(results.length > 0){
                    sap.m.MessageBox.error(oBundle.getText("Duplicate_Email_detected_Please_enter_a_different_Email"));
                    return ;
                }
            });


            busyDialog.open();
            var created_date = getIndonesianTime();
           
            let insertItems = {
               master_email:emailUser,
               driver_email:email,
               password:password,
               driver_name:driver_name,
               driver_type:driver_type,
               handover_date:handover_date,
               license_number:license_number,
               created_date:created_date,
               created_by:operatedID
            };
            console.log(insertItems)
            return
            Car_Driver_Master.insert(insertItems).done(function () {
                getDriverData();
                busyDialog.close();
                oDialog.close();
            }, failure);


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


    if(src == 2){
        oDialog.setTitle(oBundle.getText('Update_4W_Driver'));
        add4WDriverBtn.setVisible(false);
        update4WDriverBtn.setVisible(true);

    
        o4WDriver1.setValue(obj['driver_name']);
        o4WDriver5.setValue(obj['driver_email']);
        o4WDriver3.setValue(obj['password']);
        o4WDriver4.setValue(obj['driver_type']);
        o4WDriver6.setValue(obj['handover_date']);
        o4WDriver7.setValue(obj['license_number']);

        o4WDriver1.setEnabled(false);
        o4WDriver5.setEnabled(false);
        o4WDriver3.setEnabled(false);
        o4WDriver4.setEnabled(false);
        o4WDriver6.setEnabled(false);
        o4WDriver7.setEnabled(false);
        
    }else  if(src == 3){
        oDialog.setTitle(oBundle.getText('View_4W_Driver'));
        add4WDriverBtn.setVisible(false);
        update4WDriverBtn.setVisible(false);

    
        o4WDriver1.setValue(obj['driver_name']);
        o4WDriver5.setValue(obj['driver_email']);
        o4WDriver3.setValue(obj['password']);
        o4WDriver4.setValue(obj['driver_type']);
        o4WDriver6.setValue(obj['handover_date']);
        o4WDriver7.setValue(obj['license_number']);

        o4WDriver1.setEnabled(false);
        o4WDriver5.setEnabled(false);
        o4WDriver3.setEnabled(false);
        o4WDriver4.setEnabled(false);
        o4WDriver6.setEnabled(false);
        o4WDriver7.setEnabled(false);
        
    }
};

function displayMenuGrabDriver(event,obj){

    var oMenu = new sap.m.Menu({
        items: [
            new sap.m.MenuItem({visible:true, icon: "sap-icon://show",text: oBundle.getText("View"),key: "0"}),
            new sap.m.MenuItem({visible:true, icon:"sap-icon://synchronize",text: oBundle.getText("Sync Jaya"),key: "1"}),
        ],
        itemSelected: function (oEvent) {
            var oItem = oEvent.getParameter("item").getKey();
             var mid = obj['id'];
            if (oItem == "0") {
                console.log(obj)
                viewDriver(obj)
            } else if (oItem == "3") {
                var oDialog = new sap.m.Dialog({
                    title: oBundle.getText("Alert"),
                    state: sap.ui.core.ValueState.Error,
                    content: [new sap.m.Label({ text: oBundle.getText("Sure_You_want_to_delete") })],
                    buttons: [
                                new sap.m.Button({text: oBundle.getText("Delete"),icon: "sap-icon://delete",
                                    press: function () {
                                        busyDialog.open();
                                        Car_Driver_Master.del({ id: obj['id'] }).done(function () {
                                            getDriverData();
                                            oDialog.close();
                                            busyDialog.close();
                                        });
                                    }
                                }),
                                new sap.m.Button({text: oBundle.getText("Cancel"),icon: "sap-icon://decline",
                                    press: function () {
                                        oDialog.close();
                                    }
                                })
                            ]
                }).open();
            } else if(oItem == "1"){
                var oDialog = new sap.m.Dialog({
                    title: "Sync Jaya Driver Data",
                    content: [
                        new sap.m.Text({ text: "Do you want to sync data now?" })
                    ],
                    beginButton: new sap.m.Button({
                        text: "Sync",
                        icon:"sap-icon://synchronize",
                        type: "Emphasized",
                        press: function () {
                            syncJayaDriverData(obj,oDialog);
                        }
                    }),
                    endButton: new sap.m.Button({
                        text: "Cancel",
                        press: function () {
                            oDialog.close();
                        }
                    }),
                    afterClose: function () {
                        oDialog.destroy(); // Cleanup dialog from DOM
                    }
                }).open();
            }
        }
    });
    // getDeleteMenu(oMenu,"3");

    oMenu.openBy(event.getSource());
}


function viewDriver(obj){
    var oDialog = new sap.m.Dialog({
        title: "Driver Details - " + obj.driver_name,
        contentWidth: "500px",
        contentHeight: "auto",
        content: [
            new sap.m.VBox({
                items: [
                    new sap.m.Label({ text: "Driver Email" }),
                    new sap.m.Text({ text: obj.driver_email }),
    
                    new sap.m.Label({ text: "Driver Type" }),
                    new sap.m.Text({ text: obj.driver_type }),
    
                    new sap.m.Label({ text: "License Number" }),
                    new sap.m.Text({ text: obj.license_number }),

    
                    new sap.m.Label({ text: "Handover Date" }),
                    new sap.m.Text({ text: obj.handover_date }),
    
                    new sap.m.Label({ text: "Last Checkout Date" }),
                    new sap.m.Text({ text: obj.last_checkout_date ? obj.last_checkout_date : "-" }),
    
                    new sap.m.Label({ text: "Last Due Date" }),
                    new sap.m.Text({ text: obj.last_due_date ? obj.last_due_date : "-" }),
    
    
                    new sap.m.Label({ text: "Status" }),
                    new sap.m.Text({ text: obj.status }),
    
                ]
            }),
        ],
        beginButton: new sap.m.Button({
            text: "Close",
            press: function () {
                oDialog.close();
            }
        }),
        afterClose: function () {
            oDialog.destroy();
        }
    });
    
    // Open Dialog
    oDialog.open();
};

var driverJSONArray = [];
// function getDriverData(){
//     oTable4WGrabDriver.setBusy(true);
//     Car_Driver_Master.where({master_email:emailUser,status:"Active"}).take(2000).orderByDescending("createdAt").read().done(function (results) {
//         driverJSONArray = results;
//         var oModel = new sap.ui.model.json.JSONModel();
//         oModel.setData({ modelData: results });

//         oTable4WGrabDriver.setModel(oModel);
//         oModel.setSizeLimit(results.length);
//         oTable4WGrabDriver.bindItems({path: "/modelData",template: driver4WGrabTemplate});
//         oTable4WGrabDriver.setBusy(false);
//     });
// }

var driverPage4W = new sap.m.Page("driver_page_4w", {
    title:oBundle.getText("4W_Driver_Management"),
    showHeader:true,
    enableScrolling:true,
    content : [oTable4WGrabDriver] 
}); 