public JsonResult AddFloorItem(FloorTable table)
        {
            try
            {
                table.HtmlId = "table" + Guid.NewGuid().ToString("N");
                table.TableName = "T-0";
                table.Angle = table.Angle;
                table.MinCover = table.MinCover;
                table.MaxCover = table.MaxCover;
                table.TTop = "150px";
                table.TLeft = "36px";
                table.TableDesign = " ";
                table.UpdatedOn = DateTime.UtcNow.ToDefaultTimeZone(User.Identity.GetDatabaseName());
                table.CreatedOn = DateTime.UtcNow.ToDefaultTimeZone(User.Identity.GetDatabaseName());
                table.IsDeleted = false;

                Db.tabFloorTables.Add(table);
                Db.SaveChanges();

                var tblDB = Db.tabFloorTables.Include("FloorPlan").Where(t => t.FloorTableId == table.FloorTableId).Single();

                tblDB.TableName = this.AssignItemName(tblDB.FloorTableId, tblDB.Shape);
                tblDB.TableDesign = this.RenderPartialViewToString("~/Views/Floor/GetFloorItemTemplate.cshtml", tblDB);

                Db.Entry(tblDB).State = EntityState.Modified;
                Db.SaveChanges();

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

                Db.tabFloorTables.GetFloorItemCount(tblDB.FloorPlanId, out totalTables, out totalMinCovers, out totalMaxCovers);

                return Json(new
                {
                    Status = ResponseStatus.Success,
                    ItemId = tblDB.FloorTableId,
                    totalTables = totalTables,
                    totalMaxCovers = totalMaxCovers,
                    totalMinCovers = totalMinCovers,
                    Template = tblDB.TableDesign,
                    HtmlId = table.HtmlId
                });
            }
            catch (Exception)
            {
                return Json(new { Status = ResponseStatus.Fail, ItemId = 0 });
            }
            finally
            {
                ClearFloorCache();
            }
        }
        public ActionResult AddMergedTable(FloorTable table, List<long> selectedTables)
        {
            ModelState.Clear();

            try
            {
                var tbl = new MergedFloorTable();

                CopyHelper.Copy(typeof(FloorTable), table, typeof(MergedFloorTable), tbl);

                tbl.TTop = table.TTop = "150px";
                tbl.TLeft = table.TLeft = "36px";
                tbl.TableDesign = " ";
                tbl.IsTemporary = table.IsTemporary = false;
                tbl.CreatedOn = table.CreatedOn = DateTime.UtcNow.ToDefaultTimeZone(User.Identity.GetDatabaseName());
                tbl.CreatedBy = User.Identity.GetUserId<long>();

                var originalTables = db.tabFloorTables.Where(t => selectedTables.Contains(t.FloorTableId)).ToList();

                foreach (var origionalTable in originalTables)
                {
                    var mergedTables = new MergedTableOrigionalTable();
                    mergedTables.MergedFloorTableId = tbl.FloorTableId;
                    mergedTables.FloorTableId = origionalTable.FloorTableId;

                    db.tabMergedTableOrigionalTables.Add(mergedTables);
                }

                db.tabMergedFloorTables.Add(tbl);
                db.SaveChanges();

                table.FloorTableId = tbl.FloorTableId;

                ViewBag.SelectedTables = selectedTables;

                tbl.TableDesign = this.RenderPartialViewToString("~/Views/MergeTable/MergedTableTemplate.cshtml", table);

                return Json(new
                {
                    Status = ResponseStatus.Success,
                    ItemId = tbl.FloorTableId,
                    Template = tbl.TableDesign,
                    TablesToRemove = string.Join(",#", originalTables.Select(t => t.HtmlId))
                });
            }
            catch (Exception)
            {
                return Json(new { Status = ResponseStatus.Fail, ItemId = 0 });
            }
        }
        //private IList<FloorTable> InitializeAddResOptionsNew(ReservationVM model, bool isDateChanged = false, bool considerFloor = false, bool isMerging = false)
        //{
        //    int maxCoversLimit = db.GetMaxFloorCovers();
        //    ViewBag.StatusList = db.GetStatusList();
        //    ViewBag.ShiftList = db.GetFoodMenuShifts();
        //    ViewBag.LevelList = db.tabFloorPlans.ToList().Select(fp => new
        //    {
        //        Text = "L" + fp.FLevel.Value + "-" + fp.FloorName,
        //        Value = fp.FloorPlanId
        //    });
        //    var coverList = new List<object>();
        //    for (int i = 1; i <= 30; i++)
        //    {
        //        coverList.Add(new { Value = i, Text = i + " Cover" });
        //    }
        //    ViewBag.CoverList = coverList;
        //    //ViewBag.DurationList = new List<string>() { "15MIN", "30MIN", "45MIN", "1HR", "1HR 30MIN", "2HR", "2HR 30MIN", "3HR", "3HR 30MIN", "4HR" };
        //    ViewBag.DurationList = this.GetDurationList("15MIN", "4HR");
        //    if (string.IsNullOrEmpty(model.Duration))
        //    {
        //        model.Duration = "1HR 30MIN";
        //    }
        //    // code for getting time  list
        //    var day = model.resDate.DayOfWeek.ToString().Trim();
        //    int sId = model.ShiftId;
        //    var dId = db.GetWeekDays().Single(p => p.DayName.Contains(day)).DayId;
        //    var openTime = new DateTime();
        //    var closeTime = new DateTime();
        //    //if (sId != 0)
        //    //{
        //    //    var ttime = db.tabMenuShiftHours.Single(p => p.DayId == dId && p.FoodMenuShiftId == sId);
        //    //    openTime = Convert.ToDateTime(ttime.OpenAt);
        //    //    closeTime = Convert.ToDateTime(ttime.CloseAt).AddDays(Convert.ToInt32(ttime.IsNext));
        //    //}
        //    //else
        //    //{
        //    var ttime = db.GetMenuShiftHours().Where(p => p.DayId == dId).AsEnumerable();
        //    var minOpenAt = ttime.Where(p => p.OpenAt != null).Min(p => Convert.ToDateTime(p.OpenAt));
        //    var maxCloseAt = ttime.Where(p => p.CloseAt != null).Max(p => Convert.ToDateTime(p.CloseAt).AddDays(Convert.ToInt32(p.IsNext)));
        //    openTime = Convert.ToDateTime(minOpenAt);
        //    closeTime = Convert.ToDateTime(maxCloseAt);
        //    if (!string.IsNullOrEmpty(model.Duration))
        //    {
        //        closeTime = closeTime.AddMinutes(-(model.Duration.GetMinutesFromDuration() - 15));
        //    }
        //    //}
        //    var op = openTime;
        //    var cl = closeTime;
        //    var TimeList = new List<object>();
        //    var aa = db.GetMenuShiftHours().AsEnumerable().Where(p => p.DayId == dId);
        //    while (op < cl)
        //    {
        //        var startTime = op;
        //        op = op.AddMinutes(15);
        //        int tShiftId = 0;
        //        //var timeShift = aa.Where(s => Convert.ToDateTime(s.OpenAt) <= startTime && Convert.ToDateTime(s.CloseAt).AddDays(s.IsNext.Value) >= startTime).FirstOrDefault();
        //        var openTM = new DateTime();
        //        var closeTM = new DateTime();
        //        var timeShift = aa.Where(s => (DateTime.TryParse(s.OpenAt, out openTM) && DateTime.TryParse(s.CloseAt, out closeTM)) &&
        //            startTime.Date.Add(openTM.TimeOfDay) <= startTime &&
        //            startTime.Date.Add(closeTM.TimeOfDay).AddDays(s.IsNext.Value) >= startTime).FirstOrDefault();
        //        if (timeShift != null)
        //        {
        //            tShiftId = timeShift.FoodMenuShiftId;
        //        }
        //        TimeList.Add(new
        //        {
        //            Text = startTime.ToString("hh:mm tt"),
        //            Value = new DateTime().Add(startTime.TimeOfDay).ToString("ddMMyyyyhhmmtt") + " - " + new DateTime().Add(op.TimeOfDay).ToString("ddMMyyyyhhmmtt") + " - " + tShiftId
        //        });
        //    }
        //    ViewBag.TimeList = TimeList;
        //    //  end of code for getting time  list
        //    if (isDateChanged || string.IsNullOrEmpty(model.time))
        //    {
        //        model.time = ((dynamic)TimeList[0]).Value;
        //    }
        //    // code to get tables list
        //    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 reservation = db.tabReservations.SingleOrDefault(r => !r.IsDeleted && r.ReservationId == model.ReservationId);
        //    if (reservation != null)
        //    {
        //        model.EdtTableId = reservation.FloorTableId;
        //    }
        //    IList<FloorTable> table = null;
        //    var array = new string[] { "Sofa", "Chair", "SofaTable", "Wall", "SolidWall", "GlassWall", "BarTable", "Fence", "Pillar" };
        //    if (considerFloor)
        //    {
        //        if (model.FloorPlanId == 0)
        //        {
        //            model.FloorPlanId = 1;
        //        }
        //        maxCoversLimit = db.GetMaxFloorCovers(model.FloorPlanId);
        //        var floorPlan = db.tabFloorPlans.Include("FloorTables").Where(f => f.FloorPlanId == model.FloorPlanId).Single();
        //        table = floorPlan.FloorTables.Where(t => t.IsDeleted == false).AsEnumerable().Where(t => !array.Contains(t.TableName.Split('-')[0])).ToList();
        //    }
        //    else
        //    {
        //        table = db.tabFloorTables.Where(t => t.IsDeleted == false).ToList().Where(t => !array.Contains(t.TableName.Split('-')[0])).ToList();
        //    }
        //    //var sid = Db.tabFoodMenuShift.Single(p => p.MenuShift == shift).FoodMenuShiftId;
        //    var resList = db.GetReservationByDate(model.resDate);
        //    var rejectedTables = new List<long>();
        //    // check if status is FINISHED, CANCELLED, CANCELLED2
        //    var rejectedStatus = new List<long>()
        //                             {
        //                                 ReservationStatus.Finished,
        //                                 ReservationStatus.Cancelled
        //                                 //ReservationStatus.Cancelled_2
        //                             };
        //    resList = resList.Where(r => !rejectedStatus.Contains(r.StatusId.Value)).ToList();
        //    if (reservation != null)
        //    {
        //        resList = resList.Where(r => r.ReservationId != reservation.ReservationId).ToList();
        //        if (reservation.ReservationDate.Date == model.resDate.Date && startTm == reservation.TimeForm && reservation.Duration.Trim() == model.Duration.Trim())
        //        {
        //            if (reservation.MergedFloorTableId > 0)
        //            {
        //                var orgTables = reservation.MergedFloorTable.OrigionalTables.Select(ot => ot.FloorTable).ToList();
        //                ViewBag.SelectedTables = orgTables;
        //            }
        //        }
        //    }
        //    foreach (var item in resList)
        //    {
        //        var resStart = item.TimeForm;
        //        var resEnd = item.TimeForm.AddMinutes(item.Duration.GetMinutesFromDuration());
        //        if ((resStart <= startTm && resEnd >= endTime) || (resStart >= startTm && resEnd <= endTime) || (resStart < startTm && resEnd > startTm) || (resStart < endTime && resEnd > endTime)) //(resStart >= startTm && resStart < endTime) || (resEnd <= endTime && resEnd > startTm)
        //        {
        //            if (item.FloorTableId == 0 && item.MergedFloorTableId > 0)
        //            {
        //                foreach (var origionalTbl in item.MergedFloorTable.OrigionalTables)
        //                {
        //                    rejectedTables.Add(origionalTbl.FloorTableId);
        //                }
        //            }
        //            else
        //            {
        //                rejectedTables.Add(item.FloorTableId);
        //            }
        //        }
        //    }
        //    foreach (var tbl in table)
        //    {
        //        if (tbl.MaxCover < model.Covers)
        //        {
        //            if (!rejectedTables.Contains(tbl.FloorTableId))
        //            {
        //                rejectedTables.Add(tbl.FloorTableId);
        //            }
        //        }
        //    }
        //    table = table.Where(t => !rejectedTables.Contains(t.FloorTableId)).ToList();
        //    // Ends here
        //    if (model.Covers == 0)
        //    {
        //        model.Covers = 1;
        //    }
        //    //if (model.ShiftId == 0)
        //    //{
        //    model.ShiftId = Convert.ToInt32(tt[2]);
        //    //}
        //    if (string.IsNullOrEmpty(model.Status))
        //    {
        //        model.Status = ReservationStatus.Not_confirmed.ToString();
        //    }
        //    if (string.IsNullOrEmpty(model.tableIdd) || !table.Any(t => t.FloorTableId == Convert.ToInt64(model.tableIdd)))
        //    {
        //        if (table != null && table.Count() > 0 && model.Covers <= maxCoversLimit) // table != null && table.Count() > 0
        //        {
        //            model.tableIdd = table.First().FloorTableId.ToString();
        //        }
        //        else
        //        {
        //            model.tableIdd = "0";
        //            ViewBag.LevelList = new List<object>()
        //                {
        //                    new
        //                    {
        //                        Text = "-No Level-",
        //                        Value = 0
        //                    }
        //                };
        //        }
        //    }
        //    var fTblId = Convert.ToInt64(model.tableIdd);
        //    if (!isMerging)
        //    {
        //        model.FloorPlanId = (table != null && table.Count() > 0 && model.Covers <= maxCoversLimit) ? db.tabFloorTables.Find(fTblId).FloorPlanId : 0;
        //    }
        //    if (model.MergeTableId.HasValue && model.MergeTableId.Value > 0) // (table == null || table.Count() == 0) &&
        //    {
        //        var mergedTable = db.tabMergedFloorTables.Find(model.MergeTableId.Value);
        //        var flrTable = new FloorTable
        //        {
        //            FloorTableId = 0,
        //            TableName = mergedTable.TableName
        //        };
        //        table = new List<FloorTable>()
        //        {
        //            new FloorTable
        //            {
        //                FloorTableId = 0,
        //                TableName = mergedTable.TableName,
        //                FloorPlan = mergedTable.FloorPlan,
        //                MinCover = mergedTable.MinCover,
        //                MaxCover = mergedTable.MaxCover
        //            }
        //        };
        //        ViewBag.LevelList = new List<object>()
        //                {
        //                    new
        //                    {
        //                        Text = "L" + mergedTable.FloorPlan.FLevel.Value + "-" + mergedTable.FloorPlan.FloorName,
        //                        Value = 0
        //                    }
        //                };
        //    }
        //    ViewBag.MaxAvailCovers = maxCoversLimit;
        //    return table.OrderBy(t => t.FloorPlan.FLevel).ThenBy(t => t.TableName, new AlphaNumericComparer()).ToList();
        //}
        //private IList<FloorTable> InitializeAddResOptionsNew20150224(ReservationVM model, bool isDateChanged = false, bool considerFloor = false, bool isMerging = false)
        //{
        //    int maxCoversLimit = db.GetMaxFloorCovers();
        //    ViewBag.StatusList = db.GetStatusList();
        //    ViewBag.ShiftList = db.GetFoodMenuShifts();
        //    ViewBag.LevelList = db.tabFloorPlans.ToList().Select(fp => new
        //    {
        //        Text = "L" + fp.FLevel.Value + "-" + fp.FloorName,
        //        Value = fp.FloorPlanId
        //    });
        //    var coverList = new List<object>();
        //    for (int i = 1; i <= 30; i++)
        //    {
        //        coverList.Add(new { Value = i, Text = i + " Cover" });
        //    }
        //    ViewBag.CoverList = coverList;
        //    ViewBag.DurationList = this.GetDurationList("15MIN", "4HR");
        //    if (string.IsNullOrEmpty(model.Duration))
        //    {
        //        //model.Duration = "1HR 30MIN";
        //        model.Duration = "2HR"; //2015-07-01 Leigh's request
        //    }
        //    // code for getting time  list
        //    var day = model.resDate.DayOfWeek.ToString().Trim();
        //    int sId = model.ShiftId;
        //    var dId = db.GetWeekDays().Single(p => p.DayName.Contains(day)).DayId;
        //    var openTime = new DateTime();
        //    var closeTime = new DateTime();
        //    var ttime = db.GetMenuShiftHours().Where(p => p.DayId == dId).AsEnumerable();
        //    var minOpenAt = ttime.Where(p => p.OpenAt != null).Min(p => Convert.ToDateTime(p.OpenAt));
        //    var maxCloseAt = ttime.Where(p => p.CloseAt != null).Max(p => Convert.ToDateTime(p.CloseAt).AddDays(Convert.ToInt32(p.IsNext)));
        //    openTime = Convert.ToDateTime(minOpenAt);
        //    closeTime = Convert.ToDateTime(maxCloseAt);
        //    if (!string.IsNullOrEmpty(model.Duration))
        //    {
        //        closeTime = closeTime.AddMinutes(-(model.Duration.GetMinutesFromDuration() - 15));
        //    }
        //    var op = openTime;
        //    var cl = closeTime;
        //    var TimeList = new List<object>();
        //    var aa = db.GetMenuShiftHours().AsEnumerable().Where(p => p.DayId == dId);
        //    while (op < cl)
        //    {
        //        var startTime = op;
        //        op = op.AddMinutes(15);
        //        int tShiftId = 0;
        //        var openTM = new DateTime();
        //        var closeTM = new DateTime();
        //        var timeShift = aa.Where(s => (DateTime.TryParse(s.OpenAt, out openTM) && DateTime.TryParse(s.CloseAt, out closeTM)) &&
        //            startTime.Date.Add(openTM.TimeOfDay) <= startTime &&
        //            startTime.Date.Add(closeTM.TimeOfDay).AddDays(s.IsNext.Value) >= startTime).FirstOrDefault();
        //        if (timeShift != null)
        //        {
        //            tShiftId = timeShift.FoodMenuShiftId;
        //        }
        //        TimeList.Add(new
        //        {
        //            Text = startTime.ToString("hh:mm tt"),
        //            Value = new DateTime().Add(startTime.TimeOfDay).ToString("ddMMyyyyhhmmtt") + " - " + new DateTime().Add(op.TimeOfDay).ToString("ddMMyyyyhhmmtt") + " - " + tShiftId
        //        });
        //    }
        //    ViewBag.TimeList = TimeList;
        //    //  end of code for getting time  list
        //    if (isDateChanged || string.IsNullOrEmpty(model.time))
        //    {
        //        model.time = ((dynamic)TimeList[0]).Value;
        //    }
        //    // code to get tables list
        //    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 reservation = db.tabReservations.SingleOrDefault(r => !r.IsDeleted && r.ReservationId == model.ReservationId);
        //    if (reservation != null)
        //    {
        //        model.EdtTableId = reservation.FloorTableId;
        //    }
        //    IList<FloorTable> table = null;
        //    var array = new string[] { "Sofa", "Chair", "SofaTable", "Wall", "SolidWall", "GlassWall", "BarTable", "Fence", "Pillar" };
        //    if (considerFloor)
        //    {
        //        if (model.FloorPlanId == 0)
        //        {
        //            model.FloorPlanId = 1;
        //        }
        //        maxCoversLimit = db.GetMaxFloorCovers(model.FloorPlanId);
        //        var floorPlan = db.tabFloorPlans.Include("FloorTables").Where(f => f.FloorPlanId == model.FloorPlanId).Single();
        //        table = floorPlan.FloorTables.Where(t => t.IsDeleted == false).AsEnumerable().Where(t => !array.Contains(t.TableName.Split('-')[0])).ToList();
        //    }
        //    else
        //    {
        //        table = db.tabFloorTables.Where(t => t.IsDeleted == false).ToList().Where(t => !array.Contains(t.TableName.Split('-')[0])).ToList();
        //    }
        //    var resList = db.GetReservationByDate(model.resDate);
        //    var rejectedTables = new List<long>();
        //    // check if status is FINISHED, CANCELLED, CANCELLED2
        //    var rejectedStatus = new List<long>()
        //                             {
        //                                 ReservationStatus.Finished,
        //                                 ReservationStatus.Cancelled
        //                                 //ReservationStatus.Cancelled_2
        //                             };
        //    resList = resList.Where(r => !rejectedStatus.Contains(r.StatusId.Value)).ToList();
        //    if (reservation != null)
        //    {
        //        resList = resList.Where(r => r.ReservationId != reservation.ReservationId).ToList();
        //        if (reservation.ReservationDate.Date == model.resDate.Date && startTm == reservation.TimeForm && reservation.Duration.Trim() == model.Duration.Trim())
        //        {
        //            if (reservation.MergedFloorTableId > 0)
        //            {
        //                var orgTables = reservation.MergedFloorTable.OrigionalTables.Select(ot => ot.FloorTable).ToList();
        //                ViewBag.SelectedTables = orgTables;
        //            }
        //        }
        //    }
        //    foreach (var item in resList)
        //    {
        //        var resStart = item.TimeForm;
        //        var resEnd = item.TimeForm.AddMinutes(item.Duration.GetMinutesFromDuration());
        //        if ((resStart <= startTm && resEnd >= endTime)
        //            || (resStart >= startTm && resEnd <= endTime)
        //            || (resStart < startTm && resEnd > startTm)
        //            || (resStart < endTime && resEnd > endTime)) //(resStart >= startTm && resStart < endTime) || (resEnd <= endTime && resEnd > startTm)
        //        {
        //            if (item.FloorTableId == 0 && item.MergedFloorTableId > 0)
        //            {
        //                foreach (var origionalTbl in item.MergedFloorTable.OrigionalTables)
        //                {
        //                    rejectedTables.Add(origionalTbl.FloorTableId);
        //                }
        //            }
        //            else
        //            {
        //                rejectedTables.Add(item.FloorTableId);
        //            }
        //        }
        //    }
        //    if (table != null && table.Count() > 0)
        //        maxCoversLimit = table.Where(t => !rejectedTables.Contains(t.FloorTableId)).Max(t => t.MaxCover);
        //    foreach (var tbl in table)
        //    {
        //        if (tbl.MaxCover < model.Covers)
        //        {
        //            if (!rejectedTables.Contains(tbl.FloorTableId))
        //            {
        //                rejectedTables.Add(tbl.FloorTableId);
        //            }
        //        }
        //    }
        //    table = table.Where(t => !rejectedTables.Contains(t.FloorTableId)).ToList();
        //    /**** Table availability feature enabled  start here *****/
        //    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);
        //    table = table.Where(t => !availList.CheckAvailStatus(model.resDate, startTm, endTime, t, 2)
        //        && !blockList.IsTableBlocked(t.FloorTableId, startTm, endTime)).ToList();
        //    /**** Table availability feature enabled end here *****/
        //    // Ends here
        //    if (model.Covers == 0)
        //    {
        //        model.Covers = 1;
        //    }
        //    model.ShiftId = Convert.ToInt32(tt[2]);
        //    if (string.IsNullOrEmpty(model.Status))
        //    {
        //        model.Status = ReservationStatus.Not_confirmed.ToString();
        //    }
        //    if (string.IsNullOrEmpty(model.tableIdd) || !table.Any(t => t.FloorTableId == Convert.ToInt64(model.tableIdd)))
        //    {
        //        if (table != null && table.Count() > 0 && model.Covers <= maxCoversLimit)
        //        {
        //            model.tableIdd = table.First().FloorTableId.ToString();
        //        }
        //        else
        //        {
        //            model.tableIdd = "0";
        //            ViewBag.LevelList = new List<object>()
        //                {
        //                    new
        //                    {
        //                        Text = "-No Level-",
        //                        Value = 0
        //                    }
        //                };
        //        }
        //    }
        //    var fTblId = Convert.ToInt64(model.tableIdd);
        //    if (!isMerging)
        //    {
        //        if (table != null && table.Count() > 0 && model.Covers <= maxCoversLimit)
        //        {
        //            model.FloorPlanId = db.tabFloorTables.Find(fTblId).FloorPlanId;
        //        }
        //        else
        //            model.FloorPlanId = 0; //
        //    }
        //    if (model.MergeTableId.HasValue && model.MergeTableId.Value > 0)
        //    {
        //        var mergedTable = db.tabMergedFloorTables.Find(model.MergeTableId.Value);
        //        var flrTable = new FloorTable
        //        {
        //            FloorTableId = 0,
        //            TableName = mergedTable.TableName
        //        };
        //        table = new List<FloorTable>()
        //        {
        //            new FloorTable
        //            {
        //                FloorTableId = 0,
        //                TableName = mergedTable.TableName,
        //                FloorPlan = mergedTable.FloorPlan,
        //                MinCover = mergedTable.MinCover,
        //                MaxCover = mergedTable.MaxCover
        //            }
        //        };
        //        ViewBag.LevelList = new List<object>()
        //                {
        //                    new
        //                    {
        //                        Text = "L" + mergedTable.FloorPlan.FLevel.Value + "-" + mergedTable.FloorPlan.FloorName,
        //                        Value = 0
        //                    }
        //                };
        //    }
        //    ViewBag.MaxAvailCovers = maxCoversLimit;
        //    return table.OrderBy(t => t.FloorPlan.FLevel).ThenBy(t => t.TableName, new AlphaNumericComparer()).ToList();
        //}
        private IList<FloorTable> InitializeAddResOptionsNew20150512(ReservationVM model, bool isDateChanged = false, bool considerFloor = false, bool isMerging = false)
        {
            int maxCoversLimit = db.GetMaxFloorCovers();

            ViewBag.StatusList = db.GetStatusList();
            ViewBag.ShiftList = db.GetFoodMenuShifts();
            ViewBag.LevelList = db.tabFloorPlans.ToList().Select(fp => new
            {
                Text = "L" + fp.FLevel.Value + "-" + fp.FloorName,
                Value = fp.FloorPlanId

            });

            var coverList = new List<object>();

            for (int i = 1; i <= 30; i++)
            {
                coverList.Add(new { Value = i, Text = i + " Cover" });
            }

            ViewBag.CoverList = coverList;

            ViewBag.DurationList = this.GetDurationList("15MIN", "4HR");

            if (string.IsNullOrEmpty(model.Duration))
            {
                model.Duration = "1HR 30MIN";
                //model.Duration = "2HR"; //2015-07-01 Leigh's request
            }

            // code for getting time  list
            var day = model.resDate.DayOfWeek.ToString().Trim();

            int sId = model.ShiftId;

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

            var openTime = new DateTime();
            var closeTime = new DateTime();

            var ttime = db.GetMenuShiftHours().Where(p => p.DayId == dId).AsEnumerable();
            var minOpenAt = ttime.Where(p => p.OpenAt != null).Min(p => Convert.ToDateTime(p.OpenAt));
            var maxCloseAt = ttime.Where(p => p.CloseAt != null).Max(p => Convert.ToDateTime(p.CloseAt).AddDays(Convert.ToInt32(p.IsNext)));

            openTime = Convert.ToDateTime(minOpenAt);
            closeTime = Convert.ToDateTime(maxCloseAt);

            if (!string.IsNullOrEmpty(model.Duration))
            {
                closeTime = closeTime.AddMinutes(-(model.Duration.GetMinutesFromDuration() - 15));
            }

            var op = openTime;
            var cl = closeTime;

            var TimeList = new List<object>();

            var aa = db.GetMenuShiftHours().AsEnumerable().Where(p => p.DayId == dId);

            while (op < cl)
            {
                var startTime = op;
                op = op.AddMinutes(15);

                int tShiftId = 0;

                var openTM = new DateTime();
                var closeTM = new DateTime();

                var timeShift = aa.Where(s => (DateTime.TryParse(s.OpenAt, out openTM) && DateTime.TryParse(s.CloseAt, out closeTM)) &&
                    startTime.Date.Add(openTM.TimeOfDay) <= startTime &&
                    startTime.Date.Add(closeTM.TimeOfDay).AddDays(s.IsNext.Value) >= startTime).FirstOrDefault();

                if (timeShift != null)
                {
                    tShiftId = timeShift.FoodMenuShiftId;
                }

                TimeList.Add(new
                {
                    Text = startTime.ToString("hh:mm tt"),
                    Value = new DateTime().Add(startTime.TimeOfDay).ToString("ddMMyyyyhhmmtt") + " - " + new DateTime().Add(op.TimeOfDay).ToString("ddMMyyyyhhmmtt") + " - " + tShiftId
                });
            }

            ViewBag.TimeList = TimeList;

            //  end of code for getting time  list
            if (isDateChanged || string.IsNullOrEmpty(model.time))
            {
                model.time = ((dynamic)TimeList[0]).Value;
            }

            // code to get tables list

            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 reservation = db.tabReservations.SingleOrDefault(r => !r.IsDeleted && r.ReservationId == model.ReservationId);

            if (reservation != null)
            {
                model.EdtTableId = reservation.FloorTableId;
            }

            IList<FloorTable> table = null;

            var array = new string[] { "Sofa", "Chair", "SofaTable", "Wall", "SolidWall", "GlassWall", "BarTable", "Fence", "Pillar" };

            if (considerFloor)
            {
                if (model.FloorPlanId == 0)
                {
                    model.FloorPlanId = 1;
                }

                maxCoversLimit = db.GetMaxFloorCovers(model.FloorPlanId);

                var floorPlan = db.tabFloorPlans.Include("FloorTables").Where(f => f.FloorPlanId == model.FloorPlanId).Single();
                table = floorPlan.FloorTables.Where(t => t.IsDeleted == false).AsEnumerable().Where(t => !array.Contains(t.TableName.Split('-')[0])).ToList();
            }
            else
            {
                table = db.tabFloorTables.Where(t => t.IsDeleted == false).ToList().Where(t => !array.Contains(t.TableName.Split('-')[0])).ToList();
            }

            var resList = db.GetReservationByDate(model.resDate);

            var rejectedTables = new List<long>();

            // check if status is FINISHED, CANCELLED, CANCELLED2

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

            resList = resList.Where(r => !rejectedStatus.Contains(r.StatusId.Value)).ToList();

            if (reservation != null)
            {
                resList = resList.Where(r => r.ReservationId != reservation.ReservationId).ToList();
                if (reservation.ReservationDate.Date == model.resDate.Date && startTm == reservation.TimeForm && reservation.Duration.Trim() == model.Duration.Trim())
                {
                    if (reservation.MergedFloorTableId > 0)
                    {
                        var orgTables = reservation.MergedFloorTable.OrigionalTables.Select(ot => ot.FloorTable).ToList();
                        ViewBag.SelectedTables = orgTables;
                    }
                }
            }

            foreach (var item in resList)
            {
                var resStart = item.TimeForm;
                var resEnd = item.TimeForm.AddMinutes(item.Duration.GetMinutesFromDuration());

                if ((resStart <= startTm && resEnd >= endTime)
                    || (resStart >= startTm && resEnd <= endTime)
                    || (resStart < startTm && resEnd > startTm)
                    || (resStart < endTime && resEnd > endTime)) //(resStart >= startTm && resStart < endTime) || (resEnd <= endTime && resEnd > startTm)
                {
                    if (item.FloorTableId == 0 && item.MergedFloorTableId > 0)
                    {
                        foreach (var origionalTbl in item.MergedFloorTable.OrigionalTables)
                        {
                            rejectedTables.Add(origionalTbl.FloorTableId);
                        }
                    }
                    else
                    {
                        rejectedTables.Add(item.FloorTableId);
                    }
                }
            }

            /**** Enable Merge table feature enabled  start here *****/

            var isManualMerge = false;

            if (model.enableMerging)
            {
                foreach (var tbl in table)
                {
                    if (tbl.MaxCover >= model.Covers && !rejectedTables.Contains(tbl.FloorTableId))
                    {
                        rejectedTables.Add(tbl.FloorTableId);
                        isManualMerge = true;
                    }
                }
            }

            /**** Enable Merge table feature enabled  end here *****/

            if (table != null && table.Count() > 0)
                maxCoversLimit = table.Where(t => !rejectedTables.Contains(t.FloorTableId)).Any() ? table.Where(t => !rejectedTables.Contains(t.FloorTableId)).Max(t => t.MaxCover) : 1;

            foreach (var tbl in table)
            {
                if (tbl.MaxCover < model.Covers)
                {
                    if (!rejectedTables.Contains(tbl.FloorTableId))
                    {
                        rejectedTables.Add(tbl.FloorTableId);
                    }
                }
            }

            table = table.Where(t => !rejectedTables.Contains(t.FloorTableId)).ToList();

            /**** Table availability feature enabled  start here *****/

            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);

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

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

            // Ends here

            if (model.Covers == 0)
            {
                model.Covers = 1;
            }

            model.ShiftId = Convert.ToInt32(tt[2]);

            if (string.IsNullOrEmpty(model.Status))
            {
                model.Status = ReservationStatus.Not_confirmed.ToString();
            }

            if (string.IsNullOrEmpty(model.tableIdd) || !table.Any(t => t.FloorTableId == Convert.ToInt64(model.tableIdd)))
            {
                if (table != null && table.Count() > 0 && model.Covers <= maxCoversLimit)
                {
                    model.tableIdd = table.First().FloorTableId.ToString();
                }
                else
                {
                    model.tableIdd = "0";
                    ViewBag.LevelList = new List<object>()
                        {
                            new
                            {
                                Text = "-No Level-",
                                Value = 0
                            }
                        };
                }
            }

            var fTblId = Convert.ToInt64(model.tableIdd);

            if (!isMerging)
            {
                if (table != null && table.Count() > 0 && model.Covers <= maxCoversLimit)
                {
                    model.FloorPlanId = db.tabFloorTables.Find(fTblId).FloorPlanId;
                }
                else
                    model.FloorPlanId = 0; //
            }
            else
            {
            }

            if (model.MergeTableId.HasValue && model.MergeTableId.Value > 0)
            {
                var mergedTable = db.tabMergedFloorTables.Find(model.MergeTableId.Value);

                var flrTable = new FloorTable
                {
                    FloorTableId = 0,
                    TableName = mergedTable.TableName
                };

                table = new List<FloorTable>()
                {
                    new FloorTable
                    {
                        FloorTableId = 0,
                        TableName = mergedTable.TableName,
                        FloorPlan = mergedTable.FloorPlan,
                        MinCover = mergedTable.MinCover,
                        MaxCover = mergedTable.MaxCover
                    }
                };

                ViewBag.LevelList = new List<object>()
                        {
                            new
                            {
                                Text = "L" + mergedTable.FloorPlan.FLevel.Value + "-" + mergedTable.FloorPlan.FloorName,
                                Value = 0
                            }
                        };
            }

            ViewBag.MaxAvailCovers = maxCoversLimit;
            ViewBag.IsAutoMerge = !isManualMerge && (maxCoversLimit < model.Covers);

            return table.OrderBy(t => t.FloorPlan.FLevel).ThenBy(t => t.TableName, new AlphaNumericComparer()).ToList();
        }
        public ActionResult SaveFloor(TempFloorPlan model)
        {
            var fp = Db.tabTempFloorPlans.Include("TempFloorTables").Where(p => p.FloorPlanId == model.FloorPlanId).Single();

            var isFloorActive = Db.tabFloorPlans;
            int[] lvl = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            int flvl;
            if (isFloorActive.Count() == 0)
            {
                flvl = 1;
            }
            else
            {
                flvl = lvl.Where(p => !isFloorActive.Select(s => s.FLevel).ToList().Contains(p)).FirstOrDefault();
            }

            var floorPlan = new FloorPlan()
            {
                CreatedOn = fp.CreatedOn,
                FloorName = model.FloorName,
                PhotoPath = fp.PhotoPath,
                UserId = fp.UserId,
                FLevel = flvl,
                IsActive = isFloorActive.Count() == 0 ? true : false,

                UpdatedBy = User.Identity.GetUserId<long>(),
                UpdatedOn = DateTime.UtcNow,
            };

            Db.tabFloorPlans.Add(floorPlan);

            foreach (var item in fp.TempFloorTables)
            {
                var floorTable = new FloorTable()
                {
                    Angle = item.Angle,
                    CreatedOn = item.CreatedOn,
                    FloorPlanId = floorPlan.FloorPlanId,
                    TableDesign = item.TableDesign,
                    MaxCover = item.MaxCover,
                    MinCover = item.MinCover,
                    TableName = item.TableName,
                    TBottom = item.TBottom,
                    TLeft = item.TLeft,
                    TRight = item.TRight,
                    TTop = item.TTop,
                    UpdatedOn = item.UpdatedOn,
                    HtmlId = item.HtmlId,
                    Shape = item.Shape,
                    Size = item.Size,
                    IsTemporary = false
                };

                Db.tabFloorTables.Add(floorTable);

                //StringBuilder design = new StringBuilder();
                //design.Append(item.TableDesign.Substring(0, item.TableDesign.LastIndexOf("<input")));
                //design.Append("<input id=\"FloorTableId\" name=\"FloorTableId\" type=\"hidden\" value=\"" + floorTable.FloorTableId + "\"/></div>");

                //floorTable.TableDesign = design.ToString();

                //Db.Entry(floorTable).State = EntityState.Modified;
            }

            Db.SaveChanges();

            return RedirectToAction("Index");
        }
        public ActionResult NewFloorPlan()
        {
            var UserId = User.Identity.GetUserId<long>();

            var floor_Name = "Temp Floor " + ((Db.tabFloorPlans.Count() != 0) ? Db.tabFloorPlans.Max(p => p.FloorPlanId) : 0);
            //var floor_Name = "TempFloor" ;

            if (Session["TempFloorUId"] == null)
            {
                this.ManageTempTables();

                var model = new TempFloorPlan()
                {
                    UserId = UserId,
                    Guid = Guid.NewGuid().ToString(),
                    FloorName = floor_Name,
                    CreatedOn = DateTime.UtcNow.ToClientTime()
                };

                Db.tabTempFloorPlans.Add(model);
                Db.SaveChanges();

                Session["TempFloorUId"] = model.Guid;

                return View(model);
            }
            else
            {
                var Uid = (string)Session["TempFloorUId"];
                var model = Db.tabTempFloorPlans.Include("TempFloorTables").Where(tf => tf.Guid == Uid).SingleOrDefault();

                if (model == null)
                {
                    model = new TempFloorPlan()
                    {
                        UserId = UserId,
                        Guid = Guid.NewGuid().ToString(),
                        FloorName = floor_Name,
                        CreatedOn = DateTime.UtcNow.ToClientTime()
                    };

                    Db.tabTempFloorPlans.Add(model);
                    Db.SaveChanges();
                }

                if (model.TempFloorTables != null)
                {
                    foreach (var item in model.TempFloorTables)
                    {
                        FloorTable copyTable = new FloorTable();
                        CopyHelper.Copy(typeof(TempFloorTable), item, typeof(FloorTable), copyTable);

                        item.TableDesign = this.RenderPartialViewToString("GetFloorItemTemplate", copyTable);

                        copyTable = null;
                    }
                }

                Session["TempFloorUId"] = model.Guid;

                return View(model);
            }
        }
        public ActionResult UpdateMergedTable(FloorTable table, Int64 MergedFloorTableId, List<long> selectedTables)
        {
            ModelState.Clear();

            try
            {
                var tbl = db.tabMergedFloorTables.Find(table.FloorTableId);

                tbl.FloorTableId = table.FloorTableId = MergedFloorTableId;
                tbl.FloorPlanId = table.FloorPlanId;
                tbl.TableName = table.TableName;
                tbl.Angle = table.Angle;
                tbl.MinCover = table.MinCover;
                tbl.HtmlId = table.HtmlId;
                tbl.Shape = table.Shape;
                tbl.Size = table.Size;
                tbl.MaxCover = table.MaxCover;
                tbl.TTop = table.TTop;
                tbl.TLeft = table.TLeft;
                tbl.TableDesign = " ";
                tbl.IsTemporary = table.IsTemporary = false;

                //var originalTables = db.tabFloorTables.Where(t => selectedTables.Contains(t.FloorTableId)).ToList();

                //foreach (var origionalTable in originalTables)
                //{
                //    var mergedTables = new MergedTableOrigionalTable();
                //    mergedTables.MergedFloorTableId = tbl.FloorTableId;
                //    mergedTables.FloorTableId = origionalTable.FloorTableId;

                //    db.tabMergedTableOrigionalTables.Add(mergedTables);
                //}

                db.Entry(tbl).State = EntityState.Modified;
                db.SaveChanges();

                ViewBag.SelectedTables = selectedTables;

                tbl.TableDesign = this.RenderPartialViewToString("~/Views/MergeTable/MergedTableTemplate.cshtml", table);

                return Json(new
                {
                    Status = ResponseStatus.Success,
                    ItemId = tbl.FloorTableId,
                    Template = tbl.TableDesign,
                    HtmlId = tbl.HtmlId
                    //TablesToRemove = string.Join(",#", originalTables.Select(t => t.HtmlId))
                });
            }
            catch (Exception)
            {
                return Json(new { Status = ResponseStatus.Fail, ItemId = 0 });
            }
        }
        public ActionResult GetMergedTable(List<long> selectedTables, int covers)
        {
            ModelState.Clear();

            var tableName = string.Empty;
            var tableMinCovers = 0;
            var tableMaxCovers = 0;
            var floorId = 0L;

            if (selectedTables != null)
            {
                var tables = db.tabFloorTables.Where(t => selectedTables.Contains(t.FloorTableId)).ToList();

                foreach (var tbl in tables)
                {
                    tableName += tbl.TableName + " & ";
                    tableMinCovers += tbl.MinCover;
                    tableMaxCovers += tbl.MaxCover;
                }

                tableName = tableName.Remove(tableName.Length - 3);
                floorId = tables.First().FloorPlanId;
            }
            else
            {
                return Content("<h1>Preview Here</h1>");
            }

            if (tableMaxCovers < covers)
            {
                return Content("<h1>Max Covers should be more than " + covers + ".</h1>");
            }
            else if (tableMaxCovers > 16)
            {
                return Content("<h1>Max Covers should be less than 16.</h1>");
            }

            var table = new FloorTable()
            {
                FloorPlanId = floorId,
                HtmlId = "table" + Guid.NewGuid().ToString("N"),
                TableName = tableName,
                Angle = 0,
                MinCover = tableMinCovers,
                MaxCover = tableMaxCovers,
                Size = "random",
                Shape = "RANDOM",
                TTop = "0",
                TLeft = "0",
                TableDesign = " ",
                IsTemporary = true,
            };

            ViewBag.SelectedTables = selectedTables;

            return PartialView("MergedTableTemplate", table);
        }
        public static bool CheckAvailStatus(this IList<TableAvailability> availList, DateTime date, DateTime startTime, DateTime endTime, FloorTable table, int checkStatusId)
        {
            var tblAvailList = availList.Where(ta => ta.TableAvailabilityFloorTables.Any(taf => taf.FloorTableId == table.FloorTableId)).ToList();

            tblAvailList = tblAvailList.Where(ta => ta.CheckAvail(date, startTime, endTime)).OrderByDescending(ta => ta.CreatedOn).ToList();

            if (tblAvailList.Any())
            {
                var availablity = tblAvailList.FirstOrDefault();
                return checkStatusId == availablity.AvailablityStatusId;
            }
            else
            {
                return false;
            }
        }
        //public static void CheckReservations20150310(this Controller controller, IList<TableAvailability> availList, IList<FloorTableBlock> blockList,
        //    FloorTable table, string duration, DateTime? startTime, DateTime? endTime, int? shiftId, out int coverCount)
        //{
        //    coverCount = 0;
        //    var design = table.TableDesign;
        //    var TableName = GetMatchedTagsFromHtml(design, String.Format("<h3(.*?)>(.*?)</h3>")).FirstOrDefault();
        //    if (!string.IsNullOrEmpty(TableName))
        //    {
        //        IQueryable<Reservation> reservation = table.Reservations.Where(r => !r.IsDeleted).AsQueryable();
        //        IQueryable<Reservation> mergedreservation = table.MergedTables.Select(m => m.MergedFloorTable).SelectMany(mt => mt.Reservations)
        //            .Where(r => !r.IsDeleted).AsQueryable();
        //        IQueryable<Reservation> upcomingReservation = reservation.AsQueryable();
        //        IQueryable<Reservation> upcomingMergedreservation = mergedreservation.AsQueryable();
        //        if (!shiftId.HasValue)
        //        {
        //            if (startTime.HasValue)
        //            {
        //                if (startTime.HasValue && endTime.HasValue)
        //                {
        //                    var preStart = startTime.Value.AddMinutes(90);
        //                    reservation = reservation.Where(r => r.TimeForm <= startTime.Value && r.TimeTo >= endTime.Value);
        //                    mergedreservation = mergedreservation.Where(r => r.TimeForm <= startTime.Value && r.TimeForm.AddMinutes(r.Duration.GetMinutesFromDuration()) >= endTime.Value);
        //                    upcomingReservation = upcomingReservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= startTime.Value);
        //                    upcomingMergedreservation = upcomingMergedreservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= startTime.Value);
        //                }
        //                else
        //                {
        //                    var start = startTime.Value.Date.AddTicks(DateTime.UtcNow.ToClientTime().TimeOfDay.Ticks);
        //                    var preStart = start.AddMinutes(90);
        //                    reservation = reservation.Where(r => r.TimeForm <= start && r.TimeTo >= start);
        //                    mergedreservation = mergedreservation.Where(r => r.TimeForm <= start && r.TimeTo >= start);
        //                    upcomingReservation = upcomingReservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= start);
        //                    upcomingMergedreservation = upcomingMergedreservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= start);
        //                }
        //            }
        //            else
        //            {
        //                var now = DateTime.UtcNow.ToClientTime();
        //                var preStart = now.AddMinutes(90);
        //                reservation = reservation.Where(r => r.TimeForm <= now && r.TimeTo >= now);
        //                mergedreservation = mergedreservation.Where(r => r.TimeForm <= now && r.TimeTo >= now);
        //                upcomingReservation = upcomingReservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= now);
        //                upcomingMergedreservation = upcomingMergedreservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= now);
        //            }
        //        }
        //        else
        //        {
        //            if (startTime.HasValue)
        //            {
        //                var preStart = startTime.Value.AddMinutes(90);
        //                reservation = reservation.Where(r => r.ReservationDate == startTime.Value.Date);
        //                mergedreservation = mergedreservation.Where(r => r.ReservationDate == startTime.Value.Date);
        //                upcomingReservation = upcomingReservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= startTime.Value);
        //                upcomingMergedreservation = upcomingMergedreservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= startTime.Value);
        //            }
        //            else
        //            {
        //                var now = DateTime.UtcNow.ToClientTime();
        //                var preStart = now.AddMinutes(90);
        //                reservation = reservation.Where(r => r.ReservationDate == DateTime.UtcNow.ToClientTime().Date);
        //                mergedreservation = mergedreservation.Where(r => r.ReservationDate == DateTime.UtcNow.ToClientTime().Date);
        //                upcomingReservation = upcomingReservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= now);
        //                upcomingMergedreservation = upcomingMergedreservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= now);
        //            }
        //            if (shiftId.Value != 0)
        //            {
        //                reservation = reservation.Where(r => r.FoodMenuShiftId == shiftId.Value);
        //                mergedreservation = mergedreservation.Where(r => r.FoodMenuShiftId == shiftId.Value);
        //            }
        //        }
        //        // check if status is FINISHED, CANCELLED, CANCELLED2
        //        var rejectedStatus = new List<long?>()
        //                             {
        //                                 ReservationStatus.Finished,
        //                                 ReservationStatus.Cancelled
        //                                 //ReservationStatus.Cancelled_2
        //                             };
        //        var reservationList = reservation.Where(r => !rejectedStatus.Contains(r.StatusId)).ToList();
        //        var mergedreservationList = mergedreservation.Where(r => !rejectedStatus.Contains(r.StatusId)).ToList();
        //        var upcomingReservationList = upcomingReservation.Where(r => !rejectedStatus.Contains(r.StatusId)).ToList();
        //        var upcomingMergedReservationList = upcomingMergedreservation.Where(r => !rejectedStatus.Contains(r.StatusId)).ToList();
        //        upcomingReservationList.AddRange(upcomingMergedReservationList);
        //        // Ends here
        //        if (reservationList.Count > 0 || mergedreservationList.Count > 0)
        //        {
        //            var allRes = new List<Reservation>();
        //            if (reservationList.Count() > 0)
        //                allRes.AddRange(reservationList);
        //            if (mergedreservationList.Count() > 0)
        //                allRes.AddRange(mergedreservationList);
        //            allRes = allRes.OrderBy(r => r.TimeForm).ToList();
        //            //table.TableDesign = design.Replace(TableName, TableName + "<img alt=\"\" src=\"/images/red-s.png\" class=\"table-img\">");
        //            design = design.Replace(TableName, TableName + "<img alt=\"\" src=\"/images/red-s.png\" class=\"table-img\">");
        //            if (allRes.First().FloorTableId > 0)
        //            {
        //                var regex = new Regex(@"([\w-]+)\s*:\s*([^;]+)");
        //                var match = regex.Match(GetMatchedTagsFromHtml(design, String.Format("<div[^>]*?class=([\"'])[^>]*{0}[^>]*\\1[^>]*>", "table-main")).FirstOrDefault());
        //                while (match.Success)
        //                {
        //                    var key = match.Groups[1].Value;
        //                    var value = match.Groups[2].Value;
        //                    if (key == "top")
        //                    {
        //                        design = design.Replace(value, allRes.First().TablePositionTop);
        //                    }
        //                    if (key == "left")
        //                    {
        //                        design = design.Replace(value, allRes.First().TablePositionLeft);
        //                    }
        //                    match = match.NextMatch();
        //                }
        //            }
        //            var popup = controller.RenderPartialViewToString("~/Views/Floor/ReservationListPartial.cshtml", allRes);
        //            StringBuilder designer = new StringBuilder();
        //            designer.Append(design.Substring(0, design.LastIndexOf("</div>")));
        //            designer.Append(popup + "</div>");
        //            table.TableDesign = designer.ToString();
        //            coverCount = allRes.Sum(r => r.Covers);
        //        }
        //        else if (upcomingReservationList.Count > 0)
        //        {
        //            design = design.Replace(TableName, TableName + "<img alt=\"\" src=\"/images/upcom-s.png\" class=\"table-img\">");
        //            var popup = controller.RenderPartialViewToString("~/Views/Floor/ReservationListPartial.cshtml", upcomingReservationList);
        //            StringBuilder designer = new StringBuilder();
        //            designer.Append(design.Substring(0, design.LastIndexOf("</div>")));
        //            designer.Append(popup + "</div>");
        //            table.TableDesign = designer.ToString();
        //        }
        //        else
        //        {
        //            if (endTime.HasValue && !string.IsNullOrWhiteSpace(duration))
        //                endTime = startTime.Value.AddMinutes(duration.GetMinutesFromDuration());
        //            if (startTime.HasValue && endTime.HasValue && (availList.CheckAvailStatus(startTime.Value.Date, startTime.Value, endTime.Value, table, 2)
        //                    || blockList.IsTableBlocked(table.FloorTableId, startTime.Value, endTime.Value)))
        //                table.TableDesign = design.Replace(TableName, TableName + "<img alt=\"\" src=\"/images/free-s.png\" class=\"table-img\">");
        //            else
        //                table.TableDesign = design.Replace(TableName, TableName + "<img alt=\"\" src=\"/images/green-a.png\" class=\"table-img\">");
        //        }
        //    }
        //}
        public static void CheckReservations20150622(this Controller controller, IList<Reservation> todayReservations, IList<TableAvailability> availList, IList<FloorTableBlock> blockList,
            FloorTable table, string duration, DateTime? startTime, DateTime? endTime, int? shiftId, out int coverCount)
        {
            coverCount = 0;
            var deafultTimeZoneTime = DateTime.UtcNow.ToDefaultTimeZone(controller.User.Identity.GetDatabaseName());
            var design = table.TableDesign;

            var TableName = GetMatchedTagsFromHtml(design, String.Format("<h3(.*?)>(.*?)</h3>")).FirstOrDefault();

            if (!string.IsNullOrEmpty(TableName))
            {
                IList<Reservation> reservation = todayReservations.Where(r => r.FloorTableId == table.FloorTableId).ToList();
                IList<Reservation> mergedreservation = todayReservations.Where(r => r.FloorTableId == 0
                    && r.MergedFloorTable.OrigionalTables.Any(t => t.FloorTableId == table.FloorTableId)).ToList();
                IList<Reservation> upcomingReservation = reservation.ToList();
                IList<Reservation> upcomingMergedreservation = mergedreservation.ToList();

                if (!shiftId.HasValue)
                {
                    if (startTime.HasValue)
                    {
                        if (startTime.HasValue && endTime.HasValue)
                        {
                            var preStart = startTime.Value.AddMinutes(90);
                            reservation = reservation.Where(r => r.TimeForm <= startTime.Value && r.TimeTo >= endTime.Value).ToList();
                            mergedreservation = mergedreservation.Where(r => r.TimeForm <= startTime.Value && r.TimeForm.AddMinutes(r.Duration.GetMinutesFromDuration()) >= endTime.Value).ToList();
                            upcomingReservation = upcomingReservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= startTime.Value).ToList();
                            upcomingMergedreservation = upcomingMergedreservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= startTime.Value).ToList();
                        }
                        else
                        {
                            var start = startTime.Value.Date.AddTicks(deafultTimeZoneTime.TimeOfDay.Ticks);
                            var preStart = start.AddMinutes(90);
                            reservation = reservation.Where(r => r.TimeForm <= start && r.TimeTo >= start).ToList();
                            mergedreservation = mergedreservation.Where(r => r.TimeForm <= start && r.TimeTo >= start).ToList();
                            upcomingReservation = upcomingReservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= start).ToList();
                            upcomingMergedreservation = upcomingMergedreservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= start).ToList();
                        }
                    }
                    else
                    {
                        var now = deafultTimeZoneTime;
                        var preStart = now.AddMinutes(90);
                        reservation = reservation.Where(r => r.TimeForm <= now && r.TimeTo >= now).ToList();
                        mergedreservation = mergedreservation.Where(r => r.TimeForm <= now && r.TimeTo >= now).ToList();
                        upcomingReservation = upcomingReservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= now).ToList();
                        upcomingMergedreservation = upcomingMergedreservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= now).ToList();
                    }
                }
                else
                {
                    if (startTime.HasValue)
                    {
                        var preStart = startTime.Value.AddMinutes(90);
                        reservation = reservation.Where(r => r.ReservationDate == startTime.Value.Date).ToList();
                        mergedreservation = mergedreservation.Where(r => r.ReservationDate == startTime.Value.Date).ToList();
                        upcomingReservation = upcomingReservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= startTime.Value).ToList();
                        upcomingMergedreservation = upcomingMergedreservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= startTime.Value).ToList();
                    }
                    else
                    {
                        var now = deafultTimeZoneTime;
                        var preStart = now.AddMinutes(90);
                        reservation = reservation.Where(r => r.ReservationDate == now.Date).ToList();
                        mergedreservation = mergedreservation.Where(r => r.ReservationDate == now.Date).ToList();
                        upcomingReservation = upcomingReservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= now).ToList();
                        upcomingMergedreservation = upcomingMergedreservation.Where(r => r.TimeForm <= preStart && r.TimeForm >= now).ToList();
                    }

                    if (shiftId.Value != 0)
                    {
                        reservation = reservation.Where(r => r.FoodMenuShiftId == shiftId.Value).ToList();
                        mergedreservation = mergedreservation.Where(r => r.FoodMenuShiftId == shiftId.Value).ToList();
                    }
                }

                // check if status is FINISHED, CANCELLED, CANCELLED2

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

                var reservationList = reservation.Where(r => !rejectedStatus.Contains(r.StatusId)).ToList();
                var mergedreservationList = mergedreservation.Where(r => !rejectedStatus.Contains(r.StatusId)).ToList();
                var upcomingReservationList = upcomingReservation.Where(r => !rejectedStatus.Contains(r.StatusId)).ToList();
                var upcomingMergedReservationList = upcomingMergedreservation.Where(r => !rejectedStatus.Contains(r.StatusId)).ToList();
                upcomingReservationList.AddRange(upcomingMergedReservationList);

                // Ends here

                if (reservationList.Count > 0 || mergedreservationList.Count > 0)
                {
                    var allRes = new List<Reservation>();

                    if (reservationList.Count() > 0)
                        allRes.AddRange(reservationList);

                    if (mergedreservationList.Count() > 0)
                        allRes.AddRange(mergedreservationList);

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

                    //table.TableDesign = design.Replace(TableName, TableName + "<img alt=\"\" src=\"/images/red-s.png\" class=\"table-img\">");

                    design = design.Replace(TableName, TableName + "<img alt=\"\" src=\"/images/red-s.png\" class=\"table-img\">");

                    if (allRes.First().FloorTableId > 0)
                    {
                        var regex = new Regex(@"([\w-]+)\s*:\s*([^;]+)");
                        var match = regex.Match(GetMatchedTagsFromHtml(design, String.Format("<div[^>]*?class=([\"'])[^>]*{0}[^>]*\\1[^>]*>", "table-main")).FirstOrDefault());
                        while (match.Success)
                        {
                            var key = match.Groups[1].Value;
                            var value = match.Groups[2].Value;
                            if (key == "top")
                            {
                                design = design.Replace(value, allRes.First().TablePositionTop);
                            }

                            if (key == "left")
                            {
                                design = design.Replace(value, allRes.First().TablePositionLeft);
                            }

                            match = match.NextMatch();
                        }
                    }

                    var popup = controller.RenderPartialViewToString("~/Views/Floor/ReservationListPartial.cshtml", allRes);

                    StringBuilder designer = new StringBuilder();
                    designer.Append(design.Substring(0, design.LastIndexOf("</div>")));
                    designer.Append(popup + "</div>");

                    table.TableDesign = designer.ToString();

                    coverCount = allRes.Sum(r => r.Covers);
                }
                else if (upcomingReservationList.Count > 0)
                {
                    design = design.Replace(TableName, TableName + "<img alt=\"\" src=\"/images/upcom-s.png\" class=\"table-img\">");

                    var popup = controller.RenderPartialViewToString("~/Views/Floor/ReservationListPartial.cshtml", upcomingReservationList);

                    StringBuilder designer = new StringBuilder();
                    designer.Append(design.Substring(0, design.LastIndexOf("</div>")));
                    designer.Append(popup + "</div>");

                    table.TableDesign = designer.ToString();
                }
                else
                {
                    if (endTime.HasValue && !string.IsNullOrWhiteSpace(duration))
                        endTime = startTime.Value.AddMinutes(duration.GetMinutesFromDuration());

                    if (startTime.HasValue && endTime.HasValue && (availList.CheckAvailStatus(startTime.Value.Date, startTime.Value, endTime.Value, table, 2)
                            || blockList.IsTableBlocked(table.FloorTableId, startTime.Value, endTime.Value)))
                        table.TableDesign = design.Replace(TableName, TableName + "<img alt=\"\" src=\"/images/free-s.png\" class=\"table-img\">");
                    else
                        table.TableDesign = design.Replace(TableName, TableName + "<img alt=\"\" src=\"/images/green-a.png\" class=\"table-img\">");
                }
            }
        }
        public JsonResult UpdateTempItem(TempFloorTable table)
        {
            ViewBag.IsTemp = true;

            try
            {
                var tbl = Db.tabTempFloorTables.Find(table.FloorTableId);
                tbl.TableName = table.TableName;

                FloorTable copyTable = new FloorTable();
                CopyHelper.Copy(typeof(TempFloorTable), table, typeof(FloorTable), copyTable);

                tbl.TableDesign = this.RenderPartialViewToString("~/Views/Floor/GetFloorItemTemplate.cshtml", copyTable);
                tbl.Angle = table.Angle;
                //tbl.MinCover = table.MinCover;
                //tbl.HtmlId = table.HtmlId;
                //tbl.Shape = table.Shape;
                //tbl.Size = table.Size;
                //tbl.MaxCover = table.MaxCover;
                tbl.TTop = table.TTop;
                tbl.TBottom = table.TBottom;
                tbl.TLeft = table.TLeft;
                tbl.TRight = table.TRight;
                tbl.UpdatedOn = DateTime.UtcNow.ToDefaultTimeZone(User.Identity.GetDatabaseName());

                Db.Entry(tbl).State = EntityState.Modified;
                Db.SaveChanges();

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

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

                return Json(new
                {
                    Status = ResponseStatus.Success,
                    ItemId = tbl.FloorTableId,
                    totalTables = totalTables,
                    totalMaxCovers = totalMaxCovers,
                    totalMinCovers = totalMinCovers
                });
            }
            catch (Exception)
            {
                return Json(new { Status = ResponseStatus.Fail, ItemId = 0 });
            }
        }
        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);
            }
        }
        private Reservation CheckReservationStatus(FloorTable table, DateTime startTime, DateTime endTime, out bool isResStart)
        {
            isResStart = false;

            if (startTime.Date == endTime.Date)
            {
                startTime = startTime.AddDays(-1);
            }

            //var res = table.Reservations.Where(r => !r.IsDeleted && r.ReservationDate == startTime.Date && r.TimeForm <= startTime && startTime < r.TimeTo).FirstOrDefault();

            var reservations = db.GetReservationByDate(startTime.Date);

            var res = reservations.Where(r => !r.IsDeleted
                && (r.FloorTableId == 0 ? r.MergedFloorTable.OrigionalTables.Any(t => t.FloorTableId == table.FloorTableId) : r.FloorTableId == table.FloorTableId)
                && r.ReservationDate == startTime.Date
                && (r.TimeForm <= startTime && startTime < r.TimeTo)).FirstOrDefault();

            if (res != null
                && (res.FloorTableId == 0 ? res.MergedFloorTable.OrigionalTables.First().FloorTableId == table.FloorTableId : true))
            {
                isResStart = res.TimeForm == startTime;
            }

            return res;
        }
        private int CheckAvailStatus(DateTime startTime, Reservation res, List<TableAvailability> availablilies, FloorTable table)
        {
            if (res != null)
            {
                return 4;
            }

            if (availablilies != null && availablilies.Count > 0)
            {
                var avails = availablilies.Where(ta =>
                    (ta.StartDate <= ((startTime.TimeOfDay.TotalMinutes < 240) ? startTime.AddDays(-1).Date : startTime.Date) && ta.EndDate >= ((startTime.TimeOfDay.TotalMinutes < 240) ? startTime.AddDays(-1).Date : startTime.Date))
                    && ta.TableAvailabilityFloorTables.Any(t => t.FloorTableId.Equals(table.FloorTableId)))
                    .ToList();

                avails = avails.Where(ta => CheckAvail(ta, startTime)).OrderByDescending(ta => ta.CreatedOn).ToList();

                //foreach (var avail in avails)
                //{
                //    var TAstartTime = startTime.Date.AddTicks(Convert.ToDateTime(avail.StartTime).TimeOfDay.Ticks);
                //    var TAendTime = startTime.Date.AddTicks(Convert.ToDateTime(avail.EndTime).TimeOfDay.Ticks);

                //    if (!(TAstartTime <= startTime && TAendTime > startTime))
                //    {
                //        avails.Remove(avail);
                //    }
                //}

                //avails = avails.Where(ta =>
                //                (startTime.Date.AddTicks(Convert.ToDateTime(ta.StartTime).TimeOfDay.Ticks) <= startTime && startTime.Date.AddTicks(Convert.ToDateTime(ta.EndTime).TimeOfDay.Ticks) > startTime)
                //                && ta.TableAvailabilityWeekDays.Any(w => w.WeekDays.DayName.Equals(startTime.DayOfWeek.ToString()))).ToList();

                if (avails.Any())
                {
                    var availablity = avails.FirstOrDefault();
                    return availablity.AvailablityStatusId;
                }
                else
                {
                    return 0;
                }
            }

            return 0;
        }