var GetCustomers, LoadDrivers, Export, ForsanRocab;

var TaxiApp = angular.module('CreditDetails', ['ngStorage', 'ngDialog', 'ui.bootstrap'])
  function splitT(date) {

      var str = date.split("T");
      return str[0];
        }
  function splitDate(date) {

      var str = date.split("T");
      return str;
  }

var company
TaxiApp.controller('CreditDetailsCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'deductDriverBalance', 'addDriverBalance', 'deductCustomerBalance', 'addCustomerBalance', 'DriverBallanceDetails', 'CustomerBallanceDetails', 'AddNewFaresRocab', 'CustomerDetails',

    function ($scope, $http, $sessionStorage, ngDialog, deductDriverBalance, addDriverBalance, deductCustomerBalance, addCustomerBalance, DriverBallanceDetails, CustomerBallanceDetails,  AddNewFaresRocab, CustomerDetails) {


        Localization(sessionStorage.selectedLanguage, 'allreport', $scope, sessionStorage);
      
        $scope.selectInstitution = function () {
          
            SelectedEnterprise = $scope.selectedInstitution.BookingStatus;

        }
        loadContents(sessionStorage.ORGOID, sessionStorage.CompanyOID, sessionStorage.UserOID, 'DT', $scope);

        $scope.VehicleCurrentLocation = [];
        $scope.DealerList = "0";
        $scope.BlockList = "0";
        $scope.ChooseDateType = "0";
        $scope.loading = false;
        $scope.DisplayName = sessionStorage.UserName;       
        $scope.CompanyName = sessionStorage.value;
        if (sessionStorage.OrderId < 3) {
            window.location.href = "../../Access.html";
        }
        if (sessionStorage.length == (undefined || 0)) {
            window.parent.location.href = "../../Index.html";
        }
        else {
            $scope.Role = sessionStorage.RoleType;
          
            if (sessionStorage.OrderId > 2) {
                $('.tele').show();
            }
            else {
                $('.tele').hide();
            }
            var filteredList = [];
            $scope.Role = sessionStorage.RoleType;

            $scope.User = sessionStorage.Username;
        
            selectedCompany = 'undefined';
            selectedDistrict = 0;
            if (sessionStorage.CompanyOID != undefined || sessionStorage.ORGOID != undefined) {
                loadDropDownFromAppConfig("COMPANY", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, 0, $scope);
            }
            var now = new Date();

            var day = ("0" + now.getDate()).slice(-2);
            var month = ("0" + (now.getMonth() + 1)).slice(-2);

            var today = now.getFullYear() + "-" + (month) + "-" + (day);

            $scope.FromDate=formatDateToView(today);
            $scope.ToDate = formatDateToView(today);
         
            function formatDateToView(date) {


                var dateParts = date.split(" ");

                if (dateParts.length > 0) {

                    var yafa = dateParts[0].split("-");

                    var newDate = yafa[1] + "-" + yafa[2] + "-" + yafa[0]

                    var date = new Date(newDate);

                    var year = date.getFullYear();
                    var month = ("0" + (date.getMonth() + 1)).slice(-2);
                    var day = ("0" + date.getDate()).slice(-2);

                

                    return new Date(month + "/" + day + "/" + year);

                }


            }

            $scope.CustomersBalanceList = "";
            //-------------------------------------------------- panels 
            $("#DriversListBTN").click(function () {
                if ($(".DriversListPanel").css("display") == "none") {
                    $(".DriversListPanel").css("display", "block");
                    $(".CustomersListPanel").toggle();
                }

            })
            $("#CustomersListBTN").click(function () {
                if ($(".CustomersListPanel").css("display") == "none") {
                    $(".CustomersListPanel").css("display", "block");
                    $(".DriversListPanel").toggle();
                }
            })
            //-------------------------------------------------- Driver
        
            var totalD = 0;
          
            $scope.calculateTotalDrivers = function (filteredList) {
                if (filteredList != undefined) {
                    totalD = 0;
                    for (var i = 0; i < filteredList.length; i++) {
                        totalD += filteredList[i].Driver_Wallet_Balance


                    }
                    return Math.round(totalD * 100) / 100;
                }
            }
            var totalC = 0;
            $scope.calculateTotalCustomers = function (filteredList) {
                if (filteredList != undefined) {
                    totalC = 0;
                    for (var i = 0; i < filteredList.length; i++) {
                        totalC += filteredList[i].Main_Balance


                    }
                    return Math.round(totalC * 100) / 100;
                }
            }
            $scope.selectCompanydetails = function (obj) {
                sessionStorage.CompanyOID = obj.OID;
                sessionStorage.value = obj.Value;
                window.location.href = "Management.html";
            }

         
            $scope.EditDriverItemClass =  {
                deduct: function (obj) {
                    //EditItem.open(id, status, price, isDept);

                    ngDialog.open({
                        template: 'deductDriverBalance.html',
                        className: 'ngdialog-theme-default dialogforpopup CustomerBalance',
                        controller: 'deductDriverBalanceCtrl',
                        resolve: {
                            obj: function () {
                                return obj;
                            }
                          
                        }


                    });

                },
                add: function (obj) {
              
                    //EditItem.open(id, status, price, isDept);

                    ngDialog.open({
                        template: 'addDriverBalance.html',
                        className: 'ngdialog-theme-default dialogforpopup CustomerBalance',
                        controller: 'addDriverBalanceCtrl',
                        resolve: {
                            obj: function () {
                                return obj;
                            }
                          
                        }


                    })
                }
            }
            $scope.EditCustomerItemClass = {
                deduct: function (obj) {
                    //EditItem.open(id, status, price, isDept);

                    ngDialog.open({
                        template: 'deductCustomerBalance.html',
                        className: ' ngdialog-theme-default dialogforpopup CustomerBalance',
                        controller: 'deductCustomerBalanceCtrl',
                        resolve: {
                            obj: function () {
                                return obj;
                            }

                        }


                    });

                },
                add: function (obj) {

                    //EditItem.open(id, status, price, isDept);

                    ngDialog.open({
                        template: 'addCustomerBalance.html',
                        className: ' ngdialog-theme-default dialogforpopup CustomerBalance',
                        controller: 'addCustomerBalanceCtrl',
                        resolve: {
                            obj: function () {
                                return obj;
                            }

                        }


                    })
                }
            }
            $scope.UpdateBlock = {


                block: function (obj) {
                   
                    $.ajax({
                        cache: true,
                        url: ManagementServiceUrl + "UpdateCustomerApplicationBlockStatus/" + obj.OID + "/" + obj.MobileNo + "/" +"1/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID, //sessionStorage.CompanyOID,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",

                        success: function (result) {
                            if (result.UpdateCustomerApplicationBlockStatusResult == "access_denied") {
                                window.parent.location.href = "../../Access.html";
                                return;
                            }
                            data = JSON.parse(result.UpdateCustomerApplicationBlockStatusResult);
                           
                         
                            var no = $("#no").val();
                            var name = $("#name").val();


                            if (no == "") { no = 0 }
                            if (name == "") { name = 0 }



                            GetCustomers.get(no, name);
                            $scope.loading = false;
                            $scope.$apply();

                            
                        },
                        error: function () {
                            $scope.loading = false;
                            $scope.BookingList = [];
                            $scope.$apply();
                        }
                    });
                },
                disblock: function (obj) {
                    $.ajax({
                        cache: true,
                        url: ManagementServiceUrl + "UpdateCustomerApplicationBlockStatus/" + obj.OID + "/" + obj.MobileNo + "/" + "0/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID, //sessionStorage.CompanyOID,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",

                        success: function (result) {
                            if (result.UpdateCustomerApplicationBlockStatusResult == "access_denied") {
                                window.parent.location.href = "../../Access.html";
                                return;
                            }
                            data = JSON.parse(result.UpdateCustomerApplicationBlockStatusResult);
                           
                            var no = $("#no").val();
                            var name = $("#name").val();


                            if (no == "") { no = 0 }
                            if (name == "") { name = 0 }



                            GetCustomers.get(no, name);
                            $scope.loading = false;
                            $scope.$apply();


                        },
                        error: function () {
                            $scope.loading = false;
                         
                            $scope.$apply();
                        }
                    });

                }
            }

            $scope.UpdateDealer = {


                deal: function (obj) {

                    $.ajax({
                        cache: true,
                        url: ManagementServiceUrl + "UpdateCustomerDealer/" + obj.OID + "/" + obj.MobileNo + "/" + "1"+"/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID, //sessionStorage.CompanyOID,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",

                        success: function (result) {
                            if (result.UpdateCustomerDealerResult == "access_denied") {
                                window.parent.location.href = "../../Access.html";
                                return;
                            }
                            data = JSON.parse(result.UpdateCustomerDealerResult);
                            var no = $("#no").val();
                            var name = $("#name").val();


                            if (no == "") { no = 0 }
                            if (name == "") { name = 0 }



                            GetCustomers.get(no, name);


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


                        },
                        error: function () {
                            $scope.loading = false;
                            $scope.BookingList = [];
                            $scope.$apply();
                        }
                    });
                },
                disdealer: function (obj) {
                    $.ajax({
                        cache: true,
                        url: ManagementServiceUrl + "UpdateCustomerDealer/" + obj.OID + "/" + obj.MobileNo + "/" + "0"+"/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID, //sessionStorage.CompanyOID,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",

                        success: function (result) {
                            if (result.UpdateCustomerDealerResult == "access_denied") {
                                window.parent.location.href = "../../Access.html";
                                return;
                            }
                            data = JSON.parse(result.UpdateCustomerDealerResult);
                            var no = $("#no").val();
                            var name = $("#name").val();


                            if (no == "") { no = 0 }
                            if (name == "") { name = 0 }



                            GetCustomers.get(no, name);

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


                        },
                        error: function () {
                            $scope.loading = false;

                            $scope.$apply();
                        }
                    });

                }
            }
            $scope.SelectedDistrict = function (districtOid) {
                DistrictName = $.grep($scope.DistrictList, function (item) {
                    selectedDistrict = districtOid;
                    return item.OID == districtOid;
                })[0].value;
            }
            $scope.SelectCompany = function (compOid) {
                var id;
                if (compOid == undefined || compOid == "") {

                    id = 0;
                } else {
                    id = compOid
                }

                LoadDrivers.get(id);
                $scope.OIDCompany = compOid;
                company = compOid
            }
          
            $scope.CustomerBooking = {
                get: function (indx) {
                    //  SelectedCompanyID= $("#SelectedCompanyID").val();
                    $('#customerModel').modal('toggle');
               
                    GetCustomerBookings.get(data[indx].OID);


                }
            }

            var GetCustomerBookings = {
                get: function (OID) {

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

                        success: function (result) {
                            if (result.GetAllBookingsForCustomerResult == "access_denied") {
                                window.parent.location.href = "../../Access.html";
                                return;
                            }
                            Cbookings = JSON.parse(result.GetAllBookingsForCustomerResult);
                            $scope.loading = false;
                            for (var i = 0; i < Cbookings.length; i++) {
                                var str = Cbookings[i].Book_DateTime;

                                var DateTime = str.split("T")
                                //= new Date(Date.parse(data[i].Book_DateTime));
                               
                                Cbookings[i].date = DateTime[0];
                                Cbookings[i].time = DateTime[1].substring(0, 5);
                                //Cbookings[i].PickUpTime = date.getHours().pad() + ":" + date.getMinutes().pad() + "/ " + date.getDay().pad() + "/ " + date.getMonth().pad() + "/ " + date.getYear().pad();
                               
                                switch (Cbookings[i].BookingStatus) {
                                    case "B":
                                        if (Cbookings[i].Trip_Start_DateTime == null) {
                                            Cbookings[i].BookingStatusDesc = "بانتظار استلام السائق";
                                            Cbookings[i].color = "#d0d0f4";
                                            Cbookings[i].colorFont = "#333";

                                        } else {
                                            Cbookings[i].BookingStatus = "في الانتظار";
                                            Cbookings[i].BookingStatusDesc = "في الانتظار";

                                            Cbookings[i].color = "#fff";
                                            Cbookings[i].colorFont = "#333";

                                        }
                                        break;
                                    case "A":
                                        if (Cbookings[i].Trip_Start_DateTime == null) {
                                            Cbookings[i].BookingStatusDesc = "باتجاه الزبون";
                                            Cbookings[i].color = "#C27ECE";
                                            Cbookings[i].colorFont = "#333";

                                        } else {
                                            Cbookings[i].BookingStatusDesc = "قيد التوصيل";
                                            Cbookings[i].color = "#E56D54";
                                            Cbookings[i].colorFont = "#333";

                                        }

                                        break;
                                    case "C":

                                        if (Cbookings[i].CustomerReason != null) {
                                            if (Cbookings[i].CustomerReason == "Mind Change" || Cbookings[i].CustomerReason == "timeout") {
                                                Cbookings[i].BookingStatusDesc = "لم يتم الرد";
                                                Cbookings[i].color = "#f2f2f2";
                                                Cbookings[i].colorFont = "#333";
                                            }
                                            else {

                                                Cbookings[i].color = "#80b4e1";
                                                Cbookings[i].colorFont = "#333";
                                                Cbookings[i].BookingStatusDesc = Cbookings[i].CustomerReason;
                                                Cbookings[i].BookingStatusDesc = Cbookings[i].CustomerReason;

                                                if (Cbookings[i].CustomerReason == "canceled_before_accept") {

                                                    Cbookings[i].BookingStatusDesc = "الغي قبل القبول";
                                                }


                                            }


                                        } else if (Cbookings[i].DriverReason != null) {
                                            if (Cbookings[i].DriverReason == "Cancel By Driver") {
                                                Cbookings[i].BookingStatusDesc = " ملغي من السائق";
                                                Cbookings[i].color = "#80b4e1";
                                                Cbookings[i].colorFont = "#333";

                                            }

                                        }



                                        break;
                                    case "E":
                                        Cbookings[i].BookingStatusDesc = "مكتمل";
                                        // data[i].color = "#fff000";

                                        break;
                                    case "R":
                                        Cbookings[i].BookingStatusDesc = "مرفوض";
                                        Cbookings[i].color = "#AEABAF";
                                        Cbookings[i].colorFont = "#333";


                                        break;
                                    case "Q":
                                        Cbookings[i].BookingStatusDesc = "استعلام";
                                        Cbookings[i].color = "green";
                                        Cbookings[i].colorFont = "#333";

                                        break;
                                    default:
                                }

                                $scope.ReviewItem = {
                                    review: function (index) {
                                        ngDialog.open({
                                            template: 'ReviewItemScript.html',
                                            windowClass: 'ReviewItemScript',
                                            controller: 'ReviewItemScriptCtrl',
                                            resolve: {
                                                index: function () {
                                                    return index;
                                                }


                                            }

                                        });
                                    }
                                }

                            }

                            $scope.AllBookingsForCustomer = Cbookings;
                            $scope.TotalCustomerTripsCount = Cbookings.length;

                            $scope.$apply();

                        },
                        error: function () {
                            $scope.loading = false;
                            $scope.BookingList = [];
                            $scope.$apply();
                        }
                    });



                },
            }
        
            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 > الرصيد</span></th></tr> </thead> <tbody>';

                    var row = "";

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

                        var object = $scope.DriversBalanceList[i];
                        row = '<tr class="even gradeC">'; 
                        row += "<td>" + object.DriverFirstName + "</td>";
                        row += "<td>" + object.ConvertedMobileNo + "</td>";
                        row += "<td>" + object.Driver_Wallet_Balance + "</td>";
                        row += '</tr>';

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


                    $(htmlTable).table2excel({

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

                        filename: "ارقام الشوفيرية" //do not include extension

                    });

                }
            }
           function convertedMobile(no) {
              

             //  var result = str.substring(0, 2) + ":" + str.substring(2);
               var converted = no;
               converted = converted.substring(0, 3) + "-" + converted.substring(3)
               converted = converted.substring(0, 7) + "-" + converted.substring(7)
                return converted;
            }
         
            LoadDrivers = {
                get: function (selected) {
                 

                    $scope.DriversBalanceList = "";
                    $.ajax({
                        cache: true,
                        url: ManagementServiceUrl + "GetDriversBallance/" + selected + "/" + sessionStorage.UserOID + "/" + sessionStorage.TokenID, //sessionStorage.CompanyOID,
                        type: "GET",
                        contentType: "application/javascript",
                        dataType: "jsonp",

                        success: function (result) {
                            data = JSON.parse(result.GetDriversBallanceResult);
                            console.log(data);
                            if (data.length > 0) {
                                var sum = 0;
                                for (var i = 0; i < data.length; i++) {

                                    sum += parseInt(data[i].Driver_Wallet_Balance);
                                    data[i].ConvertedMobileNo = convertedMobile(data[i].CorporateMobileNumber);


                                    var time = splitT(data[i].CreatedAt);
                                    data[i].CreatedAt = time;
                                   
                                }
                                $scope.TotalTripsCount = sum;

                                $scope.loading = false;
                                $scope.DriversBalanceList = data;
                                $scope.$apply();
                               

                            }
                        },
                        error: function () {
                            $scope.loading = false;
                            $scope.BookingList = [];
                            $scope.$apply();
                        }
                    });
                },
                getBookings: function (driverOID) {

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

                        success: function (result) {
                            if (result.GetAllAppBookingsForDriverResult == "access_denied") {
                                window.parent.location.href = "../../Access.html";
                                return;
                            }
                            Dbookings = JSON.parse(result.GetAllAppBookingsForDriverResult);
                            for (var i = 0; i < Dbookings.length; i++) {
                                var str = Dbookings[i].Book_DateTime;

                                var DateTime = str.split("T")
                                //= new Date(Date.parse(data[i].Book_DateTime));
                                Dbookings[i].date = DateTime[0];
                                Dbookings[i].time = DateTime[1].substring(0, 5);

                                switch (Dbookings[i].BookingStatus) {
                                    case "B":
                                        if (Dbookings[i].Trip_Start_DateTime == null) {
                                            Dbookings[i].BookingStatusDesc = "بانتظار استلام السائق";
                                            Dbookings[i].color = "#d0d0f4";
                                            Dbookings[i].colorFont = "#333";

                                        } else {
                                            Dbookings[i].BookingStatus = "في الانتظار";
                                            Dbookings[i].BookingStatusDesc = "في الانتظار";

                                            Dbookings[i].color = "#fff";
                                            Dbookings[i].colorFont = "#333";

                                        }
                                        break;
                                    case "A":
                                        if (Dbookings[i].Trip_Start_DateTime == null) {
                                            Dbookings[i].BookingStatusDesc = "باتجاه الزبون";
                                            Dbookings[i].color = "#C27ECE";
                                            Dbookings[i].colorFont = "#333";

                                        } else {
                                            Dbookings[i].BookingStatusDesc = "قيد التوصيل";
                                            Dbookings[i].color = "#E56D54";
                                            Dbookings[i].colorFont = "#333";

                                        }

                                        break;
                                    case "C":

                                        if (Dbookings[i].CustomerReason != null) {
                                            if (Dbookings[i].CustomerReason == "Mind Change" || Dbookings[i].CustomerReason == "timeout") {
                                                Dbookings[i].BookingStatusDesc = "لم يتم الرد";
                                                Dbookings[i].color = "#f2f2f2";
                                                Dbookings[i].colorFont = "#333";
                                            }
                                            else {

                                                Dbookings[i].color = "#80b4e1";
                                                Dbookings[i].colorFont = "#333";
                                                Dbookings[i].BookingStatusDesc = Dbookings[i].CustomerReason;
                                                Dbookings[i].BookingStatusDesc = Dbookings[i].CustomerReason;

                                                if (Dbookings[i].CustomerReason == "canceled_before_accept") {

                                                    Dbookings[i].BookingStatusDesc = "الغي قبل القبول";
                                                }


                                            }


                                        } else if (Dbookings[i].DriverReason != null) {
                                            if (Dbookings[i].DriverReason == "Cancel By Driver") {
                                                Dbookings[i].BookingStatusDesc = " ملغي من السائق";
                                                Dbookings[i].color = "#80b4e1";
                                                Dbookings[i].colorFont = "#333";

                                            }

                                        }



                                        break;
                                    case "E":
                                        Dbookings[i].BookingStatusDesc = "مكتمل";
                                        // data[i].color = "#fff000";

                                        break;
                                    case "R":
                                        Dbookings[i].BookingStatusDesc = "مرفوض";
                                        Dbookings[i].color = "#AEABAF";
                                        Dbookings[i].colorFont = "#333";


                                        break;
                                    case "Q":
                                        Dbookings[i].BookingStatusDesc = "استعلام";
                                        Dbookings[i].color = "green";
                                        Dbookings[i].colorFont = "#333";

                                        break;
                                    default:
                                }

                                $scope.ReviewDriverItem = {
                                    review: function (index) {
                                        ngDialog.open({
                                            template: 'ReviewItemScript.html',
                                            windowClass: 'ReviewItemScript',
                                            controller: 'ReviewDriverItemScriptCtrl',
                                            resolve: {
                                                index: function () {
                                                    return index;
                                                }


                                            }

                                        });
                                    }
                                }
                            }



                            $scope.AllBookingsForDriver = Dbookings;
                            $scope.loading = false;
                            $scope.TotalDriverTripsCount = Dbookings.length;
                            $scope.$apply();

                        },
                        error: function () {
                            $scope.loading = false;
                            $scope.BookingList = [];
                            $scope.$apply();
                        }
                    });


                }
            }
         
            LoadDrivers.get("0");
   

        }
        /*----------------------------      GetCompanyCustomers          ---------------*/
    
        $scope.changedValue = function (item) {
            $(".ChooseDate").fadeOut(500);
            if (item == "true") {

                $(".ChooseDate").fadeIn(500);

            } 
        }
        GetCustomers = {

            get: function (no, name) {
                var sum = 0;
                function formatDateToService(date) {

                    var date = new Date(date);

                    var year = date.getFullYear();
                    var month = ("0" + (date.getMonth() + 1)).slice(-2);
                    var day = ("0" + date.getDate()).slice(-2);
                     
                    return month + "-" + day + "-" + year ;


                }

           
                var fdate;
                var todate = formatDateToService($scope.ToDate);
                if ($scope.ChooseDateType == "0") {

                    fdate= formatDateToService("Fri Jan 01 2016 00:00:00 GMT+0200 (Jerusalem Standard Time)");


                }
                else {
                    fdate = formatDateToService($scope.FromDate);
                }
                $scope.TotalCusromersCount = "";
                $scope.RegestraionDate = "";
                $scope.loading = true;
                $scope.$apply();

                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "GetBallaceForAllCustomersNew/" + name + "/" + no + "/" + $scope.BlockList + "/" + $scope.DealerList + "/" + fdate + "/" + todate + "/" + selectedDistrict+"/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID, //sessionStorage.CompanyOID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",

                    success: function (result) {
                        $scope.loading = false;
                        if (result.GetBallaceForAllCustomersNewResult == "access_denied") {
                            window.parent.location.href = "../../Access.html";
                            return;
                        }
                        data = JSON.parse(result.GetBallaceForAllCustomersNewResult);
                        $scope.CustomersBalanceList = "";
                  



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

                                sum += parseInt(data[i].Main_Balance);
                                //   data[i].IsBlocked="1"
                                Reg = data[i].CreatedAt;
                                var temp = Reg + "";
                                var dateArray = temp.split("T");
                                $scope.RegestraionDate = dateArray[0];
                                data[i].test = dateArray[0];
                              
                            }

                            $scope.TotalCusromersCount = sum;
                            $scope.loading = false;
                            $scope.CustomersBalanceList = data;
                            $scope.$apply();
                         

                       
                    },
                    error: function () {
                        $scope.loading = false;
                        $scope.BookingList = [];
                        $scope.$apply();
                    }
                });

            },


        }
        $("#viewall").click(function () {

            var no = $("#no").val();
            var name = $("#name").val();
            
                if (no == "") { no = 0 }
                if (name == "") { name = 0 }
              
                GetCustomers.get(no, name);
            
        });

        //---------------- Driver Ballance Details     ---------------------
        $scope.DriverBallanceDetails = {
            show: function (DriverOid) {
                ngDialog.open({
                    template: 'DriverBallanceDetails.html',
                    className: 'DriverBalanceD ngdialog-theme-default dialogforpopup',
                    controller: 'DriverBallanceDetailsCtrl',
                    resolve: {
                        DriverOid: function () {
                            return DriverOid;
                        }

                    }


                })

            }


        }
        $scope.AddFares = {
            add: function () {
                ngDialog.open({
                    template: 'AddNewFaresRocab.html',
                    className: 'CustomerBalance ngdialog-theme-default dialogforpopup',
                    controller: 'AddNewFaresRocabCtrl',
                    resolve: {


                    }


                })



            },
        }

      

        ForsanRocab = {
            get: function () {
                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "GetDriversExcptionList/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    success: function (result) {
                        if (result.GetDriversExcptionListResult == "access_denied") {
                            window.parent.location.href = "../../Access.html";
                            return;
                        }
                        var data = JSON.parse(result.GetDriversExcptionListResult);
                        $scope.ForsanRocabList = data;
                        $scope.$apply();
                    },
                    error: function () {
                    }
                });

            },
          
            remove: function (driverOID) {


                $.ajax({
                    cache: true,
                    url: ManagementServiceUrl + "DeleteDriverFromExcptionList/" + driverOID+"/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID,
                    type: "GET",
                    contentType: "application/javascript",
                    dataType: "jsonp",
                    success: function (result) {
                        if (result.DeleteDriverFromExcptionListResult == "access_denied") {
                            window.parent.location.href = "../../Access.html";
                            return;
                        }
                        var data = JSON.parse(result.DeleteDriverFromExcptionListResult);
                       ForsanRocab.get();
                        $scope.$apply();
                    },
                    error: function () {
                    }
                });

            }

        }
     ForsanRocab.get();
        //---------------- Customer Ballance Details     ---------------------
        $scope.CustomerBallanceDetails = {
            show: function (customerObj) {
                ngDialog.open({
                    template: 'CustomerBallanceDetails.html',
                    className: 'DriverBalanceD ngdialog-theme-default dialogforpopup',
                    controller: 'CustomerBallanceDetailsCtrl',
                    resolve: {
                        customerObj: function () {
                            return customerObj;
                        }

                    }


                })

            }


        }
    
        $scope.GetCustomerDetails = {
            get: function (customer) {


                ngDialog.open({
                    template: 'CustomerDetails.html',
                    className: ' ngdialog-theme-default dialogforpopup CustomerDetails',
                    controller: 'CustomerDetailsCtrl',
                    resolve: {
                        customer: function () {
                            return customer;
                        }

                    }


                })
            }


        }

        $scope.checkDealer = function (res,d) {
            if (res == '1') {
                var result = confirm('هل تريد تحويل المستخدم الى موزع');
                if (result) {
                    $scope.UpdateDealer.deal(d)
                }
            } else {

                var result = confirm('هل تريد تحويل الموزع الى مستخدم');
                if (result) {
                    $scope.UpdateDealer.disdealer(d)
                }


            }

           

        }
        $scope.checkBlock = function (res, d) {
            if (res == '1') {
                var result = confirm('هل تريد حظر المستخدم');
                if (result) {
                    $scope.UpdateBlock.block(d)
                }
            } else {

                var result = confirm('هل تريد الغاء حظر المستخدم');
                if (result) {
                    $scope.UpdateBlock.disblock(d)
                }


            }



        }
        $scope.checkDeleteFares = function (d) {
          
                var result = confirm('هل تريد حذف السائق من قائمة الفرسان');
                if (result) {
                    ForsanRocab.remove(d.OID)
                }
           



        }
        $scope.DriverBooking = {
            get: function (doid) {
                //  SelectedCompanyID= $("#SelectedCompanyID").val();

                if (doid != null) {
                    LoadDrivers.getBookings(doid);
                    $('#DriverModel').modal('toggle');
                }


            }
        }

    }])



