public string UpdateCarts(List <UpdateCartItem> carts)
        {
            try
            {
                UpdateCartItem     updatecart   = carts[0];
                hccCart            CurrentCart  = hccCart.GetById(updatecart.cartId);
                hccUserProfile     ownerProfile = CurrentCart.OwnerProfile;
                hccAddress         snapBillAddr = null;
                List <hccCartItem> cartItems    = null;
                bool      isAuthNet             = false;
                hccLedger ledger = null;
                string    retVal = string.Empty;

                if (CurrentCart != null && ownerProfile != null)
                {
                    hccAddress billAddr = null;
                    hccUserProfilePaymentProfile activePaymentProfile = ownerProfile.ActivePaymentProfile;

                    if (updatecart.updateStatus && CurrentCart.StatusID != updatecart.statusId)
                    {
                        CurrentCart.StatusID     = updatecart.statusId;
                        CurrentCart.ModifiedBy   = (Guid)Helpers.LoggedUser.ProviderUserKey;
                        CurrentCart.ModifiedDate = DateTime.Now;

                        if (updatecart.statusId == (int)Enums.CartStatus.Paid)
                        {
                            if (!CurrentCart.PurchaseBy.HasValue)
                            {
                                CurrentCart.PurchaseBy = (Guid)Helpers.LoggedUser.ProviderUserKey;
                            }

                            if (!CurrentCart.PurchaseDate.HasValue)
                            {
                                CurrentCart.PurchaseDate = DateTime.Now;
                            }
                        }
                        CurrentCart.Save();
                    }

                    if (updatecart.updateAddresses) // re-snap addresses
                    {
                        if (ownerProfile.BillingAddressID.HasValue)
                        {
                            billAddr = hccAddress.GetById(ownerProfile.BillingAddressID.Value);

                            if (billAddr != null)
                            {
                                snapBillAddr = new hccAddress
                                {
                                    Address1              = billAddr.Address1,
                                    Address2              = billAddr.Address2,
                                    AddressTypeID         = (int)Enums.AddressType.BillingSnap,
                                    City                  = billAddr.City,
                                    Country               = billAddr.Country,
                                    DefaultShippingTypeID = billAddr.DefaultShippingTypeID,
                                    FirstName             = billAddr.FirstName,
                                    IsBusiness            = billAddr.IsBusiness,
                                    LastName              = billAddr.LastName,
                                    Phone                 = billAddr.Phone,
                                    PostalCode            = billAddr.PostalCode,
                                    State                 = billAddr.State,
                                    ProfileName           = ownerProfile.ProfileName
                                };
                                snapBillAddr.Save();
                            }
                        }
                        else
                        {
                            retVal += "Profile has no billing address on record.";
                        }

                        if (cartItems == null)
                        {
                            cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                        }

                        cartItems.ForEach(delegate(hccCartItem ci)
                        {
                            hccAddress shipAddr = null;

                            if (snapBillAddr != null)
                            {
                                ci.SnapBillAddrId = snapBillAddr.AddressID;
                            }

                            if (ci.UserProfile == null)
                            {
                                ci.UserProfileID = ownerProfile.UserProfileID;
                            }

                            if (ci.UserProfile.ShippingAddressID.HasValue)
                            {
                                shipAddr = hccAddress.GetById(ci.UserProfile.ShippingAddressID.Value);
                            }

                            if (shipAddr != null)
                            {
                                hccAddress snapShipAddr = new hccAddress
                                {
                                    Address1              = shipAddr.Address1,
                                    Address2              = shipAddr.Address2,
                                    AddressTypeID         = (int)Enums.AddressType.ShippingSnap,
                                    City                  = shipAddr.City,
                                    Country               = shipAddr.Country,
                                    DefaultShippingTypeID = shipAddr.DefaultShippingTypeID,
                                    FirstName             = shipAddr.FirstName,
                                    IsBusiness            = shipAddr.IsBusiness,
                                    LastName              = shipAddr.LastName,
                                    Phone                 = shipAddr.Phone,
                                    PostalCode            = shipAddr.PostalCode,
                                    State                 = shipAddr.State,
                                    ProfileName           = ci.UserProfile.ProfileName
                                };
                                snapShipAddr.Save();
                                ci.SnapShipAddrId = snapShipAddr.AddressID;
                            }

                            ci.Save();
                        });
                    }

                    if (updatecart.rerunAuthNet)
                    {
                        CurrentCart.StatusID     = (int)Enums.CartStatus.Unfinalized;
                        CurrentCart.PurchaseBy   = null;
                        CurrentCart.PurchaseDate = null;

                        if (ownerProfile != null)
                        {
                            AuthNetConfig ANConfig = new AuthNetConfig();

                            if (ANConfig.Settings.TestMode)
                            {
                                CurrentCart.IsTestOrder = true;
                            }

                            if (CurrentCart.PaymentDue > 0.00m)
                            {
                                try
                                {   // if total balance remains
                                    CustomerInformationManager cim = new CustomerInformationManager();

                                    if (activePaymentProfile != null)
                                    {
                                        AuthorizeNet.Order order = new AuthorizeNet.Order(ownerProfile.AuthNetProfileID,
                                                                                          activePaymentProfile.AuthNetPaymentProfileID, null);

                                        // charge CIM account with PaymentDue balance
                                        order.Amount        = CurrentCart.PaymentDue;
                                        order.InvoiceNumber = CurrentCart.PurchaseNumber.ToString();
                                        order.Description   = "Healthy Chef Creations Purchase #" + CurrentCart.PurchaseNumber.ToString();

                                        AuthorizeNet.IGatewayResponse rsp = cim.AuthorizeAndCapture(order);

                                        try
                                        {
                                            CurrentCart.AuthNetResponse = rsp.ResponseCode + "|" + rsp.Approved.ToString()
                                                                          + "|" + rsp.AuthorizationCode + "|" + rsp.InvoiceNumber + "|" + rsp.Message
                                                                          + "|" + rsp.TransactionID + "|" + rsp.Amount.ToString() + "|" + rsp.CardNumber;
                                        }
                                        catch (Exception) { }

                                        if (rsp.ResponseCode.StartsWith("1"))
                                        {
                                            CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                            CurrentCart.ModifiedDate     = DateTime.Now;
                                            CurrentCart.PurchaseBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                            CurrentCart.PurchaseDate     = DateTime.Now;
                                            CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                            CurrentCart.StatusID         = (int)Enums.CartStatus.Paid;

                                            isAuthNet = true;
                                        }
                                        CurrentCart.Save();
                                    }
                                    else
                                    {
                                        return("No active payment profile.");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (ex is InvalidOperationException)
                                    {
                                        if (CurrentCart.IsTestOrder)
                                        {
                                            CurrentCart.ModifiedBy       = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                            CurrentCart.ModifiedDate     = DateTime.Now;
                                            CurrentCart.PaymentProfileID = activePaymentProfile.PaymentProfileID;
                                            CurrentCart.AuthNetResponse  = ex.Message;
                                            CurrentCart.StatusID         = (int)Enums.CartStatus.Unfinalized;
                                            CurrentCart.Save();
                                        }
                                        else
                                        {
                                            BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(ex.Message, this, ex);
                                        }
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                            }
                            else
                            {      // no balance left to pay on order, set as paid
                                CurrentCart.AuthNetResponse = "Paid with account balance.";
                                CurrentCart.ModifiedBy      = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                CurrentCart.ModifiedDate    = DateTime.Now;
                                CurrentCart.PurchaseBy      = (Guid)Helpers.LoggedUser.ProviderUserKey;
                                CurrentCart.PurchaseDate    = DateTime.Now;
                                CurrentCart.StatusID        = (int)Enums.CartStatus.Paid;
                                CurrentCart.Save();
                            }
                        }
                    }

                    if (updatecart.createLedgerEntry)
                    {
                        if (ledger == null)
                        {
                            ledger = hccLedger.GetBy(CurrentCart.CartID);
                        }

                        if (ledger == null)
                        {
                            SaveLedger(ledger, CurrentCart, ownerProfile);
                        }
                    }

                    if (updatecart.createNewSnapshot)
                    {
                        if (((Enums.CartStatus)CurrentCart.StatusID) == Enums.CartStatus.Paid)
                        {
                            if (ledger == null)
                            {
                                ledger = hccLedger.GetBy(CurrentCart.CartID);
                            }

                            if (ledger == null) // it still equals null
                            {
                                SaveLedger(ledger, CurrentCart, ownerProfile);
                            }

                            // create snapshot here
                            hccCartSnapshot snap = new hccCartSnapshot
                            {
                                CartId           = CurrentCart.CartID,
                                MembershipId     = ownerProfile.MembershipID,
                                LedgerId         = ledger.LedgerID,
                                AccountBalance   = ownerProfile.AccountBalance,
                                AuthNetProfileId = ownerProfile.AuthNetProfileID,
                                CreatedBy        = (Guid)Helpers.LoggedUser.ProviderUserKey,
                                CreatedDate      = DateTime.Now,
                                DefaultCouponId  = ownerProfile.DefaultCouponId,
                                Email            = ownerProfile.ASPUser.Email,
                                FirstName        = ownerProfile.FirstName,
                                LastName         = ownerProfile.LastName,
                                ProfileName      = ownerProfile.ProfileName
                            };

                            if (isAuthNet)
                            {
                                if (activePaymentProfile != null)
                                {
                                    snap.AuthNetPaymentProfileId = activePaymentProfile.AuthNetPaymentProfileID;
                                    snap.CardTypeId = activePaymentProfile.CardTypeID;
                                    snap.CCLast4    = activePaymentProfile.CCLast4;
                                    snap.ExpMon     = activePaymentProfile.ExpMon;
                                    snap.ExpYear    = activePaymentProfile.ExpYear;
                                    snap.NameOnCard = activePaymentProfile.NameOnCard;
                                }
                                else
                                {
                                    return("No active payment profile.");
                                }
                            }
                            else
                            {
                                snap.AuthNetPaymentProfileId = string.Empty;
                                snap.CardTypeId = 0;
                                snap.CCLast4    = string.Empty;
                                snap.ExpMon     = 0;
                                snap.ExpYear    = 0;
                                snap.NameOnCard = string.Empty;
                            }
                            snap.Save();

                            if (billAddr == null && ownerProfile.BillingAddressID.HasValue)
                            {
                                billAddr = hccAddress.GetById(ownerProfile.BillingAddressID.Value);
                            }

                            if (billAddr != null)
                            {
                                snapBillAddr = new hccAddress
                                {
                                    Address1              = billAddr.Address1,
                                    Address2              = billAddr.Address2,
                                    AddressTypeID         = billAddr.AddressTypeID,
                                    City                  = billAddr.City,
                                    Country               = billAddr.Country,
                                    DefaultShippingTypeID = billAddr.DefaultShippingTypeID,
                                    FirstName             = billAddr.FirstName,
                                    IsBusiness            = billAddr.IsBusiness,
                                    LastName              = billAddr.LastName,
                                    Phone                 = billAddr.Phone,
                                    PostalCode            = billAddr.PostalCode,
                                    State                 = billAddr.State,
                                    ProfileName           = ownerProfile.ProfileName
                                };
                                snapBillAddr.Save();
                            }
                            else
                            {
                                retVal += "Profile has no billing address on record.";
                            }

                            // copy and replace of all addresses for snapshot
                            if (cartItems == null)
                            {
                                cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                            }

                            cartItems.ToList().ForEach(delegate(hccCartItem ci)
                            {
                                if (snapBillAddr != null)
                                {
                                    ci.SnapBillAddrId = snapBillAddr.AddressID;
                                }

                                hccAddress shipAddr = null;
                                if (ci.UserProfile.ShippingAddressID.HasValue)
                                {
                                    shipAddr = hccAddress.GetById(ci.UserProfile.ShippingAddressID.Value);
                                }

                                if (shipAddr != null)
                                {
                                    hccAddress snapShipAddr = new hccAddress
                                    {
                                        Address1              = shipAddr.Address1,
                                        Address2              = shipAddr.Address2,
                                        AddressTypeID         = shipAddr.AddressTypeID,
                                        City                  = shipAddr.City,
                                        Country               = shipAddr.Country,
                                        DefaultShippingTypeID = shipAddr.DefaultShippingTypeID,
                                        FirstName             = shipAddr.FirstName,
                                        IsBusiness            = shipAddr.IsBusiness,
                                        LastName              = shipAddr.LastName,
                                        Phone                 = shipAddr.Phone,
                                        PostalCode            = shipAddr.PostalCode,
                                        State                 = shipAddr.State,
                                        ProfileName           = ci.UserProfile.ProfileName
                                    };
                                    snapShipAddr.Save();
                                    ci.SnapShipAddrId = snapShipAddr.AddressID;
                                }
                                else
                                {
                                    retVal += "Profile has no billing address on record.";
                                }

                                ci.Save();
                            });
                        }
                    }

                    if (updatecart.sendCustomerEmail)
                    {
                        try
                        {
                            Email.EmailController ec = new Email.EmailController();
                            ec.SendMail_OrderConfirmationMerchant(ownerProfile.FirstName + " " + ownerProfile.LastName, CurrentCart.ToHtml(), CurrentCart.CartID);
                        }
                        catch (Exception ex)
                        { BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Send Merchant Mail Failed", this, ex); }
                    }

                    if (updatecart.sendMerchantEmail)
                    {
                        try
                        {
                            Email.EmailController ec = new Email.EmailController();
                            ec.SendMail_OrderConfirmationCustomer(ownerProfile.ASPUser.Email, ownerProfile.FirstName + " " + ownerProfile.LastName, CurrentCart.ToHtml());
                        }
                        catch (Exception ex)
                        { BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Send customer Mail Failed", this, ex); }
                    }

                    if (updatecart.repairCartCals)
                    {
                        if (cartItems == null)
                        {
                            cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                        }
                        // wrap in programs

                        cartItems.ForEach(delegate(hccCartItem ci)
                        {
                            if (ci.ItemType == Enums.CartItemType.DefinedPlan)
                            {
                                hccProgramPlan cp = hccProgramPlan.GetById(ci.Plan_PlanID.Value);

                                if (cp != null)
                                {
                                    for (int i = 0; i < cp.NumWeeks; i++)
                                    {
                                        hccProductionCalendar cal;
                                        cal = hccProductionCalendar.GetBy(ci.DeliveryDate.AddDays(7 * i));

                                        if (cal != null)
                                        {
                                            hccCartItemCalendar existCal = hccCartItemCalendar.GetBy(ci.CartItemID, cal.CalendarID);
                                            if (existCal == null)
                                            {
                                                hccCartItemCalendar cartCal = new hccCartItemCalendar {
                                                    CalendarID = cal.CalendarID, CartItemID = ci.CartItemID, IsFulfilled = false
                                                };
                                                cartCal.Save();
                                            }
                                        }
                                        else
                                        {
                                            BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(
                                                "No production calendar found for Delivery Date: " + ci.DeliveryDate.AddDays(7 * i).ToShortDateString(), this);
                                        }
                                    }
                                }
                            }
                        });
                    }

                    if (updatecart.reCalcItemTax)
                    {
                        try
                        {
                            if (cartItems == null)
                            {
                                cartItems = hccCartItem.GetBy(CurrentCart.CartID);
                            }

                            List <ProfileCart> CurrentProfileCarts = new List <ProfileCart>();

                            if (cartItems.Count > 0)
                            {
                                hccUserProfile parentProfile = hccUserProfile.GetParentProfileBy(CurrentCart.AspNetUserID.Value);
                                //List<hccProductionCalendar> pc = new List<hccProductionCalendar>();

                                foreach (hccCartItem cartItem in cartItems)
                                {
                                    ProfileCart profCart;
                                    int         shippingAddressId;

                                    //if (!pc.Exists(a => a.DeliveryDate == cartItem.DeliveryDate))
                                    //    pc.Add(hccProductionCalendar.GetBy(cartItem.DeliveryDate));

                                    //hccProductionCalendar cpc = pc.SingleOrDefault(a => a.DeliveryDate == cartItem.DeliveryDate);

                                    //if (cpc != null && (cpc.OrderCutOffDate.AddDays(1) >= DateTime.Now || (HttpContext.Current.Request.Url.OriginalString.Contains("Admin"))))
                                    //{
                                    if (cartItem.UserProfile != null && (cartItem.UserProfile.UseParentShipping || cartItem.UserProfile.ShippingAddressID.HasValue))
                                    {
                                        if (cartItem.UserProfile.UseParentShipping)
                                        {
                                            shippingAddressId = parentProfile.ShippingAddressID.Value;
                                        }
                                        else
                                        {
                                            shippingAddressId = cartItem.UserProfile.ShippingAddressID.Value;
                                        }

                                        profCart = CurrentProfileCarts
                                                   .SingleOrDefault(a => a.ShippingAddressId == shippingAddressId && a.DeliveryDate == cartItem.DeliveryDate);
                                    }
                                    else
                                    {
                                        profCart = CurrentProfileCarts
                                                   .SingleOrDefault(a => a.ShippingAddressId == 0 &&
                                                                    a.DeliveryDate == cartItem.DeliveryDate);

                                        shippingAddressId = 0;
                                    }

                                    if (profCart == null)
                                    {
                                        profCart = new ProfileCart(shippingAddressId, cartItem.DeliveryDate);
                                        CurrentProfileCarts.Add(profCart);
                                    }

                                    profCart.CartItems.Add(cartItem);
                                    //}
                                    //else
                                    //{
                                    //    //cartItem.Delete();
                                    //    //lblFeedbackCart.Text = "Item(s) removed from cart due to expiration of availability.";

                                    //}
                                }
                            }

                            //// display totals
                            CurrentCart.CalculateTotals(CurrentProfileCarts);
                        }
                        catch (Exception ex)
                        { BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise("Attempt to recalculate taz for cart items failed.", this, ex); }
                    }
                }
                return("Cart Updated: " + DateTime.Now);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected override void SaveForm()
        {
            try
            {
                hccCart        userCart = hccCart.GetById(this.PrimaryKeyIndex);
                MembershipUser user     = Membership.GetUser(userCart.AspNetUserID);

                if (user != null)
                {
                    hccProgramPlan selPlan = hccProgramPlan.GetById(int.Parse(ddlPlans.SelectedValue));

                    if (selPlan != null)
                    {
                        List <hccProgramOption> progOptions = hccProgramOption.GetBy(selPlan.ProgramID);
                        hccProgramOption        option      = progOptions.Where(a => a.ProgramOptionID == (int.Parse(ddlOptions.SelectedValue))).SingleOrDefault();
                        hccProgram prog = hccProgram.GetById(selPlan.ProgramID);

                        int     numDays    = selPlan.NumDaysPerWeek * selPlan.NumWeeks;
                        decimal dailyPrice = selPlan.PricePerDay + option.OptionValue;
                        decimal itemPrice  = numDays * dailyPrice;
                        int     profileId  = 0;
                        //bool autoRenew = chkAutoRenew.Checked;
                        string   itemFullName = string.Empty;
                        DateTime startDate    = DateTime.Parse(ddlStartDates.SelectedItem.Text);

                        itemFullName = string.Format("{0} - {1} - {2} - {3}",
                                                     prog == null ? string.Empty : prog.Name, selPlan.Name, option.OptionText, startDate.ToShortDateString());

                        if (divProfiles.Visible)
                        {
                            profileId = int.Parse(ddlProfiles.SelectedValue);
                        }
                        else
                        {
                            profileId = hccUserProfile.GetParentProfileBy(userCart.AspNetUserID.Value).UserProfileID;
                        }

                        if (userCart != null && selPlan != null)
                        {
                            int         currentQty = int.Parse(txtQuantity.Text.Trim());
                            hccCartItem existItem  = hccCartItem.GetBy(userCart.CartID, itemFullName, profileId);

                            if (existItem == null)
                            {
                                hccCartItem planItem = new hccCartItem
                                {
                                    CartID               = userCart.CartID,
                                    CreatedBy            = (Guid)Membership.GetUser().ProviderUserKey,
                                    CreatedDate          = DateTime.Now,
                                    IsTaxable            = selPlan.IsTaxEligible,
                                    ItemDesc             = selPlan.Description,
                                    ItemName             = itemFullName,
                                    ItemPrice            = itemPrice,
                                    ItemTypeID           = (int)Enums.CartItemType.DefinedPlan,
                                    Plan_IsAutoRenew     = false, //autoRenew,
                                    Plan_PlanID          = selPlan.PlanID,
                                    Plan_ProgramOptionID = option.ProgramOptionID,
                                    DeliveryDate         = startDate,
                                    UserProfileID        = profileId,
                                    Quantity             = currentQty,
                                    IsCompleted          = false
                                };

                                planItem.GetOrderNumber(userCart);
                                planItem.Save();

                                hccProductionCalendar cal;

                                for (int i = 0; i < selPlan.NumWeeks; i++)
                                {
                                    cal = hccProductionCalendar.GetBy(planItem.DeliveryDate.AddDays(7 * i));

                                    if (cal != null)
                                    {
                                        hccCartItemCalendar cartCal = new hccCartItemCalendar {
                                            CalendarID = cal.CalendarID, CartItemID = planItem.CartItemID, IsFulfilled = false
                                        };
                                        cartCal.Save();
                                    }
                                    else
                                    {
                                        BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(
                                            "No production calendar found for Delivery Date: " + planItem.DeliveryDate.AddDays(7 * i).ToShortDateString(), this);
                                    }
                                }


                                if (cbxRecurring.Checked)
                                {
                                    var cartItemsRecurring = hccCartItem.GetBy(userCart.CartID);
                                    var filter             = cartItemsRecurring.Where(ci => ci.ItemType == Enums.CartItemType.DefinedPlan);
                                    var roItem             = new hccRecurringOrder();
                                    roItem.CartID         = planItem.CartID;
                                    roItem.CartItemID     = planItem.CartItemID;
                                    roItem.UserProfileID  = planItem.UserProfileID;
                                    roItem.AspNetUserID   = userCart.AspNetUserID;
                                    roItem.PurchaseNumber = userCart.PurchaseNumber;
                                    roItem.TotalAmount    = Math.Round(Convert.ToDecimal(Convert.ToDouble(planItem.ItemPrice) - Convert.ToDouble(planItem.ItemPrice) * 0.05), 2);
                                    roItem.Save();
                                    if (planItem != null)

                                    {
                                        planItem.Plan_IsAutoRenew = true;
                                        planItem.Save();
                                    }

                                    //foreach (var recurringOrder in filter.Select(item => new hccRecurringOrder
                                    //{
                                    //    CartID = item.CartID,
                                    //    CartItemID = item.CartItemID,
                                    //    UserProfileID = item.UserProfileID,
                                    //    AspNetUserID = userCart.AspNetUserID,
                                    //    PurchaseNumber = userCart.PurchaseNumber,
                                    //    TotalAmount = userCart.TotalAmount
                                    //}))
                                    //{
                                    //    recurringOrder.Save();
                                    //}
                                }
                                OnSaved(new ControlSavedEventArgs(planItem.CartItemID));
                                cbxRecurring.Checked = false;
                            }
                            else
                            {
                                if (existItem.AdjustQuantity(existItem.Quantity + currentQty))
                                {
                                    OnSaved(new ControlSavedEventArgs(existItem.CartItemID));
                                }
                                cbxRecurring.Checked = false;
                            }
                        }
                    }
                }
                //Page.Response.Redirect(Page.Request.Url.ToString()+ "#tabs9", true);
            }
            catch (Exception)
            {
                throw;
            }
        }
        //public string GetProgramImage(string programName)
        //{
        //    var fileName = "/userfiles/images/programs/" + programName.Replace(" ", "-") + ".jpg";

        //    if (!File.Exists(Server.MapPath(fileName)))
        //        return "";

        //    return "<img width='150' height='126' alt='' src='/userfiles/images/programs/" + programName.Replace(" ", "-") + ".jpg' class='left' />";
        //}

        protected void btn_add_to_cart_Click(object sender, EventArgs e)
        {
            try
            {
                Page.Validate("AddToCartGroup");

                if (Page.IsValid)
                {
                    hccCart userCart = hccCart.GetCurrentCart();

                    //Define form variables
                    int itemId   = Convert.ToInt32(Request.Form["plan_type"]);
                    int optionId = ((Request.Form["plan_option"] == null) ? 0 : Convert.ToInt32(Request.Form["plan_option"]));

                    //Select chosen Program Plan
                    hccProgramPlan plan = hccProgramPlan.GetById(itemId);
                    if (plan == null)
                    {
                        throw new Exception("ProgramPlan not found: " + itemId.ToString());
                    }

                    hccProgram       prog   = hccProgram.GetById(plan.ProgramID);
                    hccProgramOption option = hccProgramOption.GetBy(plan.ProgramID).Where(a => a.ProgramOptionID == optionId).SingleOrDefault();

                    int      numDays      = plan.NumDaysPerWeek * plan.NumWeeks;
                    int      numMeals     = numDays * plan.MealsPerDay;
                    decimal  dailyPrice   = plan.PricePerDay + option.OptionValue;
                    decimal  itemPrice    = numDays * dailyPrice;
                    DateTime deliveryDate = DateTime.Parse(ddl_delivery_date.SelectedValue);

                    MembershipUser user = Helpers.LoggedUser;

                    hccCartItem newItem = new hccCartItem
                    {
                        CartID        = userCart.CartID,
                        CreatedBy     = (user == null ? Guid.Empty : (Guid)user.ProviderUserKey),
                        CreatedDate   = DateTime.Now,
                        IsTaxable     = plan.IsTaxEligible,
                        ItemDesc      = plan.Description,
                        NumberOfMeals = numMeals,
                        //ItemName = string.Format("{0} - {1} - {2} - {3} & {4}", (prog == null ? string.Empty : prog.Name), plan.Name, option.OptionText, deliveryDate.ToShortDateString(), numMeals),
                        ItemName             = string.Format("{0} - {1} - {2} - {3}", (prog == null ? string.Empty : prog.Name), plan.Name, option.OptionText, deliveryDate.ToShortDateString()),
                        ItemPrice            = itemPrice,
                        ItemTypeID           = (int)Enums.CartItemType.DefinedPlan,
                        Plan_IsAutoRenew     = false, //chx_renew.Checked,
                        Plan_PlanID          = itemId,
                        Plan_ProgramOptionID = optionId,
                        DeliveryDate         = deliveryDate,
                        Quantity             = int.Parse(txt_quantity.Text),
                        UserProfileID        = ((ddlProfiles.Items.Count == 0) ? 0 : Convert.ToInt32(ddlProfiles.SelectedValue)),
                        IsCompleted          = false
                    };
                    Meals obj = new Meals();
                    obj.CartID    = newItem.CartID;
                    obj.MealCount = newItem.NumberOfMeals;
                    obj.NoOfWeeks = plan.NumWeeks;

                    var ID    = obj.CartID;
                    var Meal  = obj.MealCount;
                    var Weeks = obj.NoOfWeeks;

                    HealthyChef.Templates.HealthyChef.Controls.TopHeader header =
                        (HealthyChef.Templates.HealthyChef.Controls.TopHeader) this.Page.Master.FindControl("TopHeader1");
                    if (header != null)
                    {
                        header.MealsCountVal(ID, Meal);
                    }

                    newItem.GetOrderNumber(userCart);
                    int profileId = 0;
                    if (divProfiles.Visible)
                    {
                        profileId = int.Parse(ddlProfiles.SelectedValue);
                    }
                    else
                    {
                        if (CartUserASPNetId != Guid.Empty)
                        {
                            profileId = hccUserProfile.GetParentProfileBy(CartUserASPNetId).UserProfileID;
                        }
                    }

                    if (profileId > 0)
                    {
                        newItem.UserProfileID = profileId;
                    }

                    hccCartItem existItem = hccCartItem.GetBy(userCart.CartID, newItem.ItemName, profileId);

                    if (existItem == null)
                    {
                        newItem.Save();

                        hccProductionCalendar cal;

                        for (int i = 0; i < plan.NumWeeks; i++)
                        {
                            cal = hccProductionCalendar.GetBy(newItem.DeliveryDate.AddDays(7 * i));

                            if (cal != null)
                            {
                                hccCartItemCalendar cartCal = new hccCartItemCalendar {
                                    CalendarID = cal.CalendarID, CartItemID = newItem.CartItemID
                                };
                                cartCal.Save();
                            }
                            else
                            {
                                BayshoreSolutions.WebModules.WebModulesAuditEvent.Raise(
                                    "No production calendar found for Delivery Date: " + newItem.DeliveryDate.AddDays(7 * i).ToShortDateString(), this);
                            }
                        }
                    }
                    else
                    {
                        existItem.AdjustQuantity(existItem.Quantity + newItem.Quantity);
                    }

                    //Recurring Order Record
                    if (cbxRecurring.Checked)
                    {
                        List <hccRecurringOrder> lstRo = null;
                        if (Session["autorenew"] != null)
                        {
                            lstRo = ((List <hccRecurringOrder>)Session["autorenew"]);
                        }
                        else
                        {
                            lstRo = new List <hccRecurringOrder>();
                        }

                        //var filter = cartItemsRecurring.Where(ci => ci.ItemType == Enums.CartItemType.DefinedPlan);

                        //for(var i = 0; i < int.Parse(txt_quantity.Text); i++)
                        //{
                        lstRo.Add(new hccRecurringOrder
                        {
                            CartID         = userCart.CartID,
                            CartItemID     = newItem.CartItemID,
                            UserProfileID  = newItem.UserProfileID,
                            AspNetUserID   = userCart.AspNetUserID,
                            PurchaseNumber = userCart.PurchaseNumber,
                            TotalAmount    = newItem.ItemPrice
                        });
                        Session["autorenew"] = lstRo;
                        //}
                    }

                    HealthyChef.Templates.HealthyChef.Controls.TopHeader header1 =
                        (HealthyChef.Templates.HealthyChef.Controls.TopHeader) this.Page.Master.FindControl("TopHeader1");

                    if (header1 != null)
                    {
                        header.SetCartCount();
                    }

                    //Redirect user to Program Selection screen
                    Response.Redirect("~/meal-programs.aspx");
                    //multi_programs.ActiveViewIndex = 0;
                    //litMessage.Text = "Your Meal Program has been added to your cart.";
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #4
0
        public string ReplaceProgramMeals(List <DefaultMenu> defaultMenus)
        {
            try
            {
                bool tryBool;
                bool isCancel   = false;
                bool isComplete = false;
                int  cartItemId = int.Parse(this.Context.Request.QueryString["cid"]);

                hccCartItem cartItem = hccCartItem.GetById(cartItemId);
                if (cartItem != null)
                {
                    if (this.Context.Request.QueryString["can"] != null)
                    {
                        tryBool = bool.TryParse(this.Context.Request.QueryString["can"], out isCancel);
                        cartItem.IsCancelled = isCancel;
                    }

                    if (this.Context.Request.QueryString["cmplt"] != null)
                    {
                        tryBool = bool.TryParse(this.Context.Request.QueryString["cmplt"], out isComplete);
                    }
                    hccCartMenuExPref cartMenuExPref = hccCartMenuExPref.GetById(cartItem.CartItemID, defaultMenus[0].DayNumber);
                    if (cartMenuExPref == null)
                    {
                        hccCartMenuExPref hccCartMenuExPref = new hccCartMenuExPref();
                        hccCartMenuExPref.CartItemID = cartItem.CartItemID;
                        hccCartMenuExPref.DayNumber  = defaultMenus[0].DayNumber;
                        hccCartMenuExPref.IsModified = true;
                        hccCartMenuExPref.Save();
                    }
                    cartItem.Save();
                }

                decimal cals1 = 0.0m, fat1 = 0.0m, prtn1 = 0.0m, carb1 = 0.0m, fbr1 = 0.0m, sod1 = 0.0m;

                foreach (DefaultMenu defaultMenuItem in defaultMenus)
                {
                    hccCartItemCalendar cartCal = hccCartItemCalendar.GetBy(cartItem.CartItemID, defaultMenuItem.CalendarID);

                    if (cartCal != null)
                    {
                        if (isComplete != cartCal.IsFulfilled)
                        {
                            cartCal.IsFulfilled = isComplete;
                            cartCal.Save();
                        }

                        // get original defaultMenuItem for comparison of menuItem
                        hccProgramDefaultMenu origDefaultMenu =
                            hccProgramDefaultMenu.GetBy(cartCal.CalendarID, defaultMenuItem.ProgramID,
                                                        defaultMenuItem.DayNumber, defaultMenuItem.MealTypeID, defaultMenuItem.Ordinal);

                        hccCartDefaultMenuException existMenuEx = hccCartDefaultMenuException.GetBy(defaultMenuItem.DefaultMenuID, cartCal.CartCalendarID);

                        if (origDefaultMenu != null &&
                            origDefaultMenu.MenuItemID == defaultMenuItem.MenuItemID &&
                            origDefaultMenu.MenuItemSizeID == defaultMenuItem.MenuItemSizeID)
                        {
                            if (string.IsNullOrWhiteSpace(defaultMenuItem.Prefs))
                            {
                                if (existMenuEx != null)
                                {
                                    List <hccCartDefaultMenuExPref> prefs = hccCartDefaultMenuExPref.GetBy(existMenuEx.DefaultMenuExceptID);
                                    prefs.ForEach(a => a.Delete());
                                    existMenuEx.Delete();
                                }
                            }
                            else
                            {
                                if (existMenuEx == null)
                                {   // create exception menuItem
                                    existMenuEx = new hccCartDefaultMenuException
                                    {
                                        CartCalendarID = cartCal.CartCalendarID,
                                        DefaultMenuID  = defaultMenuItem.DefaultMenuID
                                    };
                                }

                                existMenuEx.MenuItemID     = defaultMenuItem.MenuItemID;
                                existMenuEx.MenuItemSizeID = defaultMenuItem.MenuItemSizeID;
                                existMenuEx.Save();

                                List <hccCartDefaultMenuExPref> prefs = hccCartDefaultMenuExPref.GetBy(existMenuEx.DefaultMenuExceptID);
                                prefs.ForEach(a => a.Delete());

                                if (!string.IsNullOrWhiteSpace(defaultMenuItem.Prefs))
                                {
                                    List <string> prefIds = defaultMenuItem.Prefs.Split(',').ToList();
                                    prefIds.ForEach(delegate(string prefId)
                                    {
                                        hccCartDefaultMenuExPref exPref = new hccCartDefaultMenuExPref
                                        {
                                            DefaultMenuExceptID = existMenuEx.DefaultMenuExceptID,
                                            PreferenceID        = int.Parse(prefId)
                                        };

                                        exPref.Save();
                                    });
                                }
                            }
                        }
                        else
                        {
                            if (existMenuEx == null)
                            {   // create exception menuItem
                                existMenuEx = new hccCartDefaultMenuException
                                {
                                    CartCalendarID = cartCal.CartCalendarID,
                                    DefaultMenuID  = defaultMenuItem.DefaultMenuID
                                };
                            }

                            existMenuEx.MenuItemID     = defaultMenuItem.MenuItemID;
                            existMenuEx.MenuItemSizeID = defaultMenuItem.MenuItemSizeID;
                            existMenuEx.Save();

                            List <hccCartDefaultMenuExPref> exPrefs = hccCartDefaultMenuExPref.GetBy(existMenuEx.DefaultMenuExceptID);
                            exPrefs.ForEach(a => a.Delete());

                            if (!string.IsNullOrWhiteSpace(defaultMenuItem.Prefs))
                            {
                                List <string> prefIds = defaultMenuItem.Prefs.Split(',').ToList();
                                prefIds.ForEach(delegate(string prefId)
                                {
                                    hccCartDefaultMenuExPref exPref = new hccCartDefaultMenuExPref
                                    {
                                        DefaultMenuExceptID = existMenuEx.DefaultMenuExceptID,
                                        PreferenceID        = int.Parse(prefId)
                                    };

                                    exPref.Save();
                                });
                            }
                        }

                        hccMenuItemNutritionData nutrition;

                        if (existMenuEx == null)
                        {
                            nutrition = hccMenuItemNutritionData.GetBy(defaultMenuItem.MenuItemID);
                        }
                        else
                        {
                            nutrition = hccMenuItemNutritionData.GetBy(existMenuEx.MenuItemID);
                        }

                        if (nutrition != null)
                        {
                            cals1 = cals1 + nutrition.Calories;
                            fat1  = fat1 + nutrition.TotalFat;
                            prtn1 = prtn1 + nutrition.Protein;
                            carb1 = carb1 + nutrition.TotalCarbohydrates;
                            fbr1  = fbr1 + nutrition.DietaryFiber;
                            sod1  = sod1 + nutrition.Sodium;
                        }
                    }
                }

                string nutri = cals1.ToString("f2") + "|" + fat1.ToString("f2") + "|" + prtn1.ToString("f2") + "|" + carb1.ToString("f2") + "|" + fbr1.ToString("f2") + "|" + sod1.ToString("f2");

                return(nutri);
            }
            catch (Exception ex)
            {
                throw;
            }
        }