public static Boolean createAccount(string email, string first, string last, string password, string gender, DateTime birthday)
        {
            try
            {
                SIEBUEntities db = new SIEBUEntities();
                if (db.Users.Where(u => u.email == email).Count() == 0)
                {
                    //populate user object with general information
                    User n_customer = new User();
                    n_customer.email = email;
                    n_customer.firstName = first;
                    n_customer.lastName = last;
                    n_customer.dob = birthday;
                    n_customer.joindate = DateTime.Now;
                    n_customer.gender = (gender == "female") ? true : false;
                    // encryption/salt creation
                    byte[] salt = new byte[48];
                    new RNGCryptoServiceProvider().GetBytes(salt);
                    n_customer.salt = salt;
                    n_customer.password = encrypt(email, password, salt);

                    db.Users.Add(n_customer);
                    db.SaveChanges();
                    return true;
                }
                return false;

            }

            catch (Exception e)
            {
                Console.WriteLine("The Error is " + e.ToString());
                return false;
            }
        }
        public Boolean LikeProduct(int p_id)
        {
            SIEBUEntities db = new SIEBUEntities();

            Product_Like p_like = db.Product_Like.FirstOrDefault(pl => pl.product_id == p_id && pl.user_id == WebSecurity.CurrentUserId);
            if (p_like != null)
            {
                db.Product_Like.Remove(p_like);
                db.SaveChanges();
                return false;
            }

            p_like = new Product_Like();
            p_like.user_id = WebSecurity.CurrentUserId;
            p_like.product_id = p_id;

            db.Product_Like.Add(p_like);
            db.SaveChanges();
            return true;
        }
 public static void createPurchaseHistory(int customerID, decimal amountPaid, int transaction_id, Boolean isPaypal)
 {
     SIEBUEntities db = new SIEBUEntities();
     //CREATE THE USER CREDIT HISTORY AND PURCHASE HISTORY
     User_Purchase_History purchaseHistory = new User_Purchase_History();
     purchaseHistory.user_id = customerID;
     purchaseHistory.value = amountPaid;
     purchaseHistory.date = DateTime.Now;
     if (isPaypal)
     {
         purchaseHistory.paypal_transaction_id = transaction_id;
     }
     else
     {
         purchaseHistory.transaction_id = transaction_id;
     }
     db.User_Purchase_History.Add(purchaseHistory);
     db.SaveChanges();
 }
        public static void createCreditHistory(Dictionary<int, int> subtransactionIds, Boolean isPaypal)
        {
            SIEBUEntities db = new SIEBUEntities();
            foreach (var pair in subtransactionIds)
            {
                int subtransactions = pair.Value;
                User_Credit_History creditHistory = new User_Credit_History();
                //get the store's user id.
                creditHistory.date = DateTime.Now;
                creditHistory.value = (decimal)db.Transaction_Subtransaction.Where(sub => sub.st_id == subtransactions).FirstOrDefault().total;
                creditHistory.user_id = pair.Key;
                if (isPaypal)
                {
                    creditHistory.paypal_subtransaction_id = subtransactions;
                }
                else
                {
                    creditHistory.subtransaction_id = subtransactions;
                }

                db.User_Credit_History.Add(creditHistory);
            }
            db.SaveChanges();
        }
        public ActionResult DeleteBlog(string blog_id)
        {
            try
            {
                SIEBUEntities db = new SIEBUEntities();
                int id = int.Parse(blog_id);
                db.Store_NewsItem.FirstOrDefault(ni => ni.sn_id == id).is_deleted = true;

                db.SaveChanges();
                return Json(true, JsonRequestBehavior.AllowGet);
            } catch (Exception e) {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult UpdateStore(StoreModel update)
        {
            //StoreModel update = JsonConvert.DeserializeObject<StoreModel>(obj);
            SIEBUEntities db = new SIEBUEntities();
            Store target_store = db.Stores.FirstOrDefault(s => s.s_id == update.id);

            //if no store is found, create one
            bool add_new = false;
            if (target_store == null)
            {
                add_new = true;
                target_store = new Store();
                target_store.creator_id = WebSecurity.CurrentUserId;
                target_store.created_on = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
                target_store.credit = 0;
            }

            //check for conflicting namespace
            if (ValidationController.checkNamespaceAvailability(update.store_namespace) != true)
                return Json(new { error = "The namespace is unavailable for use." }, JsonRequestBehavior.AllowGet);

            target_store.name = update.name;
            target_store.name_space = update.store_namespace;
            target_store.description = update.description;

            target_store.category_id = update.category;
            target_store.status = update.status;

            //create store before connections required
            if (add_new)
            {
                db.Stores.Add(target_store);
                db.SaveChanges();
            }

            if (target_store.logo == null || !(update.logo + "").Contains(target_store.logo)) //(!(target_store.logo == update.logo || update.logo.Contains(target_store.logo)))
                target_store.logo = update.logo != null ? ImageController.UploadFile(update.logo, "logo" + target_store.s_id) : null;

            if (target_store.banner_img == null || !(update.banner + "").Contains(target_store.banner_img))
                target_store.banner_img = update.banner != null ? ImageController.UploadFile(update.banner, "banner" + target_store.s_id) : null;

            if (target_store.background_img == null || !(update.background + "").Contains(target_store.background_img)) //) CHANGED FOR PARTIAL URLS
                target_store.background_img = update.background != null ? ImageController.UploadFile(update.background, "background" + target_store.s_id) : null;

            //update social media
            foreach (SocialMediaModel sm in update.social_media)
            {
                Store_Contact ssm = db.Store_Contact.FirstOrDefault(q => q.store == update.id && q.Contact.caption == sm.type);

                bool add_new_sm = false;
                if (ssm == null)
                {
                    add_new = true;
                    ssm = new Store_Contact();
                }
                ssm.value = sm.url;

                if (add_new_sm) db.Store_Contact.Add(ssm);
            }

            db.SaveChanges();

            return Json(target_store.name_space, JsonRequestBehavior.AllowGet);
        }
        public ActionResult UpdateProduct(ProductModel update)
        {
            SIEBUEntities db = new SIEBUEntities();
            Product target_product = db.Products.FirstOrDefault(p => p.p_id == update.id);

            Product_History history = new Product_History();

            //if no product is found, create one
            bool add_new = false;
            if (target_product == null)
            {
                add_new = true;
                target_product = new Product();
                target_product.dateadded = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
            }

            target_product.lastmodified = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
            history.datemodified = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
            bool change_made = false;
            if (target_product.name != update.name || target_product.sku != update.sku)
            {
                change_made = true;
                history.name = target_product.name;
                history.sku = target_product.sku;
                target_product.name = update.name;
                target_product.sku = update.sku;
            }

            if (!((target_product.cost + target_product.shipping_cost).Equals(update.cost + update.shipping_cost)))
            {
                change_made = true;
                history.cost = target_product.cost;
                history.shipping_cost = target_product.shipping_cost;
                target_product.cost = Convert.ToDecimal(update.cost, CultureInfo.GetCultureInfo("en"));
                target_product.shipping_cost = Convert.ToDecimal(update.shipping_cost, CultureInfo.GetCultureInfo("en"));
            }

            if (target_product.avail_inventory != update.avail_inventory)
            {
                change_made = true;
                history.avail_inventory = target_product.avail_inventory;
                target_product.avail_inventory = update.avail_inventory;
            }

            target_product.short_description = update.short_description;
            target_product.description = update.description;

            if (target_product.status != update.status)
            {
                change_made = true;
                history.status = target_product.status;
                target_product.status = update.status;
            }

            if (target_product.is_featured != update.is_featured)
            {
                change_made = true;
                history.is_featured = target_product.is_featured;
                target_product.is_featured = update.is_featured;
                if (update.is_featured)
                {
                    target_product.featured_since = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
                }
                else
                {
                    target_product.featured_since = null;
                }
            }

            if (add_new)
            {
                target_product.store_id = update.store_id;
                db.Products.Add(target_product);
                db.SaveChanges(); //changes must be saved so that product_id exists for image/tag/history foreign key relationships
            }

            foreach (ProductImageModel pim in update.images)
            {
                Product_Image target_image = db.Product_Image.FirstOrDefault(p => p.pi_id == pim.id);

                //only save up to 8 images per product
                if (db.Product_Image.Count(p => p.product_id == target_product.p_id) <= 8)
                {

                    bool add_new_img = false;
                    if (target_image == null)
                    {
                        add_new_img = true;
                        target_image = new Product_Image();
                    }

                    target_image.product_id = target_product.p_id;
                    target_image.sort = pim.order;

                    //check to make sure update does not match existing content
                    if ((target_image.url == null || !(pim.url + "").Contains(target_image.url)) && pim.url != null)
                    {
                        //if different from original, determine whether value is blank (for purpose of removing images)
                        if (pim.url != null)
                            target_image.url = ImageController.UploadFile(pim.url, target_image.product_id + "" + target_image.pi_id + "" + target_product.lastmodified.Value.ToString("ffffff"));
                        else target_image.url = null;
                    }

                    if (add_new_img) db.Product_Image.Add(target_image);
                }

                if (pim.delete) db.Product_Image.Remove(target_image);
            }

            foreach (ProductTagModel ptm in update.tags)
            {
                //create tag if non-existent
                Tag ref_tag = db.Tags.FirstOrDefault(t => t.caption == ptm.caption.Trim().ToLower());
                if (ref_tag == null)
                {
                    ref_tag = new Tag();
                    ref_tag.caption = ptm.caption.Trim().ToLower();
                    db.Tags.Add(ref_tag);
                    db.SaveChanges();
                }

                //tolower to compare captions
                Product_Tag target_tag = db.Product_Tag.FirstOrDefault(t => t.product_id == update.id && t.Tag.t_id == ref_tag.t_id);
                bool add_new_tag = false;
                if (target_tag == null)
                {
                    add_new_tag = true;
                    target_tag = new Product_Tag();
                }

                target_tag.product_id = target_product.p_id;
                target_tag.tag_id = ref_tag.t_id;

                if (add_new_tag) db.Product_Tag.Add(target_tag);
                if (ptm.delete) db.Product_Tag.Remove(target_tag);
            }

            if (change_made) db.Product_History.Add(history);
            history.product_id = target_product.p_id;

            db.SaveChanges();
            return Json(target_product.p_id, JsonRequestBehavior.AllowGet);
        }
        public ActionResult UpdateBlog(BlogEntryModel update)
        {
            SIEBUEntities db = new SIEBUEntities();
            Store_NewsItem target_entry = db.Store_NewsItem.FirstOrDefault(ni => ni.sn_id == update.id);

            //if no id is given, create new blog entry
            bool add_new = false;
            if (target_entry == null)
            {
                add_new = true;
                target_entry = new Store_NewsItem();
                target_entry.store_id = update.store_id;
                target_entry.author_id = WebSecurity.CurrentUserId;
                target_entry.date_added = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
            }

            target_entry.title = update.title;
            target_entry.last_modified = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
            target_entry.description = update.description;
            target_entry.text = update.body_text;

            target_entry.is_featured = update.is_featured;
            if (update.is_featured)
            {
                target_entry.featured_since = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));

            }
            else
            {
                target_entry.featured_since = null;
            }

            target_entry.is_draft = update.is_draft;

            if (add_new)
            {
                db.Store_NewsItem.Add(target_entry);
                db.SaveChanges();
            }

            //if the update is not equal to the target image
            if (target_entry.img == null || !(update.img + "").Contains(target_entry.img)) //target_entry.img != update.img)
                target_entry.img = update.img != null ? ImageController.UploadFile(update.img, update.store_id + "" + target_entry.sn_id) : null; //no unique file name required  + "" + target_entry.last_modified.Value.ToString("ffffff")

            db.SaveChanges();
            return Json(target_entry.sn_id, JsonRequestBehavior.AllowGet);
        }
        public ActionResult DeleteProducts(string[] id_list)
        {
            try
            {
                SIEBUEntities db = new SIEBUEntities();
                for (int i = 0; i < id_list.Length; i++)
                {
                    int id = int.Parse(id_list[i]);
                    db.Products.FirstOrDefault(p => p.p_id == id).is_deleted = true;
                }

                db.SaveChanges();
                return Json(true, JsonRequestBehavior.AllowGet);
            } catch (Exception e) {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }
        public static String editProfile(String email, String firstName, String lastName, String gender, DateTime Birthday, String about, String profileImage)
        {
            SIEBUEntities context = new SIEBUEntities();
            if (context.Users.Where(u => u.email == email).Count() != 0)
            {
                try
                {
                    User user = context.Users.First(c => c.email == email); // Must check if user is in the database
                    user.firstName = firstName;
                    user.lastName = lastName;
                    user.gender = (gender == "female") ? true : false;
                    user.dob = Birthday;
                    user.about = about;

                    if (user.profileimg_url == null || !(profileImage + "").Contains(user.profileimg_url))
                    {
                        user.profileimg_url = profileImage == null ? null : ImageController.UploadFile(profileImage, "profile" + WebSecurity.CurrentUserId);
                    }

                    context.SaveChanges();
                    return "";
                }
                catch
                {
                    return "Changes to your account could not be made at this time"; // Changes could not be made/
                }
            }
            //Could not find email
            return "Could not find account with associated Email";
        }
        //public static UserModel getProfile(String email)
        //{
        //    SIEBUEntities context = new SIEBUEntities();
        //    if (context.Users.Where(u => u.email == email).Count() != 0)
        //    {
        //        User user = context.Users.First(c => c.email == email); // Must check if user is in the database
        //        UserModel model = new UserModel();
        //        model.id = user.id;
        //        model.email = email;
        //        model.first_name = user.firstName;
        //        model.last_name = user.lastName;
        //        model.dob = user.dob;
        //        model.gender = Convert.ToInt32(user.gender).ToString();
        //        model.about = user.about;
        //        model.profile_image = user.profileimg_url;
        //        model.location = user.location;
        //        model.contact_email = (user.User_Contact.Count(c => c.Contact.caption == "Email Address") > 0 ? user.User_Contact.Where(c => c.Contact.caption == "Email Address").FirstOrDefault().value : "");
        //        model.website = (user.User_Contact.Count(c => c.Contact.caption == "Website") > 0 ? user.User_Contact.Where(c => c.Contact.caption == "Website").FirstOrDefault().value : "");
        //        model.social_media = SocialMediaModel.getSocialMedia(user, context);
        //        return model;
        //    }
        //    return null;
        //}
        public static String editProfile(String user_email, FormCollection form)
        {
            SIEBUEntities db = new SIEBUEntities();
            User target_user = db.Users.Where(u => u.email == user_email).FirstOrDefault();
            if (target_user == null)
            {
                try
                {
                    target_user.firstName = form["manage_firstname"];
                    target_user.lastName = form["manage_lastname"];
                    target_user.gender = (form["gender"] == "female" ? true : false);
                    target_user.dob = new DateTime(int.Parse(form["bYear"]), int.Parse(form["bMonth"]), int.Parse(form["bDay"]));
                    target_user.location = form["manage_location"];
                    target_user.about = form["about"];

                    if (target_user.profileimg_url == null || !(form["image-input"] + "").Contains(target_user.profileimg_url))
                    {
                        target_user.profileimg_url = form["image-input"] == null ? null : ImageController.UploadFile(form["image-input"], "profile" + WebSecurity.CurrentUserId);
                    }

                    User_Contact contact_email = target_user.User_Contact.Where(c => c.Contact.caption == "Email Address").FirstOrDefault();
                    if (contact_email == null)
                    {
                        contact_email = new User_Contact();
                        contact_email.u_id = target_user.id;
                        contact_email.social_media = db.Contacts.Where(c => c.caption == "Email Address").FirstOrDefault().sm_id;
                        db.User_Contact.Add(contact_email);
                        db.SaveChanges();
                    }
                    contact_email.value = form["manage_contactemail"];

                    User_Contact website = target_user.User_Contact.Where(c => c.Contact.caption == "Website").FirstOrDefault();
                    if (website == null)
                    {
                        website = new User_Contact();
                        website.u_id = target_user.id;
                        website.social_media = db.Contacts.Where(c => c.caption == "Website").FirstOrDefault().sm_id;
                        db.User_Contact.Add(contact_email);
                        db.SaveChanges();
                    }
                    website.value = form["manage_website"];

                    foreach (Contact socialmedia in db.Contacts.Where(c => c.is_socialmedia == true))
                    {
                        User_Contact sm = target_user.User_Contact.Where(c => c.social_media == socialmedia.sm_id).FirstOrDefault();
                        if (sm == null)
                        {
                            sm = new User_Contact();
                            sm.u_id = target_user.id;
                            sm.social_media = socialmedia.sm_id;
                            db.User_Contact.Add(sm);
                            db.SaveChanges();
                        }

                        sm.value = form["manage-" + socialmedia.caption];
                    }

                    db.SaveChanges();
                }
                catch (ArgumentOutOfRangeException)
                {
                    return "Date of Birth not valid";
                }
                catch
                {
                    return "Changes to your account could not be made at this time"; // Changes could not be made/
                }
            }
            //Could not find email
            return "Could not find account with associated Email";
        }
        /// <summary>
        /// Store cart in the database after session has ended
        /// </summary>
        /// <param name="userId">User's id</param>
        /// <param name="cartInSession">the cart in the session</param>
        /// <returns>true if the cart has been saved and false if otherwise</returns>
        public Boolean storeCartInDB(int userId)
        {
            //TODO: TESTING FOR ALL CASES
            SIEBUEntities db = new SIEBUEntities();
            List<Shopping_Cart> cartInDB = db.Shopping_Cart.Where(cart => cart.userID == userId).ToList();

            //Compare database with the session to remove items that have been removed in the session cart

            Boolean contains = false;
            for (int i = 0; i < cartInDB.Count; i++)
            {

                //compare every item associated to a store in the shopping cart.
                foreach (CartItem item in this.cartItems)
                {
                    contains = cartInDB[i].productID == item.productId &&
                        cartInDB[i].userID == userId;
                    if (contains)
                        break; //found the item in both database and session cart.
                }

                /*
                for (int y = 0; y < cartInSession.Items.Count && !contains; y++)
                {
                    contains = cartInDB[i].productID == cartInSession.Items[y].productId &&
                        cartInDB[i].storeID == cartInSession.Items[y].storeId && cartInDB[i].userID == userId;
                } */
                if (!contains)
                {
                    db.Shopping_Cart.Remove(cartInDB[i]); //remove items in the database that are not in the cart.
                    Debug.WriteLine("cart item: " + cartInDB[i].id + "removed");
                }
                contains = false;
            }
            db.SaveChanges();

            /*Compare session with the database to add items that are in the session but not in the db or
             modify that quantity for the item that are in both*/
            cartInDB = db.Shopping_Cart.Where(cart => cart.userID == userId).ToList(); //Retrieve the new list
            contains = false;

            foreach (CartItem cItem in this.cartItems)
            {
                int index = -1;
                for (int y = 0; !contains && y < cartInDB.Count; y++)
                {
                    contains = cartInDB[y].productID == cItem.productId &&
                        cartInDB[y].storeID == cItem.storeId && cartInDB[y].userID == userId;

                    if (contains)
                    {
                        index = y;
                    }
                }

                if (!contains) //if it's a new record then add it
                {
                    Shopping_Cart item = new Shopping_Cart();
                    item.userID = userId;
                    item.dateAdded = DateTime.Now;
                    item.productID = cItem.productId;
                    item.quantity = cItem.quantity;
                    item.storeID = cItem.storeId;
                    db.Shopping_Cart.Add(item);
                }
                else //Existing record.  Modify quantity
                {

                    Shopping_Cart item = cartInDB[index];
                    item.quantity = cItem.quantity;
                }
                contains = false;
            }
            db.SaveChanges();

            return true;
        }
        /// <summary>
        /// Update the user's recently viewed product in the cookie and database
        /// </summary>
        /// <param name="s_id">shop id</param>
        /// <param name="p_id">product id</param>
        /// <param name="max">max amount of product views</param>
        public static HttpCookie updateViewCookieHistory(int userId, HttpCookie cookie, int s_id, int p_id = 0, int max = 10)
        {
            HttpCookie returnCookie = new HttpCookie(cookie.Name);
            returnCookie.Value = "";
            SIEBUEntities db = new SIEBUEntities();
            Store store = db.Stores.FirstOrDefault(s => s.s_id == s_id);

            Product product = db.Products.FirstOrDefault(p => p.p_id == p_id);
            User_SearchHistory record = db.User_SearchHistory.FirstOrDefault(search => search.user_id == userId &&
                search.product_id == product.p_id);
            if (record != null)  //modify existing record in the database or add it
            {
                record.dateaccessed = DateTime.Now;
            }
            else //add new record in the database
            {
                record = new User_SearchHistory();
                record.product_id = product.p_id;
                record.store_id = store.s_id;
                record.user_id = userId;
                record.dateaccessed = DateTime.Now;
                db.User_SearchHistory.Add(record);
            }
            db.SaveChanges();

            //Set the cookie history
            //var cookie = Request.Cookies["item_hist"];

            String itemHist = "";
            HttpCookie productCookie = null;
            if (cookie == null) //cookie doesn't exist
            {
                productCookie = recentStoreViewedCookie(userId);
                itemHist = productCookie.Value;
                //Response.Cookies.Add(productCookie);
            }
            else //get the value
            {
                itemHist = cookie.Value;
            }

            if (itemHist != "")
            {
                String[] cookieRecords = itemHist.Split('|');
                Boolean contains = false;
                int index = -1;
                try
                {
                    for (int i = 0; i < cookieRecords.Length; i++) // Check and find the index of the item if it is in the cookie
                    {
                        String[] cookieRecord = cookieRecords[i].Split('&');
                        int storeId = int.Parse(cookieRecord[0].ToString());
                        int productId = int.Parse(cookieRecord[2].ToString());
                        if (storeId == store.s_id && product.p_id == productId)
                        {
                            contains = true;
                            index = i;
                            break;
                        }
                    }

                    if (!contains) // new record add it in the cookie
                    {

                        String cookieValue = "";
                        if (cookieRecords.Length >= max)
                        {
                            for (int i = 0; i < cookieRecords.Length - 1; i++) //Take the first items in the record
                            {
                                cookieValue = cookieValue + "|" + cookieRecords[i];
                            }
                            //add element 0 before cookieValue;
                            returnCookie.Value = getItemCookieValue(store.s_id, store.name_space, product.p_id, product.name,
                                (product.Product_Image.Count > 0 ? product.Product_Image.First().url : "/content/no-image"), store.name,
                                (store.logo != null) ? store.logo : "/content/no-image") + cookieValue;
                        }
                        else
                        {
                            returnCookie.Value = getItemCookieValue(store.s_id, store.name_space, product.p_id, product.name,
                                (product.Product_Image.Count > 0 ? product.Product_Image.First().url : "/content/no-image"), store.name,
                                (store.logo != null) ? store.logo : "/content/no-image") + "|" + cookieValue;
                        }

                    }
                    else //Modify existing record in the cookie
                    {
                        String cookieValue = "";

                        if (index != 0) //first element is not the product
                        {
                            if (index == cookieRecords.Length - 1) //the record is the last element in the cookie.
                            {
                                cookieValue = cookieRecords[cookieRecords.Length - 1];
                                for (int i = 0; i != cookieRecords.Length - 1; i++)
                                {
                                    cookieValue = cookieValue + "|" + cookieRecords[i];
                                }
                                returnCookie.Value = cookieValue;
                            }
                            else //record in the middle
                            {
                                String before = cookieRecords[0]; // for sure not the first element since we checked earlier
                                for (int i = 1; i < index; i++)
                                {
                                    before = before + "|" + cookieRecords[i];
                                }

                                String after = cookieRecords[index + 1];
                                for (int i = index + 2; i < cookieRecords.Length; i++)
                                {
                                    after = after + "|" + cookieRecords[i];
                                }
                                returnCookie.Value = cookieRecords[index] + "|" + before + "|" + after;
                            }
                        }

                        else //first element is the first product.  Just return the same thing
                        {
                            returnCookie.Value = itemHist; //just return the same cookie.
                        }
                    }
                }
                catch (Exception e)
                {
                    //Debug.WriteLine("Exception has occured with modifying the recently viewed store cookie: " + e.ToString());
                    //Response.Cookies.Add(NavigationModel.recentProductsViewedCookie(WebSecurity.CurrentUserId));
                    returnCookie.Value = itemHist;
                }

            }

            else // First record on the list
            {
                returnCookie.Value = NavigationModel.getItemCookieValue(store.s_id, store.name_space, product.p_id, product.name,
                    (product.Product_Image.Count > 0 ? product.Product_Image.First().url : "/content/no-image"), store.name,
                                (store.logo != null) ? store.logo : "/content/no-image");
            }
            return returnCookie;
        }
        /// <summary>
        /// Update the recent stores viewed in the cookie and add in the database
        /// </summary>
        /// <param name="userId">user's id</param>
        /// <param name="store">store viewed</param>
        /// <param name="max">max items in a cookie</param>
        /// <returns></returns>
        public static HttpCookie updateStoreViewHistory(int userId, HttpCookie cookie, Store store, int max = 10)
        {
            HttpCookie returnCookie = new HttpCookie(cookie.Name);
            returnCookie.Value = "";
            //add the new store in the database
            SIEBUEntities db = new SIEBUEntities();
            User_SearchHistory record = db.User_SearchHistory.FirstOrDefault(search => search.store_id == store.s_id &&
                search.product_id == null);
            if (record != null)  //modify existing record in the database or add it
            {
                record.dateaccessed = DateTime.Now;
            }
            else //add new record in the database
            {
                record = new User_SearchHistory();
                record.store_id = store.s_id;
                record.user_id = userId;
                record.dateaccessed = DateTime.Now;
                db.User_SearchHistory.Add(record);
            }
            db.SaveChanges();

            String storeHist = "";
            HttpCookie storeCookie = null;
            if (cookie == null) //cookie doesn't exist
            {
                storeCookie = recentStoreViewedCookie(userId);
                storeHist = storeCookie.Value;
            }
            else //get the value
            {
                storeHist = cookie.Value;
            }

            if (storeHist != "")
            {
                String[] cookieRecords = storeHist.Split('|');
                Boolean contains = false;
                int index = -1;
                try
                {
                    for (int i = 0; i < cookieRecords.Length; i++) // Check and find the index of the item if it is in the cookie
                    {
                        String[] cookieRecord = cookieRecords[i].Split('&');
                        int storeId = int.Parse(cookieRecord[0].ToString());

                        if (storeId == store.s_id)
                        {
                            contains = true;
                            index = i;
                            break;
                        }
                    }
                    String cookieValue = "";

                    if (!contains) //new record
                    {
                        if (cookieRecords.Length >= max)
                        {
                            for (int i = 0; i < cookieRecords.Length - 1; i++) //Take the first items in the record minus the last element
                            {
                                cookieValue = cookieValue + "|" + cookieRecords[i];
                            }
                            //add element 0 before cookieValue;
                            returnCookie.Value = getStoreCookieValue(store.s_id, store.name,
                                store.name_space, (store.logo != null) ? store.logo : "/content/no-image") + cookieValue;
                        }
                        else
                        {
                            returnCookie.Value = getStoreCookieValue(store.s_id, store.name,
                            store.name_space, (store.logo != null) ? store.logo : "/content/no-image") + "|" + storeHist;
                        }
                    }
                    else //modify existing cookie
                    {
                        if (index != 0) // if index == 0 then it's just the first element and we don't need to do anything
                        {
                            if (index == cookieRecords.Length - 1) //the record is the last element in the cookie.
                            {
                                cookieValue = cookieRecords[cookieRecords.Length - 1];
                                for (int i = 0; i != cookieRecords.Length - 1; i++)
                                {
                                    cookieValue = cookieValue + "|" + cookieRecords[i];
                                }
                                returnCookie.Value = cookieValue;
                            }
                            else //record is in the middle of the cookie
                            {
                                String before = cookieRecords[0];

                                for (int i = 1; i < index; i++)
                                {
                                    before = before + "|" + cookieRecords[i];
                                }

                                String after = cookieRecords[index + 1];
                                for (int i = index + 2; i < cookieRecords.Length; i++)
                                {
                                    after = after + "|" + cookieRecords[i];
                                }
                                returnCookie.Value = cookieRecords[index] + "|" + before + "|" + after;
                            }
                        }
                        else
                        {
                            returnCookie.Value = storeHist; //just return the same cookie.
                        }
                    }
                }
                catch (Exception e)
                {
                    //Debug.WriteLine("Exception has occured with modifying the recently viewed store cookie: " + e.ToString());
                    returnCookie.Value = storeHist;
                    //Response.Cookies.Add(recentStoreViewedCookie(WebSecurity.CurrentUserId));
                }

            }
            else //first shop viewed.
            {
                returnCookie.Value = getStoreCookieValue(store.s_id, store.name,
                        store.name_space, store.logo);
            }
            return returnCookie;
        }
 public static String editProfile(String email, String firstName, String lastName, String gender, DateTime Birthday, String about)
 {
     SIEBUEntities context = new SIEBUEntities();
     if (context.Users.Where(u => u.email == email).Count() != 0)
     {
         try
         {
             User user = context.Users.First(c => c.email == email); // Must check if user is in the database
             user.firstName = firstName;
             user.lastName = lastName;
             user.gender = (gender == "female") ? true : false;
             user.dob = Birthday;
             user.about = about;
             context.SaveChanges();
             return "";
         }
         catch
         {
             return "Changes to your account could not be made at this time"; // Changes could not be made/
         }
     }
     //Could not find email
     return "Could not find account with associated Email";
 }