// PUT api/BookingAPI/5
        public HttpResponseMessage PutBooking(long id, Booking booking)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != booking.BookingID)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            db.Entry(booking).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }
        public string GenerateBookingReference(Booking booking, Property prop)
        {
            string reference = "";

            reference += prop.LegacyReference + "/B" + booking.BookingID + "/" + ((DateTime)booking.StartDate).ToString("ddMMyyyy").Replace("/", "").Replace("-", "");
            
            return reference;

        }
 public EventCommandCreateDocument(Event anEvent, Customer customer, PRCDocument.PRCDocumentType documentType, Booking booking = null, BookingExtraSelection bes = null)
 {
     //inject properties
     this.Event = anEvent;
     this.customer = customer;
     this.documentType = documentType;
     this.booking = booking;
     this.bes = bes;
 }
        // GET api/BookingAPI

     


        public Booking SetBookingPrices(Booking booking)
        {
            var prop = db.Properties.Find(booking.PropertyID);             
            booking.Property = prop;

            // new FinalBookingDetailGatheringController().CreateBooking(booking, prop, db);

            return booking;
        }
        /// <summary>
        /// There is only one template pattern at the moment - Standard template
        /// </summary>
        /// <param name="anEvent"></param>
        /// <param name="customer"></param>
        /// <param name="documentType"></param>
        /// <param name="booking"></param>
        /// <param name="bes"></param>
        public EventCommandSendEmail(Event anEvent, int EmailTemplateId, Customer customer, Booking booking = null, BookingExtraSelection bes = null)
        {
            this.Event = anEvent;
            this.customer = customer;           
            this.booking = booking;
            this.bes = bes;
            this.EmailTemplateId = EmailTemplateId;

        }
        public ActionResult Create(Booking booking)
        {
            if (ModelState.IsValid)
            {
                db.Bookings.Add(booking);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.BookingTypeID = new SelectList(db.BookingTypes, "BookingTypeID", "BookingType1", booking.BookingTypeID);
            ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "Title", booking.CustomerID);
            ViewBag.PropertyID = new SelectList(db.Properties, "PropertyID", "LegacyReference", booking.PropertyID);
            return View(booking);
        }
        public int SendEmail(string emailAddress, int emailEnumID, Booking booking = null, BookingExtraSelection bes = null)
        {
            try
            {
                //StandardEmailTemplate template = new StandardEmailTemplate(emailAddress, emailEnumID, customer, booking, bes);
                //template.SendEmail();

                return 0;
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }
        // POST api/BookingAPI
        public HttpResponseMessage PostBooking(Booking booking)
        {
            if (ModelState.IsValid)
            {
                db.Bookings.Add(booking);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, booking);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = booking.BookingID }));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }
        public int SendEmailToCustomer(Customer customer, int EmailTemplateID, Booking booking = null, BookingExtraSelection bes = null)
        {
            try
            {
                StandardEmailTemplate template = new StandardEmailTemplate(customer.EmailAddress, EmailTemplateID, customer, booking, bes);
                template.SendEmail();

                return 0;
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }
        public PRCDocument(Customer customer, PRCDocumentType type, Booking booking = null, BookingExtraSelection  bookingExtraSelection = null)
        {
            this.Type = type;

            this.MainDataTable = new DataTable();
            this.SecondaryDataTable = new DataTable();

            this.CustomerID = customer.CustomerID;
            if(booking != null)
            {
                BookingID = booking.BookingID;
            }
            if(bookingExtraSelection != null)
            {
                this.BookingExtraSelectionID = bookingExtraSelection.BookingExtraSelectionID;
            }

        }
        internal void CalculateExtrasPriceForAPropertyBooking(Property property, Booking booking, PortugalVillasContext db)
        {
            var allTheServices = db.PropertyTypeServicesChargeInstances.Where(x => x.PropertyTypeID == property.PropertyTypeID).ToSafeReadOnlyCollection();

            var weeks = booking.NumberOfNights / 7;
            if (weeks == 0)
            {
                weeks = 1;
            }
            //towels           
            try
            {
                booking.TowelsPrice = (booking.NoOfTowelsRequested * allTheServices.First(x => x.PropertyTypeServicesID.Equals(5)).ServicePriceGBP) * weeks;
            }
            catch (Exception)
            {


            }
            //cleans
            try
            {
                booking.MidVactionCleaningPrice = booking.MidVactionCleaning * allTheServices.First(x => x.PropertyTypeServicesID.Equals(1)).ServicePriceGBP;
            }
            catch (Exception)
            {


            }
            //heating
            try
            {
                booking.HeatingPrice = booking.HeatingNoNights * allTheServices.First(x => x.PropertyTypeServicesID.Equals(3)).ServicePriceGBP;
            }
            catch (Exception)
            {

            }
            //cleaning laundry post visit
            try
            {
                booking.CleaningPostVisitPrice = allTheServices.First(x => x.PropertyTypeServicesID.Equals(4)).ServicePriceGBP;
            }
            catch (Exception)
            {


            }
            try
            {
                //swimming pool heating
                booking.SwimmingPoolHeatingPrice = booking.SwimmingPoolHeating * allTheServices.First(x => x.PropertyTypeServicesID.Equals(6)).ServicePriceGBP;
            }

            catch (Exception)
            {


            }
            try
            {
                //linen set    
                booking.ExtraLininSetPrice = (booking.ExtraLininSet * allTheServices.First(x => x.PropertyTypeServicesID.Equals(7)).ServicePriceGBP);
            }

            catch (Exception)
            {


            }

            //add all unit prices
            try
            {
                booking.CleaningPostVisitUnitPrice = allTheServices.First(x => x.PropertyTypeServicesID.Equals(4)).ServicePriceGBP;
                booking.ExtraLininSetUnitPrice= ( allTheServices.First(x => x.PropertyTypeServicesID.Equals(7)).ServicePriceGBP);
                booking.HeatingUnitPrice = allTheServices.First(x => x.PropertyTypeServicesID.Equals(3)).ServicePriceGBP;
                booking.MidVactionCleaningUnitPrice = allTheServices.First(x => x.PropertyTypeServicesID.Equals(1)).ServicePriceGBP;
                booking.SwimmingPoolHeatingUnitPrice = allTheServices.First(x => x.PropertyTypeServicesID.Equals(6)).ServicePriceGBP;
                booking.TowelsUnitPrice = allTheServices.First(x => x.PropertyTypeServicesID.Equals(5)).ServicePriceGBP;
                booking.FirewoodUnitPrice = allTheServices.First(x => x.PropertyTypeServicesID.Equals(16)).ServicePriceGBP;
            }
            catch (Exception)
            {
                
       
            }

          

        }
        public Booking ConvertCartBookingToPersistenceBooking(Booking theCartBooking)
        {
            Booking thePersistenceBooking = new Booking();

            return thePersistenceBooking;

        }
        public Booking ConvertPropertyFormBookingToCartBooking(FormCollection theBooking)
        {
            try
            {
                Booking theCartBooking = new Booking();

                //change the form into a BookingObject
                if (theBooking["bookingModalStartDatePicker"] != "" && theBooking["bookingModalStartDatePicker"] != null)
                {
                    theCartBooking.StartDate = DateTime.ParseExact(theBooking["bookingModalStartDatePicker"], "dd-MM-yyyy", System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"));
                }
                if (theBooking["bookingModalEndDatePicker"] != "" && theBooking["bookingModalEndDatePicker"] != null)
                {
                    theCartBooking.EndDate = DateTime.ParseExact(theBooking["bookingModalEndDatePicker"], "dd-MM-yyyy", System.Globalization.CultureInfo.CreateSpecificCulture("en-GB"));
                }
                if (Int32.Parse(theBooking["bookingModalPropertyID"]) != 0 && (theBooking["bookingModalPropertyID"] != null))
                {
                    theCartBooking.PropertyID = Int32.Parse(theBooking["bookingModalPropertyID"]);
                }
                if (theBooking["prcReference"] != "" && theBooking["prcReference"] != null)
                {
                    theCartBooking.BookingPRCReference = theBooking["prcReference"].ToString();
                }


                if (theBooking["Booking_Towels"] != "" && theBooking["Booking_Towels"] != null)
                {
                    theCartBooking.NoOfTowelsRequested = Convert.ToInt32(theBooking["Booking_Towels"].ToString());
                }
                if (theBooking["Booking_MidVacationCleaning"] != "" && theBooking["Booking_MidVacationCleaning"] != null)
                {
                    theCartBooking.MidVactionCleaning = Convert.ToInt32(theBooking["Booking_MidVacationCleaning"].ToString());
                }
                if (theBooking["Booking_SwimmingPoolHeating"] != "" && theBooking["Booking_SwimmingPoolHeating"] != null)
                {
                    theCartBooking.SwimmingPoolHeating= Convert.ToInt32(theBooking["Booking_SwimmingPoolHeating"].ToString());
                }
                if (theBooking["Booking_ExtraLinen"] != "" && theBooking["Booking_ExtraLinen"] != null)
                {
                    theCartBooking.ExtraLininSet = Convert.ToInt32(theBooking["Booking_ExtraLinen"].ToString());
                }
                if (theBooking["Booking_Heating"] != "" && theBooking["Booking_Heating"] != null)
                {
                    theCartBooking.HeatingNoNights = Convert.ToInt32(theBooking["Booking_Heating"].ToString());
                }

                theCartBooking.BookingGUID = Guid.NewGuid();
                

                //takes a cart booking object and converts to a 'proper' booking that can be stored in the Db.
                return theCartBooking;
            }
            catch (Exception ex)
            {
                throw ex;

            }

        }
        public Event CreateBookingEventViaFactory(long eventTypeID, Booking booking)
        {

            var returnEvent = CreateEventViaFactory(eventTypeID);
            returnEvent.BookingID = booking.BookingID;



            return returnEvent;
        }
Esempio n. 15
0
        internal void CalculateExtrasPriceForAPropertyBooking(Property property, Booking booking, PortugalVillasContext db)
        {
            var allTheServices = db.PropertyTypeServicesChargeInstances.Where(x => x.PropertyTypeID == property.PropertyTypeID).ToSafeReadOnlyCollection();

            var weeks = booking.NumberOfNights / 7;

            if (weeks == 0)
            {
                weeks = 1;
            }
            //towels
            try
            {
                booking.TowelsPrice = (booking.NoOfTowelsRequested * allTheServices.First(x => x.PropertyTypeServicesID.Equals(5)).ServicePriceGBP) * weeks;
            }
            catch (Exception)
            {
            }
            //cleans
            try
            {
                booking.MidVactionCleaningPrice = booking.MidVactionCleaning * allTheServices.First(x => x.PropertyTypeServicesID.Equals(1)).ServicePriceGBP;
            }
            catch (Exception)
            {
            }
            //heating
            try
            {
                booking.HeatingPrice = booking.HeatingNoNights * allTheServices.First(x => x.PropertyTypeServicesID.Equals(3)).ServicePriceGBP;
            }
            catch (Exception)
            {
            }
            //cleaning laundry post visit
            try
            {
                booking.CleaningPostVisitPrice = allTheServices.First(x => x.PropertyTypeServicesID.Equals(4)).ServicePriceGBP;
            }
            catch (Exception)
            {
            }
            try
            {
                //swimming pool heating
                booking.SwimmingPoolHeatingPrice = booking.SwimmingPoolHeating * allTheServices.First(x => x.PropertyTypeServicesID.Equals(6)).ServicePriceGBP;
            }

            catch (Exception)
            {
            }
            try
            {
                //linen set
                booking.ExtraLininSetPrice = (booking.ExtraLininSet * allTheServices.First(x => x.PropertyTypeServicesID.Equals(7)).ServicePriceGBP);
            }

            catch (Exception)
            {
            }

            //add all unit prices
            try
            {
                booking.CleaningPostVisitUnitPrice   = allTheServices.First(x => x.PropertyTypeServicesID.Equals(4)).ServicePriceGBP;
                booking.ExtraLininSetUnitPrice       = (allTheServices.First(x => x.PropertyTypeServicesID.Equals(7)).ServicePriceGBP);
                booking.HeatingUnitPrice             = allTheServices.First(x => x.PropertyTypeServicesID.Equals(3)).ServicePriceGBP;
                booking.MidVactionCleaningUnitPrice  = allTheServices.First(x => x.PropertyTypeServicesID.Equals(1)).ServicePriceGBP;
                booking.SwimmingPoolHeatingUnitPrice = allTheServices.First(x => x.PropertyTypeServicesID.Equals(6)).ServicePriceGBP;
                booking.TowelsUnitPrice   = allTheServices.First(x => x.PropertyTypeServicesID.Equals(5)).ServicePriceGBP;
                booking.FirewoodUnitPrice = allTheServices.First(x => x.PropertyTypeServicesID.Equals(16)).ServicePriceGBP;
            }
            catch (Exception)
            {
            }
        }
        public void TestPricingMethods()
        {

            var db = new PortugalVillasContext();

            Booking testBooks = new Booking { PropertyID = 220, StartDate = new DateTime(2014, 01, 01), EndDate = new DateTime(2014, 01, 08) };

            var price = testBooks.CalculateBookingPricingForAPropertyBooking(db);

            //test for every day in a booking (e.g. range)
            var test = 0;

        }
        public void TestNewMailAllTemplates()
        {
            Customer testCust = new Customer();
            testCust.FirstName = "Test";
            testCust.LastName = "Customer";
            testCust.EmailAddress = "*****@*****.**";

            Booking booking = new Booking();
            booking.StartDate = new DateTime(2014, 01, 04);
            booking.EndDate = new DateTime(2014, 01, 10);
            booking.NumberOfNights = 5;
            booking.PropertyID = 220;
            booking.BookingID = 513;


            BookingExtraSelection bes = new BookingExtraSelection();
            bes.ExtraRentalDate = new DateTime(2014, 01, 04);
            bes.ExtraReturnDate = new DateTime(2014, 01, 09);
            bes.BookingExtraID = 1;
            bes.BookingExtraSelectionID = 1; //primary key





            EmailController ec = new EmailController();
            /*var ok = ec.SendEmailToCustomer(testCust, , booking, bes);
            ok = ec.SendEmailToCustomer(testCust, EmailOutType.EmailOutEmailType.BookingConfirm, booking);
            ok = ec.SendEmailToCustomer(testCust, EmailOutType.EmailOutEmailType.BookingExtraSelectionConfirm, null, bes);*/




        }
        public byte[] CreateDocument(Customer customer, PRCDocument.PRCDocumentType type, Booking booking = null, BookingExtraSelection bes = null)
        {
            try
            {
                PRCDocument aDocument = new PRCDocument(customer, type, booking, bes);

                var filepathAndName = MergeDocumentWithDatabaseAndReturnFilePath(customer, type, booking, bes);

                var documentBytes = System.IO.File.ReadAllBytes(filepathAndName);

                return documentBytes;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public List<BookingParticipant> CreateBookingParticipant(List<BookingParticipant> bookingParticipants, Booking booking, PortugalVillasContext db)
        {
            //assign fields

            foreach (var bookingParticipant in bookingParticipants)
            {

                bookingParticipant.BookingID = booking.BookingID;
                bookingParticipant.BookingParticipantWhenCreated = DateTime.Now;

                //GeneralStaticHelperMethods.IsPersonAdultChildOrInfant(bookingParticipant);

                db.BookingParticipants.Add(bookingParticipant);


            }
            db.SaveChanges();

            return bookingParticipants;

        }
        public Booking CreateBooking(Booking booking, Property property, Customer theCustomer, PortugalVillasContext db)
        {

            //set default currency

            booking.BookingCurrencyConversionSymbol = theCustomer.PreferredCurrencySymbol;
            booking.BookingPreferredCurrency = theCustomer.PreferredCurrency;

            var cc = new CurrencyConverterController();



            //if the booking is not in GBP convert to EUROS



            //NEED TO CONVERT THE CURRENCY BASED ON WHETHER IT NEEDS TO BE EU OR UK





            int adults, kids, infants;

            adults = booking.NumberOfAdults ?? 0;
            kids = booking.NumberOfChildren ?? 0;
            infants = booking.NumberOfInfants ?? 0;


            booking.NumberOfAdults = adults;
            booking.NumberOfChildren = kids;
            booking.NumberOfInfants = infants;



            booking.CustomerID = theCustomer.CustomerID;
            booking.BookingTypeID = 1; //always a property booking

            booking.NumberOfGuests = adults + kids + infants;
            booking.TotalNumberOfMinors = kids + infants;
            booking.NumberOfNights = GeneralStaticHelperMethods.CalculateNoofNights(booking.StartDate, booking.EndDate);


            try
            {
                var exchangeRateFromDB = new CurrencyExchange();
                var baseCurrency = "";
                var newCurrency = "";

                booking.NumberOfNights = GeneralStaticHelperMethods.CalculateNoofNights(booking.StartDate,
                    booking.EndDate);
                booking.CalculateBookingPricingForAPropertyBooking(db);
                booking.CalculateExtrasPriceForAPropertyBooking(property, booking, db);
                //set this now because need to convert it
                booking.SetBreakageDepositDueDate(); //1 month before
                booking.SetBreakageDepositAmount(); //depends on property

                booking.BookingCurrencyLongName = "G.B. Pounds Sterling";
                //NOW CONVERT CURRENCY IF NECESSARY SO OTHER CALCS ARE CORRECT
                //CHANGE THIS!!! IT'S USING HIDDEN EXTERNAL DEPENDENY
                booking.BookingCurrencyConversionSymbol = "£";
                booking.BookingCurrencyExchangeRate = 1.00M;
                booking.BookingPreferredCurrency = "GBP";


                if (theCustomer.Country.ToLower() != "united kingdom" && ConfigurationManager.AppSettings["defaultCurrency"] == "GBP")
                {

                    //euro strategy
                    baseCurrency = "GBP";
                    newCurrency = "EUR";


                    //set exchange rate
                    booking.BookingCurrencyExchangeRate = exchangeRateFromDB.CurrencyExchangeRate;
                    booking.BookingCurrencyLongName = "Euros";
                    booking.BookingCurrencyConversionSymbol = exchangeRateFromDB.CurrencyExchangeSymbol;
                    booking.BookingCurrencyExchangeRate = exchangeRateFromDB.CurrencyExchangeRate;
                    booking.BookingPreferredCurrency = "EUR";

                    try
                    {
                        booking.BookingPrice = cc.ConvertCurrency(baseCurrency, newCurrency, (decimal)booking.BookingPrice);
                        booking.BookingCurrencyConversionPrice = booking.BookingPrice;

                        booking.TowelsPrice = cc.ConvertCurrency(baseCurrency, newCurrency, (decimal)booking.TowelsPrice);
                        booking.MidVactionCleaningPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.MidVactionCleaningPrice);
                        booking.SwimmingPoolHeatingPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.SwimmingPoolHeatingPrice);
                        booking.ExtraLininSetPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.ExtraLininSetPrice);
                        booking.BreakageDeposit = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.BreakageDeposit);
                        booking.CleaningPostVisitPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.CleaningPostVisitPrice);
                        booking.HeatingPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.HeatingPrice);





                    }
                    catch (Exception)
                    {

                        throw;
                    }

                }

                //ALL BOOKINGS FOR US SYSTEM IN USD
                else if (ConfigurationManager.AppSettings["defaultCurrency"] == "USD")
                {
                    baseCurrency = "GBP";
                    newCurrency = "USD";

                    exchangeRateFromDB =
                        db.CurrencyExchanges.First(x => x.CurrencyExchangeName == "GBP-USD");

                    //set exchange rate and currencies
                    booking.BookingCurrencyExchangeRate = exchangeRateFromDB.CurrencyExchangeRate;
                    booking.BookingCurrencyLongName = "U.S. Dollars";
                    booking.BookingCurrencyConversionSymbol = exchangeRateFromDB.CurrencyExchangeSymbol;
                    booking.BookingCurrencyExchangeRate = exchangeRateFromDB.CurrencyExchangeRate;
                    booking.BookingPreferredCurrency = "USD";




                }

                //do all cuurency conversions if not a UK booking
                if (theCustomer.Country.ToLower() != "united kingdom" || !ConfigurationManager.AppSettings["defaultCurrency"].Equals("GBP"))
                {
                    try
                    {
                        booking.BookingPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.BookingPrice);
                        booking.BookingCurrencyConversionPrice = booking.BookingPrice;

                        booking.TowelsPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.TowelsPrice);
                        booking.MidVactionCleaningPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.MidVactionCleaningPrice);
                        booking.SwimmingPoolHeatingPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.SwimmingPoolHeatingPrice);
                        booking.ExtraLininSetPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.ExtraLininSetPrice);
                        booking.BreakageDeposit = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.BreakageDeposit);
                        booking.CleaningPostVisitPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.CleaningPostVisitPrice);
                        booking.HeatingPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.HeatingPrice);


                        booking.HeatingUnitPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.HeatingUnitPrice);
                        booking.CleaningPostVisitUnitPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.CleaningPostVisitUnitPrice);
                        booking.ExtraLininSetUnitPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.ExtraLininSetUnitPrice);
                        booking.MidVactionCleaningUnitPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.MidVactionCleaningUnitPrice);
                        booking.SwimmingPoolHeatingUnitPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.SwimmingPoolHeatingUnitPrice);
                        booking.TowelsUnitPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.TowelsUnitPrice);
                        booking.FirewoodUnitPrice = cc.ConvertCurrency(baseCurrency, newCurrency,
                            (decimal)booking.FirewoodUnitPrice);

                    }
                    catch (Exception)
                    {

                        throw;
                    }
                }

            }
            catch (Exception ex)
            {
                /*Response.Redirect("http://" + Request.Url.Authority + "/Error/PropertyErrorSelection");*/
                //return RedirectToAction("PropertyErrorSelection", "Error", new { propID = CartBooking.PropertyID });                    
            }


            //CURRENCY MUST BE CONVERTED BEFORE THESE METHODS ARE CALLED

            //call meths to set dates
            booking.SetInitalDepositDate();
            booking.SetInitialDepositAmount();

            booking.SetRentalBalanceDueDate(); //1 month before
            booking.CalculateFinalRentalPaymentAmount(); //extrasSummedPrice + price - deposit


            booking.SetBreakageDepositRemittanceDate();
            booking.SetBreakageDepositRemittanceAmount();//1 month after trip end?
            //booking.SetFinalRentalPayment(); //price - deposit

            booking.SetHomeownerAndPRCComissionAmount(db);

            booking.CreationDate = DateTime.Now;


            booking.Cancelled = false;
            booking.Confirmed = false; //if they pay by paypal later, we can update;




            var refGenService = new ReferenceGenerationService();
            booking.BookingPRCReference = refGenService.GenerateBookingReference(booking, property);


            //if (ModelState.IsValid)
            //{

            db.Bookings.Add(booking);

            if (db.SaveChanges() > 0)
            {

                if (booking.BookingID > 0)
                {
                    booking.BookingPRCReference = refGenService.GenerateBookingReference(booking, property);

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

                }





            }
            return booking;
        }
        public ActionResult DetailGatheringEventChain()
        {
            //create the lists we need 

            Dictionary<BookingDataCollectionEventType.Types, BookingDataCollectionEventType.PRCDataGatheringControllerActionRedirect> DataThatNeedsGetting = CreateListOfFieldsToGatherBasedOnSessionData();

            foreach (var dataRedirect in DataThatNeedsGetting)
            {
                //if it's a booking or an extra, whack it into the session so we know which one we're using and can pull the vars                

                if (dataRedirect.Key == BookingDataCollectionEventType.Types.Booking)
                {

                    Session["CurrentBookingDataGathering"] = new Booking
                    {
                        PropertyID = (long?)dataRedirect.Value.PropertyID,
                        BookingPRCReference = dataRedirect.Value.PRCRef.ToString(),
                        StartDate = dataRedirect.Value.StartDate,
                        EndDate = dataRedirect.Value.EndDate,
                        ExtraLininSet = dataRedirect.Value.NoLinen,
                        SwimmingPoolHeating = dataRedirect.Value.NoSwimmingPool,
                        // SpecialRequests = dataRedirect.Value.SpecialRequests,
                        NoOfTowelsRequested = dataRedirect.Value.NoTowels,
                        BookingPrice = dataRedirect.Value.Price


                    };
                }
                else if (dataRedirect.Key == BookingDataCollectionEventType.Types.BookingExtraSelection)
                {
                    Session["CurrentBookingExtraDataGathering"] = new BookingExtraSelection
                    {
                        BookingExtraPRCReference = dataRedirect.Value.PRCRef.ToString(),
                        ExtraRentalDate = dataRedirect.Value.StartDate,
                        ExtraReturnDate = dataRedirect.Value.EndDate,
                        BookingExtraID = (long)dataRedirect.Value.ExtraTypeID,
                        BESPrice = dataRedirect.Value.Price
                    };

                }

                return RedirectToAction(dataRedirect.Value.Action, dataRedirect.Value.Controller);
            }



            //populate the session items with those lists






            if (DataThatNeedsGetting.Count == 0)
            //we're done
            {
                return View();
            }
            //remove all items from our list that need gathering

            //end


            return RedirectToAction("DetailGatheringEventChain");


        }
        public Booking ConvertPropertyFormBookingToCartBooking(FormCollection theBooking)
        {
            try
            {
                Booking theCartBooking = new Booking();

                //change the form into a BookingObject
                if (theBooking["bookingModalStartDatePicker"] != "" && theBooking["bookingModalStartDatePicker"] != null)
                {
                    theCartBooking.StartDate = DateTime.Parse(theBooking["bookingModalStartDatePicker"]);
                }
                if (theBooking["bookingModalEndDatePicker"] != "" && theBooking["bookingModalEndDatePicker"] != null)
                {
                    theCartBooking.EndDate = DateTime.Parse(theBooking["bookingModalEndDatePicker"]);
                }
                if (Int32.Parse(theBooking["propertyID"]) != 0 && (theBooking["propertyID"] != null))
                {
                    theCartBooking.PropertyID = Int32.Parse(theBooking["propertyID"]);
                }
                if (theBooking["prcReference"] != "" && theBooking["prcReference"] != null)
                {
                    theCartBooking.BookingPRCReference = theBooking["prcReference"].ToString();
                }

                //takes a cart booking object and converts to a 'proper' booking that can be stored in the Db.
                return theCartBooking;
            }
            catch (Exception ex)
            {
                throw ex;

            }
        }
        /// <summary>
        /// Sends an email for 1*1 bookings or extrabookings
        /// </summary>
        /// <param name="customer"></param>
        /// <param name="booking"></param>
        /// <param name="bookingExtraSelection"></param>
        public StandardEmailTemplate(string toEmailAddress, int EmailTemplateID, Customer customer, Booking booking = null, BookingExtraSelection bookingExtraSelection = null)
        {

            EmailTemplate theTemplate;
            EmailTemplate Header;
            EmailTemplate Footer;

            using (PortugalVillasContext db = new PortugalVillasContext())
            {
                theTemplate = db.EmailTemplates.Find(EmailTemplateID);
                Header = db.EmailTemplates.Find(1);
                Footer = db.EmailTemplates.Find(2);
            }
            theAsposeMessage = new MailMessage();
            Property property = null;
            BookingExtra bookingExtra = null;

            EmailOutType theMainBody = new EmailOutType();

            //map all passed in object fields
            bool bookingToggle = false;
            bool bookingExtraToggle = false;
            bool combinedServicesToggle = false;


            //gets necessary

            //assign body
            if (booking == null)
            {
                bookingExtraToggle = true;
                bookingExtra = BookingExtra.GetBookingExtraByID(bookingExtraSelection.BookingExtraID);
                //theMainBody = new EmailOutType(EmailOutType.EmailOutEmailType.BookingExtraSelectionConfirm);
            }
            else if (booking != null && bookingExtraSelection == null)
            {
                bookingToggle = true;
                long propertyID = (long)booking.PropertyID;
                property = Property.GetPropertyByID(propertyID);
                //theMainBody = new EmailOutType(EmailOutType.EmailOutEmailType.BookingConfirm);//
            }
            else if (booking != null && bookingExtraSelection != null)
            {
                long propertyID = (long)booking.PropertyID;
                property = Property.GetPropertyByID(propertyID);
                bookingExtra = BookingExtra.GetBookingExtraByID(bookingExtraSelection.BookingExtraID);
                combinedServicesToggle = true;
                //theMainBody = new EmailOutType(EmailOutType.EmailOutEmailType.BookingAndBookingExtraSelectionConfirm);
            }







            //customer
            var customerFullName = customer.FirstName + " " + customer.LastName;

            //bookings and extras

            var prcRef = booking != null ? property.LegacyReference : bookingExtra.LegacyReference;

            string bookingPropertyOrSelectionName = booking != null ? property.PropertyName : bookingExtra.BookingExtraName;
            string bookingStartDate = booking != null ? Convert.ToDateTime(booking.StartDate.ToString()).ToString("dd/MM/yyyy") : Convert.ToDateTime(bookingExtraSelection.ExtraRentalDate.ToString()).ToString("dd/MM/yyyy");
            string bookingEndDate = booking != null ? Convert.ToDateTime(booking.EndDate.ToString()).ToString("dd/MM/yyyy") : new DateTime(1901, 01, 01).ToString("dd/MM/yyyy");
            string numberOfNights = booking != null ? booking.NumberOfNights.ToString() : "0";


            theAsposeMessage.To = customer.EmailAddress;
            theAsposeMessage.From = "*****@*****.**";

            theSMTPClient.Host = "smtp.gmail.com";
            theSMTPClient.Username = LoginEmailAddress;
            theSMTPClient.Password = EmailPassword;
            theSMTPClient.Port = 587;
            theSMTPClient.EnableSsl = true;
            theSMTPClient.SecurityMode = SmtpSslSecurityMode.Explicit;


            //set some email body   
            //set the body
            //subject
            //           
            theAsposeMessage.Subject = theTemplate.EmailSubject;
            theAsposeMessage.HtmlBody = "";

            //get correct email according to emailEnumID


            var temp = "";
            //string merges
            var fullName = customer != null ? customerFullName : "";
            var legacyRef = property != null ? property.LegacyReference : bookingExtra.LegacyReference;
            var bookStart = bookingStartDate != null ? bookingStartDate : "";
            var bookEnd = bookingEndDate != null ? bookingEndDate : "";
            var NoNights = numberOfNights != null ? numberOfNights : "";
            var reference = booking != null ? booking.BookingPRCReference : bookingExtraSelection.BookingExtraPRCReference;
            var bID = booking != null ? booking.BookingID.ToString() : "";
            var besID = bookingExtraSelection != null ? bookingExtraSelection.BookingExtraSelectionID.ToString() : "";
            
            var finalRentalPayment = booking != null ? booking.BookingPrice.ToString() : "";
            var finalRentalPaymentDate = "";
                if(booking != null)
                {
                   finalRentalPaymentDate =  booking.FinalRentalPaymentDueDate != null ? ((DateTime)booking.FinalRentalPaymentDueDate).ToString("dd/MM/yyyy") : "";
                }

            var rentalDeposit = booking != null ? booking.BreakageDeposit.ToString() : "";

            temp = String.Format(theTemplate.EmailTemplateBodyHTML, fullName, legacyRef, bookStart, bookEnd, NoNights, reference, finalRentalPaymentDate, bID, besID, finalRentalPayment, rentalDeposit);

            //booking request optional
            //if (bookingToggle == true && EmailTemplateID == 17)
            //{
            //    temp = String.Format(theTemplate.EmailTemplateBodyHTML, customerFullName, property.LegacyReference, bookingStartDate, bookingEndDate, numberOfNights, bookingExtraSelection.BookingExtraSelectionID);
            //}

            ////booking request forms standard
            //else if (bookingToggle == true // && EmailTemplateID == 3 || EmailTemplateID == 4 || EmailTemplateID == 5 || EmailTemplateID == 6
            //    )
            //{


            //    temp = String.Format(theTemplate.EmailTemplateBodyHTML, customerFullName, property.LegacyReference, booking.BookingPRCReference, ((DateTime)booking.FinalRentalPaymentDueDate).ToString("dd/MM/yyyy"));


            //}


            //else if (bookingExtraToggle == true)
            //{
            //    temp = String.Format(theTemplate.EmailTemplateBodyHTML, customerFullName, prcRef, bookingExtraSelection.BookingExtraSelectionID);

            //}
            //else if (combinedServicesToggle == true)
            //{
            //    temp = String.Format(theTemplate.EmailTemplateBodyHTML, customerFullName, booking.BookingID);

            //}






            //set the body
            var completeEmail = Header.EmailTemplateBodyHTML + temp + Footer.EmailTemplateBodyHTML;

            theAsposeMessage.HtmlBody = completeEmail;


        }
 public EventManagementServiceBooking(Booking booking)
 {
     booking = booking;
 }
        public ActionResult QuickCreateBooking(Booking booking, List<BookingParticipant> bookingParticipants)
        {
            //setup
            

            booking.Test = false;

            var bookingRepo = new FinalBookingDetailGatheringController();

            BookingParentContainer parentContainer = new BookingParentContainer();
            parentContainer.CustomerID = booking.CustomerID;


            parentContainer = bookingRepo.CreateBookingParentContainer(parentContainer, db);
            db.BookingParentContainers.Add(parentContainer);

            //create booking
            var property = db.Properties.Find(booking.PropertyID);
            var customer = db.Customers.Find(booking.CustomerID);
            booking.Property = property;
            booking.BookingParentContainer = parentContainer;
            booking.BookingCurrencyConversionSymbol = customer.PreferredCurrencySymbol;
            booking.BookingPreferredCurrency = customer.PreferredCurrency;
            
            booking.BookingParticipants = null;
            bookingRepo.CreateBooking(booking, property, customer, db);
            //create parts           
            booking.Cancelled = false;
            booking.Confirmed = true;
            booking.Test = false;

            db.Bookings.Attach(booking);
            db.Entry(booking).State = EntityState.Modified;
            db.SaveChanges();



            var partstoAdd = new List<BookingParticipant>();
            if (bookingParticipants != null)
            {

                foreach (var bookingParticipant in bookingParticipants)
                {
                    if (bookingParticipant.BookingParticipantFirstName != "" &&
                        bookingParticipant.BookingParticipantFirstName != null
                        && bookingParticipant.BookingParticipantLastName != "" &&
                        bookingParticipant.BookingParticipantLastName != null &&
                        bookingParticipant.BookingParticipantAge != "")
                    {
                        bookingParticipant.BookingID = booking.BookingID;
                        partstoAdd.Add(bookingParticipant);
                    }

                }
                if (partstoAdd.Count > 0)
                {
                    bookingRepo.CreateBookingParticipant(partstoAdd, booking, db); //create all ones we need
                }
            }



            return View("QuickCreateBookingWrapper");
        }
        public int CurrencyExchange()
        {
            var cc = new CurrencyConverterController();


            Booking book = new Booking();


            book.BookingPreferredCurrency = "GBP";
            book.BookingCurrencyConversionPrice = 1M;
            book.BookingCurrencyConversionSymbol = "£";
            book.BookingCurrencyExchangeRate = 1M;

            var result = cc.ConvertCurrency("GBP", "EUR", 1.00M);


            return 0;
        }
        //insert a booking
        private static bool CreateBooking(Booking aBooking)
        {
            PortugalVillasContext _db = new PortugalVillasContext();

            _db.Bookings.Add(aBooking);

            if (_db.SaveChanges() > 0)
            {

                return true;
            };
            return false;

        }
        public static IEnumerable<DateTime> GetDateConfirmedRangeForABooking(Booking aBooking)
        {
            //check the booking is confirmed
            if (aBooking.Confirmed == true)
            {
                //use null coalescing operator
                DateTime startingDate = aBooking.StartDate ?? DateTime.Parse("1/1/1901 00:00:00 AM");
                DateTime endingDate = aBooking.EndDate ?? DateTime.Parse("1/1/1901 00:00:00 AM");


                while (startingDate <= endingDate)
                {
                    yield return startingDate;
                    startingDate = startingDate.AddDays(1);
                }

            }


        }
            //takes 
            public Document(Booking aBooking)
            {
                //get the type of document
                //pull all customer details from booking

            }
        private string MergeDocumentWithDatabaseAndReturnFilePath(Customer customer, PRCDocument.PRCDocumentType type, Booking booking = null, BookingExtraSelection bes = null)
        {
            //BOOKING needs to have a propertyID, BES needs to have the ExtraID!!!!


            var db = new PortugalVillasContext();
            var bookPartTable = new DataTable();
            var besPartTable = new DataTable();
            var extraAttributes = new DataTable();

            PRCDocument aDocument = new PRCDocument(type);
            aDocument = InitialSetUpPRCDocument(type);

            //tables for merge

            List<DataTable> tablesForMerge_PreMerge = new List<DataTable>();


            PRCDocumentData theDocumentDataInstance = new PRCDocumentData();

            //PRC
            tablesForMerge_PreMerge.Add(
                theDocumentDataInstance.GetPRCDocumentData(
                    PRCDocumentData.PRCReturnDataTableWrapperTypes.StandardPRCInformation, 1));

            //CUSTOMERS
            tablesForMerge_PreMerge.Add(
                theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.CustomerByCustomerID,
                    customer.CustomerID)); //works*/
            //CUSTOMER BANK DETAILS
            
            
            
            if (booking != null)
            {
                tablesForMerge_PreMerge.Add(
                theDocumentDataInstance.GetPRCDocumentData(
                    PRCDocumentData.PRCReturnDataTableWrapperTypes.CustomerBankDetailByCustomerID, customer.CustomerID));


                //COMMISSION FOR YEAR            
                var TotalCommisssion = new DataTable();
                TotalCommisssion.Columns.Add("TotalCommissionThisYear");
                TotalCommisssion.Columns.Add("CommissionDateTime");
                DataRow _row = TotalCommisssion.NewRow();
                _row["TotalCommissionThisYear"] = db.Bookings.Where(x => x.PropertyID == booking.PropertyID).Sum(x => x.CommissionAmount);
                _row["CommissionDateTime"] = DateTime.Now.ToShortDateString();
                TotalCommisssion.Rows.Add(_row);

                tablesForMerge_PreMerge.Add(TotalCommisssion);

                //BOOKING
                tablesForMerge_PreMerge.Add(
                    theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.BookingByBookingID, booking.BookingID));


                //PROPERTY
                tablesForMerge_PreMerge.Add(
                    theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.PropertyByPropertyID,
                        (long)booking.PropertyID));


                //TOWN
                tablesForMerge_PreMerge.Add(
                    theDocumentDataInstance.GetPRCDocumentData(
                        PRCDocumentData.PRCReturnDataTableWrapperTypes.PropertyTownByPropertyTownID, Convert.ToInt64(db.Properties.Where(x => x.PropertyID == booking.PropertyID).FirstOrDefault().PropertyTownID)));

                //REGION
                tablesForMerge_PreMerge.Add(
                    theDocumentDataInstance.GetPRCDocumentData(
                        PRCDocumentData.PRCReturnDataTableWrapperTypes.PropertyRegionByPropertyRegionID, db.Properties.Where(x => x.PropertyID == booking.PropertyID).FirstOrDefault().PropertyTown.PropertyRegionID));

                //BOOKINGPART
                bookPartTable = theDocumentDataInstance.GetPRCDocumentData(
                    PRCDocumentData.PRCReturnDataTableWrapperTypes.BookingParticipantByBookingID, booking.BookingID);
                bookPartTable.TableName = "BOOKINGPARTTABLE";
                tablesForMerge_PreMerge.Add(bookPartTable);

                if (booking.BookingParentContainerID != null)
                {
                    //PARENT
                    tablesForMerge_PreMerge.Add(
                        theDocumentDataInstance.GetPRCDocumentData(
                            PRCDocumentData.PRCReturnDataTableWrapperTypes.StandardBookingParentContainer,
                            (long)booking.BookingParentContainerID));
                }




                BookingParentContainer bookingParentContainer;

                //PROPERTY OWNER
                tablesForMerge_PreMerge.Add(
              theDocumentDataInstance.GetPRCDocumentData(
                  PRCDocumentData.PRCReturnDataTableWrapperTypes.StandardPropertyOwner, (long)booking.PropertyID));
            }




            if (bes != null)
            {

                //get top level item for same sub type to pull out attributes:
                long? extraIDforAtts = null;

                try
                {
                    extraIDforAtts = db.BookingExtras.Where(x =>
                                    x.TopLevelItem == true)
                                    .Where(y => y.BookingExtraSubTypeID == bes.BookingExtra.BookingExtraSubTypeID)
                                    .FirstOrDefault().BookingExtraID;
                }
                catch (Exception)
                {
                     extraIDforAtts = db.BookingExtras.Where(x =>
                                    x.MaxPersons > 10)
                                    .Where(y => y.BookingExtraSubTypeID == bes.BookingExtra.BookingExtraSubTypeID)
                                    .FirstOrDefault().BookingExtraID;
                    
                }

                //BES
                tablesForMerge_PreMerge.Add(
                    theDocumentDataInstance.GetPRCDocumentData(
                        PRCDocumentData.PRCReturnDataTableWrapperTypes.BookingExtraSelectionByBookingExtraSelectionID, bes.BookingExtraSelectionID));

                //BEST PART (name etc)

                besPartTable = theDocumentDataInstance.GetPRCDocumentData(
                    PRCDocumentData.PRCReturnDataTableWrapperTypes.BookingExtraParticipantByBookingExtraSelectionID,
                    bes.BookingExtraSelectionID);
                besPartTable.TableName = "BESPARTTABLE";

                tablesForMerge_PreMerge.Add(besPartTable);
                //EXTRA
                tablesForMerge_PreMerge.Add(
                    theDocumentDataInstance.GetPRCDocumentData(
                        PRCDocumentData.PRCReturnDataTableWrapperTypes.BookingExtraByBookingExtraID, bes.BookingExtraID));

                //PARENT
                if (bes.BookingParentContainerID != null)
                {
                    tablesForMerge_PreMerge.Add(
                        theDocumentDataInstance.GetPRCDocumentData(
                      PRCDocumentData.PRCReturnDataTableWrapperTypes.StandardBookingParentContainer, (long)bes.BookingParentContainerID));
                }

                //ATTRIBUTES

                if (extraIDforAtts != null)
                {
                    extraAttributes = theDocumentDataInstance.GetPRCDocumentData(
                        PRCDocumentData.PRCReturnDataTableWrapperTypes.BookingExtraAttributesByBookingExtraID,
                        (long)extraIDforAtts);
                    extraAttributes.TableName = "ATTRIBUTETABLE";
                }


                //test if there is a related booking / property IF it's a solo BES event
                if(booking != null)
                {
                    if(bes.BookingParentContainerID != 0)
                    {
                        booking = db.Bookings.Where(x => x.BookingParentContainerID == bes.BookingParentContainerID).FirstOrDefault();

                        //PROPERTY
                        tablesForMerge_PreMerge.Add(
                            theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.PropertyByPropertyID,
                                (long)booking.PropertyID));


                        //TOWN
                        tablesForMerge_PreMerge.Add(
                            theDocumentDataInstance.GetPRCDocumentData(
                                PRCDocumentData.PRCReturnDataTableWrapperTypes.PropertyTownByPropertyTownID, Convert.ToInt64(db.Properties.Where(x => x.PropertyID == booking.PropertyID).FirstOrDefault().PropertyTownID)));

                        //REGION
                        tablesForMerge_PreMerge.Add(
                            theDocumentDataInstance.GetPRCDocumentData(
                                PRCDocumentData.PRCReturnDataTableWrapperTypes.PropertyRegionByPropertyRegionID, db.Properties.Where(x => x.PropertyID == booking.PropertyID).FirstOrDefault().PropertyTown.PropertyRegionID));

                    }


                }
            }








            List<DataTable> tablesForMerge = new List<DataTable>();

            foreach (var dataTable in tablesForMerge_PreMerge)
            {
                if (dataTable.Rows.Count > 0)
                {

                    DataTable tableToModAndReturn = dataTable.Copy();
                    //clone every table
                    DataTable dtCloned = dataTable.Copy();
                    //change every datetime column to a string

                    //for every dateTime colum, load into new table
                    foreach (DataColumn col in dtCloned.Columns)
                    {
                        var theType = dtCloned.Columns[col.ColumnName].DataType.ToString();

                        if (dtCloned.Columns[col.ColumnName].DataType.ToString() == "DateTime")
                        {
                            //change the type
                            var name = col.ColumnName;
                            var value = "";
                            if (dtCloned.Rows[0][col].ToString().Count() >= 10)
                            {
                                value = /*DateTime.Parse(*/ Convert.ToDateTime(dtCloned.Rows[0][col].ToString()).ToString("dd/MM/yyyy");
                                //).ToString("dd/MM/yyyy");
                            }


                            tableToModAndReturn.Columns.Remove(name);
                            tableToModAndReturn.Columns.Add(new DataColumn
                            {
                                ColumnName = name,
                                DefaultValue = value
                            });
                        }
                    }



                    tablesForMerge.Add(tableToModAndReturn);
                }
            }


            Aspose.Words.Document theDoc = new Aspose.Words.Document(HttpRuntime.AppDomainAppPath + aDocument.ServerDocumentURL);
            //execute the merges            
            foreach (var dataTable in tablesForMerge)
            {
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    theDoc.MailMerge.Execute(dataTable.Rows[i]);
                }
            }

            //N.B The regions in the document need to correspond to the table name for the below merge to work
            theDoc.MailMerge.ExecuteWithRegions(bookPartTable);
            theDoc.MailMerge.ExecuteWithRegions(besPartTable);
            theDoc.MailMerge.ExecuteWithRegions(extraAttributes);

            string filepathAndName = aDocument.SavePath + aDocument.FileName + ".pdf";
            theDoc.Save(aDocument.SavePath + aDocument.FileName + ".pdf");


            db.Dispose();


            return filepathAndName;
        }
        public ActionResult Edit(Booking booking)
        {
            var oldbook = db.Bookings.Where(x => x.BookingID == booking.BookingID).FirstOrDefault();

            booking.CreationDate = oldbook.CreationDate;
            booking.LastUpdated = oldbook.LastUpdated;

            if (ModelState.IsValid)
            {
                using (var _db = new PortugalVillasContext())
                {
                    _db.Bookings.Attach(booking);
                    _db.Entry(booking).State = EntityState.Modified;
                    _db.SaveChanges();
                    ViewBag.BookingParentContainerID = new SelectList(db.BookingParentContainers,
                        "BookingParentContainerID", "OverallBookingReference", booking.BookingParentContainerID);
                    ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "Title", booking.CustomerID);
                    ViewBag.PropertyID = new SelectList(db.Properties, "PropertyID", "LegacyReference",
                        booking.PropertyID);

                    return View("SingleBookingIndex", db.Bookings.Include(x => x.Customer).FirstOrDefault(x => x.BookingID == booking.BookingID));
                }
            }

            ViewBag.BookingParentContainerID = new SelectList(db.BookingParentContainers, "BookingParentContainerID", "OverallBookingReference", booking.BookingParentContainerID);
            ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "Title", booking.CustomerID);
            ViewBag.PropertyID = new SelectList(db.Properties, "PropertyID", "LegacyReference", booking.PropertyID);
            return View("SingleBookingIndex", db.Bookings.Include(x => x.Customer).FirstOrDefault(x => x.BookingID == booking.BookingID));
        }