/// <summary>
        /// Sends a success message to customer
        /// </summary>
        /// <param name="reservation">Resrervation</param>
        public virtual void SendCustomerBookingSuccess(UrlHelper urlHelper, Reservation reservation, UsersContext db)
        {
            if (reservation == null)
                throw new ArgumentNullException("reseravation");

            if (reservation.Customers.Emails == null)
                return;

            var customerEmail = reservation.Customers.Emails.LastOrDefault();
            if (customerEmail == null)
                return;

            var messageTemplate = GetActiveMessageTemplate("Customer.OnlineBookingSucceed", db);
            if (messageTemplate == null)
                return;

            //tokens
            var tokens = new List<Token>();
            tokens.Add(new Token("ReservationId", reservation.ReservationId.ToString()));
            tokens.Add(new Token("ReservationDate", reservation.ReservationDate.ToString("ddd, MMM dd, yyyy")));
            tokens.Add(new Token("TimeForm", reservation.TimeForm.ToString("h:mm tt")));
            tokens.Add(new Token("Covers", reservation.Covers.ToString()));
            //tokens.Add(new Token("FullName", reservation.Customers.FirstName + " " +
            //    ((reservation.Customers.LastName.Length > 1) ? reservation.Customers.LastName.Remove(1) : reservation.Customers.LastName)));
            tokens.Add(new Token("FullName", reservation.Customers.FirstName));
            //tokens.Add(new Token("EditUrl", System.Web.HttpContext.Current.Request.Url.Host + "/Online/ReserveSuccess/" + reservation.ReservationId));
            tokens.Add(new Token("EditUrl", urlHelper.EncodedUrl("ReserveSuccess", "Online", new { id = reservation.ReservationId })));
            tokens.Add(new Token("CancelUrl", urlHelper.EncodedUrl("ReserveSuccess", "Online", new { id = reservation.ReservationId })));
            //tokens.Add(new Token("AppUrl", System.Web.HttpContext.Current.Request.Url.Host));
            tokens.Add(new Token("AppUrl", "http://media.vanfish.com/reservation_email"));

            var fromAddress = (string)ConfigurationManager.AppSettings["Email_To"];
            var fromName = (string)ConfigurationManager.AppSettings["Email_To"];

            var toEmail = customerEmail.Email;
            var toName = reservation.Customers.FirstName;

            this.SendNotification(messageTemplate, fromAddress, fromName,
                tokens, toEmail, toName);
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        //private IList<Reservation> GetFilteredReservations(GetReservationsParamVM options)
        //{
        //    IList<Reservation> reservations = new List<Reservation>();
        //    var clientDate = DateTime.UtcNow.ToClientTime().Date;
        //    using (var dbContext = new UsersContext())
        //    {
        //        reservations = dbContext.GetReservationByDate(options.Date)
        //            .Where(r => (r.FloorTableId > 0) ? (!r.FloorTable.IsDeleted) : (!r.MergedFloorTable.OrigionalTables.Any(t => t.FloorTable.IsDeleted))).ToList();
        //        if (options.FloorPlanId.HasValue)
        //        {
        //            reservations = reservations.Where(r => r.FloorPlanId == options.FloorPlanId.Value).ToList();
        //        }
        //        if (options.ShiftId.HasValue)
        //        {
        //            reservations = reservations.Where(r => r.FoodMenuShiftId == options.ShiftId.Value).ToList();
        //        }
        //        DateTime? startTime = null;
        //        string filter = string.Empty;
        //        if (!string.IsNullOrEmpty(options.Filter) && !string.IsNullOrEmpty(options.Time))
        //        {
        //            filter = options.Filter.Trim().ToUpper();
        //            switch (filter)
        //            {
        //                case "ALL":
        //                    {
        //                        break;
        //                    }
        //                case "SEATED":
        //                    {
        //                        options.IncludeStatusIds.Add(ReservationStatus.Seated);
        //                        options.ExcludeStatusIds.AddRange(
        //                            new List<long>
        //                        {
        //                            ReservationStatus.Cancelled,
        //                            ReservationStatus.Finished
        //                        });
        //                        options.Time = options.Time.Trim();
        //                        startTime = clientDate.Add(Convert.ToDateTime(options.Time).TimeOfDay);
        //                        break;
        //                    }
        //                case "UPCOMING":
        //                    {
        //                        options.ExcludeStatusIds.AddRange(
        //                            new List<long>
        //                        {
        //                            ReservationStatus.Seated,
        //                            ReservationStatus.Cancelled,
        //                            ReservationStatus.Finished
        //                        });
        //                        options.Time = options.Time.Trim();
        //                        startTime = clientDate.Add(Convert.ToDateTime(options.Time).TimeOfDay).AddMinutes(15);
        //                        break;
        //                    }
        //                default:
        //                    break;
        //            }
        //        }
        //        //var reservations = resList.ToList();
        //        if (options.IncludeStatusIds.Count > 0 && startTime.HasValue)
        //        {
        //            reservations = reservations.Where(r => options.IncludeStatusIds.Contains(r.StatusId.Value) || ((filter == "SEATED") ? (r.TimeForm <= startTime) : (r.TimeForm >= startTime))).ToList();
        //        }
        //        else if (options.IncludeStatusIds.Count > 0)
        //        {
        //            reservations = reservations.Where(r => options.IncludeStatusIds.Contains(r.StatusId.Value)).ToList();
        //        }
        //        else if (startTime.HasValue)
        //        {
        //            reservations = reservations.Where(r => ((filter == "SEATED") ? (r.TimeForm <= startTime) : (r.TimeForm >= startTime))).ToList();
        //        }
        //        if (options.ExcludeStatusIds.Count > 0)
        //        {
        //            reservations = reservations.Where(r => !options.ExcludeStatusIds.Contains(r.StatusId.Value)).ToList();
        //        }
        //    }
        //    return reservations.OrderBy(r => r.TimeForm).ToList();
        //}
        //private IList<ReservationListItemVM> GetFilteredReservations20150608(GetReservationsParamVM options)
        //{
        //    IList<Reservation> reservations = new List<Reservation>();
        //    var clientDate = DateTime.UtcNow.ToClientTime().Date;
        //    using (var dbContext = new UsersContext())
        //    {
        //        reservations = dbContext.GetReservationByDate(options.Date)
        //            .Where(r => (r.FloorTableId > 0) ? (!r.FloorTable.IsDeleted) : (!r.MergedFloorTable.OrigionalTables.Any(t => t.FloorTable.IsDeleted))).ToList();
        //        if (options.FloorPlanId.HasValue)
        //        {
        //            reservations = reservations.Where(r => r.FloorPlanId == options.FloorPlanId.Value).ToList();
        //        }
        //        if (options.ShiftId.HasValue)
        //        {
        //            reservations = reservations.Where(r => r.FoodMenuShiftId == options.ShiftId.Value).ToList();
        //        }
        //        DateTime? startTime = null;
        //        string filter = string.Empty;
        //        if (!string.IsNullOrEmpty(options.Filter) && !string.IsNullOrEmpty(options.Time))
        //        {
        //            filter = options.Filter.Trim().ToUpper();
        //            switch (filter)
        //            {
        //                case "ALL":
        //                    {
        //                        break;
        //                    }
        //                case "SEATED":
        //                    {
        //                        options.IncludeStatusIds.Add(ReservationStatus.Seated);
        //                        options.ExcludeStatusIds.AddRange(
        //                            new List<long>
        //                        {
        //                            ReservationStatus.Cancelled,
        //                            ReservationStatus.Finished
        //                        });
        //                        options.Time = options.Time.Trim();
        //                        startTime = clientDate.Add(Convert.ToDateTime(options.Time).TimeOfDay);
        //                        break;
        //                    }
        //                case "UPCOMING":
        //                    {
        //                        options.ExcludeStatusIds.AddRange(
        //                            new List<long>
        //                        {
        //                            ReservationStatus.Seated,
        //                            ReservationStatus.Cancelled,
        //                            ReservationStatus.Finished
        //                        });
        //                        options.Time = options.Time.Trim();
        //                        startTime = clientDate.Add(Convert.ToDateTime(options.Time).TimeOfDay).AddMinutes(15);
        //                        break;
        //                    }
        //                default:
        //                    break;
        //            }
        //        }
        //        //var reservations = resList.ToList();
        //        if (options.IncludeStatusIds.Count > 0 && startTime.HasValue)
        //        {
        //            reservations = reservations.Where(r => options.IncludeStatusIds.Contains(r.StatusId.Value) || ((filter == "SEATED") ? (r.TimeForm <= startTime) : (r.TimeForm >= startTime))).ToList();
        //        }
        //        else if (options.IncludeStatusIds.Count > 0)
        //        {
        //            reservations = reservations.Where(r => options.IncludeStatusIds.Contains(r.StatusId.Value)).ToList();
        //        }
        //        else if (startTime.HasValue)
        //        {
        //            reservations = reservations.Where(r => ((filter == "SEATED") ? (r.TimeForm <= startTime) : (r.TimeForm >= startTime))).ToList();
        //        }
        //        if (options.ExcludeStatusIds.Count > 0)
        //        {
        //            reservations = reservations.Where(r => !options.ExcludeStatusIds.Contains(r.StatusId.Value)).ToList();
        //        }
        //    }
        //    return reservations.OrderBy(r => r.TimeForm).Select(r => new ReservationListItemVM
        //    {
        //        Reservation = r,
        //        HTMLString = this.RenderPartialViewToString("~/Views/FloorPlan/ReservationListItemPartial.cshtml", r)
        //    }).ToList();
        //}
        private IList<ReservationListItemVM> GetFilteredReservations20150617(GetReservationsParamVM options)
        {
            IList<Reservation> reservations = new List<Reservation>();
            //var clientDate = DateTime.UtcNow.ToClientTime().Date;
            var clientDate = DateTime.UtcNow.ToDefaultTimeZone(User.Identity.GetDatabaseName()).Date;

            using (var dbContext = new UsersContext())
            {
                reservations = dbContext.GetReservationByDate(options.Date)
                    .Where(r => (r.FloorTableId > 0) ? (!r.FloorTable.IsDeleted) : (!r.MergedFloorTable.OrigionalTables.Any(t => t.FloorTable.IsDeleted))).ToList();

                if (options.FloorPlanId.HasValue)
                {
                    reservations = reservations.Where(r => r.FloorPlanId == options.FloorPlanId.Value).ToList();
                }

                if (options.ShiftId.HasValue)
                {
                    reservations = reservations.Where(r => r.FoodMenuShiftId == options.ShiftId.Value).ToList();
                }

                DateTime? startTime = null;

                string filter = string.Empty;

                if (!string.IsNullOrEmpty(options.Filter) && !string.IsNullOrEmpty(options.Time))
                {
                    filter = options.Filter.Trim().ToUpper();

                    if (!string.IsNullOrWhiteSpace(options.Time))
                    {
                        options.Time = options.Time.Trim();
                        clientDate = clientDate.Add(Convert.ToDateTime(options.Time).TimeOfDay);
                    }

                    switch (filter)
                    {
                        case "ALL":
                            {
                                break;
                            }
                        case "SEATED":
                            {
                                options.IncludeStatusIds.AddRange(new List<long>{
                                    ReservationStatus.Partially_Arrived,
                                    ReservationStatus.All_Arrived,
                                    ReservationStatus.Partially_Seated,
                                    ReservationStatus.Seated,
                                    ReservationStatus.Appetizer,
                                    ReservationStatus.Entree,
                                    ReservationStatus.Dessert,
                                    ReservationStatus.Table_Cleared,
                                    ReservationStatus.Check_Dropped,
                                    ReservationStatus.Check_Paid
                                });
                                options.ExcludeStatusIds.AddRange(new List<long>
                                {
                                    ReservationStatus.Finished,
                                    ReservationStatus.Cancelled,
                                    ReservationStatus.No_show
                                });
                                //options.Time = options.Time.Trim();
                                startTime = clientDate;
                                break;
                            }
                        case "UPCOMING":
                            {
                                options.ExcludeStatusIds.AddRange(new List<long>
                                {
                                    ReservationStatus.Partially_Arrived,
                                    ReservationStatus.All_Arrived,
                                    ReservationStatus.Partially_Seated,
                                    ReservationStatus.Seated,
                                    ReservationStatus.Appetizer,
                                    ReservationStatus.Entree,
                                    ReservationStatus.Dessert,
                                    ReservationStatus.Table_Cleared,
                                    ReservationStatus.Check_Dropped,
                                    ReservationStatus.Check_Paid,
                                    ReservationStatus.Seated,
                                    ReservationStatus.Cancelled,
                                    ReservationStatus.Finished,
                                    ReservationStatus.No_show
                                });
                                //options.Time = options.Time.Trim();
                                startTime = clientDate.AddMinutes(15);
                                break;
                            }
                        default:
                            break;
                    }
                }

                //var reservations = resList.ToList();

                if (options.IncludeStatusIds.Count > 0 && startTime.HasValue)
                {
                    //reservations = reservations.Where(r => options.IncludeStatusIds.Contains(r.StatusId.Value) || ((filter == "SEATED") ? (r.TimeForm <= startTime) : (r.TimeForm >= startTime))).ToList();
                    reservations = reservations.Where(r => options.IncludeStatusIds.Contains(r.StatusId.Value)
                        || ((filter == "SEATED") ? (r.TimeForm <= startTime && startTime <= r.TimeForm.AddMinutes(r.Duration.GetMinutesFromDuration())) : (r.TimeForm >= startTime))).ToList();
                }
                else if (options.IncludeStatusIds.Count > 0)
                {
                    reservations = reservations.Where(r => options.IncludeStatusIds.Contains(r.StatusId.Value)).ToList();
                }
                else if (startTime.HasValue)
                {
                    reservations = reservations.Where(r => ((filter == "SEATED") ? (r.TimeForm <= startTime) : (r.TimeForm >= startTime))).ToList();
                }

                if (options.ExcludeStatusIds.Count > 0)
                {
                    reservations = reservations.Where(r => !options.ExcludeStatusIds.Contains(r.StatusId.Value)).ToList();
                }
            }

            reservations = reservations.OrderBy(r => r.TimeForm).ToList();

            //if (options.Filter == "ALL")
            //{
            //    var currentTime = !string.IsNullOrWhiteSpace(options.Time) ? options.Date.Add(Convert.ToDateTime(options.Time).TimeOfDay) : clientDate;
            //    var sortedList = new List<Reservation>();
            //    sortedList.AddRange(reservations.SkipWhile(r => r.TimeForm < currentTime));
            //    sortedList.AddRange(reservations.TakeWhile(r => r.TimeForm < currentTime));

            //    return sortedList.Select(r => new ReservationListItemVM
            //    {
            //        Reservation = r,
            //        HTMLString = cache.Get<string>(string.Format(CacheKeys.RESERVATION_RIGHT_LIST_ITEM, r.ReservationId), () =>
            //        {
            //            return this.RenderPartialViewToString("~/Views/FloorPlan/ReservationListItemPartial.cshtml", r);
            //        })
            //    }).ToList();
            //}
            //else
            //{

            var htmlMinifier = new HtmlMinifier();

            return reservations.Select(r => new ReservationListItemVM
            {
                Reservation = r,
                HTMLString = cache.Get<string>(string.Format(CacheKeys.RESERVATION_RIGHT_LIST_ITEM,db.Database.Connection.Database, r.ReservationId), () =>
                {
                    ModelState.Clear();
                    return htmlMinifier.Minify(this.RenderPartialViewToString("~/Views/FloorPlan/ReservationListItemPartial.cshtml", r),
                        generateStatistics: false).MinifiedContent;

                    //return this.RenderPartialViewToString("~/Views/FloorPlan/ReservationListItemPartial.cshtml", r);
                })
            }).ToList();
            //}
        }
 public WorkflowMessageService()
 {
     this._db = new UsersContext();
     this._emailSender = new EmailSender();
     this._tokenizer = new Tokenizer();
 }
        protected virtual MessageTemplate GetActiveMessageTemplate(string messageTemplateName,UsersContext db)
        {
            var messageTemplate = db.GetMessageTemplateByName(messageTemplateName);

            //no template found
            if (messageTemplate == null)
                return null;

            //ensure it's active
            var isActive = messageTemplate.IsActive;
            if (!isActive)
                return null;

            return messageTemplate;
        }
        public JsonResult Update(List<WeekDayShift> hours, string timezone)
        {
            using (var context = new UsersContext())
            {
                // delete existing records
                context.Database.ExecuteSqlCommand(@"truncate table MenuShiftHours");
            }

            bool isSucess = false;
            if (ModelState.IsValid)
            {
                foreach (var day in hours)
                {
                    var breakfast = new MenuShiftHours
                    {
                        DayId = day.DayId,
                        FoodMenuShiftId = 1,
                        OpenAt = day.BreakfastOpen == null ? null : Convert.ToDateTime(day.BreakfastOpen, CultureInfo.CurrentCulture).ToString("hh:mm tt"),
                        CloseAt = day.BreakfastClose == null ? null : Convert.ToDateTime(day.BreakfastClose, CultureInfo.CurrentCulture).ToString("hh:mm tt"),
                        IsNext = day.BreakfastClose == null ? 0 : Convert.ToDateTime(day.BreakfastClose, CultureInfo.CurrentCulture).Date == DateTime.Now.AddDays(1).Date ? 1 : 0
                    };

                    db.tabMenuShiftHours.Add(breakfast);

                    var brunch = new MenuShiftHours
                    {
                        DayId = day.DayId,
                        FoodMenuShiftId = 2,
                        OpenAt = day.BrunchOpen == null ? null : Convert.ToDateTime(day.BrunchOpen, CultureInfo.CurrentCulture).ToString("hh:mm tt"),
                        CloseAt = day.BrunchClose == null ? null : Convert.ToDateTime(day.BrunchClose, CultureInfo.CurrentCulture).ToString("hh:mm tt"),
                        IsNext = day.BrunchClose == null ? 0 : Convert.ToDateTime(day.BrunchClose, CultureInfo.CurrentCulture).Date == DateTime.Now.AddDays(1).Date ? 1 : 0
                    };

                    db.tabMenuShiftHours.Add(brunch);

                    var lunch = new MenuShiftHours
                    {
                        DayId = day.DayId,
                        FoodMenuShiftId = 3,
                        OpenAt = day.LunchOpen == null ? null : Convert.ToDateTime(day.LunchOpen, CultureInfo.CurrentCulture).ToString("hh:mm tt"),
                        CloseAt = day.LunchClose == null ? null : Convert.ToDateTime(day.LunchClose, CultureInfo.CurrentCulture).ToString("hh:mm tt"),
                        IsNext = day.LunchClose == null ? 0 : Convert.ToDateTime(day.LunchClose, CultureInfo.CurrentCulture).Date == DateTime.Now.AddDays(1).Date ? 1 : 0
                    };

                    db.tabMenuShiftHours.Add(lunch);

                    var dinner = new MenuShiftHours
                    {
                        DayId = day.DayId,
                        FoodMenuShiftId = 4,
                        OpenAt = day.DinnerOpen == null ? null : Convert.ToDateTime(day.DinnerOpen, CultureInfo.CurrentCulture).ToString("hh:mm tt"),
                        CloseAt = day.DinnerClose == null ? null : Convert.ToDateTime(day.DinnerClose, CultureInfo.CurrentCulture).ToString("hh:mm tt"),
                        IsNext = day.DinnerClose == null ? 0 : Convert.ToDateTime(day.DinnerClose, CultureInfo.CurrentCulture).Date == DateTime.Now.AddDays(1).Date ? 1 : 0
                    };
                    db.tabMenuShiftHours.Add(dinner);

                }

                var timezoneSetting = db.tabSettings.Where(s => s.Name.Contains("TimeZone")).Single();
                timezoneSetting.Value = timezone;
                db.Entry(timezoneSetting).State = System.Data.Entity.EntityState.Modified;

                db.SaveChanges();

                UpdateShiftHoursCache();

                isSucess = true;
                return Json(new
                {
                    IsSucess = isSucess,
                });
            }
            return Json(new
            {
                IsSucess = isSucess,
            });
        }
        public ActionResult ReserveSuccess(long id,string company)
        {
            var clientTime = DateTime.UtcNow.ToDefaultTimeZone(company); //.ToClientTime();
            UsersContext _context = new UsersContext(company);
            var reservation = _context.tabReservations.SingleOrDefault(r => !r.IsDeleted && r.ReservationId == id);

            if (reservation == null || reservation.StatusId == ReservationStatus.Cancelled)
            {
                return RedirectToAction("ReserveFail", new { id = 4, company = context.Database.Connection.Database });
            }

            if (!IsOnlineUser15062015(reservation.UserId, _context))
            {
                return RedirectToAction("ReserveFail", new { id = 6, company = context.Database.Connection.Database });
            }

            if (reservation.ReservationDate < clientTime.Date || clientTime > reservation.TimeForm.AddHours(-2))
            {
                return RedirectToAction("ReserveFail", new { id = 5, company = context.Database.Connection.Database });
            }
            ViewBag.company = company;
            return View(reservation);
        }
        private bool IsOnlineUser15062015(long userId, UsersContext context)
        {
            var onlineUsers = context.Users.Where(c => c.Roles.Any(ur => ur.RoleId == context.Roles.Where(r => r.Name == "Online").FirstOrDefault().Id)).Single().UserName;
            var user = context.Users.Find(userId);

            return onlineUsers.Contains(user.UserName);
        }
        public static DateTime ToDefaultTimeZone(this DateTime dt,string companyName)
        {
            string settingkey = string.Format(CacheKeys.SETTING_BY_NAME_KEY,companyName, "TimeZone");

            var timeZoneSetting = cache.Get<Setting>(settingkey, () =>
            {
                Setting setting;
                using (var _db = new UsersContext())
                {
                    var query = _db.tabSettings.AsQueryable();
                    query = query.Where(t => t.Name == "TimeZone");
                    query = query.OrderBy(t => t.SettingId);
                    var settings = query.ToList();

                    setting = settings.FirstOrDefault();
                }

                return setting;
            });

            var systemTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneSetting.Value);
            return TimeZoneInfo.ConvertTimeFromUtc(dt, systemTimeZone);
        }
        public void BroadcastUpdate(object state)
        {
            try
            {
                SAASContext _db = new SAASContext();
                var databaseName = _db.Users.Where(c => c.Approved != null).ToList();
                foreach (var item in databaseName)
                {
                    string databasename = item.RestaurantName;
                    databasename = databasename.Replace(" ", "");
                    //databasename = "vanfish";
                    //if (databaseName != null)
                    //{
                    try
                    {
                        int minToAdd = 15;
                        int checkIfMins = 13;
                        var timeZone = _cache.Get<Setting>(string.Format(CacheKeys.SETTING_BY_NAME_KEY, databasename, "TimeZone"), () =>
                        {
                            using (var db = new UsersContext(databasename))
                            {
                                return db.GetSettingByName("TimeZone");
                            }
                        });

                        DateTime defaultClientTime = TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(timeZone.Value));
                        if ((defaultClientTime.TimeOfDay.Minutes % 15) == checkIfMins)
                        {
                            var openCloseTimeOfDay = defaultClientTime.DayOfWeek.GetOpenAndCloseTime(databasename);

                            if (openCloseTimeOfDay.OpenTime <= defaultClientTime && defaultClientTime <= openCloseTimeOfDay.CloseTime.AddMinutes(-15))
                            {
                                using (var db = new UsersContext(databasename))
                                {
                                    List<Reservation> singleTableReservations = null;
                                    List<long> conflictedRes = new List<long>();

                                    var allResToday = db.tabReservations.Where(r => !r.IsDeleted && r.ReservationDate == defaultClientTime.Date).ToList();

                                    singleTableReservations = allResToday.Where(r => r.FloorTableId > 0).ToList();

                                    var rejectedStatus = new List<long>()
                                     {
                                         ReservationStatus.Finished,
                                         ReservationStatus.Cancelled
                                     };

                                    singleTableReservations = singleTableReservations.Where(r => !rejectedStatus.Contains(r.StatusId.Value)).ToList();
                                    singleTableReservations = singleTableReservations.Where(r => r.TimeForm.AddMinutes(r.Duration.GetMinutesFromDuration()) > defaultClientTime &&
                                        r.TimeForm.AddMinutes(r.Duration.GetMinutesFromDuration()) < defaultClientTime.AddMinutes(15 - checkIfMins)).ToList();

                                    int resCount = singleTableReservations.Count;
                                    decimal processedReservations = 0;
                                    if (resCount > 0)
                                        _hubContext.Clients.All.startProgress();

                                    foreach (var res in singleTableReservations)
                                    {
                                        var upcomingReservation = allResToday
                                            .FirstOrDefault(r => (r.TimeForm > defaultClientTime && r.TimeForm < defaultClientTime.AddMinutes(minToAdd))
                                                && (r.FloorTableId == 0 ? r.MergedFloorTable.OrigionalTables.Any(t => t.FloorTableId == res.FloorTableId) : r.FloorTableId == res.FloorTableId));

                                        if (upcomingReservation != null)
                                        {
                                            bool isMergeConflict = (upcomingReservation.FloorTableId == 0);
                                            var oldDuration = res.Duration;
                                            try
                                            {
                                                if (!isMergeConflict && TryShiftUpcomingReservationToOtherAvailableTable(db, upcomingReservation))
                                                {
                                                    try
                                                    {
                                                        ExtendReservationDuration(minToAdd, db, res, out oldDuration);

                                                        _hubContext.Clients.Group(databasename).updateEndingReservation(
                                                            string.Format(RESERVATION_EXTENDED_CONFLICT_RESOLVED_SUCCESSFULLY,
                                                            res.FloorTable.TableName,
                                                            res.TimeForm.AddMinutes(oldDuration.GetMinutesFromDuration()).ToShortTimeString(),
                                                            upcomingReservation.TimeForm.ToShortTimeString(),
                                                            upcomingReservation.FloorTable.TableName), NotifyType.INFO);
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        _hubContext.Clients.Group(databasename).updateEndingReservation(
                                                            string.Format(FAILED_TO_EXTEND_RESERVATION,
                                                            res.FloorTable.TableName,
                                                            res.TimeForm.AddMinutes(oldDuration.GetMinutesFromDuration()).ToShortTimeString(),
                                                            ex.Message), NotifyType.ERROR);
                                                    }
                                                }
                                                else
                                                {
                                                    if (isMergeConflict)
                                                    {
                                                        _hubContext.Clients.Group(databasename).updateEndingReservation(
                                                            string.Format(CANNOT_EXTEND_CONFICT_MERGE_RESERVATION,
                                                            res.FloorTable.TableName,
                                                            res.TimeForm.AddMinutes(res.Duration.GetMinutesFromDuration()).ToShortTimeString(),
                                                            upcomingReservation.TimeForm.ToShortTimeString()), NotifyType.ERROR);
                                                    }
                                                    else
                                                    {
                                                        _hubContext.Clients.Group(databasename).updateEndingReservation(
                                                            string.Format(CANNOT_EXTEND_RESERVATION,
                                                            res.FloorTable.TableName,
                                                            res.TimeForm.AddMinutes(res.Duration.GetMinutesFromDuration()).ToShortTimeString(),
                                                            upcomingReservation.TimeForm.ToShortTimeString()), NotifyType.ERROR);
                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                _hubContext.Clients.Group(databasename).updateEndingReservation(
                                                    string.Format(FAILED_TO_EXTEND_RESERVATION,
                                                    res.FloorTable.TableName,
                                                    res.TimeForm.AddMinutes(res.Duration.GetMinutesFromDuration()).ToShortTimeString(),
                                                    ex.Message), NotifyType.ERROR);
                                            }
                                        }
                                        else if (res.TimeForm.AddMinutes(res.Duration.GetMinutesFromDuration() + minToAdd) > openCloseTimeOfDay.CloseTime)
                                        {
                                            _hubContext.Clients.Group(databasename).updateEndingReservation(
                                               string.Format(FAILED_EXCEED_DAY_CLOSE_TIME,
                                               res.FloorTable.TableName,
                                               res.TimeForm.AddMinutes(res.Duration.GetMinutesFromDuration()).ToShortTimeString()), NotifyType.ERROR);
                                        }
                                        else
                                        {
                                            var oldDuration = res.Duration;
                                            try
                                            {
                                                ExtendReservationDuration(minToAdd, db, res, out oldDuration);
                                                _hubContext.Clients.Group(databasename).updateEndingReservation(
                                                    string.Format(RESERVATION_EXTENDED_SUCCESSFULLY,
                                                    res.FloorTable.TableName,
                                                    res.TimeForm.AddMinutes(oldDuration.GetMinutesFromDuration()).ToShortTimeString()), NotifyType.SUCCESS);
                                            }
                                            catch (Exception ex)
                                            {
                                                _hubContext.Clients.Group(databasename).updateEndingReservation(
                                                    string.Format(FAILED_TO_EXTEND_RESERVATION,
                                                    res.FloorTable.TableName,
                                                    res.TimeForm.AddMinutes(oldDuration.GetMinutesFromDuration()).ToShortTimeString(),
                                                    ex.Message), NotifyType.ERROR);
                                            }
                                        }

                                        processedReservations++;
                                        var percent = Convert.ToInt32(Math.Floor((processedReservations / resCount) * 100));
                                        _hubContext.Clients.All.updateProgress(percent);

                                        Thread.Sleep(200);
                                    }

                                    _hubContext.Clients.Group(databasename).updateProgress(100);
                                }
                            }

                            ClearReservationCache(databasename);
                        }
                    }
                    catch (Exception ex)
                    {
                        _hubContext.Clients.Group(databasename).updateEndingReservation(ex.Message, NotifyType.ERROR);
                    }
                }
            }
            catch (Exception ex)
            {
                _hubContext.Clients.All.updateEndingReservation(ex.Message, NotifyType.ERROR);
            }
        }
        private bool TryShiftUpcomingReservationToOtherAvailableTable(UsersContext db, Reservation upcomingReservation)
        {
            ReservationVM model;
            IList<Int64> upcomingTableIds;
            IList<Int64> smallTableIds;
            var availableTable = db.GetAvailableFloorTables(upcomingReservation, out upcomingTableIds, out smallTableIds, out model, true, true)
                .Where(t => t.FloorTableId != upcomingReservation.FloorTableId);
            //.FirstOrDefault();

            #region Check for entries in tableavailabilities
            /**** Table availability feature enabled  start here *****/

            var tt = model.time.Split('-');
            var startTm = model.resDate.Add(DateTime.ParseExact(tt[0].Trim(), "ddMMyyyyhhmmtt", CultureInfo.InvariantCulture).TimeOfDay);
            var endTime = new DateTime();
            if (string.IsNullOrEmpty(model.Duration))
            {
                endTime = model.resDate.Add(DateTime.ParseExact(tt[1].Trim(), "ddMMyyyyhhmmtt", CultureInfo.InvariantCulture).TimeOfDay);
            }
            else
            {
                endTime = startTm.AddMinutes(model.Duration.GetMinutesFromDuration());
            }

            var day = upcomingReservation.ReservationDate.DayOfWeek.ToString();
            var dId = db.GetWeekDays().Single(p => p.DayName.Contains(day)).DayId;

            var availList = db.tabTableAvailabilities
                .Include("TableAvailabilityFloorTables")
                .Include("TableAvailabilityWeekDays")
                .Where(ta => ta.StartDate <= model.resDate && model.resDate <= ta.EndDate
                && ta.TableAvailabilityWeekDays.Any(taw => taw.DayId == dId)).ToList();

            var blockList = db.GetFloorTableBlockTimeList(model.resDate);

            availableTable = availableTable.Where(t => availList.CheckAvailStatus(model.resDate, startTm, endTime, t, 1)
                && !blockList.IsTableBlocked(t.FloorTableId, startTm, endTime)).ToList();

            /**** Table availability feature enabled end here *****/
            #endregion

            var firstAvailableTable = availableTable.FirstOrDefault();

            if (firstAvailableTable != null)
            {
                upcomingReservation.FloorTableId = firstAvailableTable.FloorTableId;
                upcomingReservation.TablePositionLeft = firstAvailableTable.TLeft;
                upcomingReservation.TablePositionTop = firstAvailableTable.TTop;
                db.Entry(upcomingReservation).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                return true;
            }

            return false;
        }
        private void ExtendReservationDuration(int minToAdd, UsersContext db, Reservation res, out string oldDuration)
        {
            oldDuration = res.Duration;
            var newDuration = oldDuration.AddMinutesToDuration(minToAdd);

            res.Duration = newDuration;
            res.TimeTo = res.TimeForm.AddMinutes(newDuration.GetMinutesFromDuration());
            db.Entry(res).State = System.Data.Entity.EntityState.Modified;
            //db.LogEditReservation(reservation, loginUser, null);

            db.SaveChanges();
        }
        public JsonResult Create(List<WeekDayShift> model)
        {
            using (var context = new UsersContext())
            {
                // delete existing records
                context.Database.ExecuteSqlCommand(@"truncate table [AIS].[dbo].[MenuShiftHours]");
            }
            bool isSucess = false;
            if (ModelState.IsValid)
            {
                foreach (var day in model)
                {
                    var breakfast = new MenuShiftHours
                    {
                        DayId = day.DayId,
                        FoodMenuShiftId = 1,
                        OpenAt = day.BreakfastOpen,
                        CloseAt = day.BreakfastClose
                    };

                    db.tabMenuShiftHours.Add(breakfast);

                    var brunch = new MenuShiftHours
                    {
                        DayId = day.DayId,
                        FoodMenuShiftId = 2,
                        OpenAt = day.BrunchOpen,
                        CloseAt = day.BrunchClose
                    };

                    db.tabMenuShiftHours.Add(brunch);

                    var lunch = new MenuShiftHours
                    {
                        DayId = day.DayId,
                        FoodMenuShiftId = 3,
                        OpenAt = day.LunchOpen,
                        CloseAt = day.LunchClose
                    };

                    db.tabMenuShiftHours.Add(lunch);

                    var dinner = new MenuShiftHours
                    {
                        DayId = day.DayId,
                        FoodMenuShiftId = 4,
                        OpenAt = day.DinnerOpen,
                        CloseAt = day.DinnerClose
                    };
                    db.tabMenuShiftHours.Add(dinner);
                }

                db.SaveChanges();
                isSucess = true;
                return Json(new
                {
                    IsSucess = isSucess,

                });
            }
            return Json(new
            {
                IsSucess = isSucess,

            });
        }
        public JsonResult ChangeTempItem(TempFloorTable table, bool SaveChanges = false, bool CancelChanges = false)
        {
            ModelState.Clear();

            ViewBag.IsSelected = true;
            ViewBag.IsTemp = true;

            var totalTables = 0;
            var totalMaxCovers = 0;
            var totalMinCovers = 0;

            try
            {
                if (!CancelChanges)
                {
                    FloorTable copyTable = new FloorTable();
                    CopyHelper.Copy(typeof(TempFloorTable), table, typeof(FloorTable), copyTable);

                    if (SaveChanges)
                    {
                        ViewBag.IsSelected = false;

                        table.TableDesign = this.RenderPartialViewToString("~/Views/Floor/GetFloorItemTemplate.cshtml", copyTable);

                        var tblDB = Db.tabTempFloorTables.Find(table.FloorTableId);

                        tblDB.TableName = table.TableName;
                        tblDB.Shape = table.Shape;
                        tblDB.Size = table.Size;
                        tblDB.Angle = table.Angle;
                        tblDB.TableDesign = table.TableDesign;
                        tblDB.MinCover = table.MinCover;
                        tblDB.MaxCover = table.MaxCover;
                        tblDB.UpdatedOn = DateTime.UtcNow.ToDefaultTimeZone(User.Identity.GetDatabaseName());

                        Db.Entry(table).State = EntityState.Modified;
                        Db.SaveChanges();
                    }
                    else
                    {
                        table.TableDesign = this.RenderPartialViewToString("~/Views/Floor/GetFloorItemTemplate.cshtml", copyTable);
                    }

                    Db.tabTempFloorTables.GetFloorItemCount(table.FloorPlanId, out totalTables, out totalMinCovers, out totalMaxCovers);

                    var response = new
                    {
                        Status = ResponseStatus.Success,
                        HtmlId = table.HtmlId,
                        Template = table.TableDesign,
                        totalTables = totalTables,
                        totalMaxCovers = totalMaxCovers,
                        totalMinCovers = totalMinCovers,
                        IsUpdated = SaveChanges
                    };

                    return Json(response, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    ViewBag.IsSelected = false;

                    var origionalTable = Db.tabTempFloorTables.Find(table.FloorTableId);

                    FloorTable copyOrigionalTable = new FloorTable();
                    CopyHelper.Copy(typeof(TempFloorTable), origionalTable, typeof(FloorTable), copyOrigionalTable);

                    origionalTable.TableDesign = this.RenderPartialViewToString("~/Views/Floor/GetFloorItemTemplate.cshtml", copyOrigionalTable);

                    Db.tabTempFloorTables.GetFloorItemCount(table.FloorPlanId, out totalTables, out totalMinCovers, out totalMaxCovers);

                    var response = new
                    {
                        Status = ResponseStatus.Success,
                        HtmlId = origionalTable.HtmlId,
                        Template = origionalTable.TableDesign,
                        totalTables = totalTables,
                        totalMaxCovers = totalMaxCovers,
                        totalMinCovers = totalMinCovers,
                        IsUpdated = SaveChanges
                    };

                    return Json(response, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception)
            {
                Db.Dispose();

                Db = new UsersContext();

                ViewBag.IsSelected = false;

                var origionalTable = Db.tabTempFloorTables.Find(table.FloorTableId);

                FloorTable copyOrigionalTable = new FloorTable();
                CopyHelper.Copy(typeof(TempFloorTable), origionalTable, typeof(FloorTable), copyOrigionalTable);

                origionalTable.TableDesign = this.RenderPartialViewToString("~/Views/Floor/GetFloorItemTemplate.cshtml", copyOrigionalTable);

                Db.tabTempFloorTables.GetFloorItemCount(table.FloorPlanId, out totalTables, out totalMinCovers, out totalMaxCovers);

                var response = new
                {
                    Status = ResponseStatus.Fail,
                    HtmlId = origionalTable.HtmlId,
                    Template = origionalTable.TableDesign,
                    totalTables = totalTables,
                    totalMaxCovers = totalMaxCovers,
                    totalMinCovers = totalMinCovers,
                    IsUpdated = SaveChanges
                };

                return Json(response, JsonRequestBehavior.AllowGet);
            }
        }
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {

            if (ModelState.IsValid)
            {
                var user = UserManager.FindByName(model.Email);
                if (user == null)
                {
                    ModelState.AddModelError("", "Invalid login attempt..");
                    if (Request.IsAjaxRequest())
                    {
                        return PartialView("~/Views/Mondofi/_SignInModal.cshtml", model);
                    }
                    return View(model);
                }
                if (user.Approved == false)
                {
                    ModelState.AddModelError("", "Your Account is not Approved");
                    if (Request.IsAjaxRequest())
                    {
                        return PartialView("~/Views/Mondofi/_SignInModal.cshtml", model);
                    }
                    return View(model);
                }
                string databasename = user.RestaurantName;
                databasename = databasename.Replace(" ", "");
                UsersContext db = new UsersContext(databasename);


                using (var companyUserManger = ApplicationUserManager.Create(databasename))
                using (var companySignInManager = ApplicationSignInManager.Create(databasename))
                {
                    var getUser = db.Users.Where(c => c.RestaurantName == user.RestaurantName).ToList();
                    if (getUser.Count() == 0)
                    {
                        var getresult = companyUserManger.Create(new UserProfile
                        {
                            Email = user.Email,
                            FirstName = user.FirstName,
                            LastName = user.LastName,
                            UserName = user.Email,
                            UserCode = 1234,
                            PhotoPath = user.PhotoPath,
                            Availability = user.Availability,
                            DesignationId = user.DesignationId,
                            RestaurantName = databasename,
                            TermAndCondition = true,
                            Approved = false,
                            EmailConfirmed = true

                        }, model.Password);
                        if (getresult.Succeeded)
                        {

                            var getUseradd = db.Users.Where(c => c.Email == model.Email).FirstOrDefault();
                            companyUserManger.AddToRole(getUseradd.Id, "SuperAdmin");

                        }

                    }

                    var companyUser = companyUserManger.FindByName(model.Email);
                    if (companyUser == null)
                    {
                        ModelState.AddModelError("", "Invalid login attempt.");
                        if (Request.IsAjaxRequest())
                        {
                            return PartialView("~/Views/Mondofi/_SignInModal.cshtml", model);
                        }
                        return View(model);
                    }

                    //Add this to check if the email was confirmed.
                    if (!await companyUserManger.IsEmailConfirmedAsync(companyUser.Id))
                    {
                        ModelState.AddModelError("", "You need to confirm your email.");
                        if (Request.IsAjaxRequest())
                        {
                            return PartialView("~/Views/Mondofi/_SignInModal.cshtml", model);
                        }
                        return View(model);
                    }

                    var result = await companySignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
                    switch (result)
                    {
                        case SignInStatus.Success:
                            if (Request.IsAjaxRequest())
                            {
                                return Json("Success", JsonRequestBehavior.AllowGet);
                            }
                            return RedirectToAction("FloorPlan", "FloorPlan");
                        case SignInStatus.LockedOut:
                            return View("Lockout");
                        case SignInStatus.RequiresVerification:
                            return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                        case SignInStatus.Failure:
                        default:
                            ModelState.AddModelError("", "Invalid login attempt");
                            if (Request.IsAjaxRequest())
                            {
                                return PartialView("~/Views/Mondofi/_SignInModal.cshtml", model);
                            }
                            return View(model);
                    }
                }
            }
            return View(model);

        }