//Edit partner
        public static void Edit(PartnerDTO PartnerDTO)
        {
            try
            {
                GlobalSettings.LoggedInPartnerId = PartnerDTO.Id;

                UnitOfWork uow = new UnitOfWork();
                Partner Partner = Transform.PartnerToDomain(PartnerDTO);
                uow.PartnerRepo.Update(Partner);
                uow.SaveChanges();
            }
            catch
            {
                throw;
            }
        }
 public void Edit(string accessId, PartnerDTO PartnerDTO)
 {
     try
     {
         PartnerService.Edit(PartnerDTO);
     }
     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"
         });
     }
 }
 //Get login details by email
 public static bool ForgotPassword(string Email)
 {
     try
     {
         UnitOfWork uow = new UnitOfWork();
         PartnerDTO PartnerDTO = new PartnerDTO();
         IEnumerable<Partner> Partner = uow.PartnerRepo.GetAll().Where(e => e.Email.ToLower() == Email.ToLower());
         if (Partner.ToList().Count > 0)
         {
             foreach (var item in Partner)
             {
                 PartnerDTO = Transform.PartnerToDTO(item);
             }
             CommonService.SendEmail("msgBlaster Credentials", "Hello " + PartnerDTO.Name + ", <br/><br/> <p>Your msgBlaster username and password is as follows - </p> <br/> <table><tr><td> Username</td><td> = " + PartnerDTO.Email + "</td></tr><tr><td>Password</td><td> = " + PartnerDTO.Password + "</td></tr></table>", PartnerDTO.Email, "", false);
             return true;
         }
         else return false;
     }
     catch
     {
         throw;
     }
 }
        //Partner sign in by using email and password
        public static PartnerDTO SignIn(string Email, string Password)
        {
            try
            {
                PartnerDTO PartnerDTO = new PartnerDTO();
                List<PartnerDTO> PartnerDTOList = new List<PartnerDTO>();

                UnitOfWork uow = new UnitOfWork();
                IEnumerable<Partner> Partner = uow.PartnerRepo.GetAll().Where(e => e.Email.ToLower() == Email.ToLower() && e.Password == Password);
                if (Partner != null)
                {
                    foreach (var item in Partner)
                    {
                        PartnerDTO = Transform.PartnerToDTO(item);
                        GlobalSettings.LoggedInPartnerId = PartnerDTO.Id;
                    }
                }
                return PartnerDTO;
            }
            catch
            {
                throw;
            }
        }
        //Returns Campaign list as per partner and search
        public static List<CampaignDTO> GetCampaignsbyPartnerId(int PartnerId, string search, PagingInfo pagingInfo)
        {
            List<CampaignDTO> CampaignDTO = new List<CampaignDTO>();
            List<Client> Clients = new List<Client>();

            int skip = (pagingInfo.Page - 1) * pagingInfo.ItemsPerPage;
            int take = pagingInfo.ItemsPerPage;

            try
            {
                UnitOfWork uow = new UnitOfWork();
                IEnumerable<Client> Client = uow.ClientRepo.GetAll().Where(e => e.PartnerId == PartnerId).ToList();

                if (Client != null)
                {
                    foreach (var itemClient in Client)
                    {
                        PartnerDTO PartnerDTO = new PartnerDTO();
                        PartnerDTO = PartnerService.GetById(PartnerId);
                        itemClient.Partner = Transform.PartnerToDomain(PartnerDTO);
                        Clients.Add(itemClient);
                    }

                    List<CampaignDTO> CampaignsDTO = new List<CampaignDTO>();
                    if (Clients != null)
                    {
                        foreach (var itemCampaign in Clients)
                        {
                            CampaignsDTO = GetCampaignListByClientId(itemCampaign.Id);
                        }

                        var Campaign = uow.CampaignRepo.GetAll().OrderByDescending(e => e.CreatedDate).ToList().Skip(skip).Take(take);// uow.CampaignRepo.GetAll().Where(e => e.Client.PartnerId == PartnerId).ToList();

                        if (Campaign != null)
                        {
                            if (search != "" && search != null)
                            {

                                bool IsDate = CommonService.IsDate(search);
                                if (IsDate != true)
                                {
                                    // string search
                                    var Campaignsearch = uow.CampaignRepo.GetAll().Where(e => e.Name.ToLower().Contains(search.ToLower()) || e.RecipientsNumber.Contains(search) || e.RequiredCredits.ToString() == (search) || (e.ScheduledDate.ToString() != null ? (Convert.ToDateTime(e.ScheduledDate).ToString("dd-MMM-yyyy").ToLower().Contains(pagingInfo.Search.ToLower())) : false)).OrderByDescending(e => e.CreatedDate).Skip(skip).Take(take);

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

                                            CampaignDTO.Add(Transform.CampaignToDTO(item));
                                        }
                                    }
                                    return CampaignDTO;
                                }
                                else
                                {
                                    //date wise search
                                    DateTime date = Convert.ToDateTime(search);
                                    var Campaignsearch = uow.CampaignRepo.GetAll().Where(e => e.CreatedDate >= date && e.CreatedDate < date.AddDays(1) || e.ScheduledDate >= date && e.ScheduledDate < date.AddDays(1)).OrderByDescending(e => e.CreatedDate).Skip(skip).Take(take);

                                    if (Campaignsearch != null)
                                    {
                                        foreach (var item in Campaignsearch)
                                        {
                                            CampaignDTO.Add(Transform.CampaignToDTO(item));
                                        }
                                    }
                                    return CampaignDTO;

                                }

                            }
                            else
                            {

                                foreach (var item in Campaign)
                                {
                                    CampaignDTO.Add(Transform.CampaignToDTO(item));
                                }
                            }
                        }

                    }

                }

                return CampaignDTO;
            }
            catch (Exception)
            {

                throw;
            }
        }
        //Create credit request
        public static CreditRequestDTO Create(CreditRequestDTO CreditRequestDTO)
        {
            try
            {
                CreditRequestDTO CreditRequestDTONew = new CreditRequestDTO();

                PartnerDTO PartnerDTO = new PartnerDTO();
                ClientDTO ClientDTO = new ClientDTO();
                UserDTO UserDTO = new UserDTO();

                PartnerDTO = PartnerService.GetById(CreditRequestDTO.PartnerId);
                ClientDTO = ClientService.GetById(CreditRequestDTO.ClientId);
                UserDTO = UserService.GetById(CreditRequestDTO.RequestedBy);

                GlobalSettings.LoggedInClientId = ClientDTO.Id;
                GlobalSettings.LoggedInUserId = UserDTO.Id;
                int PartnerId = PartnerDTO.Id;
                GlobalSettings.LoggedInPartnerId = PartnerId;

                if (CreditRequestDTO.RequestedCredit <= 0)
                {
                    return null; //0
                }
                var CreditRequest = new CreditRequest();
                using (var uow = new UnitOfWork())
                {
                    CreditRequest = Transform.CreditRequestToDomain(CreditRequestDTO);
                    CreditRequest.Date = System.DateTime.Now;
                    CreditRequest.OldBalance = ClientDTO.SMSCredit;
                    CreditRequest.IsProvided = false;
                    //CreditRequest.ProvidedCredit = CreditRequest.RequestedCredit;
                    CreditRequest.Amount = CreditRequest.RequestedCredit * CreditRequest.RatePerSMS;
                    double tax = (CreditRequest.Amount * Convert.ToDouble(CreditRequest.Tax)) / 100;
                    CreditRequest.TaxAmount = tax;
                    CreditRequest.GrandTotal = CreditRequest.Amount + tax;

                    bool IsOnlinepaymentSuccess = Onlinepayment(CreditRequest.GrandTotal);

                    if (IsOnlinepaymentSuccess == true)
                    {
                        //CreditRequest.IsPaymentSuccessful = true;
                        //CreditRequest.PaymentDate = System.DateTime.Now;
                        CreditRequest.ProvidedDate = System.DateTime.Now;
                        CreditRequest.IsProvided = true;
                        CreditRequest.IsBillGenerated = true;
                        CreditRequest.PaymentMode = PaymentMode.Card;
                        CreditRequest.PaymentDate = System.DateTime.Now;
                        CreditRequest.IsPaid = true;
                        CreditRequest.ProvidedCredit = CreditRequest.RequestedCredit;

                        uow.CreditRequestRepo.Insert(CreditRequest);
                        uow.SaveChanges();

                        ClientDTO.SMSCredit = ClientDTO.SMSCredit + CreditRequest.RequestedCredit;
                        ClientService.Edit(ClientDTO);

                    }
                    else
                    {
                        //CreditRequest.IsPaymentSuccessful = false;
                        CreditRequest.IsPaid = false;
                        uow.CreditRequestRepo.Insert(CreditRequest);
                        uow.SaveChanges();
                    }

                    //Update TotalAppliedCredit
                    ClientDTO.TotalAppliedCredit = ClientDTO.TotalAppliedCredit + CreditRequest.RequestedCredit;
                    ClientService.Edit(ClientDTO);

                    //Generate Link to provide mail trhough mail
                    string APILink = ConfigurationManager.AppSettings["APILink"].ToString() + "api/CreditRequest/ProvideCreditByMailLink?CreditRequestId=" + CreditRequest.Id;

                    // Send Email To Partner
                    bool IsMailSent = CommonService.SendEmail("SMS Credit Request", "Hello " + PartnerDTO.Name + ", <br/><br/> The New request of " + CreditRequest.RequestedCredit + " credits applied by " + ClientDTO.Company + "<br/><br/> <a href=" + APILink + ">Approve</a>", PartnerDTO.Email, "", false);

                    CreditRequestDTONew = GetById(CreditRequest.Id);
                    if (CreditRequest.PaymentMode == PaymentMode.Card)
                    {
                        CreditRequestDTONew.OnlinePaymentURL = OnlinePaymentLinkWithTemperproofData(UserDTO.Email, CreditRequest.GrandTotal, UserDTO.Mobile, UserDTO.Name, CreditRequest.Id);
                    }
                    return (CreditRequestDTONew); //.Id);

                }

            }
            //catch (LoggedInUserException)
            //{
            //    throw new System.TimeoutException();
            //}
            catch (Exception)
            {
                throw;
            }
        }
 public static Partner PartnerToDomain(PartnerDTO PartnerDTO)
 {
     if (PartnerDTO == null) return null;
      Mapper.CreateMap<PartnerDTO, Partner>();
      Partner Partner = Mapper.Map<Partner>(PartnerDTO);
      return Partner;
 }
        //Upload Sender code document to the server
        public static string UploadSenderCodeDocument(HttpPostedFile file, string documentPath, int ClientId, string FileName)
        {
            try
            {
                var b = new byte[file.ContentLength];
                string result = "";
                documentPath = documentPath + ClientId; //"\\" + ModuleName
                MemoryStream ms = new MemoryStream(b);
                // MemoryStream ms = new MemoryStream(file.ContentLength);
                bool IsExists = System.IO.Directory.Exists(documentPath);
                if (IsExists == false)
                {
                    System.IO.Directory.CreateDirectory(documentPath);
                }

                var path = System.IO.Path.Combine(documentPath, FileName); //file.FileName

                if (File.Exists(path))
                {
                    result = "File already Exists";
                    return result;
                }
                else
                {
                    file.SaveAs(documentPath + "/" + FileName); //file.FileName
                    ms.Close();

                    ClientDTO ClientDTO = new ClientDTO();
                    ClientDTO = ClientService.GetById(ClientId);
                    ClientDTO.SenderCodeFilePath = ClientId + "/" + FileName;// file.FileName;
                    ClientService.Edit(ClientDTO);
                    result = "File uploaded successfully";

                    // Send Mail to Admin
                    PartnerDTO PartnerDTO = new PartnerDTO();
                    PartnerDTO = PartnerService.GetById(ClientDTO.PartnerId);
                    CommonService.SendEmail("New sendercode application request", "<HTML><BODY><P>Hello " + CommonService.GetFirstname(PartnerDTO.Name) + "</P><P>" + ClientDTO.Company + " has requested for new sender code.</P></BODY></HTML>", PartnerDTO.Email, "", false);
                    return result;

                }
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
        //Delete sender code document
        public static bool DeleteSenderCodeDocument(string filePath, int ClientId)
        {
            try
            {
                if (File.Exists(filePath))
                {

                    File.Delete(filePath);
                    ClientDTO ClientDTO = new ClientDTO();
                    ClientDTO = GetById(ClientId);
                    ClientDTO.SenderCodeFilePath = null;

                    GlobalSettings.LoggedInClientId = ClientDTO.Id;
                    int PartnerId = ClientService.GetById(ClientDTO.Id).PartnerId;
                    GlobalSettings.LoggedInPartnerId = PartnerId;

                    Edit(ClientDTO);

                    // Send Mail to Admin
                    PartnerDTO PartnerDTO = new PartnerDTO();
                    PartnerDTO = PartnerService.GetById(ClientDTO.PartnerId);
                    CommonService.SendEmail("Removed sendercode application request", "<HTML><BODY><P>Hello " + CommonService.GetFirstname(PartnerDTO.Name) + "</P><P>Request for sender code from " + ClientDTO.Company + " has been removed.</P></BODY></HTML>", PartnerDTO.Email, "", false);

                    return true;
                }

                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }