public ActionResult Create(CustomersEmails customersemails)
        {
            if (ModelState.IsValid)
            {
                db.tabCustomersEmails.Add(customersemails);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.CustomerId = new SelectList(db.tabCustomers, "CustomerId", "FirstName", customersemails.CustomerId);
            return View(customersemails);
        }
        public ActionResult ReservationSave(DateTime date, string fname, string lname, string shift, string mobileNo, string email, int cover, string time, Int64 tableId, Int64 floorId, string TopTablePosition, string LeftTablePosition)
        {
            email = email.Trim();
            mobileNo = mobileNo.Trim();
            shift = shift.Trim();

            var tt = time.Split('-');

            var startTime = date.Add(DateTime.ParseExact(tt[0].Trim(), "ddMMyyyyhhmmtt", CultureInfo.InvariantCulture).TimeOfDay);
            var endTime = date.Add(DateTime.ParseExact(tt[1].Trim(), "ddMMyyyyhhmmtt", CultureInfo.InvariantCulture).TimeOfDay);

            var customer = Db.tabCustomers.Where(c => c.PhoneNumbers.Any(cn => cn.PhoneNumbers.Contains(mobileNo))).FirstOrDefault();

            int shiftId = Convert.ToInt32(tt[2]);
            //if (shift == "All")
            //{
            //    var sh = Db.tabMenuShiftHours.AsEnumerable();

            //    if (endTime.Date == startTime.AddDays(1).Date)
            //    {
            //        DateTime openAt = new DateTime();
            //        DateTime closeAt = new DateTime();

            //        //var shifts = sh.Where(s => (DateTime.TryParse(s.OpenAt, out openAt) && (startTime.TimeOfDay >= openAt.TimeOfDay)) && (DateTime.TryParse(s.CloseAt, out closeAt) && (startTime.TimeOfDay <= closeAt.AddMinutes(-15).TimeOfDay))).FirstOrDefault();
            //        shiftId = 1;
            //    }
            //    else
            //{
            //        DateTime openAt = new DateTime();
            //        DateTime closeAt = new DateTime();
            //        var shifts = sh.Where(s => (DateTime.TryParse(s.OpenAt, out openAt) && (startTime.TimeOfDay >= openAt.TimeOfDay)) && (DateTime.TryParse(s.CloseAt, out closeAt) && (startTime.TimeOfDay <= closeAt.AddMinutes(-15).TimeOfDay))).FirstOrDefault();

            //        shiftId = shifts.FoodMenuShiftId;
            //    }
            //}
            //else
            //{
            //    shiftId = Db.tabFoodMenuShift.Where(s => s.MenuShift.Contains(shift)).Single().FoodMenuShiftId;
            //}

            if (customer != null)
            {
                var reservation = new Reservation()
                {
                    FloorPlanId = floorId,
                    Covers = cover,
                    CustomerId = customer.CustomerId,
                    FoodMenuShiftId = shiftId,
                    ReservationDate = date,
                    TimeForm = startTime,
                    TimeTo = endTime,
                    FloorTableId = tableId,
                    StatusId = 13,
                    UserId = User.Identity.GetUserId<long>(),
                    TablePositionLeft = LeftTablePosition,
                    TablePositionTop = TopTablePosition
                };

                Db.tabReservations.Add(reservation);

            }
            else
            {
                var cust = new Customers()
                {
                    FirstName = fname,
                    LastName = lname,
                    DateCreated = DateTime.UtcNow,
                    DateOfBirth = DateTime.UtcNow,
                    Address1 = "1",
                    Address2 = "2",
                    Anniversary = DateTime.UtcNow,
                };

                Db.tabCustomers.Add(cust);

                if (!string.IsNullOrEmpty(email))
                {
                    var cemail = new CustomersEmails()
                    {
                        CustomerId = cust.CustomerId,
                        Email = email,
                        EmailTypeId = 1
                    };
                    Db.tabCustomersEmails.Add(cemail);
                }

                var cphone = new CustomersPhoneNumbers()
                {
                    CustomerId = cust.CustomerId,
                    PhoneNumbers = mobileNo,
                    PhoneTypeId = 1
                };

                Db.tabCustomersPhoneNumbers.Add(cphone);

                var reservation = new Reservation()
                {
                    FloorPlanId = floorId,
                    Covers = cover,
                    CustomerId = cust.CustomerId,
                    FoodMenuShiftId = shiftId,
                    ReservationDate = date,
                    TimeForm = startTime,
                    TimeTo = endTime,
                    FloorTableId = tableId,
                    StatusId = 13,
                    UserId = User.Identity.GetUserId<long>(),
                    TablePositionLeft = LeftTablePosition,
                    TablePositionTop = TopTablePosition
                };
                Db.tabReservations.Add(reservation);
            }

            Db.SaveChanges();
            return null;
        }
        public ActionResult SaveReservationWithPIN(ReservationVM model)
        {
            try
            {
                var loginUser = db.Users.Find(User.Identity.GetUserId<long>());
                UserProfile pinUser = null;
                Waiting waiting = null;

                if ((model.PIN.HasValue || loginUser.EnablePIN) && !model.MobileNumber.Contains("9999999999"))
                {
                    pinUser = db.Users.Where(u => u.UserCode == model.PIN.Value).FirstOrDefault();

                    if (pinUser == null)
                    {
                        return Json(new
                        {
                            Status = ResponseStatus.Fail,
                            Message = "Please enter a valid user PIN."
                        }, JsonRequestBehavior.AllowGet);
                    }
                }

                FloorTableServer server = null;
                var fTblId = Convert.ToInt64(model.tableIdd);

                if (fTblId == 0 && model.MergeTableId == 0)
                {
                    return Json(new
                    {
                        Status = ResponseStatus.Fail,
                        Message = "Please select a table."
                    }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    if (fTblId > 0)
                    {
                        var flrTbl = db.tabFloorTables.Find(fTblId);
                        model.FloorPlanId = flrTbl.FloorPlanId;
                        model.MergeTableId = 0;
                        server = flrTbl.FloorTableServer;
                    }
                    else
                    {
                        model.FloorPlanId = db.tabMergedFloorTables.Find(model.MergeTableId.Value).FloorPlanId;
                    }
                }

                double time = 0;
                long resId = 0;
                if (!string.IsNullOrEmpty(model.Email))
                {
                    model.Email = model.Email.Trim();
                }

                model.MobileNumber = model.MobileNumber.Trim();
                // model.ShiftId = model.ShiftId;

                var tt = model.time.Split('-');

                var startTime = model.resDate.Add(DateTime.ParseExact(tt[0].Trim(), "ddMMyyyyhhmmtt", CultureInfo.InvariantCulture).TimeOfDay);
                var endTime = model.resDate.Add(DateTime.ParseExact(tt[1].Trim(), "ddMMyyyyhhmmtt", CultureInfo.InvariantCulture).TimeOfDay);

                bool isFakeMobileNo = long.Parse(model.MobileNumber) == 0L;

                if (model.WaitingId > 0)
                {
                    waiting = db.tabWaitings.Find(model.WaitingId);
                }

                var customer = db.tabCustomers.Where(c => !isFakeMobileNo && c.PhoneNumbers.Any(cn => cn.PhoneNumbers.Contains(model.MobileNumber))).FirstOrDefault();

                if (isFakeMobileNo && waiting != null)
                {
                    customer = waiting.Customer;
                    customer.FirstName = model.FirstName;
                    customer.LastName = model.LastName;
                }

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

                model.Status = (!string.IsNullOrEmpty(model.Status)) ? model.Status : ReservationStatus.Not_confirmed.ToString();

                if (customer != null)
                {
                    var reservation = new Reservation()
                    {
                        FloorPlanId = model.FloorPlanId,
                        Covers = model.Covers,
                        CustomerId = customer.CustomerId,
                        FoodMenuShiftId = model.ShiftId,
                        ReservationDate = model.resDate,
                        TimeForm = startTime,
                        TimeTo = startTime.AddMinutes(model.Duration.GetMinutesFromDuration()),
                        FloorTableId = fTblId,
                        MergedFloorTableId = model.MergeTableId.Value,
                        StatusId = Convert.ToInt64(model.Status),
                        UserId = User.Identity.GetUserId<long>(),
                        TablePositionLeft = model.TablePositionLeft,
                        TablePositionTop = model.TablePositionTop,
                        Duration = model.Duration,
                        ReservationNote = model.ReservationNote,
                        CreatedOn = DateTime.UtcNow,
                        UpdatedBy = User.Identity.GetUserId<long>(),
                        UpdatedOn = DateTime.UtcNow
                    };

                    if (server != null && server.ServerId != null)
                    {
                        reservation.ReservationServer = new ReservationServer() { ServerId = server.ServerId.Value };
                    }

                    db.tabReservations.Add(reservation);

                    if (!string.IsNullOrEmpty(model.GuestNote))
                    {
                        customer.Notes = model.GuestNote;
                    }

                    if (!string.IsNullOrEmpty(model.Email))
                    {
                        if (customer.Emails == null || (customer.Emails != null && !customer.Emails.Any(ce => ce.Email.Contains(model.Email))))
                        {
                            var cemail = new CustomersEmails()
                            {
                                CustomerId = customer.CustomerId,
                                Email = model.Email,
                                EmailTypeId = 1
                            };
                            db.tabCustomersEmails.Add(cemail);
                        }
                    }

                    time = reservation.TimeForm.TimeOfDay.TotalMinutes;

                    db.LogAddReservation(reservation, loginUser, pinUser);
                }
                else
                {
                    var cust = new Customers()
                    {
                        FirstName = model.FirstName,
                        LastName = model.LastName,
                        DateCreated = DateTime.UtcNow.ToDefaultTimeZone(User.Identity.GetDatabaseName()),
                        DateOfBirth = DateTime.UtcNow.ToDefaultTimeZone(User.Identity.GetDatabaseName()),
                        Address1 = "1",
                        Address2 = "2",
                        Anniversary = DateTime.UtcNow.ToDefaultTimeZone(User.Identity.GetDatabaseName()),
                    };

                    db.tabCustomers.Add(cust);

                    if (!string.IsNullOrEmpty(model.Email))
                    {
                        var cemail = new CustomersEmails()
                        {
                            CustomerId = cust.CustomerId,
                            Email = model.Email,
                            EmailTypeId = 1
                        };
                        db.tabCustomersEmails.Add(cemail);
                    }

                    var cphone = new CustomersPhoneNumbers()
                    {
                        CustomerId = cust.CustomerId,
                        PhoneNumbers = model.MobileNumber,
                        PhoneTypeId = 1
                    };

                    db.tabCustomersPhoneNumbers.Add(cphone);

                    var reservation = new Reservation()
                    {
                        FloorPlanId = model.FloorPlanId,
                        Covers = model.Covers,
                        CustomerId = cust.CustomerId,
                        FoodMenuShiftId = model.ShiftId,
                        ReservationDate = model.resDate,
                        TimeForm = startTime,
                        TimeTo = startTime.AddMinutes(model.Duration.GetMinutesFromDuration()),
                        FloorTableId = fTblId,
                        MergedFloorTableId = model.MergeTableId.Value,
                        StatusId = Convert.ToInt64(model.Status),
                        UserId = User.Identity.GetUserId<long>(),
                        TablePositionLeft = model.TablePositionLeft,
                        TablePositionTop = model.TablePositionTop,
                        Duration = model.Duration,
                        ReservationNote = model.ReservationNote,
                        CreatedOn = DateTime.UtcNow,
                        UpdatedBy = User.Identity.GetUserId<long>(),
                        UpdatedOn = DateTime.UtcNow
                    };

                    if (server != null && server.ServerId != null)
                    {
                        reservation.ReservationServer = new ReservationServer() { ServerId = server.ServerId.Value };
                    }

                    db.tabReservations.Add(reservation);

                    if (!string.IsNullOrEmpty(model.GuestNote))
                    {
                        cust.Notes = model.GuestNote;
                    }

                    time = reservation.TimeForm.TimeOfDay.TotalMinutes;

                    db.LogAddReservation(reservation, loginUser, pinUser);
                }

                if (waiting != null)
                {
                    waiting.ReservationId = resId;
                    db.Entry(waiting).State = EntityState.Modified;

                    ClearWaitingCache();
                }

                db.SaveChanges();

                return Json(new
                {
                    Status = ResponseStatus.Success,
                    Message = "Reservation saved successfully.",
                    Time = time
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new
                {
                    Status = ResponseStatus.Fail,
                    Message = "Failed to save reservation, please try later..."
                }, JsonRequestBehavior.AllowGet);
            }
            finally
            {
                this.ClearReservationCache(model.resDate);
            }
        }
        public ActionResult Reserve(ReservationVM model)
        {
            Reservation reservation = null;

            try
            {
                var onlineUserName = context.Users.Where(c => c.Roles.Any(ur => ur.RoleId == context.Roles.Where(r => r.Name == "Online").FirstOrDefault().Id)).Single().UserName;
                var onlineUser = context.Users.Where(u => u.UserName.Contains(onlineUserName)).First();

                FloorTableServer server = null;
                var fTblId = Convert.ToInt64(model.tableIdd);

                var flrTbl = context.tabFloorTables.Find(fTblId);
                model.FloorPlanId = flrTbl.FloorPlanId;
                model.MergeTableId = 0;
                server = flrTbl.FloorTableServer;

                double time = 0;
                if (!string.IsNullOrEmpty(model.Email))
                {
                    model.Email = model.Email.Trim();
                }

                model.MobileNumber = model.MobileNumber.Trim();
                // model.ShiftId = model.ShiftId;

                var startTime = model.resDate.Add(DateTime.ParseExact(model.time.Trim(), "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay);

                bool isFakeMobileNo = long.Parse(model.MobileNumber) == 0L;

                var customer = context.tabCustomers.Where(c => !isFakeMobileNo && c.PhoneNumbers.Any(cn => cn.PhoneNumbers.Contains(model.MobileNumber))).FirstOrDefault();

                int tShiftId = 0;

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

                var day = model.resDate.DayOfWeek.ToString();
                var dId = context.GetWeekDays().Single(p => p.DayName.Contains(day)).DayId;

                var aa = context.GetMenuShiftHours().AsEnumerable().Where(p => p.DayId == dId);
                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;
                }

                model.ShiftId = tShiftId;

                model.Status = (!string.IsNullOrEmpty(model.Status)) ? model.Status : ReservationStatus.Online_Booking.ToString();

                #region Old Customer
                //if (customer != null)
                //{
                if (customer != null &&
                   StringComparer.OrdinalIgnoreCase.Equals(customer.FirstName.Trim(), model.FirstName.Trim()) &&
                   StringComparer.OrdinalIgnoreCase.Equals(customer.FirstName.Trim(), model.FirstName.Trim()))
                {
                    reservation = new Reservation()
                    {
                        FloorPlanId = model.FloorPlanId,
                        Covers = model.Covers,
                        CustomerId = customer.CustomerId,
                        FoodMenuShiftId = model.ShiftId,
                        ReservationDate = model.resDate,
                        TimeForm = startTime,
                        TimeTo = startTime.AddMinutes(model.Duration.GetMinutesFromDuration()),
                        FloorTableId = fTblId,
                        MergedFloorTableId = model.MergeTableId.Value,
                        StatusId = Convert.ToInt64(model.Status),
                        UserId = onlineUser.Id,
                        TablePositionLeft = model.TablePositionLeft,
                        TablePositionTop = model.TablePositionTop,
                        Duration = model.Duration,
                        ReservationNote = model.ReservationNote,
                        CreatedOn = DateTime.UtcNow,
                        UpdatedBy = onlineUser.Id,
                        UpdatedOn = DateTime.UtcNow
                    };

                    if (server != null && server.ServerId != null)
                    {
                        reservation.ReservationServer = new ReservationServer() { ServerId = server.ServerId.Value };
                    }

                    context.tabReservations.Add(reservation);

                    if (!string.IsNullOrEmpty(model.GuestNote))
                    {
                        customer.Notes = model.GuestNote;
                    }

                    if (!string.IsNullOrEmpty(model.Email))
                    {
                        if (customer.Emails == null || (customer.Emails != null && !customer.Emails.Any(ce => ce.Email.Contains(model.Email))))
                        {
                            var cemail = new CustomersEmails()
                            {
                                CustomerId = customer.CustomerId,
                                Email = model.Email,
                                EmailTypeId = 1
                            };
                            context.tabCustomersEmails.Add(cemail);
                        }
                    }

                    time = reservation.TimeForm.TimeOfDay.TotalMinutes;

                    context.LogAddReservation(reservation, onlineUser, null);
                }
                #endregion
                #region new customer
                else
                {
                    var cust = new Customers()
                    {
                        FirstName = model.FirstName,
                        LastName = model.LastName,
                        DateCreated = DateTime.UtcNow, //.ToClientTime(),
                        DateOfBirth = DateTime.UtcNow, //.ToClientTime(),
                        Address1 = "1",
                        Address2 = "2",
                        Anniversary = DateTime.UtcNow //.ToClientTime(),
                    };

                    context.tabCustomers.Add(cust);

                    if (!string.IsNullOrEmpty(model.Email))
                    {
                        var cemail = new CustomersEmails()
                        {
                            CustomerId = cust.CustomerId,
                            Email = model.Email,
                            EmailTypeId = 1
                        };
                        context.tabCustomersEmails.Add(cemail);
                    }

                    var cphone = new CustomersPhoneNumbers()
                    {
                        CustomerId = cust.CustomerId,
                        PhoneNumbers = model.MobileNumber,
                        PhoneTypeId = 1
                    };

                    context.tabCustomersPhoneNumbers.Add(cphone);

                    reservation = new Reservation()
                    {
                        FloorPlanId = model.FloorPlanId,
                        Covers = model.Covers,
                        CustomerId = cust.CustomerId,
                        FoodMenuShiftId = model.ShiftId,
                        ReservationDate = model.resDate,
                        TimeForm = startTime,
                        TimeTo = startTime.AddMinutes(model.Duration.GetMinutesFromDuration()),
                        FloorTableId = fTblId,
                        MergedFloorTableId = model.MergeTableId.Value,
                        StatusId = Convert.ToInt64(model.Status),
                        UserId = onlineUser.Id,
                        TablePositionLeft = model.TablePositionLeft,
                        TablePositionTop = model.TablePositionTop,
                        Duration = model.Duration,
                        ReservationNote = model.ReservationNote,
                        CreatedOn = DateTime.UtcNow,
                        UpdatedBy = onlineUser.Id,
                        UpdatedOn = DateTime.UtcNow
                    };

                    if (server != null && server.ServerId != null)
                    {
                        reservation.ReservationServer = new ReservationServer() { ServerId = server.ServerId.Value };
                    }

                    context.tabReservations.Add(reservation);

                    if (!string.IsNullOrEmpty(model.GuestNote))
                    {
                        cust.Notes = model.GuestNote;
                    }

                    time = reservation.TimeForm.TimeOfDay.TotalMinutes;

                    context.LogAddReservation(reservation, onlineUser, null);
                }

                #endregion

                context.SaveChanges();

                _wfmService.SendCustomerBookingSuccess(this.Url, reservation,context);

                return Redirect(this.Url.EncodedUrl("ReserveSuccess", "Online", new { id = reservation.ReservationId, company = context.Database.Connection.Database }));
            }
            catch (SmtpException)
            {
                return Redirect(this.Url.EncodedUrl("ReserveSuccess", "Online", new { id = reservation.ReservationId ,company=context.Database.Connection.Database}));
            }
            catch (Exception)
            {
                return RedirectToAction("ReserveFail", new { id = 2, company = context.Database.Connection.Database });
            }
            finally
            {
                this.ClearReservationCache(context.Database.Connection.Database);
            }
        }
 public ActionResult Edit(CustomersEmails customersemails)
 {
     if (ModelState.IsValid)
     {
         db.Entry(customersemails).State = EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");
     }
     ViewBag.CustomerId = new SelectList(db.tabCustomers, "CustomerId", "FirstName", customersemails.CustomerId);
     return View(customersemails);
 }
        public ActionResult SaveWaiting(WaitingVM model)
        {
            try
            {
                bool isFakeMobileNo = long.Parse(model.MobileNumber) == 0L;

                if (!string.IsNullOrEmpty(model.Email))
                {
                    model.Email = model.Email.Trim();
                }

                model.MobileNumber = model.MobileNumber.Trim();

                var customer = db.tabCustomers.Where(c => !isFakeMobileNo && c.PhoneNumbers.Any(cn => cn.PhoneNumbers.Contains(model.MobileNumber))).FirstOrDefault();

                if (customer != null)
                {
                    var waiting = new Waiting()
                    {
                        Covers = model.Covers,
                        CustomerId = customer.CustomerId,
                        WaitingDate = model.WaitDate,
                        Notes = model.Notes,
                        CreatedOn = DateTime.UtcNow
                    };

                    db.tabWaitings.Add(waiting);
                }
                else
                {
                    var cust = new Customers()
                    {
                        FirstName = model.FirstName,
                        LastName = model.LastName,
                        DateCreated = DateTime.UtcNow,
                        DateOfBirth = DateTime.UtcNow,
                        Address1 = "1",
                        Address2 = "2",
                        Anniversary = DateTime.UtcNow,
                    };

                    db.tabCustomers.Add(cust);

                    if (!string.IsNullOrEmpty(model.Email))
                    {
                        var cemail = new CustomersEmails()
                        {
                            CustomerId = cust.CustomerId,
                            Email = model.Email,
                            EmailTypeId = 1
                        };
                        db.tabCustomersEmails.Add(cemail);
                    }

                    var cphone = new CustomersPhoneNumbers()
                    {
                        CustomerId = cust.CustomerId,
                        PhoneNumbers = model.MobileNumber,
                        PhoneTypeId = 1
                    };

                    db.tabCustomersPhoneNumbers.Add(cphone);

                    var waiting = new Waiting()
                    {
                        Covers = model.Covers,
                        CustomerId = cust.CustomerId,
                        WaitingDate = model.WaitDate,
                        Notes = model.Notes,
                        CreatedOn = DateTime.UtcNow
                    };

                    db.tabWaitings.Add(waiting);

                }

                db.SaveChanges();

                ClearWaitingCache();

                return Json(new
                {
                    Status = ResponseStatus.Success,
                    Message = "Waitlist updated successfully.",
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                return Json(new
                {
                    Status = ResponseStatus.Fail,
                    Message = "Failed to add waitlist booking, please try later..."
                }, JsonRequestBehavior.AllowGet);
            }
        }