public async Task<ActionResult> manage( RoomReservationViewModel model)
          {

              if (!ModelState.IsValid)
              {
                  var errors = ModelState.Where(a => a.Value.Errors.Count > 0);
                  await GetTypes(model);
                  return View(model);
              }
              // Save data

              //Add/Edit Guest data, 
              try{
                  if (model.RoomReservation.BookingForId ==(int) BookingFor.Guest)
                  { model.RoomReservation.GuestID =await Create_or_Update_Guest(model.Guest);
                  IFileUploadManager fileuploader = new FileUploadManager(_Document_TypeRepository, _Guest_DocumentsRepository );
                  fileuploader.GuestID = model.RoomReservation.GuestID;
                  await  fileuploader.UploadWholeFiles(model.Guest_DocumentsViewModel, System.Web.HttpContext.Current);

                  model.Guest_DocumentsViewModel.init_InputDocs();
                  
                  }




              model.RoomReservation.Rooms = model.RoomReservation_RoomDetailsViewDetailList.Count();
              
              model.RoomReservation.Id =await Create_Or_Update_RoomReservation(model.RoomReservation );
              //Add room reservation 
              DateTime?  RoomReservation_StatusDate= await Create_or_UpdateRoomStatus(model.RoomReservation_StatusViewModelList, model.RoomReservation.ReservationStatusTypeId, model.RoomReservation.Id);

              //Add room detail, 
              await Create_or_Update_RoomDetail(model.RoomReservation.Id, model.RoomReservation_RoomDetailsViewDetailList, model.RoomReservation.ReservationStatusTypeId, model.RoomReservation.Arrival_Date, model.RoomReservation.Departure_Date, RoomReservation_StatusDate);

             

              await  Create_or_Update_RoomFacilities(model.RoomReservation.Id, model.RoomReservation_FacilitiesViewModelList);
             

               

              //payment info in database
              model.RoomReservation_Payment.Total = model.Reservation_Total;


           await   Create_or_Update_RoomPayment(model.RoomReservation.Id, model.RoomReservation_Payment);

             


              return RedirectToAction("index");

               }

           
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        ModelState.AddModelError(ve.PropertyName, string.Format ("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage));

                         
                    }
                }
                
            }
            catch (Exception exp)
              {
                  ModelState.AddModelError("Error", string.Format("- Error:   \"{0}\"",
                      exp.Message +((exp.InnerException != null)? " Inner Exception :"+ exp.InnerException.Message :"")) +"\nStack:" +exp.StackTrace);
              }

              await GetTypes(model);
               
              return View(model);
          }
          public async Task<ActionResult> manage(int? id)
          {
              if ( id!=null)
              {
                  RoomReservationViewModel model = new RoomReservationViewModel();
                  model.Id = id;
                  //Get room reservations with all children
                  var roomreservationwithdetail =await _RoomReservationRepository.GetByIdwithChildren (id.Value.ToString());
                  var roomreservation  =await _RoomReservationRepository.GetById (id.Value.ToString ());
                  model.RoomReservation = roomreservation;

                  model.RoomReservation_RoomDetailsViewDetailList =new List<RoomReservation_RoomDetailsViewDetail> ();

                  foreach(var roomdetail in roomreservationwithdetail.RoomReservation_RoomDetails )
                      
                  {   var roomdetailview= new RoomReservation_RoomDetailsViewDetail();
                      roomdetailview.RoomReservation_RoomDetails= roomdetail;
                      roomdetail.RoomAllocation =await _RoomAllocationRepository.GetById(roomdetail.RoomAllocationId.Value.ToString ());
                      roomdetailview.Wing = await _WingRepository.GetById(roomdetail.RoomAllocation.WingId.ToString()); 

                      model.RoomReservation_RoomDetailsViewDetailList.Add(roomdetailview); }
                      
                  model.RoomReservation_Payment = roomreservationwithdetail.RoomReservation_Payment.LastOrDefault();
                  model.RoomReservation_FacilitiesViewModelList = await FillFacilties(roomreservationwithdetail.RoomReservation_Facilities.ToList());
                  model.RoomReservation_StatusViewModelList = await FillStatus(roomreservationwithdetail.RoomReservation_Status.LastOrDefault());

                  if (roomreservation.BookingForId ==(int) BookingFor.Guest )
                  {
                     var RoomReservation_SponsorViewModel = new RoomReservation_SponsorViewModel();

                      if (model.RoomReservation.SponsorTypeId ==(int) SponsorType.Club)
                  {
                     
                    var sponsor_club= await _ClubRepository.GetById(model.RoomReservation.Sponsor_ClubId.ToString());

                    RoomReservation_SponsorViewModel.CreditLimit = sponsor_club.CreditLimit.ToString ();
                    RoomReservation_SponsorViewModel.Name = sponsor_club.Name;


                  
                  }
                  else
                      {
                          var sponsor_member = await _MemberRepository.GetById(model.RoomReservation.Sponsor_MemberId.ToString());

                          RoomReservation_SponsorViewModel.CreditLimit = "";
                          RoomReservation_SponsorViewModel.Name = sponsor_member.FirstName + (string.IsNullOrEmpty (sponsor_member.Middle)? (" "+ sponsor_member.Middle) :"") +" " + sponsor_member.LastName; 
                      }


                      model.RoomReservation_SponsorViewModel = RoomReservation_SponsorViewModel;
                  }
                  await GetTypes(model);
                  


                  return View(model );
              }
                  else
                  {
                      await GetTypes();
              ModelState.Clear();
              
              RoomReservation_Payment roompayment = new RoomReservation_Payment();
            var paymentbyguest= await _PaymentByRepository.GetByName(RoomReservationSystem.Model.Enums.ePaymentBy.Guest.ToString ());
            roompayment.PaymentById = paymentbyguest.Id;
            var billtime_now =await _BillTimeRepository.GetByName(RoomReservationSystem.Model.Enums.BillTime.Now.ToString());
            roompayment.BillTimeId = billtime_now.Id;
              return View(new RoomReservationViewModel(){ RoomReservation =new RoomReservation ( ), RoomReservation_FacilitiesViewModelList= await FillFacilties (null), RoomReservation_StatusViewModelList=await FillStatus (), RoomReservation_Payment=roompayment }   );
              }

              
          }
 public async Task<ActionResult> manageinner(  RoomReservationViewModel model)
 {
     return await manage(model);
 }
          private async Task GetTypes(RoomReservationViewModel  model=null)
          {
              ViewBag.Sponsor_ClubId = new SelectList(await _ClubRepository.GetAllEnabled(), "Id", "Name");
              ViewBag.Reservation_SourceId = new SelectList(await _Reservation_SourceRepository.GetAllEnabled(), "Id", "Name");
              ViewBag.CountryId = new SelectList(await _CountryRepository.GetAllEnabled(), "Id", "Name");
              var default_language=await _LanguageRepository.GetByName(RoomReservationSystem.Model.Enums.Language.English.ToString());
              var lang = await _LanguageRepository.GetAllEnabled();
              ViewBag.LanguageID = new SelectList(lang.OrderBy(a=>a.Name), "Id", "Name", default_language.Id);

              var titles=await _TitleRepository.GetAll();
             var titles_selectlist = new SelectList(titles.OrderBy(a=>a.Name), "Id", "Name").ToList();
              titles_selectlist.Insert(0, new SelectListItem() { Text = "Select Title", Value = "0", Selected =true});
              ViewBag.TitleID = titles_selectlist;


              var all_doctype = await _Document_TypeRepository.GetAllEnabled();

             var doc_types = new SelectList(all_doctype, "Id", "Name", 0).ToList();
                  doc_types.Insert(0, new SelectListItem() { Text = "Select Type", Value = "0", Selected =true});
                  ViewBag.Document_TypeId = doc_types;

              
              if (model == null)
              {

                  var roomtypes = new SelectList(await _RoomTypeRepository.GetAllEnabled(), "Id", "Name").ToList();
                  roomtypes.Insert(0, new SelectListItem() { Text = "Room type", Value = "0" });
                  ViewData["RoomReservation_RoomDetails.RoomTypeId"] = roomtypes;

                  var wings = new SelectList(await _WingRepository.GetAllEnabled(), "Id", "Name").ToList();
                  wings.Insert(0, new SelectListItem() { Text = "Wing", Value = "0" });
                  ViewData["Wing.WingId"] = wings;


                  List<SelectListItem> room_allocation = new List<SelectListItem>();
                  room_allocation.Insert(0, new SelectListItem() { Text = "Room #", Value = "0" });
                  ViewData["RoomReservation_RoomDetails.RoomAllocationId_0"] = room_allocation;

                 

              }
              else
              {
                  var index = 0;
                  var roomtypeslist = _RoomTypeRepository.GetAllEnabled();
                  var wingslist = _WingRepository.GetAllEnabled();



                  foreach (var roomdetailviewmodel in model.RoomReservation_RoomDetailsViewDetailList)
                  {
                      var postfix =  "_" + index;

                      var roomtypes = new SelectList(await roomtypeslist, "Id", "Name", roomdetailviewmodel.RoomReservation_RoomDetails.RoomTypeId).ToList();
                      roomtypes.Insert(0, new SelectListItem() { Text = "Room type", Value = "0" });
                      ViewData["RoomReservation_RoomDetails.RoomTypeId" + postfix] = roomtypes;

                      var wings = new SelectList(await wingslist, "Id", "Name", roomdetailviewmodel.Wing.Id).ToList();
                      wings.Insert(0, new SelectListItem() { Text = "Wing", Value = "0" });
                      ViewData["Wing.WingId" + postfix] = wings;


                      List<SelectListItem> room_allocation = new List<SelectListItem>();
                      if (roomdetailviewmodel.RoomReservation_RoomDetails.RoomTypeId.HasValue)

                          room_allocation = new SelectList(await _RoomAllocationRepository.GetByRoomTypeId(roomdetailviewmodel.RoomReservation_RoomDetails.RoomTypeId.Value), "Id", "Name", roomdetailviewmodel.RoomReservation_RoomDetails.RoomAllocationId).ToList();
                       
                      room_allocation.Insert(0, new SelectListItem() { Text = "Room #", Value = "0" });
                      ViewData["RoomReservation_RoomDetails.RoomAllocationId" + postfix ] = room_allocation;
                      index++;
                  }
              }

              var reasons = new SelectList(await _Reason_TypeRepository.GetAllEnabled(), "Id", "Name" ).ToList();

              ViewBag.Reason_TypeId = reasons;
              var pkr=await _CurrencyRepository.GetByName(RoomReservationSystem.Model.Enums.Currency.PKR.ToString());

              var currencies = new SelectList(await _CurrencyRepository.GetCurrencyForDropDoown(), "Id", "Label", pkr.Id + "|" + Math.Round (pkr.Rate.Value , 4) + "|" + pkr.Code).ToList();
              currencies.Insert(0, new SelectListItem() { Text = "Select Currency", Value = "0" });
              ViewBag.CurrencyId = currencies;


              var paymentmodes_cash = await _PaymentModeRepository.GetByName(RoomReservationSystem.Model.Enums.PaymentMode.Cash.ToString ()  );
              var paymentModes = new SelectList(await _PaymentModeRepository.GetAllEnabled(), "Id", "Name", paymentmodes_cash.Id ).ToList();
             // paymentModes.Insert(0, new SelectListItem() { Text = "Select Payment mode", Value = "0" });
              ViewBag.PaymentModeId = paymentModes;

              //For radiobutton lists in payment info
             var billtime=  await _BillTimeRepository.GetAllEnabled();
             ViewBag.BillTime_RadioButtonList = billtime.OrderByDescending(x => x.Id);
             IEnumerable<PaymentBy> paymentby;



             if (model == null)
                 paymentby = await _PaymentByRepository.PaymentBy_GetByIds((int)RoomReservationSystem.Model.Enums.BookingFor.Member, (int)RoomReservationSystem.Model.Enums.SponsorType.noType);
             else
             {
                 if (model.RoomReservation.BookingForId == (int)RoomReservationSystem.Model.Enums.BookingFor.Member)
                     model.RoomReservation.SponsorTypeId = (int)RoomReservationSystem.Model.Enums.SponsorType.noType;

                 paymentby = await _PaymentByRepository.PaymentBy_GetByIds(model.RoomReservation.BookingForId, (model.RoomReservation.SponsorTypeId.HasValue ? model.RoomReservation.SponsorTypeId.Value : 0)); }

      
              ViewBag.PaymentBy_RadioButtonList =   paymentby.OrderByDescending(x => x.Id);

              if ((model != null) && ( model.RoomReservation.Member ==null))
              {

                  model.RoomReservation.Member = new Member();
              }

          }