TaxiApp.service('deductDriverBalance', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (balance) {
        var modalInstance = $modal.open({
            className: 'CustomerBalance',
            templateUrl: 'deductDriverBalance.html',
            controller: 'deductDriverBalanceCtrl',
            resolve: {
                obj: function () {
                    return obj;
                }
             
            }

        });

    };



    return service;

})
TaxiApp.controller('deductDriverBalanceCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, obj) {


    $scope.loading = true;
    loadPaymentType($scope,"sub");
   

    $scope.SelectedDDPT = function (aPayOid) {
        PaymentType = $.grep($scope.PaymentTypes, function (item) {

            return item.OID == aPayOid;
        })[0].value;
    }

    $scope.ClickClose = function () {

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

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

    }


    $scope.save = function () {
     
        var amount = $('#Amount').val();
      
        var notes = $('#notes').val();

        if (notes == "") {
            notes = "$A"
        }
        if (amount != "") {
             amount = "-" + amount
                $.ajax({
                cache: true,
                url: ManagementServiceUrl + "AddDriverTransaction/" + obj.OID + "/" + obj.DriverFirstName + "/" + amount + "/" + obj.IMEINumber + "/" + notes + "/" + sessionStorage.UserOID + "/" + $scope.PaymentType+"/"+sessionStorage.TokenID,
                type: "GET",
                contentType: "application/javascript",
                dataType: "jsonp",
                success: function (result) {
                    if (result.AddDriverTransactionResult == "access_denied") {
                        window.parent.location.href = "../../Access.html";
                        return;
                    }
                    if (company == undefined || company=="")
                        company = 0;

                    LoadDrivers.get(company);
                },
                error: function () {
                }
                });
                
         //  LoadDrivers.get($scope.selectedCompany);
            $scope.ClickClose();


        } else {
            alert("الرجاء ادخال المبلغ");
        }
    }
})


