public ActionResult Dashboard(int page = 1)
        {
            LayoutViewModel.ActiveLink = Links.SupplierDashboard;

            ProfileModel profileModel =
                new ProfileService().GetMyProfile(
                LayoutViewModel.ProviderUserKey, LayoutViewModel.CurrentUserEmail, page);

            DashboardViewModel viewModel = new DashboardViewModel();
            viewModel.ProfileModel = profileModel;
            viewModel.RewardsSummaryListModel = new RewardsService().GetSupplierRewardsSummary(new Guid(LayoutViewModel.ProviderUserKey), page, 5);
            viewModel.ActivitySummaryModel = new RewardsService().GetActivitySummaryModelModel(LayoutViewModel.ProviderUserKey);
            viewModel.HouseholdMemberModel = new HouseholdMemberModel();

            bool isDefaultSupplierAddress;
            viewModel.Address = GetSupplierAddress(profileModel.Address, out isDefaultSupplierAddress);

            return View(viewModel);
        }
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);

            var returnUrl = requestContext.HttpContext.Request.QueryString["ReturnUrl"];
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = requestContext.HttpContext.Request.Url.PathAndQuery;
            }

            LayoutViewModel = new LayoutViewModel
            {
                Title = "Green Money"
            };

            if (Request.IsAuthenticated)
            {

                var membershipUser = Membership.GetUser();

                if (membershipUser == null)
                {
                    FormsAuthentication.SignOut();
                    Session.Abandon();
                }
                else
                {
                    var currentUserId = membershipUser.ProviderUserKey.ToString();
                    //currentUserId = "C26B6CA5-6262-4AFA-8AC7-529929CAB0B1";
                    //currentUserId = "CDEE65FA-FD6C-40D7-A134-43A4B0AD696D";
                    //currentUserId = "A26E61B4-016D-4ECD-8F04-4CE10632A94D";

                    var user = new ProfileService().GetMyProfileBase(currentUserId, membershipUser.Email);

                    LayoutViewModel.IsAuthenticated = true;
                    LayoutViewModel.IsSuplier = Roles.IsUserInRole(membershipUser.Email, "Supplier");
                    LayoutViewModel.IsCouncil = Roles.IsUserInRole(membershipUser.Email, "Council");

                    var privateClientId = ConfigurationManager.AppSettings["PrivateClientId"] == null
                    ? 5
                    : int.Parse(ConfigurationManager.AppSettings["PrivateClientId"]);
                    LayoutViewModel.IsAusPost = user.Instance_Id == privateClientId;

                    LayoutViewModel.CurrentAccountId = new Guid(currentUserId);
                    LayoutViewModel.CurrentFirstName = user.User.FirstName;
                    LayoutViewModel.CurrentLastName = user.User.LastName;
                    LayoutViewModel.CurrentUserEmail = membershipUser.Email;
                    LayoutViewModel.CurrentUserPhotoId = user.User.PhotoID;
                    LayoutViewModel.ProviderUserKey = currentUserId;

                    LayoutViewModel.CurrentUserTotalPoints = user.PointsAvailable;
                    LayoutViewModel.CurrentUserTotalCart = user.CartTotal;
                    LayoutViewModel.CurrentUserTotalChallenges = user.ChallengesTotal;

                    LayoutViewModel.Instance_Id = user.Instance_Id;

                    // for Council
                    if (Roles.IsUserInRole(membershipUser.Email, "Council"))
                    {
                        LayoutViewModel.UserChallengesCount = (new ProfileService().GetCouncilProfile(Convert.ToInt32(user.Instance_Id))).UserChallengesCount;
                    }
                }
            }
        }
        public ActionResult Index(UpdateSupplierProfileViewModel viewModel)
        {
            LayoutViewModel.ActiveLink = Links.SupplierUpdateProfile;

            var membershipUser = Membership.GetUser();

            if (ModelState.IsValid)
            {
                UserModel userModel = new UserModel
                {
                    Id = LayoutViewModel.CurrentAccountId,
                    FirstName = viewModel.FirstName,
                    LastName = viewModel.LastName,
                    PhotoID = viewModel.PhotoID,
                    BusinessName = viewModel.BusinessName,
                    BusinessNumberABN = viewModel.BusinessNumberABN,
                    BusinessType = viewModel.BusinessType,
                    BussinesEmail = viewModel.BussinesEmail,
                    BussinesLocation = viewModel.BussinesLocation,
                    BussinesPhone = viewModel.BussinesPhone,
                    BussinesPhoneArea = viewModel.BussinesPhoneArea,
                    BussinesPhoneMobile = viewModel.BussinesPhoneMobile,
                    BussinesWebSite = viewModel.BussinesWebSite,
                    EmailBussinesOnVoucherRedeem = viewModel.EmailBussinesOnVoucherRedeem,
                    SendEmailUpdates = viewModel.SendEmailUpdates
                };

                var success = true;

                // change password
                if (!string.IsNullOrEmpty(viewModel.OldPassword) || !string.IsNullOrEmpty(viewModel.NewPassword)
                    || !string.IsNullOrEmpty(viewModel.ConfirmNewPassword))
                {
                    if (string.IsNullOrEmpty(viewModel.OldPassword))
                    {
                        ModelState.AddModelError("OldPassword", "The Old password field is required.");
                        success = false;
                    }

                    if (string.IsNullOrEmpty(viewModel.NewPassword))
                    {
                        ModelState.AddModelError("NewPassword", "The New password field is required.");
                        success = false;
                    }

                    if (string.IsNullOrEmpty(viewModel.ConfirmNewPassword))
                    {
                        ModelState.AddModelError("ConfirmNewPassword", "The Confirm new password field is required.");
                        success = false;
                    }

                    if (success && viewModel.NewPassword != viewModel.ConfirmNewPassword)
                    {
                        ModelState.AddModelError("ConfirmNewPassword", "New password and confirmation password do not match.");
                        success = false;
                    }

                    if (success && !membershipUser.ChangePassword(viewModel.OldPassword, viewModel.NewPassword))
                    {
                        ModelState.AddModelError("OldPassword", "Old password is incorrect.");
                        success = false;
                    }
                }

                if (viewModel.Photo != null && viewModel.Photo.ContentLength > 0)
                {
                    MemoryStream target = new MemoryStream();
                    viewModel.Photo.InputStream.CopyTo(target);
                    byte[] data = target.ToArray();

                    UploadModel model = new UploadModel
                    {
                        ContentType = viewModel.Photo.ContentType,
                        Contents = data,
                        FileName = viewModel.Photo.FileName
                    };

                    UploadModel upload = new UploadService().UploadFile(membershipUser.ProviderUserKey.ToString(), model, true);

                }

                if (success)
                {
                    var updated = new UserService().UpdateSupplierUser(userModel);

                    // change username COMPLICATED
                    if (membershipUser.UserName != viewModel.BussinesEmail)
                    {

                        var config = WebConfigurationManager.OpenWebConfiguration("~");
                        var section = config.SectionGroups["system.web"].Sections["membership"] as MembershipSection;
                        var defaultProvider = section.DefaultProvider;
                        var connectionStringName = section.Providers[defaultProvider].ElementInformation.Properties["connectionStringName"].Value.ToString();

                        string connectionString = config.ConnectionStrings.ConnectionStrings[connectionStringName].ConnectionString;

                        var changed = new ProfileService().ChangeUsername(membershipUser.UserName, viewModel.BussinesEmail, connectionString);

                        if (changed)
                        {
                            // change email as well
                            membershipUser.Email = viewModel.BussinesEmail;

                            // need to re-verify
                            membershipUser.IsApproved = false;
                            //SendVerifyEmail(membershipUser, user, false);
                            //instead I'm showing verifucation code in the view

                            Membership.UpdateUser(membershipUser);

                            // need to sign out to force verification
                            FormsAuthentication.SignOut();

                            TempData["VerifyCode"] = ZBase32.Encode(LayoutViewModel.CurrentAccountId.ToByteArray());

                            // redirect to screen which tells user to check email
                            return RedirectToAction("EmailChangeSuccess", "Account");
                        }
                        else
                        {
                            ModelState.AddModelError("", "A user for that email address already exists. Please enter a different email address.");
                        }
                    }

                    return RedirectToAction("Dashboard");
                }

                return View(viewModel);
            }

            return View(viewModel);
        }
        public ActionResult MyProfile(int page = 1)
        {
            if (LayoutViewModel.IsSuplier)
            {
                return RedirectToAction("Dashboard", "Supplier");
            }

            if (LayoutViewModel.IsCouncil)
            {
                return RedirectToAction("Index", "ChallengesAdmin");
            }

            LayoutViewModel.ActiveLink = Links.AccountMyProfile;

            //Code to change user password from the code
            //string username = membershipUser.UserName;
            //string password = "******";
            //MembershipUser mu = Membership.GetUser(username);
            //mu.ChangePassword(mu.ResetPassword(), password);

            ProfileModel profileModel =
                new ProfileService().GetMyProfile(
                LayoutViewModel.ProviderUserKey, LayoutViewModel.CurrentUserEmail, page);

            MyProfileViewModel viewModel = new MyProfileViewModel();
            viewModel.ProfileModel = profileModel;
            viewModel.EmailAddress = LayoutViewModel.CurrentUserEmail; //TODO - fix this
            viewModel.HouseholdMemberModel = new HouseholdMemberModel();

            if (profileModel.User.DateOfBirth != null)
            {
                viewModel.BirthDate = profileModel.User.DateOfBirth.Value.ToString("dd MMM yyyy");
            }

            //Auspost specific
            if (LayoutViewModel.IsAusPost)
            {
                if (profileModel.User.DateOfBirth != null)
                {
                    viewModel.BirthDate = profileModel.User.DateOfBirth.Value.ToString("dd MMM yyyy");

                    var numOfYears = DateTime.Today.Year - profileModel.User.DateOfBirth.Value.Year;
                    const int interval = 8;

                    string range = CheckValueInRange(0, 17, numOfYears)
                        ? "< 18"
                        : (CheckValueInRange(18, interval, numOfYears)
                            ? "18-25"
                            : (CheckValueInRange(26, interval, numOfYears)
                                ? "26-33"
                                : (CheckValueInRange(34, interval, numOfYears)
                                    ? "34-41"
                                    : (CheckValueInRange(42, interval, numOfYears)
                                        ? "42-49"
                                        : (CheckValueInRange(50, interval, numOfYears)
                                             ? "50-57"
                                             : (CheckValueInRange(58, interval, numOfYears)
                                                ? "58-65"
                                                : (CheckValueInRange(66, interval, numOfYears)
                                                    ? "66-73"
                                                    : "74 >"
                                    )))))));

                    viewModel.NumberOfYears = String.Format("{0} years", range);
                }

                viewModel.NumberOfChallenges = new ChallengesService().GetNumberOfMyChallenges(LayoutViewModel.ProviderUserKey, DateTime.Today.AddMonths(-12));

                return View("MyProfileAuspost", viewModel);
            }

            viewModel.AddressFull = ViewModelHelper.GetUserAddress(profileModel.Address);

            return View(viewModel);
        }
        public ActionResult UpdateAuspost()
        {
            LayoutViewModel.ActiveLink = Links.AccountUpdateProfile;

            var profileModel = new ProfileService().GetMyProfile(LayoutViewModel.ProviderUserKey,
                LayoutViewModel.CurrentUserEmail, 1);

            UpdateProfileAuspostViewModel viewModelCompany = new UpdateProfileAuspostViewModel
            {
                FirstName = profileModel.User.FirstName,
                LastName = profileModel.User.LastName,
                PhoneNumber = profileModel.User.PhoneNumber,
                Sex = profileModel.User.Sex,
                Email = LayoutViewModel.CurrentUserEmail,
                CompanyEmail = LayoutViewModel.CurrentUserEmail.Split('@')[0],
                CompanyEmailDomain = string.Format("@{0}", LayoutViewModel.CurrentUserEmail.Split('@')[1]),
                PhotoId = profileModel.User.PhotoID,
                Address = ViewModelHelper.GetUserAddress(profileModel.Address),
                SupportEmail = ConfigurationManager.AppSettings["SupportEmail"],
                PushNotifications = profileModel.User.PushNotifications
            };

            //Private company - auspost
            viewModelCompany.EmploymentType = profileModel.User.EmploymentType;

            if (profileModel.User.DateOfBirth.HasValue)
            {
                DateTime date = profileModel.User.DateOfBirth.Value;
                viewModelCompany.DateOfBirthDay = date.Day;
                viewModelCompany.DateOfBirthMonth = date.Month;
                viewModelCompany.DateOfBirthYear = date.Year;
            }

            var streetTypes = new UserService().GetAllStreetTypes((int)LayoutViewModel.Instance_Id);
            var streetNames = new UserService().GetAllStreetNames((int)LayoutViewModel.Instance_Id);
            var suburbs = new UserService().GetAllSuburbs((int)LayoutViewModel.Instance_Id);
            var states = new UserService().GetAllStates((int)LayoutViewModel.Instance_Id);

            viewModelCompany.StreetTypes = new SelectList(streetTypes);
            viewModelCompany.StreetNames = new SelectList(streetNames);
            viewModelCompany.Subrps = new SelectList(suburbs);
            viewModelCompany.States = new SelectList(states);

            viewModelCompany.StreetType = profileModel.Address.StreetType;
            viewModelCompany.StreetName = profileModel.Address.StreetName;
            viewModelCompany.Subrp = profileModel.Address.Suburb;
            viewModelCompany.State = profileModel.Address.State;

            return View("UpdateProfileAuspost", viewModelCompany);
        }
        public ActionResult Checkout(bool failure = false)
        {
            LayoutViewModel.ActiveLink = Links.AccountMyCart;

            CartModel cartModel = new ProfileService().GetMyCart(LayoutViewModel.ProviderUserKey);

            MyCartCheckoutViewModel viewModel = new MyCartCheckoutViewModel();
            viewModel.CartModel = cartModel;
            viewModel.TotalQuantity = cartModel.Items.Sum(i => i.Quantity).ToString();
            viewModel.TotalPoints = cartModel.CartTotal.ToString("#,##0");
            viewModel.UserEmail = LayoutViewModel.CurrentUserEmail;

            if (failure)
            {
                viewModel.CheckoutFailure = true;
            }

            return View(viewModel);
        }
        public ActionResult CheckoutSubmit()
        {
            LayoutViewModel.ActiveLink = Links.AccountMyCart;

            CheckoutSubmitModel addToMyWallet = new ProfileService().AddCartToMyWallet(LayoutViewModel.ProviderUserKey);

            // Send email to reward owner user
            // + Send email to current user
            string url = Request.Url.Host;
            var voucherUrlBase = Url.Action("Voucher", "Rewards", null, Request.Url.Scheme);
            string contentPath = Server.MapPath("~/App_Data/Emails/reward-redeemed.cshtml");
            string contentPath1 = Server.MapPath("~/App_Data/Emails/product-order-confirmation.cshtml");
            string contentPath2 = Server.MapPath("~/App_Data/Emails/order-confirmation.cshtml");
            EmailService.SendEmailsOnRewardsRedeem(contentPath, contentPath1, contentPath2,
                LayoutViewModel.CurrentUserEmail, LayoutViewModel.CurrentFirstName, LayoutViewModel.CurrentLastName,
                url, voucherUrlBase, addToMyWallet);

            if (addToMyWallet.CheckoutSubmitModelState == CheckoutSubmitModelState.NoItemsFound)
            {
                return RedirectToAction("Checkout");
            }

            if (addToMyWallet.CheckoutSubmitModelState == CheckoutSubmitModelState.NotEnoughPoints)
            {
                return RedirectToAction("Checkout", new {failure = true});
            }

            if (addToMyWallet.CheckoutSubmitModelState == CheckoutSubmitModelState.SuccessWithOrderConfirmation)
            {
                // TODO Send Order Confirmation email
                return RedirectToAction("Wallet");
            }

            if (addToMyWallet.CheckoutSubmitModelState == CheckoutSubmitModelState.SuccessWithProductOrderConfirmation)
            {
                // TODO Send Product Order Confirmation email
                return RedirectToAction("Wallet");
            }

            return RedirectToAction("Wallet");
        }
        public bool CartToAdd(int id, int quantity = 1)
        {
            bool rewardAddedToCart = new ProfileService().AddToMyCart(LayoutViewModel.ProviderUserKey, id);

            return rewardAddedToCart;
        }
        public ActionResult Cart(MyCartViewModel myCartViewModel)
        {
            LayoutViewModel.ActiveLink = Links.AccountMyCart;

            bool updated = new ProfileService().UpdateMyCart(LayoutViewModel.ProviderUserKey, myCartViewModel.CartModel.Items);

            return RedirectToAction("Cart");
        }
        public ActionResult Cart()
        {
            LayoutViewModel.ActiveLink = Links.AccountMyCart;

            CartModel cartModel = new ProfileService().GetMyCart(LayoutViewModel.ProviderUserKey);

            MyCartViewModel viewModel = new MyCartViewModel();
            viewModel.CartModel = cartModel;

            return View(viewModel);
        }
        public ActionResult UpdateProfileAuspost(UpdateProfileAuspostViewModel viewModel)
        {
            LayoutViewModel.ActiveLink = Links.AccountUpdateProfile;

            var membershipUser = Membership.GetUser();

            if (ModelState.IsValid)
            {
                UpdateProfileModel updateModel = new UpdateProfileModel();

                updateModel.FirstName = viewModel.FirstName;
                updateModel.LastName = viewModel.LastName;
                updateModel.PhoneNumber = viewModel.PhoneNumber;
                updateModel.Sex = viewModel.Sex;
                updateModel.PushNotifications = viewModel.PushNotifications;
                updateModel.EmploymentType = viewModel.EmploymentType;

                if (viewModel.DateOfBirthDay != null && viewModel.DateOfBirthMonth != null && viewModel.DateOfBirthYear != null)
                {
                    updateModel.BirthDate =
                        new DateTime(year: viewModel.DateOfBirthYear.Value,
                            month: viewModel.DateOfBirthMonth.Value,
                            day: viewModel.DateOfBirthDay.Value);
                }

                // find new user's address
                //int? addressId = new UserService().FindMatchingAuspostAddressId(
                //    streetName: viewModel.StreetName,
                //    streetType: viewModel.StreetType,
                //    suburb: viewModel.Subrp,
                //    state: viewModel.State
                //    );

                //if (addressId != null)
                //{
                //    updateModel.AddressId = addressId;
                //}
                //else
                //{
                //    FillBaseViewModelData(viewModel);

                //    ModelState.AddModelError("", "Incomplete workplace details. Please update your details and save.");
                //    return View(viewModel);
                //}

                var success = true;

                // change password
                if (!string.IsNullOrEmpty(viewModel.OldPassword) || !string.IsNullOrEmpty(viewModel.NewPassword)
                    || !string.IsNullOrEmpty(viewModel.ConfirmNewPassword))
                {
                    if (string.IsNullOrEmpty(viewModel.OldPassword))
                    {
                        ModelState.AddModelError("OldPassword", "The Old password field is required.");
                        success = false;
                    }

                    if (string.IsNullOrEmpty(viewModel.NewPassword))
                    {
                        ModelState.AddModelError("NewPassword", "The New password field is required.");
                        success = false;
                    }

                    if (string.IsNullOrEmpty(viewModel.ConfirmNewPassword))
                    {
                        ModelState.AddModelError("ConfirmNewPassword", "The Confirm new password field is required.");
                        success = false;
                    }

                    if (success && viewModel.NewPassword != viewModel.ConfirmNewPassword)
                    {
                        ModelState.AddModelError("ConfirmNewPassword", "New password and confirmation password do not match.");
                        success = false;
                    }

                    if (success && !membershipUser.ChangePassword(viewModel.OldPassword, viewModel.NewPassword))
                    {
                        ModelState.AddModelError("OldPassword", "Old password is incorrect.");
                        success = false;
                    }
                }

                if (viewModel.Photo != null && viewModel.Photo.ContentLength > 0)
                {
                    MemoryStream target = new MemoryStream();
                    viewModel.Photo.InputStream.CopyTo(target);
                    byte[] data = target.ToArray();

                    UploadModel model = new UploadModel
                    {
                        ContentType = viewModel.Photo.ContentType,
                        Contents = data,
                        FileName = viewModel.Photo.FileName
                    };

                    UploadModel upload = new UploadService().UploadFile(LayoutViewModel.ProviderUserKey, model, true);

                }

                if (success)
                {

                    var updated =
                        new ProfileService().UpdateProfile(LayoutViewModel.ProviderUserKey, updateModel);

                    // change username COMPLICATED
                    if (membershipUser.UserName != viewModel.Email)
                    {

                        var config = WebConfigurationManager.OpenWebConfiguration("~");
                        var section = config.SectionGroups["system.web"].Sections["membership"] as MembershipSection;
                        var defaultProvider = section.DefaultProvider;
                        var connectionStringName = section.Providers[defaultProvider].ElementInformation.Properties["connectionStringName"].Value.ToString();

                        string connectionString = config.ConnectionStrings.ConnectionStrings[connectionStringName].ConnectionString;

                        string companyEmail = string.Join(viewModel.CompanyEmail, viewModel.CompanyEmailDomain);

                        var changed = new ProfileService().ChangeUsername(membershipUser.UserName, companyEmail, connectionString);

                        if (changed)
                        {
                            // change email as well
                            membershipUser.Email = companyEmail;

                            // need to re-verify
                            membershipUser.IsApproved = false;
                            SendVerifyEmail(membershipUser.Email, updateModel.FirstName, LayoutViewModel.CurrentAccountId, false);

                            //instead I'm showing verifucation code in the view
                            Membership.UpdateUser(membershipUser);

                            // need to sign out to force verification
                            FormsAuthentication.SignOut();

                            TempData["VerifyCode"] = ZBase32.Encode(LayoutViewModel.CurrentAccountId.ToByteArray());

                            // redirect to screen which tells user to check email
                            return RedirectToAction("EmailChangeSuccess");
                        }
                        else
                        {
                            ModelState.AddModelError("", "A user for that email address already exists. Please enter a different email address.");
                        }
                    }

                    return RedirectToAction("MyProfile");

                }

                //Something not valid, show errors
                viewModel.SupportEmail = ConfigurationManager.AppSettings["SupportEmail"];

                return View(viewModel);
            }

            FillBaseViewModelData(viewModel);

            return View(viewModel);
        }
        public ActionResult UpdateProfile()
        {
            LayoutViewModel.ActiveLink = Links.AccountUpdateProfile;

            var profileModel = new ProfileService().GetMyProfile(LayoutViewModel.ProviderUserKey, LayoutViewModel.CurrentUserEmail, 1);

            UpdateProfileViewModel viewModel = new UpdateProfileViewModel
            {
                FirstName = profileModel.User.FirstName,
                LastName = profileModel.User.LastName,
                PhoneNumber = profileModel.User.PhoneNumber,
                Sex = profileModel.User.Sex,
                Email = LayoutViewModel.CurrentUserEmail,
                PhotoId = profileModel.User.PhotoID,
                Address = ViewModelHelper.GetUserAddress(profileModel.Address),
                SupportEmail = ConfigurationManager.AppSettings["SupportEmail"],
                SendEmailUpdates = profileModel.User.SendEmailUpdates,
                PushNotifications = profileModel.User.PushNotifications,
                PostToFacebook = profileModel.User.PostToFacebook
            };

            if (profileModel.User.DateOfBirth.HasValue)
            {
                DateTime date = profileModel.User.DateOfBirth.Value;
                viewModel.DateOfBirthDay = date.Day;
                viewModel.DateOfBirthMonth = date.Month;
                //viewModel.DateOfBirthMonthText =
                //    viewModel.Months.Where(m => int.Parse(m.Value) == date.Month).First().Text;

                viewModel.DateOfBirthYear = date.Year;
            }

            //Auspost
            if (LayoutViewModel.IsAusPost)
            {
                return RedirectToAction("UpdateAuspost");
            }

            return View(viewModel);
        }