//loads advertise property view
        public ActionResult AdvertiseProperty()
        {
            if (!String.IsNullOrEmpty(HttpContext.User.Identity.Name))
            {
                Session["userSignedInCheck"] = "Click add property to add a new property";

                return(RedirectToAction("Dashboard", "LandlordManagement"));
            }

            AdvertisePropertyViewModel Newmodel = new AdvertisePropertyViewModel()
            {
                FirstName       = "Lodeane",
                LastName        = "Kelly",
                CellNum         = "3912600",
                Email           = "*****@*****.**",
                StreetAddress   = "12 Coolshade Drive",
                Country         = "Jamaica",
                Division        = "Kingston 19",
                Community       = "Havendale",
                Price           = 4000,
                SecurityDeposit = 4000,
                TermsAgreement  = "Terms",
                TotRooms        = 1,
                IsReviewable    = true,
                Description     = "Very good property"
            };

            return(View(Newmodel));
        }
        public ActionResult GetAdvertisePropertyView()
        {
            Owner owner = null;
            AdvertisePropertyViewModel newModel = null;
            Guid userId;

            using (EasyFindPropertiesEntities dbCtx = new EasyFindPropertiesEntities())
            {
                if (Session["userId"] != null)
                {
                    userId = (Guid)Session["userId"];

                    UnitOfWork unitOfWork = new UnitOfWork(dbCtx);

                    owner = unitOfWork.Owner.GetOwnerByUserID(userId);
                }

                newModel = new AdvertisePropertyViewModel()
                {
                    FirstName       = owner.User.FirstName,
                    LastName        = owner.User.LastName,
                    CellNum         = owner.User.CellNum,
                    Email           = owner.User.Email,
                    StreetAddress   = "12 Coolshade Drive",
                    Country         = "Jamaica",
                    Division        = "Kingston 19",
                    Community       = "Havendale",
                    Price           = 4000,
                    SecurityDeposit = 4000,
                    TermsAgreement  = "Terms",
                    TotRooms        = 1,
                    IsReviewable    = true,
                    Description     = "Very good property"
                };
            }
            return(PartialView("_partialAdvertiseProperty", newModel));
        }
        /// <summary>
        /// Inserts the property along with it's owner, subscription period and also the property images
        /// </summary>
        /// <param name="model"></param>
        private void insertProperty(AdvertisePropertyViewModel model, UnitOfWork unitOfWork, User user)
        {
            bool doesOwnerExist = user != null && user.Owner.Select(x => x.ID).Count() > 0 ? true : false;
            Guid ownerID        = doesOwnerExist ? user.Owner.Select(x => x.ID).Single() : Guid.NewGuid();

            Guid   propertyID = Guid.NewGuid();
            String lat        = String.Empty;
            String lng        = String.Empty;

            //generate enrolment key for users with Landlord subscription
            if (model.SubscriptionType.Equals(nameof(EFPConstants.PropertySubscriptionType.Landlord)))
            {
                model.EnrolmentKey = getRandomKey(6);
            }

            //Coordinate priority : streetaddress then community
            if (!String.IsNullOrEmpty(model.saCoordinateLat) && !String.IsNullOrEmpty(model.saCoordinateLng))
            {
                lat = model.saCoordinateLat;
                lng = model.saCoordinateLng;
            }
            else if (!String.IsNullOrEmpty(model.cCoordinateLat) && !String.IsNullOrEmpty(model.cCoordinateLng))
            {
                //check if lat and lng is already set; if they are then dont using community
                if (string.IsNullOrEmpty(lat) && string.IsNullOrEmpty(lng))
                {
                    lat = model.saCoordinateLat;
                    lng = model.saCoordinateLng;
                }
            }

            Property property = new Property()
            {
                ID                     = propertyID,
                Title                  = model.Title,
                OwnerID                = ownerID,
                PurposeCode            = PropertyHelper.mapPropertyPurposeNameToCode(model.PropertyPurpose),
                TypeID                 = unitOfWork.PropertyType.GetPropertyTypeIDByName(model.PropertyType),
                AdTypeCode             = PropertyHelper.mapPropertyAdTypeNameToCode(model.AdvertismentType),
                AdPriorityCode         = PropertyHelper.mapPropertyAdpriorityNameToCode(model.AdvertismentPriority),
                ConditionCode          = EFPConstants.PropertyCondition.NotSurveyed,
                CategoryCode           = unitOfWork.PropertyType.GetPopertyTypeCategoryCodeByName(model.PropertyType),
                StreetAddress          = model.StreetAddress,
                Division               = model.Division,
                Community              = model.Community,
                NearByEstablishment    = model.NearBy,
                Country                = model.Country,
                Latitude               = lat,
                Longitude              = lng,
                NearByEstablishmentLat = model.nearByCoordinateLat,
                NearByEstablishmentLng = model.nearByCoordinateLng,
                Price                  = model.Price,
                SecurityDeposit        = model.SecurityDeposit,
                Occupancy              = model.Occupancy,
                GenderPreferenceCode   = model.GenderPreferenceCode,
                Description            = model.Description,
                Availability           = true,
                EnrolmentKey           = model.EnrolmentKey,
                TermsAgreement         = model.TermsAgreement,
                TotAvailableBathroom   = model.TotAvailableBathroom,
                TotRooms               = model.TotRooms,
                Area                   = model.Area,
                IsReviewable           = model.IsReviewable,
                DateTCreated           = DateTime.Now
            };

            Subscription subscription = new Subscription()
            {
                ID           = Guid.NewGuid(),
                OwnerID      = ownerID,
                TypeCode     = PropertyHelper.mapPropertySubscriptionTypeToCode(model.SubscriptionType),
                Period       = model.SubscriptionPeriod,
                DateTCreated = DateTime.Now
            };

            if (!doesOwnerExist)
            {
                Guid   guid     = Guid.NewGuid();
                String fileName = String.Empty;

                if (model.organizationLogo != null)
                {
                    fileName = guid.ToString() + Path.GetExtension(model.organizationLogo.FileName);
                    uploadPropertyImages(model.organizationLogo, fileName);
                }

                Owner owner = new Owner()
                {
                    ID           = ownerID,
                    UserID       = user.ID,
                    Organization = model.Organization,
                    LogoUrl      = fileName,
                    DateTCreated = DateTime.Now
                };

                unitOfWork.Owner.Add(owner);
            }
            unitOfWork.Property.Add(property);
            unitOfWork.Subscription.Add(subscription);

            associateTagsWithProperty(unitOfWork, propertyID, model.selectedTags);
            associateImagesWithProperty(unitOfWork, model.flPropertyPics, propertyID);
        }
        public JsonResult AdvertiseProperty(AdvertisePropertyViewModel model)
        {
            ErrorModel errorModel = new ErrorModel();

            if (ModelState.IsValid)
            {
                using (EasyFindPropertiesEntities dbCtx = new EasyFindPropertiesEntities())
                {
                    using (var dbCtxTran = dbCtx.Database.BeginTransaction())
                    {
                        try
                        {
                            if (!model.Password.Equals(model.ConfirmPassword))
                            {
                                throw new Exception("The fields Password and Confirm Password are not equal");
                            }

                            PropertyHelper.createRolesIfNotExist();

                            var unitOfWork = new UnitOfWork(dbCtx);

                            var doesUserExist = unitOfWork.User.DoesUserExist(model.Email);

                            var user = doesUserExist ? unitOfWork.User.GetUserByEmail(model.Email) : null;
                            //if user already exists and they are not a property owner, then associate user with that user type as well
                            //TODO: user's role will have to be manipulated as well
                            if (user != null)
                            {
                                var  userTypes       = unitOfWork.UserTypeAssoc.GetUserTypesByUserID(user.ID);
                                bool isUserPropOwner = PropertyHelper.isUserOfType(userTypes, EFPConstants.UserType.PropertyOwner);

                                if (!isUserPropOwner)
                                {
                                    PropertyHelper.associateUserWithUserType(unitOfWork, user.ID, EFPConstants.UserType.PropertyOwner);
                                }
                            }
                            else
                            {
                                user = PropertyHelper.createUser(unitOfWork, EFPConstants.UserType.PropertyOwner, model.SubscriptionType, model.Email, model.FirstName,
                                                                 model.LastName, model.CellNum, DateTime.MinValue);

                                PropertyHelper.createUserAccount(unitOfWork, model.Email, model.Password);
                            }


                            insertProperty(model, unitOfWork, user);

                            unitOfWork.save();
                            dbCtxTran.Commit();
                        }
                        catch (Exception ex)
                        {
                            dbCtxTran.Rollback();

                            if (uploadedImageNames != null && uploadedImageNames.Count > 0)
                            {
                                PropertyHelper.removeUploadedImages(uploadedImageNames);
                            }

                            errorModel.hasErrors     = true;
                            errorModel.ErrorMessages = new List <string>();
                            errorModel.ErrorMessages.Add(ex.Message);
                        }
                    }
                }
            }
            else
            {
                var errors = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage);

                errorModel.hasErrors     = true;
                errorModel.ErrorMessages = new List <string>();
                errorModel.ErrorMessages.AddRange(errors);
            }

            return(Json(errorModel));
        }