TaxiApp.service('addDriverBalance', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (obj) {
        var modalInstance = $modal.open({
            className: 'CustomerBalance',
            templateUrl: 'addDriverBalance.html',
            controller: 'addDriverBalanceCtrl',
            resolve: {
                obj: function () {
                    return obj;
                }

            }

        });

    };



    return service;

})

TaxiApp.controller('addDriverBalanceCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, obj) {


    $scope.loading = true;

    loadPaymentType($scope,"add");

    $scope.SelectedADPT = function (aPayOid) {
        PaymentType = $.grep($scope.PaymentTypes, function (item) {

            return item.OID == aPayOid;
        })[0].value;
    }


    $scope.ClickClose = function () {

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

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

    }
    $scope.save = function () {
        var amount = $('#Amount').val();
        var notes = $('#notes').val();

        if (notes == "") {
            notes="$P"
        }
        if (amount != "") {
          
        

            $.ajax({
                cache: true,
                url: ManagementServiceUrl + "AddDriverTransaction/" + obj.OID + "/" + obj.DriverFirstName + "/" + amount + "/" + obj.IMEINumber + "/" + notes + "/" + sessionStorage.UserOID + "/" + $scope.PaymentType+"/"+sessionStorage.TokenID,
                type: "GET",
                contentType: "application/javascript",
                dataType: "jsonp",
                success: function (result) {
                    if (result.AddDriverTransactionResult == "access_denied") {
                        window.parent.location.href = "../../Access.html";
                        return;
                    }
                    if (company == undefined || company == "")
                        company = 0;
                    LoadDrivers.get(company);
                },
                error: function () {
                }
            });
          
            $scope.ClickClose();
        

        } else {
            alert("الرجاء ادخال المبلغ");

}
    }

})

