// ToDo: GetStoreCategories
        // ToDo: GetCategoryItems        
        // ToDo: Checkout


        public static Guid? GetShoppingCartId(HttpContextBase context)
        {
            try
            {
                Guid? shoppingCartId = null;
                if (context.Session["ShoppingCartId"] != null)
                {
                    Guid cartId;
                    if (Guid.TryParse(context.Session["ShoppingCartId"].ToString(), out cartId))
                        shoppingCartId = cartId;
                }
                if (shoppingCartId == null && context.User.Identity.IsAuthenticated)
                {
                    StoreGateway sg = new StoreGateway();
                    shoppingCartId = sg.GetShoppingCartId(RDN.Library.Classes.Account.User.GetUserId());
                    context.Session["ShoppingCartId"] = shoppingCartId;
                }
                return shoppingCartId;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return null;
        }
        public ActionResult AddToCart(StoreItem storeItem)
        {
            try
            {
                var sg = new StoreGateway();
                var shoppingCartId = StoreGateway.GetShoppingCartId(HttpContext);
                StoreShoppingCart cart = null;

                if (shoppingCartId == null)
                {
                    cart = sg.CreateNewShoppingCart(storeItem.Store.MerchantId, RDN.Library.Classes.Account.User.GetUserId(), true, Request.UserHostAddress);
                    StoreGateway.SetShoppingCartSession(cart.ShoppingCartId, HttpContext);
                }
                else
                    cart = sg.GetShoppingCart(shoppingCartId.Value);

                int quantity = Convert.ToInt32(Request.Form["quantityToBuy"]);

                sg.AddItemToCart(cart.ShoppingCartId, storeItem.Store.MerchantId, storeItem.StoreItemId, quantity, storeItem.ItemSizeEnum, storeItem.ColorTempSelected);
                this.AddItemToCart(HttpContext.Session, quantity);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/roller-derby-item/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(storeItem.Name) + "/" + storeItem.StoreItemId));

        }
        public ActionResult SearchStoreItem(string q, int limit)
        {
            StoreGateway sg = new StoreGateway();
            List<StoreItemJson> item = sg.SearchStoreItems(q, limit);

            System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string sJSON = oSerializer.Serialize(item);
            return Content(sJSON);
        }
        //
        // GET: /Receipt/

        public ActionResult ReceiptIndex(Guid invoiceId)
        {
            DisplayInvoice invoice = null;
            try
            {
                var sg = new StoreGateway();
                invoice = sg.GetInvoice(invoiceId);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return View(invoice);
        }
 /// <summary>
 /// deletes the store item.
 /// </summary>
 /// <param name="pictureId"></param>
 /// <param name="storeItemId"></param>
 /// <param name="mId"></param>
 /// <returns></returns>
 public JsonResult DeleteStoreItemPicture(string pictureId, string storeItemId, string mId)
 {
     try
     {
         StoreGateway sg = new StoreGateway();
         bool isSuccess = sg.DeleteStoreItemPhoto(Convert.ToInt32(pictureId), Convert.ToInt32(storeItemId), new Guid(mId));
         return Json(new { result = isSuccess }, JsonRequestBehavior.AllowGet);
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return Json(new { result = false }, JsonRequestBehavior.AllowGet);
 }
 public ActionResult UpdateViewsCount(string storeItemId)
 {
     try
     {
         StoreGateway sg = new StoreGateway();
         bool done = sg.UpdateStoreItemViewCount(Convert.ToInt64(storeItemId));
         return Json(new { success = done }, JsonRequestBehavior.AllowGet);
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return Json(new { answer = false }, JsonRequestBehavior.AllowGet);
 }
        public ActionResult ViewListing(string name, string id)
        {
            StoreItem item = null;
            try
            {
                StoreGateway sg = new StoreGateway();
                item = sg.GetStoreItem(Convert.ToInt32(id), true);
                item.Note = RDN.Utilities.Strings.StringExt.ConvertTextAreaToHtml(item.Note);
                Dictionary<String, Int32> sizes = new Dictionary<string, int>();
                if (item.ItemSize.HasFlag(StoreItemShirtSizesEnum.X_Small))
                {
                    sizes.Add(RDN.Utilities.Enums.EnumExt.ToFreindlyName(StoreItemShirtSizesEnum.X_Small), Convert.ToInt32(StoreItemShirtSizesEnum.X_Small));
                }
                if (item.ItemSize.HasFlag(StoreItemShirtSizesEnum.Small))
                {
                    sizes.Add(RDN.Utilities.Enums.EnumExt.ToFreindlyName(StoreItemShirtSizesEnum.Small), Convert.ToInt32(StoreItemShirtSizesEnum.Small));
                }
                if (item.ItemSize.HasFlag(StoreItemShirtSizesEnum.Medium))
                {
                    sizes.Add(RDN.Utilities.Enums.EnumExt.ToFreindlyName(StoreItemShirtSizesEnum.Medium), Convert.ToInt32(StoreItemShirtSizesEnum.Medium));
                }
                if (item.ItemSize.HasFlag(StoreItemShirtSizesEnum.Large))
                {
                    sizes.Add(RDN.Utilities.Enums.EnumExt.ToFreindlyName(StoreItemShirtSizesEnum.Large), Convert.ToInt32(StoreItemShirtSizesEnum.Large));
                }
                if (item.ItemSize.HasFlag(StoreItemShirtSizesEnum.X_Large))
                {
                    sizes.Add(RDN.Utilities.Enums.EnumExt.ToFreindlyName(StoreItemShirtSizesEnum.X_Large), Convert.ToInt32(StoreItemShirtSizesEnum.X_Large));
                }
                if (item.ItemSize.HasFlag(StoreItemShirtSizesEnum.XX_Large))
                {
                    sizes.Add(RDN.Utilities.Enums.EnumExt.ToFreindlyName(StoreItemShirtSizesEnum.XX_Large), Convert.ToInt32(StoreItemShirtSizesEnum.XX_Large));
                }
                ViewBag.ItemSizes = new SelectList(sizes, "value", "key");
                ViewBag.Colors = new SelectList(item.Colors, "HexColor", "NameOfColor");
                var shoppingCartId = StoreGateway.GetShoppingCartId(HttpContext);
                if (shoppingCartId != null)
                {
                    StoreShoppingCart cart = sg.GetShoppingCart(shoppingCartId.Value);
                    item.CartItemsCount = cart.ItemsCount;
                }

            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return View(item);
        }
        public ActionResult ConfirmFromStripe()
        {
            try
            {
                var stateId = HttpContext.Request.Params["state"];
                if (String.IsNullOrEmpty(stateId))
                    return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.na));

                string returnType = stateId.Split('-')[0];
                string privId = stateId.Split('-')[1];

                StripeStateReturnCodeEnum typeOfReturn = (StripeStateReturnCodeEnum)Enum.Parse(typeof(StripeStateReturnCodeEnum), returnType);

                var errorCode = HttpContext.Request.Params["error"];
                if (!String.IsNullOrEmpty(errorCode))
                {
                    if (errorCode == StripeConnectCodes.access_denied.ToString())
                    {
                        var sg = new MerchantGateway();
                        var store = sg.GetMerchant(new Guid(privId));

                        if (store != null && typeOfReturn == StripeStateReturnCodeEnum.store)
                            return Redirect(Url.Content("~/store/settings/" + privId + "/" + store.MerchantId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.sced));
                        else if (store != null && typeOfReturn == StripeStateReturnCodeEnum.merchant)
                            return Redirect(Url.Content("~/merchant/settings?u=" + SiteMessagesEnum.sced));

                    }
                }
                var stripeCode = HttpContext.Request.Params["code"];
                if (!String.IsNullOrEmpty(stripeCode))
                {
                    var sg = new StoreGateway();
                    sg.UpdateStripeKey(stripeCode, new Guid(privId));
                    var mg = new MerchantGateway();
                    var store = mg.GetMerchant(new Guid(privId));

                    if (store != null && typeOfReturn == StripeStateReturnCodeEnum.store)
                        return Redirect(Url.Content("~/store/settings/" + privId + "/" + store.MerchantId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.sca));
                    else if (store != null && typeOfReturn == StripeStateReturnCodeEnum.merchant)
                        return Redirect(Url.Content("~/merchant/settings?u=" + SiteMessagesEnum.sca));

                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
        }
        public void RemoveItemFromCart()
        {
            var shoppingCartId = GetShoppingCartId();
            if (!shoppingCartId.HasValue)
                Response.Redirect(Url.Action("ViewRDNStore"));

            var cartItemIdRaw = Request.Form["shoppingcartitem"];

            int cartItemId;
            if (!Int32.TryParse(cartItemIdRaw, out cartItemId))
                Response.Redirect(Url.Action("ViewRDNStore"));

            var sg = new StoreGateway();
            sg.RemoveItemFromCart(shoppingCartId.Value, cartItemId);
            Response.Redirect(Url.Action("ViewRDNStore"));
        }
        public ActionResult CheckOut()
        {
            var shoppingCartId = GetShoppingCartId();
            if (!shoppingCartId.HasValue)
            {
                Response.Redirect(Url.Action("ViewRDNStore"));
                return null;
            }

            var sg = new StoreGateway();
            var checkout = sg.GetCheckoutData(shoppingCartId.Value, new Guid());
            if (checkout == null || checkout.ShoppingCart.Stores.Count == 0)
            {
                Response.Redirect(Url.Action("ViewRDNStore"));
                return null;
            }

            var checkoutObject = new CheckOut();
            checkoutObject.MerchantId = checkout.MerchantId;
            checkoutObject.ShoppingCart = checkout.ShoppingCart;
            checkoutObject.Tax = checkout.Tax;
            checkoutObject.TaxRate = checkout.TaxRate;
            checkoutObject.TotalExclVat = checkout.TotalExclVat;
            checkoutObject.TotalInclVat = checkout.TotalInclVat;
            checkoutObject.Currency = checkout.Currency;
        
                checkoutObject.Currency =checkout.Currency;
                checkoutObject.CurrencyCost =checkout.CurrencyCost;
        
            checkoutObject.ShippingOptions =
                checkout.ShippingOptionsRaw.Select(
                    x => new SelectListItem
                    {
                        Selected = false,
                        Text = string.Format("{0} {1} {2}", x.Value.Name.ToString(), x.Value.Price, checkoutObject.Currency),
                        Value = x.Key.ToString()
                    }).ToList();
            checkoutObject.ShippingOptions[0].Selected = true;

            var paymentProviders = Enum.GetNames(typeof(PaymentProvider));
            checkoutObject.PaymentProviders = paymentProviders.Select(x => new SelectListItem { Selected = false, Text = x, Value = x }).ToList();
            checkoutObject.PaymentProviders[0].Selected = true;
            checkout.ShippingAddress = new StoreShoppingCartContactInfo();
            checkout.BillingAddress = new StoreShoppingCartContactInfo();
            return View(checkoutObject);
        }
        protected void CartCount(HttpSessionStateBase session)
        {
            if (session["cartCount"] == null || string.IsNullOrEmpty(session["cartCount"].ToString()))
            {
                var shoppingCartId = StoreGateway.GetShoppingCartId(HttpContext);
                if (shoppingCartId != null)
                {
                    var sg = new StoreGateway();
                    var cart = sg.GetShoppingCart(shoppingCartId.Value);
                    if (cart != null)
                    {
                        session["cartCount"] = cart.ItemsCount;
                        return;
                    }
                }
                session["cartCount"] = 0;
            }

        }
        public ActionResult Shop(string id, string name)
        {
            DisplayStore item = new DisplayStore();
            try
            {
                NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(Request.Url.Query);
                string category = nameValueCollection["category"];

                int cat = 0;
                if (!String.IsNullOrEmpty(category))
                {
                    cat = Convert.ToInt32(category);
                }
                StoreGateway sg = new StoreGateway();
                item = sg.GetPublicStore(new Guid(id), cat);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return View(item);
        }
 public JsonResult MoveInvoiceToNextStatus(string invoiceId, string status)
 {
     try
     {
         status = status.Replace("Move To", "").Trim();
         PaymentGateway pg = new PaymentGateway();
         string s = status.Replace(" ", "_");
         InvoiceStatus st = (InvoiceStatus)Enum.Parse(typeof(InvoiceStatus), s);
         pg.SetInvoiceStatus(new Guid(invoiceId), st);
         if (st == InvoiceStatus.Shipped)
         {
             var voice = pg.GetDisplayInvoice(new Guid(invoiceId));
             StoreGateway sg = new StoreGateway();
             sg.CompileAndSendShippedEmailsForStore(voice);
         }
         return Json(new { isSuccess = true, status = st.ToString() }, JsonRequestBehavior.AllowGet);
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return Json(new { isSuccess = false }, JsonRequestBehavior.AllowGet);
 }
        public void AddItemToCart()
        {
            var shoppingCartId = GetShoppingCartId();
            if (!shoppingCartId.HasValue)
                Response.Redirect(Url.Action("ViewRDNStore"));

            var merchantIdRaw = Request.Form["merchantid"];
            var articleIdRaw = Request.Form["articleid"];
            var quantityRaw = Request.Form["quantity"];

            Guid merchantId;
            if (!Guid.TryParse(merchantIdRaw, out merchantId))
                Response.Redirect(Url.Action("ViewRDNStore"));

            int itemId, quantity;
            if (!Int32.TryParse(articleIdRaw, out itemId))
                Response.Redirect(Url.Action("ViewRDNStore"));
            if (!Int32.TryParse(quantityRaw, out quantity))
                Response.Redirect(Url.Action("ViewRDNStore"));

            var sg = new StoreGateway();
            sg.AddItemToCart(shoppingCartId.Value, merchantId, itemId, quantity, 0, null);
            Response.Redirect(Url.Action("ViewRDNStore"));
        }
        public ActionResult StoreHome(Guid? privId, Guid? storeId)
        {
            DisplayStore displayStore = null;
            try
            {
                if (storeId == null)
                {
                    var store = new DisplayStore();
                    //when creating a store, the store is created with the users 
                    //member id or the federation or league id.
                    if (privId == null || privId == new Guid())
                    {
                        privId = RDN.Library.Classes.Account.User.GetMemberId();
                        //check if they already have a store, if they do, we load it.
                        bool hasStore = MemberCache.HasPersonalStoreAlreadyForUser(privId.Value);
                        if (hasStore)
                            return Redirect(Url.Content("~/store/home/" + MemberCache.GetStoreManagerKeysForUrlUser(privId.Value)));
                    }
                    store.InternalReference = privId.Value;
                    NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(Request.Url.Query);
                    string updated = nameValueCollection["u"];

                    if (!String.IsNullOrEmpty(updated) && updated == SiteMessagesEnum.wbc.ToString())
                    {
                        SiteMessage message = new SiteMessage();
                        message.MessageType = SiteMessageType.Error;
                        message.Message = "Wrong Beta Code, Please Try Again.";
                        this.AddMessage(message);
                    }
                    return View(store);
                }
                var sg = new StoreGateway();
                displayStore = sg.GetStoreForManager(storeId, privId, false);
                if (!displayStore.AcceptPaymentsViaStripe && !displayStore.AcceptPaymentsViaPaypal)
                {
                    SiteMessage message = new SiteMessage();
                    message.MessageType = SiteMessageType.Info;
                    message.Message = "Please Setup a Payment Provider in the Store Settings.";
                    this.AddMessage(message);
                }
                else if (!displayStore.IsPublished)
                {
                    SiteMessage message = new SiteMessage();
                    message.MessageType = SiteMessageType.Info;
                    message.Message = "Your Store Is Not Yet Published. Publish the Store in the Settings.";
                    this.AddMessage(message);
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return View(displayStore);
        }
        public ActionResult CreateStore(DisplayStore store)
        {
            try
            {

                var sg = new StoreGateway();
                DisplayStore sto = sg.CreateNewStoreAndMerchantAccount(store.InternalReference);
                var id = RDN.Library.Classes.Account.User.GetMemberId();
                MemberCache.Clear(id);
                MemberCache.ClearApiCache(id);

                return Redirect(Url.Content("~/store/home/" + sto.PrivateManagerId.ToString().Replace("-", "") + "/" + sto.MerchantId.ToString().Replace("-", "")));

            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
        }
 public ActionResult StoreNewItem(Guid privId, Guid storeId)
 {
     StoreItemDisplayModel storeItem = new StoreItemDisplayModel();
     try
     {
         var sg = new StoreGateway();
         var store = sg.GetStoreForManager(storeId, privId, false);
         storeItem.InternalId = store.InternalReference;
         storeItem.MerchantId = store.MerchantId;
         storeItem.Currency = store.Currency;
         storeItem.PrivateManagerId = store.PrivateManagerId;
         StoreItemTypeEnum[] notInList = { StoreItemTypeEnum.None };
         storeItem.ItemTypeSelectList = StoreItemTypeEnum.Item.ToSelectList(notInList);
         var colors = ColorDisplayFactory.GetColors();
         storeItem.ColorList = new SelectList(colors, "HexColor", "NameOfColor");
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return View(storeItem);
 }
        public ActionResult StoreNewItem(StoreItemDisplayModel storeItem)
        {
            var sg = new StoreGateway();
            try
            {
                StoreItemDisplay display = new StoreItemDisplay();
                display.CanPickUpLocally = storeItem.CanPickUpLocally;
                display.ArticleNumber = storeItem.ArticleNumber;
                display.CanRunOutOfStock = storeItem.CanRunOutOfStock;
                display.Currency = storeItem.Currency;
                display.Description = storeItem.Description;
                display.InternalId = storeItem.InternalId;
                display.Note = storeItem.HtmlNote;
                display.Price = storeItem.Price;
                display.PrivateManagerId = storeItem.PrivateManagerId;
                display.QuantityInStock = storeItem.QuantityInStock;
                display.StoreItemId = storeItem.StoreItemId;
                display.Merchant.Name = storeItem.StoreName;
                display.Weight = storeItem.Weight;
                display.MerchantId = storeItem.MerchantId;
                display.Name = storeItem.Name;
                display.Shipping = storeItem.Shipping;
                display.HasExtraLarge = storeItem.HasExtraLarge;
                display.HasExtraSmall = storeItem.HasExtraSmall;
                display.HasLarge = storeItem.HasLarge;
                display.HasMedium = storeItem.HasMedium;
                display.HasSmall = storeItem.HasSmall;
                display.HasXXLarge = storeItem.HasXXLarge;
                display.ItemTypeEnum = storeItem.ItemTypeEnum;
                display.ItemType = storeItem.ItemType;
                display.ColorTempSelected = storeItem.ColorsSelected;

                display = sg.CreateNewStoreItem(display);
                if (display.StoreItemId > 0)
                    return Redirect(Url.Content("~/store/item/edit/" + display.StoreItemId + "/" + display.PrivateManagerId.ToString().Replace("-", "") + "/" + display.MerchantId.ToString().Replace("-", "")));

            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            //if the item didn't actually get created.
            var store = sg.GetStoreForManager(storeItem.MerchantId, storeItem.PrivateManagerId, false);
            storeItem.InternalId = store.InternalReference;
            storeItem.MerchantId = store.MerchantId;
            storeItem.PrivateManagerId = store.PrivateManagerId;
            return View(storeItem);
        }
[RequireHttps] //apply to all actions in controller
#endif
        public ActionResult Review(string name, string id, string invoiceId)
        {
            StoreItem item = null;
            try
            {
                StoreGateway sg = new StoreGateway();
                item = sg.GetStoreItem(Convert.ToInt32(id));
                var invoice = sg.GetInvoice(new Guid(invoiceId));
                var storeItem = invoice.InvoiceItems.Where(x => x.StoreItemId == Convert.ToInt32(id)).FirstOrDefault();
                if (storeItem == null)
                    return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
                var review = ItemReview.GetItemReviewForInvoiceItem(storeItem.InvoiceItemId, Convert.ToInt32(id));
                if (review != null)
                {
                    item.ReviewTitle = review.title;
                    item.ReviewComment = review.comment;
                    item.rate = review.rate;
                    item.ReviewId = review.ReviewId;

                }
                item.InvoiceItemId = storeItem.InvoiceItemId;
                return View(item);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));

        }
 public ActionResult ViewCategory(string name, string id)
 {
     StoreGateway sg = new StoreGateway();
     DisplayCategory item = sg.GetCategoryAndItems(Convert.ToInt64(id));
     return View(item);
 }
        private Classes.Display.DisplayInvoice PendingPaypalPayment(string invoiceId)
        {
            try
            {
                PaymentGateway pg = new PaymentGateway();
                var invoice = pg.GetDisplayInvoice(new Guid(invoiceId));
                if (invoice != null)
                {
                    if (invoice.Subscription != null)
                    {
                        InvoiceFactory.EmailLeagueAboutSuccessfulSubscription(invoice.Subscription.InternalObject, invoice.InvoiceId, invoice.Subscription.Price, invoice.Subscription.ValidUntil, invoice.InvoiceBilling.Email);

                        RDN.Library.Classes.League.LeagueFactory.UpdateLeagueSubscriptionPeriod(invoice.Subscription.ValidUntil, false, invoice.Subscription.InternalObject);

                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: New Payment Pending!!", invoice.InvoiceId + " Amount:" + invoice.Subscription.Price + CompileReportString());
                        pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Pending_Payment_From_Paypal);
                        WebClient client = new WebClient();
                        client.DownloadDataAsync(new Uri(ServerConfig.URL_TO_CLEAR_LEAGUE_MEMBER_CACHE + invoice.Subscription.InternalObject));
                        WebClient client1 = new WebClient();
                        client1.DownloadDataAsync(new Uri(ServerConfig.URL_TO_CLEAR_LEAGUE_MEMBER_CACHE_API + invoice.Subscription.InternalObject));
                    }
                    else if (invoice.Paywall != null)
                    {
                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: New Paywall Payment Pending!!", invoice.InvoiceId + " Amount:" + invoice.Paywall.Price + CompileReportString());
                        pg.SetInvoiceStatus(invoice.InvoiceId, InvoiceStatus.Pending_Payment_From_Paypal);
                    }
                    else if (invoice.DuesItems.Count > 0)
                        HandleDuesPaymentPending(invoice);
                    else if (invoice.InvoiceItems.Count > 0)
                    {
                        StoreGateway sg = new StoreGateway();
                        sg.HandleStoreItemPaymentPending(invoice, CompileReportString());
                    }
                    else
                    {
                        EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: Couldn't Find Subscription", CompileReportString());
                    }
                }
                else
                {
                    EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "Paypal: Couldn't Find Invoice", CompileReportString());
                }
                return invoice;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: CompileReportString());
            }
            return null;
        }
        public ActionResult StoreOrder(Guid privId, Guid storeId, Guid invoiceId)
        {
            DisplayInvoice invoice = null;
            try
            {
                NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(Request.Url.Query);
                string updated = nameValueCollection["u"];

                if (!String.IsNullOrEmpty(updated) && updated == SiteMessagesEnum.s.ToString())
                {
                    SiteMessage message = new SiteMessage();
                    message.MessageType = SiteMessageType.Success;
                    message.Message = "Successfully Updated.";
                    this.AddMessage(message);
                }

                var sg = new StoreGateway();
                invoice = sg.GetInvoiceForManager(storeId, privId, invoiceId);
                if (invoice.InvoiceStatus == InvoiceStatus.Awaiting_Shipping)
                    ViewData["invoiceStatus"] = "Move To " + InvoiceStatus.Shipped;
                else if (invoice.InvoiceStatus == InvoiceStatus.Shipped)
                    ViewData["invoiceStatus"] = "Move To " + InvoiceStatus.Archived_Item_Completed;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return View(invoice);
        }
        public ActionResult StoreSettings(Guid privId, Guid storeId)
        {
            DisplayStoreModel displayStore = null;
            try
            {
                NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(Request.Url.Query);
                string updated = nameValueCollection["u"];

                if (!String.IsNullOrEmpty(updated) && updated == SiteMessagesEnum.sced.ToString())
                {
                    SiteMessage message = new SiteMessage();
                    message.MessageType = SiteMessageType.Error;
                    message.Message = "You did not Connect to Stripe. In order to Accept Customer Credit Cards, you should connect to Stripe.";
                    this.AddMessage(message);
                }
                if (!String.IsNullOrEmpty(updated) && updated == SiteMessagesEnum.sca.ToString())
                {
                    SiteMessage message = new SiteMessage();
                    message.MessageType = SiteMessageType.Success;
                    message.Message = "Stripe Connected Successfully.";
                    this.AddMessage(message);
                }

                ViewBag.IsSuccessful = false;
                var sg = new StoreGateway();
                var realStore = sg.GetStoreSettings(storeId, privId);
                string stripe = "https://connect.stripe.com/oauth/authorize?response_type=code&client_id=" + ServerConfig.STRIPE_CONNECT_LIVE_KEY + "&scope=read_write&state=" + StripeStateReturnCodeEnum.store + "-" + privId.ToString().Replace("-", "");
                


                displayStore = new DisplayStoreModel( realStore);
                displayStore.CurrencyList = new SelectList(SiteCache.GetCurrencyExchanges(), "CurrencyAbbrName", "CurrencyNameDisplay", "USD");
                ViewBag.StripeUrl = stripe;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return View(displayStore);

        }
        public ActionResult StoreSettings(DisplayStoreModel store)
        {
            try
            {
                ViewBag.IsSuccessful = false;
                var sg = new StoreGateway();
                ViewBag.IsSuccessful = sg.UpdateStoreSettings(store);

                return Redirect(Url.Content("~/store/settings/" + store.PrivateManagerId.ToString().Replace("-", "") + "/" + store.MerchantId.ToString().Replace("-", "")));
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
        }
        public ActionResult UploadItemPictures(StoreItemDisplayModel display)
        {
            try
            {
                foreach (string pictureFile in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[pictureFile];
                    if (file.ContentLength > 0)
                    {
                        StoreGateway sg = new StoreGateway();
                        sg.AddStoreItemPhoto(display.StoreItemId, file.InputStream, file.FileName);
                    }
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/store/item/edit/" + display.StoreItemId + "/" + display.PrivateManagerId.ToString().Replace("-", "") + "/" + display.MerchantId.ToString().Replace("-", "")));

        }
 public ActionResult StoreOrder(DisplayInvoice invoice)
 {
     try
     {
         var sg = new StoreGateway();
         sg.UpdateInvoiceForStoreOrder(invoice);
         return Redirect(Url.Content("~/store/order/" + invoice.Merchant.PrivateManagerId.ToString().Replace("-", "") + "/" + invoice.Merchant.MerchantId.ToString().Replace("-", "") + "/" + invoice.InvoiceId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.s));
     }
     catch (Exception exception)
     {
         ErrorDatabaseManager.AddException(exception, exception.GetType());
     }
     return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
 }
        public ActionResult NewLocation(Models.Location.NewLocation location)
        {
            try
            {
                // if a create another was clicked instead of just submitting the event.
                bool createAnother = false;
                if (Request.Form["createAnother"] != null)
                    createAnother = true;

                var locType = (LocationOwnerType)Enum.Parse(typeof(LocationOwnerType), location.RedirectTo);
                var id = RDN.Library.Classes.Location.LocationFactory.CreateNewLocation(locType, location.LocationName, location.Address1, location.Address2, location.CityRaw, location.Country, location.StateRaw, location.Zip, location.Website, location.OwnerId);

                if (!createAnother)
                {
                    if (locType == LocationOwnerType.calendar)
                        return Redirect(Url.Content("~/calendar/new/" + location.OwnerType + "/" + location.OwnerId.ToString().Replace("-", "") + "/" + id.LocationId.ToString().Replace("-", "")));
                    else if (locType == LocationOwnerType.shop)
                    {
                        var sg = new StoreGateway();
                        var realStore = sg.GetStoreForManager(location.OwnerId);
                        return Redirect(Url.Content("~/store/settings/" + realStore.PrivateManagerId.ToString().Replace("-", "") + "/" + realStore.MerchantId.ToString().Replace("-", "")));
                    }
                }
                else
                {
                    return Redirect(HttpContext.Request.Url.AbsoluteUri + "?u=" + SiteMessagesEnum.sal);
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return View(location);
        }
        public ActionResult StoreEditItem(int itemId, Guid privId, Guid storeId)
        {
            StoreItemDisplayModel model = new StoreItemDisplayModel();
            try
            {
                var sg = new StoreGateway();
                var store = sg.GetStoreItemManager(storeId, privId, itemId);
                model.ArticleNumber = store.ArticleNumber;
                model.CanRunOutOfStock = store.CanRunOutOfStock;
                model.CanPickUpLocally = store.CanPickUpLocally;
                model.Currency = store.Currency;
                model.Description = store.Description;
                model.HtmlNote = store.Note;
                model.InternalId = store.InternalId;
                model.MerchantId = store.MerchantId;
                model.Name = store.Name;
                model.Price = store.Price;
                model.Shipping = store.Shipping;
                model.ShippingAdditional = store.ShippingAdditional;
                model.PrivateManagerId = store.PrivateManagerId;
                model.QuantityInStock = store.QuantityInStock;
                model.StoreItemId = store.StoreItemId;
                model.StoreName = store.Merchant.Name;
                model.Weight = store.Weight;
                model.Photos = store.Photos;
                model.IsPublished = store.IsPublished;
                model.ItemSizeEnum = store.ItemSizeEnum;
                model.ItemTypeEnum = store.ItemTypeEnum;
                model.ItemType = store.ItemType;
                model.ItemSize = store.ItemSize;
                model.ColorsSelected = store.ColorTempSelected;
                model.Colors = store.Colors;
                store.ColorTempSelected = String.Empty;
                StoreItemTypeEnum[] notInList = { StoreItemTypeEnum.None };
                model.ItemTypeSelectList = store.ItemType.ToSelectList(notInList);
                var colors = ColorDisplayFactory.GetColors();
                model.ColorList = new SelectList(colors, "HexColor", "NameOfColor");

                if (model.ItemType == StoreItemTypeEnum.Shirt)
                {
                    Dictionary<String, Int32> sizes = new Dictionary<string, int>();
                    if (model.ItemSize.HasFlag(StoreItemShirtSizesEnum.Large))
                    {
                        sizes.Add(RDN.Portable.Util.Enums.EnumExt.ToFreindlyName(StoreItemShirtSizesEnum.Large), Convert.ToInt32(StoreItemShirtSizesEnum.Large));
                        model.HasLarge = true;
                    }
                    if (model.ItemSize.HasFlag(StoreItemShirtSizesEnum.Medium))
                    {
                        sizes.Add(RDN.Portable.Util.Enums.EnumExt.ToFreindlyName(StoreItemShirtSizesEnum.Medium), Convert.ToInt32(StoreItemShirtSizesEnum.Medium));
                        model.HasMedium = true;
                    }
                    if (model.ItemSize.HasFlag(StoreItemShirtSizesEnum.Small))
                    {
                        sizes.Add(RDN.Portable.Util.Enums.EnumExt.ToFreindlyName(StoreItemShirtSizesEnum.Small), Convert.ToInt32(StoreItemShirtSizesEnum.Small));
                        model.HasSmall = true;
                    }
                    if (model.ItemSize.HasFlag(StoreItemShirtSizesEnum.X_Large))
                    {
                        sizes.Add(RDN.Portable.Util.Enums.EnumExt.ToFreindlyName(StoreItemShirtSizesEnum.X_Large), Convert.ToInt32(StoreItemShirtSizesEnum.X_Large));
                        model.HasExtraLarge = true;
                    }
                    if (model.ItemSize.HasFlag(StoreItemShirtSizesEnum.X_Small))
                    {
                        sizes.Add(RDN.Portable.Util.Enums.EnumExt.ToFreindlyName(StoreItemShirtSizesEnum.X_Small), Convert.ToInt32(StoreItemShirtSizesEnum.X_Small));
                        model.HasExtraSmall = true;
                    }
                    if (model.ItemSize.HasFlag(StoreItemShirtSizesEnum.XX_Large))
                    {
                        sizes.Add(RDN.Portable.Util.Enums.EnumExt.ToFreindlyName(StoreItemShirtSizesEnum.XX_Large), Convert.ToInt32(StoreItemShirtSizesEnum.XX_Large));
                        model.HasXXLarge = true;
                    }

                    model.ItemSizes = new SelectList(sizes);
                }

            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return View(model);
        }
        public ActionResult StoreOrders(Guid privId, Guid storeId)
        {
            DisplayStore displayStore = null;
            try
            {
                NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(Request.Url.Query);
                string updated = nameValueCollection["u"];

                if (!String.IsNullOrEmpty(updated) && updated == SiteMessagesEnum.sced.ToString())
                {
                    SiteMessage message = new SiteMessage();
                    message.MessageType = SiteMessageType.Error;
                    message.Message = "You did not Connect to Stripe. In order to Accept Customer Credit Cards, you should connect to Stripe.";
                    this.AddMessage(message);
                }
                if (!String.IsNullOrEmpty(updated) && updated == SiteMessagesEnum.sca.ToString())
                {
                    SiteMessage message = new SiteMessage();
                    message.MessageType = SiteMessageType.Success;
                    message.Message = "Stripe Connected Successfully.";
                    this.AddMessage(message);
                }

                ViewBag.IsSuccessful = false;
                var sg = new StoreGateway();
                var realStore = sg.GetStoreForManager(storeId, privId, false);

                displayStore = realStore;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return View(displayStore);

        }
[RequireHttps] //apply to all actions in controller
#endif
        public ActionResult Shops()
        {
            StoreGateway sg = new StoreGateway();
            List<DisplayStore> shops = sg.GetPublicShops(0, 30);
            return View(shops);
        }