
var TaxiApp = angular.module('Enterprises', ['ngStorage', 'ngDialog', 'ui.bootstrap'])
 

TaxiApp.controller('EnterprisesCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'EditEnterprise', 'AddEnterprise', 'GetAdmins',

    function ($scope, $http, $sessionStorage, ngDialog, EditEnterprise, AddEnterprise, GetAdmins) {
        Localization(sessionStorage.selectedLanguage, 'allreport', $scope, sessionStorage);
      
        $scope.selectInstitution = function () {
            // console.log($scope.selectedInstitution);
            SelectedEnterprise = $scope.selectedInstitution.BookingStatus;

        }
        $scope.VehicleCurrentLocation = [];
      
        $scope.loading = false;
        if (sessionStorage.length == (undefined || 0)) {
            window.parent.location.href = "../../Index.html";
        }
        else {
            $scope.Role = sessionStorage.RoleType;

            if (sessionStorage.RoleType == "Organization Admin") {
                $('.tele').show();
            }
            else {
                $('.tele').hide();
            }

            $scope.Role = sessionStorage.RoleType;

            $scope.User = sessionStorage.Username;

            selectedCompany = 'undefined';
            if (sessionStorage.CompanyOID != undefined || sessionStorage.ORGOID != undefined) {
                loadDropDownFromAppConfig("COMPANY", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, 0, $scope);
            }
           
            

            function onlyLettersAndNumbers(str) {
                return /^[A-Za-z0-9]*$/.test(str);
            }

            function containsNumbers(str) {
                return /\d/.test(str);
            }

            function hasBothLettersAndNumbers(str) {
                var numeric_alpha = /^(?=.*[a-zA-Z])(?=.*[0-9])/;

                return str.match(numeric_alpha);
            }
         
            function GetAllEnterprises() {
            
                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "GetEnterpriseCustomers/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID ,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        //var a = result;
                        $scope.loading = false;
                       
                            var data = JSON.parse(result.GetEnterpriseCustomersResult);

                            for (var i = 0 ; i < data.length; i++) {





                            }

                            $scope.List = data;
                            $scope.$apply();
                        }
                 
                });

            }
            GetAllEnterprises();

            $scope.Enterprise = {
                resetPassword: function (obj) {
                    $scope.e_Password = '';
                    $scope.e_ConfirmPassword = '';
                    $scope.e_EnterpriseTelephone = obj.EnterpriseTelephone;
                    $('#ResetPassword').modal('toggle');


                },
                savePassword: function (obj) {
                    if ($scope.e_Password == '') {
                        alert('يجب ادخال كلمة المرور!');
                        return;
                    }

                    if ($scope.e_Password.length < 5 || !hasBothLettersAndNumbers($scope.e_Password)) {
                        alert('كلمة المرور يجب ان تكون 5 احرف على الاقل ويجي ان تحتوي احرف وارقام!');
                        return;
                    }

                    if ($scope.e_Password != $scope.e_ConfirmPassword) {
                        alert('كلمة المرور وتاكيد كلمة المرور غير متطابقة!');
                        return;
                    }

                    $.ajax({
                        cache: true,
                        url: ManagementServiceUrl + "ResetUserPassword/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID + "/" + $scope.e_EnterpriseTelephone + "/" + md5($scope.e_Password),
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",

                        success: function (result) {
                            //var a = result;
                            $scope.loading = false;

                            var data = JSON.parse(result.ResetUserPasswordResult);

                            if (data == "success") { alert('تم تعيين كلمة المرور') }
                            else if (data == "notfound") { alert('المستخدم غير موجود') }
                            else (alert('حدث خطأ'))

                            $scope.List = data;
                            $scope.$apply();
                        }

                    });

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


                },
            edit: function (obj) {
                ngDialog.open({
                    windowClass: 'EditEnterprise',
                    templateUrl: 'EditEnterprise.html',
                    controller: 'EditEnterpriseCtrl',
                    resolve: {
                        obj: function () {  return obj; }
                         }


                });
            },
            add: function () {

                ngDialog.open({
                    windowClass: 'AddEnterprise',
                    templateUrl: 'AddEnterprise.html',
                    controller: 'AddEnterpriseCtrl',
                    resolve: {
                      
                    }


                });

              }

            }
            $scope.adminstrartors = {
                getList: function (EnterpriseId) {

                    ngDialog.open({
                        windowClass: 'GetAdmins',
                        templateUrl: 'GetAdmins.html',
                        controller: 'GetAdminsCtrl',
                        resolve: {
                            EnterpriseId: function () { return EnterpriseId; }
                        
                        }


                    });

                }


            }
            
        }
    
    }])