TaxiApp.service('deductCustomerBalance', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (balance) {
        var modalInstance = $modal.open({
            className: ' ngdialog-theme-default dialogforpopup CustomerBalance',
            templateUrl: 'deductCustomerBalance.html',
            controller: 'deductCustomerBalanceCtrl',
            resolve: {
                obj: function () {
                    return obj;
                }

            }

        });

    };



    return service;

})
TaxiApp.controller('deductCustomerBalanceCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, obj) {


    $scope.loading = true;
    GetCustomerTransactionTypes($scope,"sub");

    $scope.SelectedDCTT = function (dTransactionTypeoid) {
        CustomerTT = $.grep($scope.CustomerTransactionTypes, function (item) {

            return item.OID == dTransactionTypeoid;
        })[0].value;
    }

  
    $scope.ClickClose = function () {


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

    }


    $scope.save = function () {
      
        var amount = $('#Amount').val();

        var notes = $('#notes').val();
        var amount = $('#Amount').val();
        var SelectedTT = $scope.CustomerTT;
        if (notes == "") {
            notes = "$A"
        }

        if (amount != "") {
            


            $.ajax({
                cache: true,
                url: ManagementServiceUrl + "AddCustomerTransaction/" + obj.OID + "/" + amount + "/" + notes + "/" + SelectedTT+"/null/null/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID,
                type: "GET",
                contentType: "application/javascript",
                dataType: "jsonp",
                success: function (result) {
                    if (result.AddCustomerTransactionResult == "access_denied") {
                        window.parent.location.href = "../../Access.html";
                        return;
                    }
                    var no = $("#no").val();
            var name = $("#name").val();


            if (no == "") { no = 0 }
            if (name == "") { name = 0 }



            GetCustomers.get(no, name);
                },
                error: function () {
                }
            });
          
            $scope.ClickClose();


        } else {
            alert("الرجاء ادخال المبلغ");
        }
    }
})


