//Expire all coupons by campaign id
        public static bool ExpireAllCouponsByCampaignId(int EcouponCampaignId)
        {
            try
            {
                UnitOfWork uow = new UnitOfWork();
                IEnumerable<Coupon> Coupon = uow.CouponRepo.GetAll().Where(e => (e.EcouponCampaignId == EcouponCampaignId && e.IsRedeem != true));
                if (Coupon != null)
                {
                    foreach (var item in Coupon)
                    {
                        CouponDTO CouponDTO = new CouponDTO();
                        CouponDTO = GetById(item.Id);
                        CouponDTO.IsExpired = true;
                        Edit(CouponDTO);
                    }
                    return true;
                }
                else return false;

            }
            catch
            {
                throw;
            }
        }
 //Edit Coupon
 public static void Edit(CouponDTO CouponDTO)
 {
     try
     {
         UnitOfWork uow = new UnitOfWork();
         Coupon Coupon = Transform.CouponToDomain(CouponDTO);
         uow.CouponRepo.Update(Coupon);
         uow.SaveChanges();
     }
     catch
     {
         throw;
     }
 }
        //Create Coupon
        public static int Create(CouponDTO CouponDTO)
        {
            try
            {
                var Coupon = new Coupon();

                UnitOfWork uow = new UnitOfWork();

                Coupon = Transform.CouponToDomain(CouponDTO);
                uow.CouponRepo.Insert(Coupon);
                uow.SaveChanges();
                CouponDTO.Id = Coupon.Id;
                return CouponDTO.Id;

            }

            catch (Exception)
            {
                throw;
            }
        }
        public static void ExpireCoupon()
        {
            List<CouponDTO> CouponDTOList = new List<CouponDTO>();
            CouponDTOList = CouponService.GetCouponListWhichNotExpired();
            if (CouponDTOList != null)
            {
                foreach (var item in CouponDTOList)
                {
                    EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                    EcouponCampaignDTO = EcouponCampaignService.GetById(item.EcouponCampaignId);
                    if (EcouponCampaignDTO.ExpiresOn != null)
                    {
                        if (EcouponCampaignDTO.ExpiresOn < System.DateTime.Now)
                        {
                            CouponDTO CouponDTO = new CouponDTO();
                            CouponDTO = item;// CouponService.GetById(item.Id);

                            CouponDTO.IsExpired = true;
                            CouponService.Edit(CouponDTO);

                        }
                    }

                }
            }
        }
        private static bool ActualSmsSend(string mobilenumber, string message, string Gateway, EcouponCampaignDTO EcouponCampaignDTO, ClientDTO ClientDTO, string CouponCode)
        {
            string result = "";
            bool IsSent = false;
            int SMSMsgCount = GetMessageCount(message);
            message = MsgCorrect(message);

            if (message != "" && mobilenumber != "")// Check for empty message.
            {

                string Url = ConfigurationManager.AppSettings["TransactionalGateWay"].ToString();
                Url = Url.Replace("%26", "&");
                Url = Url.Replace("[recipient]", mobilenumber);
                Url = Url.Replace("[message]", message);
                if (Gateway != "022751") //if (Gateway.ToLower() != "default")
                {
                    Url = Url.Replace("[gateway]", Gateway); //Gateway = "MSGBLS"
                }
                else
                {
                    Url = "";
                    Url = ConfigurationManager.AppSettings["PromotionalGateWay"].ToString();
                    Url = Url.Replace("%26", "&");
                    Url = Url.Replace("[recipient]", mobilenumber);
                    Url = Url.Replace("[message]", message);
                }

                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
                myRequest.Method = "GET";
                WebResponse myResponse = myRequest.GetResponse();
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
                result = sr.ReadToEnd();
                sr.Close();

                string statuscode = "";
                //if (result.Contains('|'))
                //    statuscode = result.Substring(0, result.IndexOf('|'));
                //else
                //    statuscode = result;

                //string SMSReplyMessage = SMSResult(statuscode) + "-" + result; //result

                if (result.Contains('|'))
                {
                    //statuscode = result.Substring(0, result.IndexOf('|'));
                    statuscode = "";
                    string[] words = result.Split('|');
                    foreach (string word in words)
                    {
                        Console.WriteLine(word);
                        try
                        {
                            int code = Convert.ToInt32(word);

                            statuscode = code.ToString();
                        }
                        catch (Exception)
                        {
                            string code = word.Replace(" ", "");
                            if (code == "Success")
                            {
                                code = "0";
                                statuscode = code.ToString();
                                IsSent = true;
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }

                }
                else
                {
                    statuscode = result;
                }

                myResponse.Close();
                if (IsSent == true)
                {
                CouponDTO CouponDTO = new CouponDTO();
                //CouponDTO.IsSuccess = true;
                CouponDTO.EcouponCampaignId = EcouponCampaignDTO.Id;
                CouponDTO.MobileNumber = mobilenumber;
                CouponDTO.Code = CouponCode;
                CouponDTO.IsRedeem = false;

                CouponDTO.MessageId = result;
                SettingDTO SettingDTO = new SettingDTO();
                SettingDTO = SettingService.GetById(1);
                double ActualSMSMsgCount = SettingDTO.NationalCouponSMSCount * SMSMsgCount;
                CouponDTO.MessageCount = SMSMsgCount;
                CouponDTO.RequiredCredits = ActualSMSMsgCount;

                CouponDTO.Message = message;
                //CouponDTO.MessageStatus = SMSReplyMessage;
                //CouponDTO.GatewayID = Gateway;
                CouponDTO.SentDateTime = System.DateTime.Now;
                CouponDTO.IsCouponSent = true;
                //CouponDTO.MessageID = statuscode;

                //if (statuscode == "1701")
                //{
                //    CampaignLogDTO.IsSuccess = true;
                //}
                //else if (statuscode != "1701")
                //{
                //    CampaignLogDTO.IsSuccess = false;
                //}
                CouponService.Create(CouponDTO);

                //// Reduce SMS Credits From Client
                //ClientDTO.SMSCredit = ClientDTO.SMSCredit - ActualSMSMsgCount;  //SMSMsgCount;
                //ClientService.Edit(ClientDTO);

                }

            }

            return IsSent; // result;
        }
 public static Coupon CouponToDomain(CouponDTO CouponDTO)
 {
     if (CouponDTO == null) return null;
      Mapper.CreateMap<CouponDTO, Coupon>();
      Coupon Coupon = Mapper.Map<Coupon>(CouponDTO);
      return Coupon;
 }
        //Get ecoupon campaign details from mobile and code
        public static EcouponCampaignDTO GetEcouponCampaignDetailsFromMobileAndCode(string Mobile, string Code)
        {
            try
            {
                CouponDTO CouponDTO = new CouponDTO();
                EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();

                using (var uow = new UnitOfWork())
                {
                    IEnumerable<Coupon> Coupon = uow.CouponRepo.GetAll().Where(e => e.MobileNumber == Mobile && e.Code == Code && e.IsExpired != true && e.IsRedeem != true);
                    if (Coupon != null)
                    {
                        foreach (var item in Coupon)
                        {
                            CouponDTO.Id = item.Id;
                            CouponDTO.EcouponCampaignId = item.EcouponCampaignId;
                        }

                        EcouponCampaignDTO = EcouponCampaignService.GetById(CouponDTO.EcouponCampaignId);

                    }

                }
                return EcouponCampaignDTO;
            }
            catch (Exception)
            {
                throw;
            }
        }
        //Return Coupon list as per partner id
        public static List<CouponDTO> GetCouponListSearchByPartnerId(int PartnerId, string search)
        {
            List<EcouponCampaignDTO> EcouponCampaignDTOList = new List<EcouponCampaignDTO>();
            List<CouponDTO> CouponDTOList = new List<CouponDTO>();
            try
            {
                EcouponCampaignDTOList = EcouponCampaignService.GetEcouponCampaignListSearchByPartnerId(PartnerId, "");

                if (EcouponCampaignDTOList.Count > 0)
                {
                    foreach (var item in EcouponCampaignDTOList)
                    {
                        var EcouponCampaign = CouponDTOList.Where(e => e.ClientId == item.ClientId).OrderByDescending(e => e.SentDateTime);// uow.EcouponCampaignRepo.GetAll().Where(e => e.ClientId == ClientId);
                        if (EcouponCampaign != null)
                        {

                            foreach (var itemEcouponCampaign in EcouponCampaign)
                            {
                                CouponDTO CouponDTONew = new CouponDTO();
                                CouponDTONew = itemEcouponCampaign;
                                UserDTO UserDTO = new UserDTO();

                                EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                                EcouponCampaignDTO = EcouponCampaignService.GetById(itemEcouponCampaign.EcouponCampaignId);
                                CouponDTONew.CouponCampaignName = EcouponCampaignDTO.Title;

                                if (itemEcouponCampaign.UserId != null)
                                {
                                    int UserId = (int)itemEcouponCampaign.UserId;
                                    UserDTO = UserService.GetById(UserId);
                                    CouponDTONew.UserName = UserDTO.Name;
                                }
                                else
                                {
                                    CouponDTONew.UserName = "";
                                }

                                CouponDTOList.Add(CouponDTONew);
                            }
                        }
                    }
                }

                if (search != "" && search != null)
                {
                    bool Isdate = CommonService.IsDate(search);
                    if (Isdate != true)
                    {
                        List<CouponDTO> CouponDTOSearchList = new List<CouponDTO>();
                        var CouponSearch = CouponDTOList.Where(e => e.Code.Contains(search) || (e.MobileNumber != null ? (e.MobileNumber.Contains(search)) : false) || (e.Remark != null ? (e.Remark.ToLower().Contains(search.ToLower())) : false) || e.UserName.ToLower().Contains(search.ToLower()) || (e.RedeemDateTime.ToString() != null ? (Convert.ToDateTime(e.RedeemDateTime).ToString("dd-MMM-yyyy").ToLower().Contains(search.ToLower())) : false) || (e.CouponCampaignName != null ? (e.CouponCampaignName.ToLower().Contains(search.ToLower())) : false)).OrderByDescending(e => e.SentDateTime);
                        if (CouponSearch != null)
                        {
                            foreach (var itemsearch in CouponSearch)
                            {

                                CouponDTOSearchList.Add(itemsearch);
                            }
                        }
                        return CouponDTOSearchList;

                    }
                    else
                    {
                        List<CouponDTO> CouponDTOSearchList = new List<CouponDTO>();
                        DateTime date = Convert.ToDateTime(search);
                        var CouponSearch = CouponDTOList.Where(e => e.RedeemDateTime >= date && e.RedeemDateTime < date.AddDays(1)).OrderByDescending(e => e.SentDateTime);
                        if (CouponSearch != null)
                        {
                            foreach (var itemsearch in CouponSearch)
                            {

                                CouponDTOSearchList.Add(itemsearch);
                            }
                        }
                        return CouponDTOSearchList;
                    }
                }
                return CouponDTOList;
            }

              //catch (LoggedInUserException)
            //{
            //    throw new System.TimeoutException();
            //}
            catch (Exception)
            {

                throw;
            }
        }
        //Return Coupon list as per Ecoupon campaign id and Is sent status
        public static List<CouponDTO> GetCouponListSearchByEcouponCampaignId(int EcouponCampaignId, string search, bool IsSent, PagingInfo pagingInfo)
        {
            List<CouponDTO> CouponDTOList = new List<CouponDTO>();
            try
            {
                using (var uow = new UnitOfWork())
                {
                    IEnumerable<EcouponCampaign> EcouponCampaign = uow.EcouponCampaignRepo.GetAll().Where(e => e.Id == EcouponCampaignId && e.IsSent == IsSent).OrderByDescending(e => e.CreatedDate);
                    //var EcouponCampaigncoupons = from c in EcouponCampaign where (from g in c.Coupons where c.ClientId == ClientId  select g).Any() select c;
                    int skip = (pagingInfo.Page - 1) * pagingInfo.ItemsPerPage;
                    int take = pagingInfo.ItemsPerPage;

                    if (EcouponCampaign != null)
                    {
                        foreach (var item in EcouponCampaign)
                        {
                            IQueryable<Coupon> Coupon = uow.CouponRepo.GetAll().Where(e => e.EcouponCampaignId == item.Id).AsQueryable();//.OrderByDescending(e => e.SentDateTime).Skip(skip).Take(take);
                            Coupon = PagingService.Sorting<Coupon>(Coupon, pagingInfo.SortBy, pagingInfo.Reverse);
                            Coupon = Coupon.Skip(skip).Take(take);

                            if (Coupon != null)
                            {
                                foreach (var itemCoupon in Coupon)
                                {
                                    CouponDTO CouponDTO = new CouponDTO();
                                    if (itemCoupon.EcouponCampaignId == item.Id)
                                    {
                                        UserDTO UserDTO = new UserDTO();
                                        CouponDTO = Transform.CouponToDTO(itemCoupon);

                                        EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                                        EcouponCampaignDTO = EcouponCampaignService.GetById(itemCoupon.EcouponCampaignId);
                                        CouponDTO.CouponCampaignName = EcouponCampaignDTO.Title;
                                        CouponDTO.MinPurchaseAmount = EcouponCampaignDTO.MinPurchaseAmount;

                                        if (CouponDTO.UserId != null)
                                        {
                                            int UserId = (int)CouponDTO.UserId;
                                            UserDTO = UserService.GetById(UserId);
                                            CouponDTO.UserName = UserDTO.Name;
                                        }
                                        else
                                        {
                                            CouponDTO.UserName = "";
                                        }

                                        CouponDTOList.Add(CouponDTO);
                                        //CouponDTOList.Add(Transform.CouponToDTO(itemCoupon));
                                    }
                                }
                            }
                        }
                        if (search != "" & search != null)
                        {
                            EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                            EcouponCampaignDTO = EcouponCampaignService.GetById(EcouponCampaignId);
                            //int UserId = 0;
                            //UserId = UserService.GetUserByName(search,EcouponCampaignDTO.ClientId);
                            int CampaignId = 0;

                            string UserIdString = UserService.GetUserIdarrayByName(search, EcouponCampaignDTO.ClientId);

                            CampaignId = EcouponCampaignService.GetEcouponCampaignByName(search, EcouponCampaignDTO.ClientId);

                            bool Isdate = CommonService.IsDate(search);
                            if (Isdate != true)
                            {
                                List<CouponDTO> CouponDTOSearchList = new List<CouponDTO>();
                                IQueryable<Coupon> CouponSearch = uow.CouponRepo.GetAll().Where(e => (e.Code.Contains(search) || (e.MobileNumber != null ? (e.MobileNumber.Contains(search)) : false) || (e.Remark != null ? (e.Remark.ToLower().Contains(search.ToLower())) : false) || (e.RedeemDateTime.ToString() != null ? (Convert.ToDateTime(e.RedeemDateTime).ToString("dd-MMM-yyyy").ToLower().Contains(pagingInfo.Search.ToLower())) : false) || (UserIdString != null ? (e.UserId.ToString().Split(',').Any(UserId => UserIdString.Contains(UserId))) : false) || (e.EcouponCampaignId != 0 ? (e.EcouponCampaignId == CampaignId) : false) || (e.BillNumber != null ? (e.BillNumber.ToLower().Contains(pagingInfo.Search.ToLower())) : false) || (e.BillDate.ToString() != null ? (Convert.ToDateTime(e.BillDate).ToString("dd-MMM-yyyy").ToLower().Contains(pagingInfo.Search.ToLower())) : false)) && e.EcouponCampaignId == EcouponCampaignId).AsQueryable();//.OrderByDescending(e => e.SentDateTime).Skip(skip).Take(take); //|| e.UserName.ToLower().Contains(search.ToLower()) || (e.CouponCampaignName != null ? (e.CouponCampaignName.ToLower().Contains(search.ToLower())) : false)

                                CouponSearch = PagingService.Sorting<Coupon>(CouponSearch, pagingInfo.SortBy, pagingInfo.Reverse);
                                CouponSearch = CouponSearch.Skip(skip).Take(take);

                                if (CouponSearch != null)
                                {
                                    foreach (var itemsearch in CouponSearch)
                                    {
                                        if (itemsearch.EcouponCampaignId == EcouponCampaignId)
                                        {
                                            CouponDTO CouponDTO = new CouponDTO();
                                            CouponDTO = Transform.CouponToDTO(itemsearch);

                                            EcouponCampaignDTO EcouponCampaignDTOSearch = new EcouponCampaignDTO();
                                            EcouponCampaignDTOSearch = EcouponCampaignService.GetById(itemsearch.EcouponCampaignId);
                                            CouponDTO.CouponCampaignName = EcouponCampaignDTOSearch.Title;
                                            CouponDTO.MinPurchaseAmount = EcouponCampaignDTOSearch.MinPurchaseAmount;

                                            UserDTO UserDTO = new UserDTO();
                                            if (itemsearch.UserId == null)
                                            { itemsearch.UserId = 0; }
                                            int userId = (int)itemsearch.UserId;
                                            if (userId != 0)
                                            {
                                                UserDTO = UserService.GetById(userId);
                                                CouponDTO.UserName = UserDTO.Name;
                                            }
                                            CouponDTOSearchList.Add(CouponDTO);
                                        }
                                    }
                                }
                                return CouponDTOSearchList;

                            }
                            else
                            {
                                List<CouponDTO> CouponDTOSearchList = new List<CouponDTO>();
                                DateTime date = Convert.ToDateTime(search);
                                IQueryable<Coupon> CouponSearch = uow.CouponRepo.GetAll().Where(e => (e.RedeemDateTime >= date && e.RedeemDateTime < date.AddDays(1) && e.BillDate >= date && e.BillDate < date.AddDays(1)) && e.EcouponCampaignId == EcouponCampaignId).AsQueryable();//.OrderByDescending(e => e.SentDateTime).Skip(skip).Take(take);
                                CouponSearch = PagingService.Sorting<Coupon>(CouponSearch, pagingInfo.SortBy, pagingInfo.Reverse);
                                CouponSearch = CouponSearch.Skip(skip).Take(take);

                                if (CouponSearch != null)
                                {
                                    foreach (var itemsearch in CouponSearch)
                                    {
                                        if (itemsearch.EcouponCampaignId == EcouponCampaignId)
                                        {
                                            CouponDTO CouponDTO = new CouponDTO();
                                            CouponDTO = Transform.CouponToDTO(itemsearch);
                                            UserDTO UserDTO = new UserDTO();

                                            EcouponCampaignDTO EcouponCampaignDTOSearch = new EcouponCampaignDTO();
                                            EcouponCampaignDTOSearch = EcouponCampaignService.GetById(itemsearch.EcouponCampaignId);
                                            CouponDTO.CouponCampaignName = EcouponCampaignDTOSearch.Title;
                                            CouponDTO.MinPurchaseAmount = EcouponCampaignDTOSearch.MinPurchaseAmount;

                                            if (itemsearch.UserId == null)
                                            { itemsearch.UserId = 0; }

                                            int userId = (int)itemsearch.UserId;
                                            if (userId != 0)
                                            {
                                                UserDTO = UserService.GetById(userId);
                                                CouponDTO.UserName = UserDTO.Name;
                                            }
                                            CouponDTOSearchList.Add(CouponDTO);
                                        }

                                        //CouponDTOSearchList.Add(Transform.CouponToDTO(itemsearch));
                                    }
                                }
                                return CouponDTOSearchList;

                            }

                        }

                    }

                }

                return CouponDTOList;
            }
            //catch (LoggedInUserException)
            //{
            //    throw new System.TimeoutException();
            //}
            catch (Exception)
            {

                throw;
            }
        }
        //Get coupon as per Mobile and code
        public static CouponDTO GetCouponDetailsFromMobileAndCode(string Mobile, string Code)
        {
            try
            {
                CouponDTO CouponDTO = new CouponDTO();
                EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();

                using (var uow = new UnitOfWork())
                {
                    IEnumerable<Coupon> Coupon = uow.CouponRepo.GetAll().Where(e => e.MobileNumber == Mobile && e.Code == Code);
                    if (Coupon != null)
                    {
                        foreach (var item in Coupon)
                        {
                            CouponDTO = GetById(item.Id);

                        }

                        if (CouponDTO.Id != 0)
                        {
                            EcouponCampaignDTO = EcouponCampaignService.GetById(CouponDTO.EcouponCampaignId);
                            CouponDTO.CouponCampaignName = EcouponCampaignDTO.Title;
                            CouponDTO.ExpiresOn = EcouponCampaignDTO.ExpiresOn;
                            CouponDTO.MinPurchaseAmount = EcouponCampaignDTO.MinPurchaseAmount;
                        }
                    }

                }
                return CouponDTO;
            }
            catch (Exception)
            {
                throw;
            }
        }
        //Return Coupon list as per user id
        public static List<CouponDTO> GetCouponListByUserId(int UserId, PagingInfo pagingInfo)
        {
            List<CouponDTO> CouponDTOList = new List<CouponDTO>();
            try
            {
                UserDTO UserDTO = new UserDTO();
                UserDTO = UserService.GetById(UserId);

                using (var uow = new UnitOfWork())
                {
                    int skip = (pagingInfo.Page - 1) * pagingInfo.ItemsPerPage;
                    int take = pagingInfo.ItemsPerPage;

                    IQueryable<Coupon> Coupon = uow.CouponRepo.GetAll().Where(e => e.UserId == UserId && e.IsExpired != true && e.IsRedeem == true).AsQueryable(); //.OrderByDescending(e => e.SentDateTime);
                    Coupon = PagingService.Sorting<Coupon>(Coupon, pagingInfo.SortBy, pagingInfo.Reverse);
                    Coupon = Coupon.Skip(skip).Take(take);

                    if (Coupon != null)
                    {
                        foreach (var item in Coupon)
                        {

                            CouponDTO CouponDTO = new CouponDTO();
                            CouponDTO = Transform.CouponToDTO(item);
                            CouponDTO.UserName = UserDTO.Name;

                            EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                            EcouponCampaignDTO = EcouponCampaignService.GetById(CouponDTO.EcouponCampaignId);
                            CouponDTO.CouponCampaignName = EcouponCampaignDTO.Title;
                            CouponDTO.ExpiresOn = EcouponCampaignDTO.ExpiresOn;
                            CouponDTO.MinPurchaseAmount = EcouponCampaignDTO.MinPurchaseAmount;

                            CouponDTOList.Add(CouponDTO);// (Transform.CouponToDTO(item));
                        }
                    }

                    if (pagingInfo.Search != "" && pagingInfo.Search != null)
                    {

                        bool Isdate = CommonService.IsDate(pagingInfo.Search);
                        if (Isdate != true)
                        {

                            IQueryable<CouponDTO> CouponList = CouponDTOList.Where(e => e.CouponCampaignName.ToLower().Contains(pagingInfo.Search.ToLower()) || (e.MobileNumber != null ? (e.MobileNumber.Contains(pagingInfo.Search)) : false) || (e.Amount != null ? (e.Amount.ToString() == pagingInfo.Search.ToString()) : false) || (e.Code != null ? (e.Code.Contains(pagingInfo.Search)) : false) || (e.Message != null ? (e.Message.ToLower().Contains(pagingInfo.Search.ToLower())) : false) || (e.RedeemDateTime.ToString() != null ? (Convert.ToDateTime(e.RedeemDateTime).ToString("dd-MMM-yyyy").ToLower().Contains(pagingInfo.Search.ToLower())) : false) || (e.Remark != null ? (e.Remark.ToLower().Contains(pagingInfo.Search.ToLower())) : false) || (e.BillNumber != null ? (e.BillNumber.ToLower().Contains(pagingInfo.Search.ToLower())) : false) || (e.BillDate.ToString() != null ? (Convert.ToDateTime(e.BillDate).ToString("dd-MMM-yyyy").ToLower().Contains(pagingInfo.Search.ToLower())) : false)).AsQueryable();//.OrderByDescending(e => e.SentDateTime).ToList();
                            CouponList = PagingService.Sorting<CouponDTO>(CouponList, pagingInfo.SortBy, pagingInfo.Reverse);
                            CouponList = CouponList.Skip(skip).Take(take);

                            List<CouponDTO> CouponDTOListNew = new List<CouponDTO>();
                            if (CouponDTOList.Count > 0)
                            {
                                foreach (var item in CouponList)
                                {
                                    EcouponCampaignDTO EcouponCampaignDTOSearch = new EcouponCampaignDTO();
                                    EcouponCampaignDTOSearch = EcouponCampaignService.GetById(item.EcouponCampaignId);
                                    item.CouponCampaignName = EcouponCampaignDTOSearch.Title;
                                    item.ExpiresOn = EcouponCampaignDTOSearch.ExpiresOn;
                                    item.MinPurchaseAmount = EcouponCampaignDTOSearch.MinPurchaseAmount;

                                    CouponDTOListNew.Add(item);
                                }
                                return CouponDTOListNew;
                            }

                        }
                        else
                        {
                            List<CouponDTO> CouponDTOListNew = new List<CouponDTO>();
                            DateTime date = Convert.ToDateTime(pagingInfo.Search);
                            IQueryable<CouponDTO> CouponList = CouponDTOList.Where(e => e.RedeemDateTime >= date && e.RedeemDateTime < date.AddDays(1) && e.BillDate >= date && e.BillDate < date.AddDays(1)).AsQueryable();//.OrderByDescending(e => e.SentDateTime).ToList();
                            CouponList = PagingService.Sorting<CouponDTO>(CouponList, pagingInfo.SortBy, pagingInfo.Reverse);
                            CouponList = CouponList.Skip(skip).Take(take);
                            if (CouponDTOList.Count > 0)
                            {
                                foreach (var item in CouponList)
                                {
                                    EcouponCampaignDTO EcouponCampaignDTOSearch = new EcouponCampaignDTO();
                                    EcouponCampaignDTOSearch = EcouponCampaignService.GetById(item.EcouponCampaignId);
                                    item.CouponCampaignName = EcouponCampaignDTOSearch.Title;
                                    item.ExpiresOn = EcouponCampaignDTOSearch.ExpiresOn;
                                    item.MinPurchaseAmount = EcouponCampaignDTOSearch.MinPurchaseAmount;

                                    CouponDTOListNew.Add(item);
                                }
                                return CouponDTOListNew;
                            }
                        }

                    }

                }

                return CouponDTOList;
            }
            //catch (LoggedInUserException)
            //{
            //    throw new System.TimeoutException();
            //}
            catch (Exception)
            {

                throw;
            }
        }
        //Return Coupon redeemed list as per client
        public static List<CouponDTO> GetCouponListByClientIdWithRedeem(int ClientId)
        {
            List<CouponDTO> CouponDTOList = new List<CouponDTO>();

            try
            {

                using (var uow = new UnitOfWork())
                {
                    IEnumerable<EcouponCampaign> EcouponCampaign = uow.EcouponCampaignRepo.GetAll().Where(e => e.ClientId == ClientId);
                    //var EcouponCampaigncoupons = from c in EcouponCampaign where (from g in c.Coupons where c.ClientId == ClientId  select g).Any() select c;

                    if (EcouponCampaign != null)
                    {
                        foreach (var item in EcouponCampaign)
                        {
                            IEnumerable<Coupon> Coupon = uow.CouponRepo.GetAll().Where(e => e.EcouponCampaignId == item.Id && e.IsRedeem == true);
                            if (Coupon != null)
                            {
                                foreach (var itemCoupon in Coupon)
                                {
                                    CouponDTO CouponDTO = new CouponDTO();
                                    if (itemCoupon.EcouponCampaignId == item.Id)
                                    {
                                        UserDTO UserDTO = new UserDTO();
                                        CouponDTO = Transform.CouponToDTO(itemCoupon);
                                        if (CouponDTO.UserId != null)
                                        {
                                            int UserId = (int)CouponDTO.UserId;
                                            UserDTO = UserService.GetById(UserId);
                                            CouponDTO.UserName = UserDTO.Name;
                                        }
                                        else { CouponDTO.UserName = ""; }
                                        CouponDTOList.Add(CouponDTO);
                                        // CouponDTOList.Add(Transform.CouponToDTO(itemCoupon));
                                    }
                                }
                            }
                        }

                    }
                }

                return CouponDTOList;
            }
            //catch (LoggedInUserException)
            //{
            //    throw new System.TimeoutException();
            //}
            catch (Exception)
            {

                throw;
            }
        }
        //Resend coupon by coupon id and client id
        public static CouponDTO ResendCoupon(int CouponId, int ClientId)
        {
            try
            {
                CouponDTO CouponDTO = new CouponDTO();
                CouponDTO = GetById(CouponId);

                ClientDTO ClientDTO = new ClientDTO();
                ClientDTO = ClientService.GetById(ClientId);

                SettingDTO SettingDTO = new SettingDTO();
                SettingDTO = SettingService.GetById(1);
                double RequiredCredit = CommonService.GetMessageCount(CouponDTO.Message);
                double ActualRequiredCredits = RequiredCredit * SettingDTO.NationalCouponSMSCount;

                if (ClientDTO.SMSCredit >= ActualRequiredCredits) //RequiredCredit
                {

                    // Send Direct SMS
                    //bool IsSent = CommonService.ResendCoupon(CouponDTO.MobileNumber, CouponDTO.Message, ClientDTO.Id);

                    CouponDTO CouponDTONew = new CouponDTO();
                    CouponDTONew = CommonService.ResendCouponByCouponDTOAndClientId(CouponDTO, ClientDTO.Id);
                    return CouponDTONew;

                    //if (IsSent == true)
                    //{
                        //CouponDTO.SentDateTime = System.DateTime.Now;
                        //CouponDTO.Id = 0;
                        //int NewCouponId = Create(CouponDTO);
                        //CouponDTO CouponDTONew = new CouponDTO();
                        //CouponDTONew = GetById(NewCouponId);

                        //////Expire previous coupon
                        //CouponDTO CouponDTOPrevious = new CouponDTO();
                        //CouponDTOPrevious = GetById(CouponId);
                        //CouponDTOPrevious.IsExpired = true;
                        //Edit(CouponDTOPrevious);

                        ////// Modify EcouponCampaign message count
                        //EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                        //EcouponCampaignDTO = EcouponCampaignService.GetById(CouponDTONew.EcouponCampaignId);
                        //EcouponCampaignDTO.ReceipentNumber = EcouponCampaignDTO.ReceipentNumber + "," + CouponDTO.MobileNumber;
                        //EcouponCampaignDTO.RecipientsCount = EcouponCampaignDTO.RecipientsCount + 1;
                        //if (EcouponCampaignDTO.GroupId == 0)
                        //{
                        //    EcouponCampaignDTO.GroupId = null;
                        //    EcouponCampaignDTO.Group = null;
                        //}

                        //EcouponCampaignDTO.RequiredCredits = GetECouponCampaignRequiredCreditsByEcouponCampaignId(EcouponCampaignDTO.Id);

                        //EcouponCampaignService.EditForEcouponResend(EcouponCampaignDTO);

                        //////Modify client SMS credits
                        //ClientDTO.SMSCredit = ClientDTO.SMSCredit - ActualRequiredCredits;// RequiredCredit;
                        //ClientService.Edit(ClientDTO);

                        //return CouponDTONew;
                    //}
                    //else
                    //{
                    //    CouponDTO = null;
                    //    return CouponDTO;
                    //}
                }
                CouponDTO = null;
                return CouponDTO;
            }
            catch
            {
                throw;
            }
        }
        //int Id,
        //Redeem Coupon
        public static CouponDTO RedeemCoupon(CouponDTO CouponDTO)
        {
            try
            {
                CouponDTO CouponDTONew = new CouponDTO();
                List<CouponDTO> CouponDTOList = new List<CouponDTO>();

                 using (var uow = new UnitOfWork())
                 {
                    List<Coupon> CouponList = new List<Coupon>();
                    CouponList = uow.CouponRepo.GetAll().Where(e => e.EcouponCampaignId == CouponDTO.EcouponCampaignId && e.MobileNumber == CouponDTO.MobileNumber && e.Code == CouponDTO.Code).ToList();

                    if (CouponList != null)
                    {
                        foreach (var item in CouponList)
                        {
                            CouponDTOList.Add(Transform.CouponToDTO(item));
                        }
                    }
                 }

               // CouponDTOList = GetCouponListByClientId(CouponDTO.ClientId);
                //IEnumerable<CouponDTO> CouponDTOSearch = CouponDTOList.Where(e => e.MobileNumber == CouponDTO.MobileNumber && e.Code == CouponDTO.Code); // && e.IsRedeem == false
                 IEnumerable<CouponDTO> CouponDTOSearch = CouponDTOList;

                foreach (var item in CouponDTOSearch)
                {
                    CouponDTONew = item;
                }

                if (CouponDTONew.Id != 0 && CouponDTONew.IsExpired != true && CouponDTONew.IsRedeem != true)
                {

                    CouponDTONew.IsRedeem = true;
                    CouponDTONew.Remark = CouponDTO.Remark;
                    CouponDTONew.UserId = CouponDTO.UserId;
                    CouponDTONew.Amount = CouponDTO.Amount;
                    CouponDTONew.RedeemDateTime = System.DateTime.Now;
                    CouponDTONew.BillDate = CouponDTO.BillDate;
                    CouponDTONew.BillNumber = CouponDTO.BillNumber;

                    UnitOfWork uow = new UnitOfWork();
                    Coupon Coupon = Transform.CouponToDomain(CouponDTONew);
                    uow.CouponRepo.Update(Coupon);
                    uow.SaveChanges();

                    EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                    EcouponCampaignDTO = EcouponCampaignService.GetById(Coupon.EcouponCampaignId);
                    ClientDTO ClientDTO = new ClientDTO();
                    ClientDTO = ClientService.GetById(EcouponCampaignDTO.ClientId);

                    UpdateRedeemCount(Convert.ToInt32(Coupon.UserId), ClientDTO.Id, Coupon.EcouponCampaignId);

                }

                return CouponDTONew;
            }
            catch
            {
                throw;
            }
        }
        public static CouponDTO ResendCouponByCouponDTOAndClientId(CouponDTO CouponDTO, int ClientId)
        {
            SettingDTO SettingDTO = new SettingDTO();
            SettingDTO = SettingService.GetById(1);
            double RequiredCredit = CommonService.GetMessageCount(CouponDTO.Message);
            double ActualRequiredCredits = RequiredCredit * SettingDTO.NationalCouponSMSCount;
            int OldId = 0;

            OldId = CouponDTO.Id;
            CouponDTO CouponDTONew = new CouponDTO();
            CouponDTONew = null;

            string result = "";
            bool IsSent = false;
            if (CouponDTO.Message != "" && CouponDTO.MobileNumber != "")// Check for empty message.
            {
                ClientDTO ClientDTO = new ClientDTO();
                ClientDTO = ClientService.GetById(ClientId);
                string Url = null;

                if (ClientDTO.SenderCode != null && ClientDTO.SenderCode != "")
                {
                    Url = ConfigurationManager.AppSettings["TransactionalGateWay"].ToString();
                }
                else
                {

                    Url = ConfigurationManager.AppSettings["PromotionalGateWay"].ToString();
                }

                Url = Url.Replace("%26", "&");
                Url = Url.Replace("[recipient]", CouponDTO.MobileNumber);
                Url = Url.Replace("[message]", CouponDTO.Message);
                Url = Url.Replace("[gateway]", ClientDTO.SenderCode);   //SMSGatewayDTO.Name

                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
                myRequest.Method = "GET";
                WebResponse myResponse = myRequest.GetResponse();
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
                result = sr.ReadToEnd();
                sr.Close();

                string statuscode = "";
                if (result.Contains('|'))
                    statuscode = result.Substring(0, result.IndexOf('|'));
                else
                    statuscode = result;

                SMSResult(result);
                myResponse.Close();

                if (statuscode == "1701" || statuscode == "1705" || statuscode == "1706" || statuscode == "1032")
                {
                    IsSent = true;

                    CouponDTO.SentDateTime = System.DateTime.Now;
                    CouponDTO.Id = 0;
                    CouponDTO.IsExpired = false;
                    int NewCouponId = CouponService.Create(CouponDTO);

                    CouponDTONew = CouponService.GetById(NewCouponId);

                    //Expire previous coupon
                    CouponDTO CouponDTOPrevious = new CouponDTO();
                    CouponDTOPrevious = CouponService.GetById(OldId);
                    CouponDTOPrevious.IsExpired = true;
                    CouponDTOPrevious.MessageId = result;
                    CouponService.Edit(CouponDTOPrevious);

                    // Modify EcouponCampaign message count
                    EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                    EcouponCampaignDTO = EcouponCampaignService.GetById(CouponDTONew.EcouponCampaignId);
                    EcouponCampaignDTO.ReceipentNumber = EcouponCampaignDTO.ReceipentNumber + "," + CouponDTO.MobileNumber;
                    EcouponCampaignDTO.RecipientsCount = EcouponCampaignDTO.RecipientsCount + 1;
                    if (EcouponCampaignDTO.GroupId == 0)
                    {
                        EcouponCampaignDTO.GroupId = null;
                        EcouponCampaignDTO.Group = null;
                    }

                    EcouponCampaignDTO.RequiredCredits = CouponService.GetECouponCampaignRequiredCreditsByEcouponCampaignId(EcouponCampaignDTO.Id);

                    EcouponCampaignService.EditForEcouponResend(EcouponCampaignDTO);

                    //Modify client SMS credits
                    ClientDTO.SMSCredit = ClientDTO.SMSCredit - ActualRequiredCredits;// RequiredCredit;
                    ClientService.Edit(ClientDTO);

                }
                else
                {
                    IsSent = false;

                    string UrlWhiz = "";
                    string resultWhiz = "";
                    if (ClientDTO.SenderCode != null && ClientDTO.SenderCode != "")
                    {
                        UrlWhiz = ConfigurationManager.AppSettings["TransactionalGateWayWhiz"].ToString();
                    }
                    else
                    {

                        UrlWhiz = ConfigurationManager.AppSettings["PromotionalGateWayWhiz"].ToString();
                    }

                    UrlWhiz = UrlWhiz.Replace("%26", "&");
                    UrlWhiz = UrlWhiz.Replace("[recipient]", CouponDTO.MobileNumber);
                    UrlWhiz = UrlWhiz.Replace("[message]", CouponDTO.Message);
                    UrlWhiz = UrlWhiz.Replace("[gateway]", ClientDTO.SenderCode);   //SMSGatewayDTO.Name

                    HttpWebRequest myRequesWhiz = (HttpWebRequest)WebRequest.Create(UrlWhiz);
                    myRequesWhiz.Method = "GET";
                    WebResponse myResponseWhiz = myRequesWhiz.GetResponse();
                    StreamReader srWhiz = new StreamReader(myResponseWhiz.GetResponseStream(), System.Text.Encoding.UTF8);
                    resultWhiz = srWhiz.ReadToEnd();
                    srWhiz.Close();

                    if (resultWhiz.Contains('|'))
                    {
                        //statuscode = result.Substring(0, result.IndexOf('|'));
                        statuscode = "";
                        string[] words = resultWhiz.Split('|');
                        foreach (string word in words)
                        {
                            Console.WriteLine(word);
                            try
                            {
                                int code = Convert.ToInt32(word);

                                statuscode = code.ToString();
                            }
                            catch (Exception)
                            {
                                string code = word.Replace(" ", "");
                                if (code == "Success")
                                {
                                    code = "0";
                                    statuscode = code.ToString();
                                    IsSent = true;

                                    CouponDTO.SentDateTime = System.DateTime.Now;
                                    CouponDTO.Id = 0;
                                    CouponDTO.IsExpired = false;
                                    int NewCouponId = CouponService.Create(CouponDTO);

                                    CouponDTONew = CouponService.GetById(NewCouponId);

                                    //Expire previous coupon
                                    CouponDTO CouponDTOPrevious = new CouponDTO();
                                    CouponDTOPrevious = CouponService.GetById(OldId);
                                    CouponDTOPrevious.IsExpired = true;
                                    CouponDTOPrevious.MessageId = resultWhiz;
                                    CouponService.Edit(CouponDTOPrevious);

                                    // Modify EcouponCampaign message count
                                    EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                                    EcouponCampaignDTO = EcouponCampaignService.GetById(CouponDTONew.EcouponCampaignId);
                                    EcouponCampaignDTO.ReceipentNumber = EcouponCampaignDTO.ReceipentNumber + "," + CouponDTO.MobileNumber;
                                    EcouponCampaignDTO.RecipientsCount = EcouponCampaignDTO.RecipientsCount + 1;
                                    if (EcouponCampaignDTO.GroupId == 0)
                                    {
                                        EcouponCampaignDTO.GroupId = null;
                                        EcouponCampaignDTO.Group = null;
                                    }

                                    EcouponCampaignDTO.RequiredCredits = CouponService.GetECouponCampaignRequiredCreditsByEcouponCampaignId(EcouponCampaignDTO.Id);

                                    EcouponCampaignService.EditForEcouponResend(EcouponCampaignDTO);

                                    //Modify client SMS credits
                                    ClientDTO.SMSCredit = ClientDTO.SMSCredit - ActualRequiredCredits;// RequiredCredit;
                                    ClientService.Edit(ClientDTO);

                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }

                    }
                    else
                    {
                        statuscode = resultWhiz;

                    }

                }
            }
            return CouponDTONew;
        }
 public CouponDTO RedeemCoupon(CouponDTO CouponDTO)
 {
     try
     {
         //return CouponService.RedeemCoupon(Id, Remark, ClientUserId);
         return CouponService.RedeemCoupon(CouponDTO);
     }
     catch (TimeoutException)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.RequestTimeout)
         {
             Content = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
     catch (Exception)
     {
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
         {
             Content = new StringContent("An error occurred, please try again or contact the administrator."),
             ReasonPhrase = "Critical Exception"
         });
     }
 }
        //Return Coupon list as per mobile and Client id
        public static List<CouponDTO> GetMobileNumberAndClientIdWiseCouponList(String Mobile, int ClientId)
        {
            List<CouponDTO> CouponDTODTOList = new List<CouponDTO>();
            try
            {
                UnitOfWork uow = new UnitOfWork();
                IEnumerable<Coupon> Coupon = uow.CouponRepo.GetAll().Where(e => (e.MobileNumber.Equals(Mobile) && e.IsExpired != true && e.IsRedeem != true));
                if (Coupon != null)
                {
                    foreach (var item in Coupon)
                    {
                        CouponDTO CouponDTO = new CouponDTO();
                        CouponDTO = Transform.CouponToDTO(item);
                        EcouponCampaignDTO EcouponCampaignDTO = new EcouponCampaignDTO();
                        EcouponCampaignDTO = EcouponCampaignService.GetById(CouponDTO.EcouponCampaignId);
                        CouponDTO.CouponCampaignName = EcouponCampaignDTO.Title;
                        CouponDTO.Message = EcouponCampaignDTO.Message;
                        if (EcouponCampaignDTO.ClientId == ClientId)
                        {
                            CouponDTODTOList.Add(CouponDTO);
                        }
                    }
                }

                return CouponDTODTOList;
            }
            catch
            {
                throw;
            }
        }