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

TaxiApp.controller('PromotionCodeCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog',  'EditPromotionCode', 'AddPromotionCode',

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

        }
        $scope.VehicleCurrentLocation = [];
      
        $scope.loading = false;
        $scope.DisplayName = sessionStorage.UserName;       
        $scope.CompanyName = sessionStorage.value;
        $scope.DistrictOID = sessionStorage.DistrictOID;
        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();
            }

            $scope.Role = sessionStorage.RoleType;
            $scope.RoleID = sessionStorage.RoleID;


            $scope.User = sessionStorage.Username;

            selectedCompany = 'undefined';
            if (sessionStorage.CompanyOID != undefined || sessionStorage.ORGOID != undefined) {
                loadDropDownFromAppConfig("COMPANY", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, 0, $scope);
            }
           
            function load() {
                $scope.FromDate = new Date();
                $scope.ToDate = new Date();
                //$scope.GetAllAcceptanceRecords();
            }
            load();


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

                    success: function (result) {
                        if (result.GetPromotionCode_CreditListResult == "access_denied") {
                            window.parent.location.href = "../../Access.html";

                            return;
                        }
                        //var a = result;
                        $scope.loading = false;
                        var data = JSON.parse(result.GetPromotionCode_CreditListResult);                    
                        $scope.List = data;
                        $scope.$apply();
                    }
                });

            }
        GetAllCodes();
        function load() {
            $scope.FromDate = new Date();
            $scope.ToDate = new Date();
            //$scope.GetAllAcceptanceRecords();
        }
        load();

        function getFormattedFromDate(tDate) {

            var year = tDate.getFullYear();
            var month = (1 + tDate.getMonth()).toString();
            month = month.length > 1 ? month : '0' + month;
            var day = tDate.getDate().toString();
            day = day.length > 1 ? day : '0' + day;
            DatePart = year + month + day;
            return year + '-' + month + '-' + day;

        }

        $scope.PromotionCode = {
            edit: function (obj) {
                ngDialog.open({
                    windowClass: 'EditPromotionCode',
                    templateUrl: 'EditPromotionCode.html',
                    controller: 'EditPromotionCodeCtrl',
                    className: 'customDialog ngdialog ngdialog-theme-default',

                    resolve: {
                        obj: function () {  return obj; }
                         }


                });
            },
            add: function () {

                ngDialog.open({
                    windowClass: 'AddPromotionCode',
                    templateUrl: 'AddPromotionCode.html',
                    className: 'customDialog ngdialog ngdialog-theme-default',

                    controller: 'AddPromotionCodeCtrl',
                    resolve: {
                      
                    }


                });
              


            }

        }

        }
    
    }])


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


        });

    };



    return service;
})
TaxiApp.controller('EditPromotionCodeCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, obj) {
    loadCurrencyTypes($scope);
   
    $scope.eSelectedCurrency = function (cOid) {
        eCurrencyType = $.grep($scope.CurrencyTypes, function (item) {

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

    $scope.eCode = obj.Promotion_Code;
    $scope.eAmount = obj.Credit_Amount;
    $scope.eMaxUse = obj.MaxNumberOfUse;

    $scope.eCurrencyType= obj.CurrencyOID
   
    
    $scope.eFromDate = formatDateToView(obj.From_Date);
    $scope.eFromTime = formatTimeToView(obj.From_Date);


    

    $scope.eToDate = formatDateToView(obj.To_Date);
    $scope.eToTime = formatTimeToView(obj.To_Date);

    if (obj.PeriodOfExpireAfterRedeemInDays != null) {

 $scope.ePeriodOfExpireAfterRedeemInDays = obj.PeriodOfExpireAfterRedeemInDays;

    }
   
    if (obj.BalanceExpireDate != null) {

        $scope.eBalanceExpireDate = formatDateToView(obj.BalanceExpireDate);

    }
  

 
    $scope.ClickClose = function () {

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

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

    }
    //  console.log(obj);
    $scope.EditItem = function () {
      
       // console.log($scope.eFromTime);
  
        if ($scope.eCode != undefined && $scope.eAmount != undefined  && $scope.eFromDate != undefined && $scope.eFromTime != undefined &&
            
           $scope.eToDate != undefined && $scope.eToTime != undefined && $scope.eCurrencyType != undefined ) {
            var ConvertedaBalanceExpireDate;
            if($scope.eMaxUse==undefined){
                $scope.eMaxUse=null;
            }
            if ($scope.eBalanceExpireDate == undefined) {
                ConvertedaBalanceExpireDate = "";
            } else {


                ConvertedaBalanceExpireDate = formatDateToService($scope.eBalanceExpireDate) + " 23:59";
            }
            if ($scope.ePeriodOfExpireAfterRedeemInDays == undefined) {
                $scope.ePeriodOfExpireAfterRedeemInDays = null;
            }
            var ConvertedeFromDate = formatDateToService($scope.eFromDate);
            var ConvertedeToDate = formatDateToService($scope.eToDate);



            var ConvertedeFromTime = formatTimeToService($scope.eFromTime);
            var ConvertedeToTime = formatTimeToService($scope.eToTime);


            var EFromDate = ConvertedeFromDate + " " + ConvertedeFromTime;
            var EToDate = ConvertedeToDate + " " + ConvertedeToTime;



            var promoCreditObject = {}
            

         

            var temp = {
                promoCreditObject: {
                    'OID':obj.OID,
                    'Promotion_Code':$scope.eCode,
                    'Credit_Amount': $scope.eAmount,
                    'From_Date': EFromDate,
                    'To_Date': EToDate,
                    'MaxNumberOfUse': $scope.eMaxUse,
                    'Is_Active': true,
                    'CurrencyOID': $scope.eCurrencyType,
                    'BalanceExpireDate': ConvertedaBalanceExpireDate,
                    'PeriodOfExpireAfterRedeemInDays': $scope.ePeriodOfExpireAfterRedeemInDays,
                    'CreatedBy': sessionStorage.UserOID,
                    'TokenID': sessionStorage.TokenID

                  
                }
            }

            $.ajax({
                type: "POST",
                url: ManagementServiceUrl + "UpdatePromotionCode_Credit",
                data: JSON.stringify(temp),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data) {
                    if (data.UpdatePromotionCode_CreditResult == "access_denied") {
                        window.parent.location.href = "../../Access.html";

                        return;
                    }
                    // $scope.clear();   
                    alert("تم تعديل  الكود بنجاح");
                    $scope.ClickClose();
                   load
                    $scope.loading = false;
                    $scope.$apply();
                },
                error: function (a, b, c) { console.log(a); }

            });

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

    }





})
// Add Promotion Code


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


        });

    };



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

    loadCurrencyTypes($scope);
    $scope.today = GetTodayDate();

    $scope.aFromDate = $scope.today
    $scope.aToDate = $scope.today;
    
    $scope.SelectedCurrency = function (cOid) {
        aCurrencyType = $.grep($scope.CurrencyTypes, function (item) {

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



    $scope.aCode ="";
    $scope.aAmount ="";
    $scope.aMaxUse ="";



    $scope.eFromDate = "";
    $scope.eFromTime = "";




    $scope.eToDate ="";
    $scope.eToTime = "";



    



    $scope.ClickClose = function () {

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

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

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

       // console.log($("#eFromTime"));

        if ($scope.aCode != undefined && $scope.aAmount != undefined && $scope.aFromDate != undefined && $scope.aFromTime != undefined &&

           $scope.aToDate != undefined && $scope.aToTime != undefined && $scope.aCurrencyType != undefined ) {
            var ConvertedaBalanceExpireDate;
            if ($scope.aMaxUse == undefined || $scope.aMaxUse=="") {
                $scope.aMaxUse = null;
            }
            if ($scope.aBalanceExpireDate == undefined) {
                ConvertedaBalanceExpireDate = "";
            } else {


            ConvertedaBalanceExpireDate = formatDateToService($scope.aBalanceExpireDate) + " 23:59";
            }
            if ($scope.aPeriodOfExpireAfterRedeemInDays == undefined) {
                $scope.aPeriodOfExpireAfterRedeemInDays = null;
            }
            var ConvertedeFromDate = formatDateToService($scope.aFromDate);
            var ConvertedeToDate = formatDateToService($scope.aToDate);



            var ConvertedeFromTime = formatTimeToService($scope.aFromTime);
            var ConvertedeToTime = formatTimeToService($scope.aToTime);


            var EFromDate = ConvertedeFromDate + " " + ConvertedeFromTime;
            var EToDate = ConvertedeToDate + " " + ConvertedeToTime;




            var promoCreditObject = {}




            var temp = {
                promoCreditObject: {
                 
                    'Promotion_Code': $scope.aCode,
                    'Credit_Amount': $scope.aAmount,
                    'From_Date': EFromDate,
                    'To_Date': EToDate,
                    'MaxNumberOfUse': $scope.aMaxUse,
                    'Is_Active': true,
                    'CurrencyOID': $scope.aCurrencyType,
                    'BalanceExpireDate':ConvertedaBalanceExpireDate,
                    'PeriodOfExpireAfterRedeemInDays': $scope.aPeriodOfExpireAfterRedeemInDays,
                    'CreatedBy': sessionStorage.UserOID,
                    'TokenID': sessionStorage.TokenID


                }
            }

            $.ajax({
                type: "POST",
                url: ManagementServiceUrl + "AddPromotionCode_Credit",
                data: JSON.stringify(temp),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                processData: true,
                success: function (data) {
                    if (data.AddPromotionCode_CreditResult == "access_denied") {
                        window.parent.location.href = "../../Access.html";

                        return;
                    }
                    // $scope.clear();   
                    alert("تم اضافة  الكود بنجاح");
                    $scope.ClickClose();
                    GetAllCodes();
                    $scope.loading = false;
                    $scope.$apply();
                },
                error: function (a, b, c) { console.log(a); }

            });



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

    }





})
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 day + "-" + month + "-" + year;


}



function formatTimeToService(date) {
    date = new Date(date);


    var minutes = ("0" + (date.getMinutes())).slice(-2);
    var hour = ("0" + date.getHours()).slice(-2);



    return hour + ":" + minutes;

}


function formatDateToView(date) {


    var dateParts = date.split(" ");

    if (dateParts.length > 0) {

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

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

        var date = new Date(newDate);

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

        //  console.log(year + "/" + month + "/" + day);

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

    }


}




function formatTimeToView(date) {

    var dateParts = date.split(" ");

    if (dateParts.length > 0) {

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

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

        var date = new Date(newDate);



        return new Date(date.getTime());

    }

    // date = new Date(date);
    // return new Date(date.getTime());

}
