var TaxiApp = angular.module('NewDriver', ['ngStorage', 'ngDialog', 'angularUtils.directives.dirPagination', 'ui.bootstrap']);
var company, Drivers;
TaxiApp.service('EditDriverInfo', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (idd) {
        var modalInstance = $modal.open({
            windowClass: 'EditDriverInfo',
            templateUrl: 'EditDriverInfo.html',
            controller: 'EditDriverInfoCtrl',


        });

    };



    return service;
})
TaxiApp.controller('EditDriverInfoCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, obj) {
   




    $scope.ClickClose = function () {
        $(".ngdialog-close").trigger("click");

    }
    $scope.EditItem = function () {
        var message = $('#message').val();
        $.ajax({
            cache: true,
            url: ManagementServiceUrl + "SendCompanyDriversSMS/" + sessionStorage.SelectedCompany + "/" + sessionStorage.UserOID + "/" + message + "/" + sessionStorage.TokenID,
            type: "GET",
            contentType: "application/javascript",
            dataType: "jsonp",
            success: function (result) {
                if (result.SendCompanyDriversSMSResult == "access_denied") {
                    window.parent.location.href = "../../Access.html";
                    return;
                }
                var count =result.SendCompanyDriversSMSResult.replace('"', '');
                if (count >= 0) {
                    alert("تم الارسال الى "+count+" سائق");                               //  console.log($scope.driverList)

                } else {
                    alert("حدث خطأ: "+count)
                }

                $scope.loading = false; $scope.$apply();
            }
        });



    }





})
TaxiApp.controller('NewDriverCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 
    function ($scope, $http, $sessionStorage, ngDialog, $confirm) {
        $scope.Role = sessionStorage.RoleType;
        $scope.RoleID = sessionStorage.RoleID;
        $scope.DisplayName = sessionStorage.UserName;
        $scope.CompanyName = sessionStorage.value;
        $scope.dataSimCard = false;
        $scope.appDisabled = false;
        $scope.negativeBalance = false;

        if (sessionStorage.OrderId <1) {
            window.location.href = "../../Access.html";
        }
        else {
            Localization(sessionStorage.selectedLanguage, 'user', $scope, sessionStorage);
            $scope.loading = true;
            // $('.driveradd').hide();

            if (sessionStorage.length == (undefined || 0)) {
                window.parent.location.href = "../../Index.html";
            }
            else {
                var TokenID = sessionStorage.TokenID;
                var orgOID = sessionStorage.ORGOID;
                var userOID = sessionStorage.UserOID;
                var roleType = sessionStorage.RoleType;
                var roleID = sessionStorage.RoleID;
                var companyOID = sessionStorage.CompanyOID;
                $scope.Role = sessionStorage.RoleType;
         
                loadDropDownFromAppConfig("CARTYPE", userOID, companyOID, orgOID, 0, $scope);
                // console.log($scope.CARTYPE)

                loadDropDownFromAppConfig("Group", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, 0, $scope);
                if (sessionStorage.CompanyOID != undefined || sessionStorage.ORGOID != undefined) {
                    loadDropDownFromAppConfig("COMPANY", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, 0, $scope);
                }
                var Base64 = {
                    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

                    encode: function (e) { var t = ""; var n, r, i, s, o, u, a; var f = 0; e = Base64._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64 } else if (isNaN(i)) { a = 64 } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a) } console.log(t); return t },


                    decode: function (e) { var t = ""; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9+/=]/g, ""); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r) } if (a != 64) { t = t + String.fromCharCode(i) } } t = Base64._utf8_decode(t); return t }, _utf8_encode: function (e) { e = e.replace(/rn/g, "n"); var t = ""; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r) } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128) } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128) } } return t }, _utf8_decode: function (e) { var t = ""; var n = 0; var r = c1 = c2 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++ } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode((r & 31) << 6 | c2 & 63); n += 2 } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3 } } return t }
                }
              
                $scope.currentPage =1
               $scope.Export = {

                    exportToExcel: function () {

                        var htmlTable = '<table class="alltable table table-bordered sortableTable responsive-table table-hover" id="table1"  style="direction: rtl;">';
                        htmlTable += '<thead><tr><th> <span > الاسم</span></th><th> <span > الرقم</span></th><th> <span > EMEI</span></th><th> <span > رقم السيارة</span></th><th> <span > الرصيد</span></th><th> <span > اصدار التطبيق</span></th></tr> </thead> <tbody>';

                        var row = "";

                        for (var i = 0; i < $scope.driverList.length; i++) {

                            var object = $scope.driverList[i];
                            row = '<tr class="even gradeC">';
                            row += "<td>" + object.DriverFirstName + "</td>";
                            row += "<td>" + object.CorporateMobileNumber + "</td>";
                            row += "<td>" + object.IMEINumber + "</td>";
                            row += "<td>" + object.VehRegistrationNo + "</td>";
                            row += "<td>" + object.Driver_Wallet_Balance + "</td>";
                            row += "<td>" + object.DriverAppVersion + "</td>";
                            row += '</tr>';

                            htmlTable += row;
                            row = "";
                        }

                        htmlTable += "</tbody></table>";


                        $(htmlTable).table2excel({

                            type: "Text",
                            name: "Worksheet Name",

                            filename: "قائمة السائقين " //do not include extension

                        });

                    }
               }

                $scope.SelectMake = function (make) {
                    $scope.$loading = true;
                    $scope.Lookups.loadModels(make);
                    $scope.$loading = false;
                }
                $scope.SelectGovernorate = function (gov) {
                    $scope.$loading = true;
                    $scope.Lookups.loadCities(gov);
                    $scope.$loading = false;
                }
                $scope.Lookups = {
                    load: function () {
                        $scope.$loading = true;
                        this.loadGovernorates();
                        this.loadMakes();
                        this.loadColors();
                        this.loadYears();
                        $scope.$loading = false;

                    },
                    loadGovernorates: function () {
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "GetGovernorates/" + "/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                if (result.GetGovernoratesResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                $scope.Governorates = JSON.parse(result.GetGovernoratesResult);
                                //  console.log($scope.driverList)
                            }
                        });
                    },
                    loadCities: function (gov, city) {
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "GetGovernorateCitiesByName/" + gov + "/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                if (result.GetGovernorateCitiesByNameResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                $scope.Cities = JSON.parse(result.GetGovernorateCitiesByNameResult);

                                $scope.$apply();
                                if (city)
                                    $scope.e_City = city;
                                $scope.$apply();

                                //  console.log($scope.driverList)
                            }
                        });
                    },
                    loadMakes: function () {
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "GetMakes/" + "/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                if (result.GetMakesResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                $scope.Makes = JSON.parse(result.GetMakesResult);
                                //  console.log($scope.driverList)
                            }
                        });

                    },
                    loadModels: function (make, model) {
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "GetModelsByName/" + make + "/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                if (result.GetModelsByNameResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                $scope.Models = JSON.parse(result.GetModelsByNameResult);
                                $scope.$apply();
                                if (model)
                                    $scope.e_Model = model;
                                $scope.$apply();
                                //  console.log($scope.driverList)
                            }
                        });

                    },
                    loadColors: function () {
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "GetColors/" + "/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                if (result.GetColorsResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                $scope.Colors = JSON.parse(result.GetColorsResult);
                                //  console.log($scope.driverList)
                            }
                        });

                    },
                    loadYears: function () {
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "GetYears/" + "/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                if (result.GetYearsResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                $scope.Years = JSON.parse(result.GetYearsResult);
                                //  console.log($scope.driverList)
                            }
                        });

                    }

                }      
                $scope.Drivers = {
                    waslCheckAllDriversEligibility: function () {

                        $scope.loading = true;
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "CheckAllDriversEligibility/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                if (result.CheckAllDriversEligibilityResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                var ret = JSON.parse(result.CheckAllDriversEligibilityResult);
                                if (ret != "success") {
                                    alert("error: " + ret);
                                }
                                //  console.log($scope.driverList)
                                $scope.Drivers.get($scope.Company);
                                $scope.loading = false; $scope.$apply();
                            }
                        });


                    },

                    waslCheckDriverEligibility: function (driver) {

                        $scope.loading = true;
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "CheckDriverEligibility/" + driver.Nationl_ID + "/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                if (result.CheckDriverEligibilityResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                var ret = JSON.parse(result.CheckDriverEligibilityResult);
                                if (ret != "success") {
                                    alert("error: " + ret);
                                }
                                //  console.log($scope.driverList)
                                $scope.Drivers.get($scope.Company);
                                $scope.loading = false; $scope.$apply();
                            }
                        });


                    },
                    filter: function () {
                        this.get($scope.Company);
                    },
                    get: function (compOid) {
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "GetCompanyDrivers/" + compOid + "/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                if (result.GetCompanyDriversResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                $scope.driverList = JSON.parse(result.GetCompanyDriversResult);
                              //  console.log($scope.driverList)
                                for (var i = 0; i < $scope.driverList.length; i++) {
                                   
                                    if ($scope.driverList[i].driver.LastActivityDateTime != null) {
                                        var days = new Date() - Date.parse($scope.driverList[i].driver.LastActivityDateTime);
                                        days = Math.trunc(days / (1000 * 60 * 60 * 24));
                                        if (days == 0)
                                            $scope.driverList[i].driver.LastActivityTime = 'اليوم';
                                        else
                                            $scope.driverList[i].driver.LastActivityTime = days+ ' '+'يوم';



                                    }
                                }
                                if ($scope.dataSimCard == true) {
                                    $scope.driverList = $scope.driverList.filter(value =>
                                        value.driver.DataSimCard != null
                                    );
                                }

                                if ($scope.appDisabled == true) {
                                    $scope.driverList = $scope.driverList.filter(value =>
                                        value.driver.Show_Car_In_CutomerApp == false
                                    );
                                }

                                if ($scope.negativeBalance == true) {
                                    $scope.driverList = $scope.driverList.filter(value =>
                                        value.driver.Driver_Wallet_Balance < 0
                                    );
                                }
                                $scope.loading = false; $scope.$apply();
                            }
                        });
                    }, 
                    remove: function (driver_obj) {
                        $scope.removeDriverOID = driver_obj.OID
                        $scope.removeCompanyId = driver_obj.CompanyId
                        $('#DeleteDriver').modal('toggle');
               
                     
                    },
                    edit: function (d,c) {
                        var DriverSetupObject = {};
                        var driverSetupObject = {


                            "OID": d.OID,
                            "CreatedBy": userOID,
                            "TokenID": sessionStorage.TokenID,
                        }

                        DriverSetupObject["driverSetupObject"] = driverSetupObject;
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "getDriverProofingDocuments",
                            type: "POST",
                            data: JSON.stringify(DriverSetupObject),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (result) {
                                if (result.getDriverProofingDocumentsResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                $scope.driverDocuments = JSON.parse(result.getDriverProofingDocumentsResult);
                                //  console.log($scope.driverList)

                                $scope.loading = false;
                                $scope.$apply();
                            }
                        });
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "GetDriverPhoto/" + d.OID + "/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {

                                $scope.DriverPhoto = result.GetDriverPhotoResult;
                                $scope.$apply();
                                //  console.log($scope.driverList)

                            }
                        });
                               $.ajax({
                            cache: true,
       url: ManagementServiceUrl + "GetDriverHistoryTrans/" + d.OID + "/" + userOID + "/" + sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                $scope.driverHistory = JSON.parse(result);

                                $scope.$apply();
                                //  console.log($scope.driverList)

                            }
                        });


                        $scope.e_OID = d.OID
                        $scope.e_IMEI = d.IMEINumber;

                        $scope.e_Name = d.DriverFirstName;
                        $scope.e_Mobile = d.CorporateMobileNumber;
                        $scope.e_Company = d.CompanyId;
                        $scope.e_Nationality = d.Nationality;
                        $scope.e_ID = d.Nationl_ID;
                        $scope.e_Birthdate = d.DateOfBirth;
                        $scope.e_Gender = d.GenderOID;
                        $scope.e_Governorate = d.Address_District;
                        $scope.Lookups.loadCities(d.Address_District, d.Address_City);

                        $scope.e_Make = d.Car_Make;
                        $scope.Lookups.loadModels(d.Car_Make, d.Car_Model);

                        $scope.e_Color = d.Car_Color;
                        $scope.e_Year = d.Car_Year;
                        $scope.e_SerialNo = d.Car_Serialno;
                        $scope.e_Plate = d.Car_Plateno;
                        $scope.e_Letters = d.Car_Plate_letters;
                        $scope.e_Type = d.Car_Plate_Type;
                        $scope.e_ServiceType = d.CarTypeOID;
                        $scope.e_AppEnabled = d.Show_Car_In_CutomerApp;
                        $scope.e_DataSimCard = d.DataSimCard;

                        $scope.e_ClassBefore = c.ClassName;


                        $('#EditModal').modal('toggle');
                        var DriverSetupObject = {};
                        var driverSetupObject = {


                            "OID": d.OID,
                            "CreatedBy": userOID,
                            "TokenID": sessionStorage.TokenID,
                        }

                        DriverSetupObject["driverSetupObject"] = driverSetupObject;
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "getRequestDocuments",
                            type: "POST",
                            data: JSON.stringify(DriverSetupObject),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (result) {
                                if (result.getRequestDocumentsResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                $scope.driverDocuments = JSON.parse(result.getRequestDocumentsResult);
                                //  console.log($scope.driverList)

                                $scope.loading = false;
                                $scope.$apply();
                            }
                        });

                    },
                    ShowFinancials: function () {
                        $('#EditModal').modal('toggle');
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "GetDriverBallanceDetails/" + $scope.e_OID + "/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID + "/0/0/0",
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",

                            success: function (result) {
                                if (result.GetDriverBallanceDetailsResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                //var a = result;
                                var data = JSON.parse(result.GetDriverBallanceDetailsResult);

                                $scope.List = data;
                                for (var i = 0; i < $scope.List.length; i++) {
                                    if (Math.sign($scope.List[i].Amount) == -1) {
                                        $scope.List[i].color = 'red';
                                    } else {

                                        $scope.List[i].color = 'green';
                                    }

                                   

                                }
                                $('#FinancialsModal').modal('toggle');
                                $scope.loading = false;
                                $scope.$apply();
                            }
                        });
                    },
                    AddPenalty: function () {
                        $('#EditModal').modal('toggle');
                        $('#PenaltyModal').modal('toggle');
                        $scope.e_ClassAfter = "برونزي";
                    },
                    savePenalty: function () {

                        if ($scope.e_Explenation == null || $scope.e_Explenation.length < 20) {
                            alert("يرجى ادخال السبب بشكل واضح وكامل!")
                            return;
                        }
                        if ($scope.e_Credit == null) {
                            $scope.e_Credit = 0;
                        }
                        $scope.loading = true;

                        var DriverTransObject = {};

                        // var DriverSetupObject = [];
                        var transObject = {
                            "OID": $scope.e_OID,
                            "CreatedBy": userOID,
                            "UserName": $scope.DisplayName,
                            "TokenID": sessionStorage.TokenID,
                            "explenation": $scope.e_Explenation,
                            "type": "penality",
                            "amount": Math.abs($scope.e_Credit)
                            
                        };

                        DriverTransObject["obj"] = transObject;
                        $.ajax({
                            type: "POST",
                            url: ManagementServiceUrl + "AddDriverHistoryTrans",
                            data: JSON.stringify(DriverTransObject),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (data) {
                                if (data.AddDriverHistoryTransResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                var res = JSON.parse(data.AddDriverHistoryTransResult).replace("\"", "");
                                if (res == "success") {
                                    $('#PenaltyModal').modal('toggle');


                                }
                               else {
                                    alert(res + "حدث خطأ  ")
                                }
                                $scope.loading = false;
                                $scope.$apply();
                            },
                        });
                    
                    },
                    AddPromotion: function () {
                        $('#EditModal').modal('toggle');
                        $('#PromotionModal').modal('toggle');
                        $scope.e_ClassAfter = "برونزي";
                    },
                    savePromotion: function () {
                        if ($scope.e_Explenation == null || $scope.e_Explenation.length < 20) {
                            alert("يرجى ادخال السبب بشكل واضح وكامل!")
                            return;
                        }
                        if ($scope.e_Credit == null) {
                            $scope.e_Credit = 0;
                        }
                        $scope.loading = true;

                        var DriverTransObject = {};

                        // var DriverSetupObject = [];
                        var transObject = {
                            "OID": $scope.e_OID,
                            "CreatedBy": userOID,
                            "UserName": $scope.DisplayName,
                            "TokenID": sessionStorage.TokenID,
                            "explenation": $scope.e_Explenation,
                            "type": "promotion",
                            "amount": Math.abs($scope.e_Credit)

                        };

                        DriverTransObject["obj"] = transObject;
                        $.ajax({
                            type: "POST",
                            url: ManagementServiceUrl + "AddDriverHistoryTrans",
                            data: JSON.stringify(DriverTransObject),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (data) {
                                if (data.AddDriverHistoryTransResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                var res = JSON.parse(data.AddDriverHistoryTransResult).replace("\"", "");
                                if (res == "success") {
                                    $('#PromotionModal').modal('toggle');
                                } else {
                                    alert(res)
                                } 
                                $scope.loading = false;
                                $scope.$apply();
                            },
                        });

                    },
                    AddNote: function () {
                        $('#EditModal').modal('toggle');
                        $('#NoteModal').modal('toggle');
                        $scope.e_ClassAfter = "برونزي";
                    },
                    saveNote: function () {
                        if ($scope.e_Explenation == null || $scope.e_Explenation.length < 20) {
                            alert("يرجى ادخال السبب بشكل واضح وكامل!")
                            return;
                        }
                        if ($scope.e_Credit == null) {
                            $scope.e_Credit = 0;
                        }
                        $scope.loading = true;

                        var DriverTransObject = {};

                        // var DriverSetupObject = [];
                        var transObject = {
                            "OID": $scope.e_OID,
                            "CreatedBy": userOID,
                            "UserName": $scope.DisplayName,
                            "TokenID": sessionStorage.TokenID,
                            "explenation": $scope.e_Explenation,
                            "type": "note",
                            "amount": Math.abs($scope.e_Credit)

                        };

                        DriverTransObject["obj"] = transObject;
                        $.ajax({
                            type: "POST",
                            url: ManagementServiceUrl + "AddDriverHistoryTrans",
                            data: JSON.stringify(DriverTransObject),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (data) {
                                if (data.AddDriverHistoryTransResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                var res = JSON.parse(data.AddDriverHistoryTransResult).replace("\"", "");
                                if (res == "success") {
                                    $('#NoteModal').modal('toggle');
                                } else {
                                    alert(res)
                                }
                                $scope.loading = false;
                                $scope.$apply();
                            },
                        });
                    },
                    BanDriver: function () {
                        $('#EditModal').modal('toggle');
                        $('#BanModal').modal('toggle');
                        $scope.e_ClassAfter = "برونزي";
                    },
                    saveBan: function () {
                        if ($scope.e_Explenation == null || $scope.e_Explenation.length < 20) {
                            alert("يرجى ادخال السبب بشكل واضح وكامل!")
                            return;
                        }
                        if ($scope.e_Credit == null) {
                            $scope.e_Credit = 0;
                        }
                        $scope.loading = true;

                        var DriverTransObject = {};

                        // var DriverSetupObject = [];
                        var transObject = {
                            "OID": $scope.e_OID,
                            "CreatedBy": userOID,
                            "UserName": $scope.DisplayName,
                            "TokenID": sessionStorage.TokenID,
                            "explenation": $scope.e_Explenation,
                            "type": "ban",
                            "amount": Math.abs($scope.e_Credit)

                        };

                        DriverTransObject["obj"] = transObject;
                        $.ajax({
                            type: "POST",
                            url: ManagementServiceUrl + "AddDriverHistoryTrans",
                            data: JSON.stringify(DriverTransObject),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (data) {
                                if (data.AddDriverHistoryTransResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                var res = JSON.parse(data.AddDriverHistoryTransResult).replace("\"", "");
                                if (res == "success") {
                                    $('#BanModal').modal('toggle');
                                } else {
                                    alert(res)
                                }
                                $scope.loading = false;
                                $scope.$apply();
                            },
                        });
                    },
                    UnbanDriver: function () {
                        $('#EditModal').modal('toggle');
                        $('#UnbanModal').modal('toggle');
                        $scope.e_ClassAfter = "برونزي";
                    },
                    saveUnban: function () {
                        if ($scope.e_Explenation == null || $scope.e_Explenation.length < 20) {
                            alert("يرجى ادخال السبب بشكل واضح وكامل!")
                            return;
                        }
                        if ($scope.e_Credit == null) {
                            $scope.e_Credit = 0;
                        }
                        $scope.loading = true;

                        var DriverTransObject = {};

                        // var DriverSetupObject = [];
                        var transObject = {
                            "OID": $scope.e_OID,
                            "CreatedBy": userOID,
                            "UserName": $scope.DisplayName,
                            "TokenID": sessionStorage.TokenID,
                            "explenation": $scope.e_Explenation,
                            "type": "unban",
                            "amount": Math.abs($scope.e_Credit)

                        };

                        DriverTransObject["obj"] = transObject;
                        $.ajax({
                            type: "POST",
                            url: ManagementServiceUrl + "AddDriverHistoryTrans",
                            data: JSON.stringify(DriverTransObject),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (data) {
                                if (data.AddDriverHistoryTransResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                var res = JSON.parse(data.AddDriverHistoryTransResult).replace("\"", "");
                                if (res == "success") {
                                    $('#UnbanModal').modal('toggle');
                                } else {
                                    alert(res)
                                }
                                $scope.loading = false;
                                $scope.$apply();
                            },
                        });
                    },
                    saveEdits: function () {
                        if (this.validateInputs()) {
                            $scope.loading = true;
                            var DriverSetupObject = {};

                            // var DriverSetupObject = [];
                            var registerObject = {
                                "OID": $scope.e_OID,
                                "company": $scope.e_Company,
                                "CreatedBy": userOID,
                                "TokenID": sessionStorage.TokenID,
                                "imei": $scope.e_IMEI,

                                "name": $scope.e_Name,
                                "mobile": $scope.e_Mobile,
                                "ID": $scope.e_ID,

                                "nationality": $scope.e_Nationality,
                                "dateofbirth": $scope.e_Birthdate,
                                "gender": $scope.e_Gender,
                                "district": $scope.e_Governorate,
                                "city": $scope.e_City,

                                "serialno": $scope.e_SerialNo,
                                "plate": $scope.e_Plate,
                                "letters": $scope.e_Letters,
                                "type": $scope.e_Type,
                                "make": $scope.e_Make,
                                "model": $scope.e_Model,
                                "color": $scope.e_Color,
                                "year": $scope.e_Year,
                                "service_type": $scope.e_ServiceType,
                                "app_enabled": $scope.e_AppEnabled,
                                "dataSimCard": $scope.e_DataSimCard
                            };

                            DriverSetupObject["obj"] = registerObject;
                            $.ajax({
                                type: "POST",
                                url: ManagementServiceUrl + "UpdateDriver",
                                data: JSON.stringify(DriverSetupObject),
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                processData: true,
                                success: function (data) {
                                    if (data.UpdateDriverResult == "access_denied") {
                                        window.parent.location.href = "../../Access.html";
                                        return;
                                    }
                                    var res = JSON.parse(data.UpdateDriverResult).replace("\"", "");
                                    if (res == "success") {
                                        $('#EditModal').modal('toggle');
                                        $scope.Drivers.get($scope.Company);

                                    }
                                    else if (res == "err_mobile") {
                                        alert("خطأ، رقم الهاتف مستخدم من قبل لكابتن اخر");
                                    }
                                    else if (res == "err_id") {
                                        alert("خطأ، رقم الهوية مسجل لكابتن اخر");
                                    }
                                    else if (res == "err_plate") {
                                        alert("خطأ، رقم اللوحة المعدنية مسجل لكابتن اخر");
                                    }
                                    else if (res == "err_serialno") {
                                        alert("خطا، الرقم المتسلسل مسجل لكابتن اخر");
                                    }
                                    else if (res == "err_emei") {
                                        alert("خطأ، رقم الجهاز مسجل لكابتن اخر");
                                    }
                                    else if (res == "saved_not_enabled") {
                                        alert("تم حفظ البيانات ولكن لم يتم تفعيل التطبيق بسبب عدم استكمال التسجيل على منصة هيئة النقل");
                                        $('#EditModal').modal('toggle');
                                        $scope.Drivers.get(companyOID);
                                    }else {
                                        alert(res + "حدث خطأ  ")
                                    }
                                    $scope.loading = false;
                                    $scope.$apply();
                                },
                            });
                        }


                    },
                    validateInputs: function () {

                        if ($scope.e_Name == undefined || $scope.e_Name == "") {
                            alert("يرجى ادخال اسم السائق");
                            return false;
                        } else if ($scope.e_Mobile == undefined || $scope.e_Mobile == "") {
                            alert("يرجى ادخال رقم الهاتف");
                            return false;
                        } else if ( $scope.e_Mobile.length <10) {
                            alert("رقم الهاتف غير صحيح");
                            return false;
                        }else if ($scope.e_ID == undefined || $scope.e_ID == "") {
                            alert("يرجى ادخال رقم الهوية");
                            return false;
                        } else if ($scope.e_ID.length < 9) {
                            alert("رقم الهوية غير صحيح ");
                            return false;
                        }else if ($scope.e_Nationality == undefined || $scope.e_Nationality == "") {
                            alert("يرجى تحديد الجنسية");
                            return false;
                        } else if ($scope.e_Gender == undefined || $scope.e_Gender == "") {
                            alert("يرجى تحديد الجنس");
                            return false;
                        }
                        else if ($scope.e_Birthdate == undefined || $scope.e_Birthdate == "") {
                            alert("يرجى ادخال تاريخ الميلاد");
                            return false;
                        }
                        else if ($scope.e_Governorate == undefined || $scope.e_Governorate == "") {
                            alert("يرجى تحديد المحافظة");
                            return false;
                        }
                        else if ($scope.e_City == undefined || $scope.e_City == "") {
                            alert("يرجى تحديد المدينة");
                            return false;
                        } 
                        else if ($scope.e_Plate == undefined || $scope.e_Plate == "") {
                            alert("يرجى ادخال رقم اللوحة المعدنية");
                            return false;
                        } /*else if ($scope.e_Letters == undefined || $scope.e_Letters == "") {
                            alert("يرجى ادخال ترميز اللوحة");
                            return false;
                        } else if ($scope.e_Letters.length < 2) {
                            alert("يجب ادخال الترميز المكون من خانتين ");
                            return false;
                        }*/
                        else if ($scope.e_Make == undefined || $scope.e_Make == "") {
                            alert("يرجى تحديد نوع المركبة");
                            return false;
                        } else if ($scope.e_Model == undefined || $scope.e_Model == "") {
                            alert("يرجى تحديد طراز المركبة");
                            return false;
                        } else if ($scope.e_Color == undefined || $scope.e_Color == "") {
                            alert("يرجى تحديد لون المركبة");
                            return false;
                        } else if ($scope.e_Year == undefined || $scope.e_Year == "") {
                            alert("يرجى تحديد سنة انتاج المركبة");
                            return false;
                        } else if ($scope.e_Type == undefined || $scope.e_Type == "") {
                            alert("يرجى تحديد نوع رخصة المركبة");
                            return false;
                        }else if ($scope.e_ServiceType == undefined || $scope.e_ServiceType == "") {
                           alert("يرجى تحديد نوع الخدمة");
                           return false;
                        } else if ($scope.e_IMEI == undefined || $scope.e_IMEI == "") {
                           alert("يرجى تحديد رقم الجهاز المستخدم");
                           return false;
                        } else if ($scope.e_Company == undefined || $scope.e_Company == "") {
                           alert("يرجى تحديد المكتب");
                           return false;
                       }
                        return true;
                    },
                    ViewWslDtls: function (driver) {
                        $scope.waslDriverEligibility = driver.Wasl_DriverEligibility;
                        $scope.waslEligibilityExpiryDate = driver.Wasl_Eligibility_ExpiryDate;
                        $scope.WaslDriverRejectionReason = driver.Wasl_DriverRejection_Reasons;
                        $scope.WaslCriminalRecordCheck = driver.Wasl_CriminalRecordStatus;
                        $scope.WaslVehicleEligibility = driver.Wasl_VehicleEligibility;
                        $scope.WaslVehicleRejectionReason = driver.Wasl_VehicleRejectionReasons;

                        $('#ViewModal').modal('toggle');


                    }


            },

                
                    $scope.Lookups.load();

               Drivers = $scope.Drivers;
               $scope.SelectCompany = function (compOid) {
                    $scope.Drivers.get(compOid)
                    $scope.Company = compOid
                    company = compOid;
                    sessionStorage.SelectedCompany = compOid;
                }
                $scope.Drivers.get(companyOID)
               
                $scope.Company = companyOID
                company = companyOID;
                sessionStorage.SelectedCompany = companyOID;
                // initial image index
                $scope._Index = 0;
                // if a current image is the same as requested image
                $scope.isActive = function (index) {
                    return $scope._Index === index;
                };
                // show prev image
                $scope.showPrev = function () {
                    $scope._Index = ($scope._Index > 0) ? --$scope._Index : $scope.driverDocuments.length - 1;
                };
                // show next image
                $scope.showNext = function () {
                    $scope._Index = ($scope._Index < $scope.driverDocuments.length - 1) ? ++$scope._Index : 0;
                };
                // show a certain image
                $scope.showPhoto = function (index) {
                    $scope._Index = index;
                };
                $scope.removeDriver = function () {

                 
                    var DriverSetupObject = {};

                    // var DriverSetupObject = [];
                    var driverSetupObject = {
                        "CompanyId": $scope.removeCompanyId,
                        "ModifiedBy": sessionStorage.UserOID,
                        "DriverOID": $scope.removeDriverOID,
                        "TokenID": sessionStorage.TokenID,

                        
                    };
                    DriverSetupObject["driverSetupObject"] = driverSetupObject;
                    $.ajax({
                        type: "POST",
                        url: ManagementServiceUrl + "RemoveDriver",
                        data: JSON.stringify(DriverSetupObject),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        processData: true,
                        success: function (data) {

                            if (data.RemoveDriverResult == "access_denied") {
                                window.parent.location.href = "../../Access.html";
                                return;
                            }
                            var res = JSON.parse(data.RemoveDriverResult);
                            res = parseInt(res)
                            if (res > 0) {
                                $('#DeleteDriver').modal('toggle');
                                $scope.Drivers.get($scope.Company)

                            } else if (res == -2) {
                                alert("يوجد رصيد للسائق")

                            } else if (res == -1) {
                                alert("السائق غير موجود")

                            }
                            else {
                                alert("حدث خطأ")
                            }


                        }
                    });



                }


            }
        }
    }]);



