public JsonResult UpdateUserClient(Guid userId, string clientIdText)
 {
     try
     {
         int clientId = 0;
         if (int.TryParse(clientIdText, out clientId))
         {
             var db = new AromaContext();
             var client = db.Clients.FirstOrDefault(m=>m.ClientId == clientId);
             if (client == null)
             {
                 return Json("Client not found");
             }
             else
             {
                 var userClient = db.UserClients.FirstOrDefault(m=>m.UserId.Equals(userId));
                 if (userClient == null)
                 {
                     userClient = new UserClient() {UserId=userId };
                     db.UserClients.Add(userClient);
                 }
                 userClient.ClientId = clientId;
                 db.SaveChanges();
                 return Json(string.Empty);
             }
         }
         else
         {
             return Json("Invalid client Id");
         }
     }
     catch (Exception ex)
     {
         return Json(ex.Message);
     }
 }
        public static void SendSMSEvent(AromaContext db, int systemSMSEventId, int clientId, Guid userId, Guid? source, params KeyValuePair<string, string>[] pars)
        {
            try
            {
                var systemSMSevent = db.SystemSMSEvents.Find(systemSMSEventId);
                var template = systemSMSevent.SystemSMSTemplate;
                var client = db.Clients.Find(clientId);
                if (!source.HasValue) source = userId;
                try
                {
                
                    if (systemSMSevent.Active)
                    {
                        

                        var contact = db.Contacts.Where(m => m.ContactTypeID == 3 && m.ClientID == clientId).FirstOrDefault();
                        var smsSub = new SystemSMSTemplateModel(template.Text, client, db);
                        smsSub.EventInfo = pars;
                        var textResult = smsSub.Generate();
                        if (contact != null)
                        {

                            var sms = (from item in db.SystemSMSes
                                       where item.ClientID == clientId
                                       && item.SMSDescription == textResult
                                       select item).FirstOrDefault();
                            if (sms == null)
                            {
                                sms = new SystemSMS()
                                {
                                    Active = true,
                                    ClientID = clientId,
                                    iDate = DateTime.Now,
                                    Number = contact.ContactName,
                                    SMSDescription = textResult,
                                    Source = source,
                                    SystemSMSStatusId = 1
                                };
                                db.SystemSMSes.Add(sms);
                                db.SaveChanges();
                            }
                        }
                        else
                        {
                            var ticket = new SupportTicket()
                            {
                                ClientID = clientId,
                                Description = string.Format("An attemt was made to send a SMS to this client ({0}) but the cell number could not be found.\r\n{1}", clientId, textResult),
                                iDate = DateTime.Now,
                                SupportTicketStatusID = 1,
                                SupportTicketTypeId = 2,
                                UserID = userId
                            };
                            db.SupportTickets.Add(ticket);
                            db.SaveChanges();
                        }
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        var ticket = new SupportTicket()
                        {
                            ClientID = client.ClientId,
                            Description = string.Format("Unable to create system sms:\"{0}\" Message:{1}", template.Description, ex.Message),
                            iDate = DateTime.Now,
                            SupportTicketStatusID = 1,
                            SupportTicketTypeId = 2,
                            UserID = userId
                        };
                        db.SupportTickets.Add(ticket);
                        db.SaveChanges();
                    }
                    catch
                    {
                        throw;
                    }
                }
            }
            catch
            {
                throw;
            }
        }
        internal static Guid Create(Guid accountId, int clientId, AromaContext db)
        {
            var clientAccount = (from item in db.ClientAccounts
                                 where item.AccountId.Equals(accountId)
                                 && item.ClientID == clientId
                                 select item).FirstOrDefault();
            if (clientAccount == null)
            {
                var account = (from item in db.Accounts
                               where item.AccountId.Equals(accountId)
                               select item).FirstOrDefault();
                if (account == null)
                {
                    throw new Exception("Cannot create client account");
                }

                if (account.IsSystemAccount) return account.AccountId;

                clientAccount = new finClientAccount()
                {
                    AccountId = account.AccountId,
                    Active = true,
                    ClientID = clientId,
                    ClientAccountId = Guid.NewGuid()
                };
                db.ClientAccounts.Add(clientAccount);
                db.SaveChanges();
            }
            return clientAccount.ClientAccountId;
        }
        internal static void PersistTicket(AromaContext db, Guid systemEventId, Guid id,int clientId, int supportTicketType, string text, Guid userId)
        {
            var evnt = db.SystemEvents.Find(systemEventId);
                      
            var links = (from item in db.SystemLinks
                        where item.Parent.Equals(id)
                        select item.Child).ToArray();
            var ticket = (from item in db.SupportTickets
                          where links.Contains(item.SupportTicketId)
                          && item.SupportTicketTypeId == supportTicketType
                          select item).FirstOrDefault();
            if (ticket == null)
            {
                ticket = new SupportTicket()
                {
                    ClientID = clientId,
                    Description = text,
                    iDate = DateTime.Now,
                    SupportTicketId=Guid.NewGuid(),
                    SupportTicketStatusID = 1,
                    SupportTicketTypeId = supportTicketType,
                    UserID = evnt.UserId
                };
                db.SupportTickets.Add(ticket);

                var link = new SystemLink() {
                    Parent =id,
                    Child = ticket.SupportTicketId,
                    Created = DateTime.Now,
                    UserID = userId,
                    LinkId = Guid.NewGuid()
                };
                db.SystemLinks.Add(link);

                db.SaveChanges();
            }
        }
 public static Invoice GetInvoice(AromaContext db, Guid id)
 {
     var invoice = db.Invoices.Find(id);
     if (invoice == null)
     {
         invoice = new Invoice() { InvoiceId = id, Number = string.Format("INB{0:000000}", db.Invoices.Count() + 1) };
         db.Invoices.Add(invoice);
         db.SaveChanges();
     }
     return invoice;
 }
        public static void CreateClientBankingDetails(AromaContext db,int clientId, string initials, string surname, int cellContactId, int homeContactId, int workContactId, int emailContactId)
        {
            const string accountHolderText = "Self";
            const string accountTypeText = "Cheque";
            const string BankText = "ABSA";

            var accountHolder = db.AccountHolders.FirstOrDefault(m => m.AccountHolderName == accountHolderText);
            if (accountHolder == null)
            {
                string errorMessage = string.Format("Account holder \"{0}\" not defined in lookup", accountHolderText);
                throw new Exception(errorMessage);
            }
            var accountType = db.AccountTypes.FirstOrDefault(m => m.AccountTypeName == accountTypeText);
            if (accountType == null)
            {
                string errorMessage = string.Format("Account type \"{0}\" not defined in lookup", accountTypeText);
                throw new Exception(errorMessage);
            }
            var bank = db.Banks.FirstOrDefault(m => m.BankName == BankText);
            if (bank == null)
            {
                string errorMessage = string.Format("Bank name \"{0}\" not defined in lookup", BankText);
                throw new Exception(errorMessage);
            }

            var branch = db.Branches.FirstOrDefault(m => m.BankId == bank.BankId);
            if (branch == null)
            {
                string errorMessage = string.Format("No branch defined for \"{0}\" not defined in lookup", BankText);
                throw new Exception(errorMessage);
            }

            if (db.BankingDetails.Where(m => m.ClientID == clientId).Count() == 0)
            {
                var bankingDetail = new BankingDetail()
                {
                    Initials = initials,
                    Surname = surname,
                    AccountHolderID = accountHolder.AccountHolderId,
                    AccountTypeID = accountType.AccountTypeId,
                    BankID = bank.BankId,
                    ClientID = clientId,
                    CommencementDate = DateTime.Now.AddMonths(1),
                    SalaryDate = DateTime.Now,
                    AccountNumber = "0",
                    BranchID = branch.BranchId,
                    CellContact = db.Contacts.First(m => m.ContactId == cellContactId).ContactName,
                    HomeContact = db.Contacts.First(m => m.ContactId == homeContactId).ContactName,
                    WorkContact = db.Contacts.First(m => m.ContactId == workContactId).ContactName,
                    EmailContact = db.Contacts.First(m => m.ContactId == emailContactId).ContactName,
                     Interval=1,
                    Active = false
                };

                db.BankingDetails.Add(bankingDetail);
                db.SaveChanges();
            }
        }