TaxiApp.service('addCustomerBalance', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (obj) {
        var modalInstance = $modal.open({
            className: ' ngdialog-theme-default dialogforpopup CustomerBalance',
            templateUrl: 'addCustomerBalance.html',
            controller: 'addCustomerBalanceCtrl',
            resolve: {
                obj: function () {
                    return obj;
                }

            }

        });

    };



    return service;

})
TaxiApp.controller('addCustomerBalanceCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, obj) {


    $scope.loading = true;

    GetCustomerTransactionTypes($scope, "add");

    $scope.SelectedACTT = function (aTransactionTypeoid) {
        CustomerTT = $.grep($scope.CustomerTransactionTypes, function (item) {

            return item.OID == aTransactionTypeoid;
        })[0].value;
    }


    $scope.ClickClose = function () {


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

    }
    $scope.save = function () {
        var amount = $('#Amount').val();
        var notes = $('#notes').val();
        var SelectedTT = $scope.CustomerTT;
       
        var SelectedIsBonus = $scope.checked
        var IsBonus;
        var selectedBalanceExpireDate;
        if (SelectedIsBonus == true) {
            selectedBalanceExpireDate = formatDateToService($scope.BalanceExpireDate)+" 23~59";
            IsBonus =true;
        } else {
            IsBonus = null;
            selectedBalanceExpireDate =null;
        }


        if (notes == "") {
            notes = "$P"
        }
        if (amount != "") {



            $.ajax({
                cache: true,
                url: ManagementServiceUrl + "AddCustomerTransaction/" + obj.OID + "/" + amount + "/" + notes + "/" + SelectedTT + "/" + IsBonus + "/" + selectedBalanceExpireDate+"/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID,
                type: "GET",
                contentType: "application/javascript",
                dataType: "jsonp",
                success: function (result) {
                    if (result.AddCustomerTransactionResult == "access_denied") {
                        window.parent.location.href = "../../Access.html";
                        return;
                    }
                    var no = $("#no").val();
                    var name = $("#name").val();


                    if (no == "") { no = 0 }
                    if (name == "") { name = 0 }



                    GetCustomers.get(no, name);
                },
                error: function () {
                }
            });
         
            $scope.ClickClose();


        } else {
            alert("الرجاء ادخال المبلغ");

        }
    }

})





TaxiApp.service('DriverBallanceDetails', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (DriverOid) {
        var modalInstance = $modal.open({
            windowClass: '',
            templateUrl: 'DriverBallanceDetails.html',
            controller: 'DriverBallanceDetailsCtrl',
            resolve: {
                DriverOid: function () {
                    return DriverOid;
                }

            }

        });

    };



    return service;

})
TaxiApp.controller('DriverBallanceDetailsCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, DriverOid) {
   
    function GetDriverBallanceDetails() {
    

        $.ajax({
            cache: true,
            url: ManagementServiceUrl + "GetDriverBallanceDetails/" + DriverOid + "/" + 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;
                $scope.loading = false;
                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';
                    }

                    var date = splitDate($scope.List[i].Transaction_DateTime)
                    $scope.List[i].date = date[0] + " -  " + date[1].substring(0, 5);

                }
                //$scope.DriverNameDetails = $scope.List[0].DriverName;
                $scope.$apply();
            }
        });

    }
    GetDriverBallanceDetails();
    $scope.loading = true;

    $scope.ClickClose = function () {

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

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

    }


    
})



TaxiApp.service('CustomerBallanceDetails', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (customerOid) {
        var modalInstance = $modal.open({
            dialogClass: 'balance_details',
            templateUrl: 'CustomerBallanceDetails.html',
            controller: 'CustomerBallanceDetailsCtrl',
            resolve: {
                customerObj: function () {
                    return customerObj;
                }

            }

        });

    };



    return service;

})
TaxiApp.controller('CustomerBallanceDetailsCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, customerObj) {

    function GetCustomerBallanceDetails() {


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

            success: function (result) {
                if (result.GetCustomerBallanceDetailsResult == "access_denied") {
                    window.parent.location.href = "../../Access.html";
                    return;
                }
                //var a = result;
                $scope.loading = false;
                var data = JSON.parse(result.GetCustomerBallanceDetailsResult);
                $scope.cList = data;
                for (var i = 0; i < $scope.cList.length; i++) {
                    if (Math.sign($scope.cList[i].Amount) == -1) {
                        $scope.cList[i].color = 'red';
                    } else {

                        $scope.cList[i].color='green';
                    }
                    
                    var date= splitDate( $scope.cList[i].Transaction_DateTime)
                    $scope.cList[i].date = date[0] + " -  " + date[1].substring( 0, 5);
                   
                }
                //$scope.DriverNameDetails = $scope.List[0].DriverName;
                $scope.$apply();
            }
        });

    }
    GetCustomerBallanceDetails();
    $scope.Bonus_Balance = customerObj.Bonus_Balance;
    if (customerObj.Bonus_Balance_ExpireDate!=null) {
    
       var date = splitDate(customerObj.Bonus_Balance_ExpireDate)
    $scope.Bonus_Balance_ExpireDate= date[0] + " -  " + date[1].substring(0, 5);
    }
 

  
    $scope.loading = true;

    $scope.ClickClose = function () {

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

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

    }



})