TaxiApp.service('EditEnterprise', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (idd) {
        var modalInstance = $modal.open({
            windowClass: 'EditEnterprise',
            templateUrl: 'EditEnterprise.html',
            controller: 'EditEnterpriseCtrl',


        });

    };



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

    $scope.eName = obj.EnterpriseName;
    $scope.eEmail = obj.EnterpriseEmail;
    $scope.eTelephone = obj.EnterpriseTelephone;
    $scope.eContactPerson = obj.ContactPerson;
    $scope.eActivationCode = obj.ActivationCode;




    $scope.ClickClose = function () {

        // $modalInstance.dismiss('Cancel');

        $(".ngdialog-close").trigger("click");

    }
    //  console.log(obj);
    $scope.EditItem = function () {
      
       
        if ($scope.eName != undefined && $scope.eEmail != undefined && $scope.eTelephone != undefined && $scope.eContactPerson != undefined &&

          $scope.eActivationCode != undefined) {




            var eCustomer = {}




            var EnterpriseCustomersObject = {
                eCustomer: {
                    'EnterpriseCustomerId': obj.EnterpriseCustomerId,
                    'EnterpriseName': $scope.eName,
                    'EnterpriseEmail': $scope.eEmail,
                    'EnterpriseTelephone': $scope.eTelephone,
                    'ContactPerson': $scope.eContactPerson,
                    'ActivationCode': $scope.eActivationCode,
                    'CreatedBy': sessionStorage.UserOID,
                    'TokenID': sessionStorage.TokenID,

                }
            }


            $.ajax({
                type: "POST",
                url: ManagementServiceUrl + "ModifeyEnterpriseCustomers",
                data: JSON.stringify(EnterpriseCustomersObject),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data) {
                    // $scope.clear();   
                    alert("تم تعديل  المؤسسة بنجاح");
                    $scope.ClickClose();
                   
                    $scope.loading = false;
                    $scope.$apply();
                },
                error: function (a, b, c) { console.log(a); }

            });

            
        
        }else {
            alert("ارجاء التاكد من تعبئة جميع الحقول ")
        }

    }





})
// Add Promotion Code


TaxiApp.service('AddEnterprise', function ($modal) {
    var service = {};
    var self = this;
    service.open = function () {
        var modalInstance = $modal.open({
            windowClass: 'AddEnterprise',
            templateUrl: 'AddEnterprise.html',
            controller: 'AddEnterpriseCtrl',


        });

    };



    return service;
})
TaxiApp.controller('AddEnterpriseCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window) {
    $scope.aName = "";
    $scope.aEmail = "";
    $scope.aTelephone = "";
    $scope.aContactPerson = "";
    $scope.aActivationCode = "";
    //$scope.checkboxModel.value1 = "N";




    $scope.ClickClose = function () {

        // $modalInstance.dismiss('Cancel');

        $(".ngdialog-close").trigger("click");

    }
    //  console.log(obj);
    $scope.AddItem = function () {

        if ($scope.aName != "" && $scope.aEmail != "" && $scope.aTelephone != "" && $scope.aContactPerson != "" &&

           $scope.aActivationCode != "") {

           
          

            var eCustomer = {}

            //console.log($scope.checkboxModel);


            var EnterpriseCustomersObject = {
                 eCustomer: {
                 
                    'EnterpriseName': $scope.aName,
                    'EnterpriseEmail': $scope.aEmail,
                    'EnterpriseTelephone': $scope.aTelephone,
                    'ContactPerson': $scope.aContactPerson,
                    'ActivationCode': $scope.aActivationCode,
                    'CreatedBy': sessionStorage.UserOID,
                    'TokenID': sessionStorage.TokenID,

                
                }
            }

            $.ajax({
                type: "POST",
                url: ManagementServiceUrl + "AddEnterpriseCustomers",
                data: JSON.stringify(EnterpriseCustomersObject),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data) {
                    // $scope.clear();   
                    alert("تم اضافة  المؤسسة بنجاح");
                    $scope.ClickClose();
                   
                    $scope.loading = false;
                    $scope.$apply();
                },
                error: function (a, b, c) { console.log(a); }

            });



        } else {
            alert("ارجاء التاكد من تعبئة جميع الحقول ")
        }

    }





})
// Get Admins


TaxiApp.service('GetAdmins', function ($modal) {
    var service = {};
    var self = this;
    service.open = function () {
        var modalInstance = $modal.open({
            windowClass: 'GetAdmins',
            templateUrl: 'GetAdmins.html',
            controller: 'GetAdminsCtrl',


        });

    };



    return service;
})


TaxiApp.controller('GetAdminsCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window,EnterpriseId) {
  



    $scope.ClickClose = function () {

        // $modalInstance.dismiss('Cancel');

        $(".ngdialog-close").trigger("click");

    }
  


    function GetAllEnterpriseAdmins() {

        $.ajax({
            cache: true,
            url: ManagementServiceUrl + "GetEnterpriseAdmin/" + EnterpriseId +"/"+ sessionStorage.UserOID + "/" + sessionStorage.TokenID,
            type: "GET",
            contentType: "application/javascript",
            dataType: "jsonp",

            success: function (result) {
                //var a = result;
                $scope.loading = false;

                var data = JSON.parse(result.GetEnterpriseAdminResult);

                for (var i = 0 ; i < data.length; i++) {





                }

                $scope.adminList = data;
                $scope.$apply();
            }

        });

    }
    $scope.delete = function () {
        var unassign = 1;

        $scope.confirmAdmin();
    }
    GetAllEnterpriseAdmins();
    $scope.AssignAdmin = function () {

        $(".ToBeHidden").fadeIn(500);
        $scope.confirmAdmin = function (d) {

            if(d=="r"){
                EnterpriseId=0;
            }
            if ($scope.AdminMobileNo != undefined) {
             

                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "AssgineEnterpriseAdmin/" + $scope.AdminMobileNo + "/" + EnterpriseId+"/"+ sessionStorage.UserOID + "/" + sessionStorage.TokenID ,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        //var a = result;
                        $scope.loading = false;

                        var data = JSON.parse(result.AssgineEnterpriseAdminResult);
                        if (data == "-1") {
                          alert("الرقم مسجل مسبقا ..ادخل رقم اخر");

                        } else if (data == "0") {
                            alert("رقم المستخدم غير موجود ");


                        } else if (data == "1") {



                            alert("لقد تم تعيين الرقم بنجاح ");
                            $scope.ClickClose();

                        } else if (data == "2") {

                        }
                        $scope.adminList = data;
                        $scope.$apply();
                    }

                });

            } else {
            alert("الرجاء ادخال رقم الهاتف")}


        }


    }
})