TaxiApp.service('AddNewFaresRocab', function ($modal) {
    var service = {};
    var self = this;
    service.open = function () {
        var modalInstance = $modal.open({
            className: 'CustomerBalance ngdialog-theme-default dialogforpopup',
            templateUrl: 'AddNewFaresRocab.html',
            controller: 'AddNewFaresRocabCtrl',
            resolve: {
              

            }

        });

    };



    return service;

})
TaxiApp.controller('AddNewFaresRocabCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window) {
   
    loadContents(sessionStorage.ORGOID, sessionStorage.CompanyOID, sessionStorage.UserOID, 'DT', $scope);

    $scope.SelectedDistrict = function (districtOid) {
        DistrictName = $.grep($scope.DistrictList, function (item) {

            return item.OID == districtOid;
        })[0].value;
    }

    $scope.loading = true;

    $scope.ClickClose = function () {

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

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

    }
    $scope.save = function () {
    
        $.ajax({
            cache: true,
            url: ManagementServiceUrl + "GetDriverInfo/0" + $scope.addFaresNo+"/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID, //sessionStorage.CompanyOID,
            type: "GET",
            contentType: "application/javascript",
            dataType: "jsonp",

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

                    alert(" الرقم المدخل غير موجود او مكرر لاكثر من شوفير ")


                }
                else { 
                    
                    if ($scope.DistrictName != undefined) {
                    $("#DriverNameToConfirm").append("<span >السائق : </span><span>" + data.DriverFirstName + "</span></br>");
                    $("#DriverNameToConfirm").append("<span >الرقم : </span><span>" + data.IMEINumber + "</span>")
                   // $scope.showphoneNo = data.OID;
                    $(".ToBeHiddenToConfirm").fadeOut(500);
                    $(".ToBeShownToConfirm").fadeIn(500);
                    $scope.confirm = function () {

                     
                            var EimiNo = data.IMEINumber;
                            var DOID = data.OID;
                            $.ajax({
                                cache: true,
                                url: ManagementServiceUrl + "AddDriverToExcptionList/" + DOID + "/" + EimiNo + "/" + $scope.DistrictName+"/"+sessionStorage.UserOID+"/"+sessionStorage.TokenID, //sessionStorage.CompanyOID,
                                type: "GET",
                                contentType: "application/javascript",
                                dataType: "jsonp",

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

                                        $scope.ClickClose();
                                        ForsanRocab.get();
                                        $scope.$apply();
                                    }
                                    else {
                                        alert("حدث خطأ يرجى اعادة المحاولة")

                                      
                                    }
                                },
                                error: function () {
                                    $scope.loading = false;
                                    $scope.BookingList = [];
                                    $scope.$apply();
                                }
                            });

                         
                      }
                    }
                        else {
                            alert("الرجاء ادخال المحافظة")
                       


                    }
               
                }
            },
            error: function () {
                $scope.loading = false;
                $scope.BookingList = [];
                $scope.$apply();
            }
        });

    }
   

})
        
TaxiApp.service('CustomerDetails', function ($modal) {
    var service = {};
    var self = this;
    service.open = function (customer) {
        var modalInstance = $modal.open({
            className: ' ngdialog-theme-default dialogforpopup CustomerDetails',
            templateUrl: 'CustomerDetails.html',
            controller: 'CustomerDetailsCtrl',
            resolve: {
                customer: function () {
                    return customer;
                }

            }

        });

    };



    return service;

})
TaxiApp.controller('CustomerDetailsCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, customer) {
  
    $scope.CustomersDetailsList = customer;
    var time ;
    if($scope.CustomersDetailsList.DateOfBirth!=null){
    
        time = splitT($scope.CustomersDetailsList.DateOfBirth);
    }
    $scope.CustomersDetailsList.DateOfBirth = time;
    $scope.loading = true;

    $scope.ClickClose = function () {

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

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

    }



})

function formatDateToService(date) {

    var date = new Date(date);

    var year = date.getFullYear();
    var month = ("0" + (date.getMonth() + 1)).slice(-2);
    var day = ("0" + date.getDate()).slice(-2);

    return year + "-" + month + "-" + day ;


}