public ActionResult PaywallRefundOrder(DisplayInvoice invoice)
        {
            try
            {
                bool isSuccess = false;
                var sg = new Paywall();
                PaymentGateway pg = new PaymentGateway();
                var f = pg.StartInvoiceWizard().Initalize(invoice.Merchant.MerchantId, "USD", invoice.PaymentProvider, PaymentMode.Live, ChargeTypeEnum.Refund_Paywall)
                    .SetInvoiceId(invoice.InvoiceId)
                .SetRefundAmount(invoice.RefundAmount)
                .SetNotes(null, invoice.AdminNote);

                var response = f.FinalizeInvoice();
                if (response.Status == InvoiceStatus.Refunded)
                    isSuccess = true;

                if (isSuccess)
                    return Redirect(Url.Content("~/paywall/order/" + invoice.Merchant.PrivateManagerId.ToString().Replace("-", "") + "/" + invoice.Merchant.MerchantId.ToString().Replace("-", "") + "/" + invoice.InvoiceId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.ro));
                else
                    return Redirect(Url.Content("~/paywall/order/" + invoice.Merchant.PrivateManagerId.ToString().Replace("-", "") + "/" + invoice.Merchant.MerchantId.ToString().Replace("-", "") + "/" + invoice.InvoiceId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.sww));
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
        }
        public ActionResult MakePaywallPayment(GameOutModel crap)
        {
            var memId = RDN.Library.Classes.Account.User.GetMemberId();
            GameOutModel game = new GameOutModel();
            game.Game = GameServerViewModel.GetGameFromCache(crap.Game.GameId);
            Paywall wall = new Paywall();
            game.Paywall = wall.GetPaywall(game.Game.PaywallId);

            try
            {
                string paymentProvider = Request.Form["PaymentType"].ToString();
                string stripeToken = "none";

                PaymentProvider provider = PaymentProvider.None;
                if (paymentProvider == PaymentProvider.Stripe.ToString())
                {
                    provider = PaymentProvider.Stripe;
                    stripeToken = Request.Form["stripeToken"].ToString();
                }
                else if (paymentProvider == PaymentProvider.Paypal.ToString())
                {
                    provider = PaymentProvider.Paypal;
                }
                string subType = Request.Form["PaymentCost"].ToString();
                PaywallPriceTypeEnum sub = (PaywallPriceTypeEnum)Enum.Parse(typeof(PaywallPriceTypeEnum), subType);
                decimal price = .99M;

                DateTime now = DateTime.UtcNow;
                DateTime validTill = DateTime.UtcNow.AddDays(1);

                if (sub == PaywallPriceTypeEnum.Daily_Payment)
                {
                    validTill = DateTime.UtcNow.AddDays(1);
                }
                else if (sub == PaywallPriceTypeEnum.Full_Payment)
                {
                    validTill = game.Paywall.EndDate.Value.AddDays(1);
                }

                PaymentGateway pg = new PaymentGateway();
                var f = pg.StartInvoiceWizard().Initalize(game.Paywall.MerchantId, "USD", provider, PaymentMode.Live, ChargeTypeEnum.Paywall)
                    .SetInvoiceId(Guid.NewGuid())
                    .SetPaywall(new InvoicePaywall
                    {
                        ValidUntil = validTill,
                        PaywallId = game.Paywall.PaywallId,
                        PriceType = sub,
                        Description = "Paid For " + game.Game.GameName + " with a " + RDN.Utilities.Enums.EnumExt.ToFreindlyName(sub) + " Pass",
                        Name = "Game Streaming Paid",
                        Price = price,
                        InternalObject = game.Game.GameId,
                        MemberPaidId = memId,
                        PaywallLocation = ServerConfig.WEBSITE_DEFAULT_LOCATION + "/roller-derby-game/" + game.Game.GameId.ToString().Replace("-", "") + "/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(game.Game.GameName) + "/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(game.Game.Team1.TeamName) + "/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(game.Game.Team2.TeamName)
                    })
                    .SetInvoiceContactData(new InvoiceContactInfo
                    {
                        Email = crap.Paywall.EmailAddress,
                        Phone = crap.Paywall.PhoneNumber,
                    });

                if (provider == PaymentProvider.Stripe)
                    f.SetStripeTokenId(stripeToken);

                var response = f.FinalizeInvoice();

                //succesfully charged.
                if (response.Status == InvoiceStatus.Payment_Successful)
                    return Redirect(ServerConfig.PAYWALL_RECEIPT_URL + response.InvoiceId.ToString().Replace("-", ""));
                else if (response.Status == InvoiceStatus.Pending_Payment_From_Paypal)
                    return Redirect(response.RedirectLink);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/roller-derby-game/" + game.Game.GameId.ToString().Replace("-", "") + "/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(game.Game.GameName) + "/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(game.Game.Team1.TeamName) + "/" + RDN.Utilities.Strings.StringExt.ToSearchEngineFriendly(game.Game.Team2.TeamName) + "?u=" + SiteMessagesEnum.sww));

        }
        /// <summary>
        /// no need to do anything here just yet.
        /// I think when leagues start changing their subscriptions, we will need to update this code to change the plan
        /// 
        /// </summary>
        /// <param name="se"></param>
        /// <returns></returns>
        public static bool SubscriptionUpdated(StripeEvent se, string json)
        {
            try
            {
                //{ "id": "evt_1Myn3gX10D21o6", "created": 1361989292, "livemode": true, "type": "customer.subscription.updated", "data": { "object": { "plan": { "interval": "month", "name": "Monthly_Plan", "amount": 1599, "currency": "usd", "id": "Monthly_Plan", "object": "plan", "livemode": true, "interval_count": 1, "trial_period_days": null }, "object": "subscription", "start": 1359310832, "status": "active", "customer": "cus_1BMmWWvjng8Mug", "cancel_at_period_end": false, "current_period_start": 1361989232, "current_period_end": 1364408432, "ended_at": null, "trial_start": null, "trial_end": null, "canceled_at": null, "quantity": 1 }, "previous_attributes": { "current_period_start": 1359310832, "current_period_end": 1361989232 } }, "object": "event", "pending_webhooks": 1 } 

                PaymentGateway pg = new PaymentGateway();
                var f = pg.StartInvoiceWizard().Initalize(ServerConfig.RDNATION_STORE_ID, "USD",
PaymentProvider.Stripe, PaymentMode.Live, ChargeTypeEnum.SubscriptionUpdated)
                    .SetInvoiceId(Guid.NewGuid())
                    .SetInvoiceStatus(InvoiceStatus.Subscription_Should_Be_Updated_On_Charge);


                var dc = new ManagementContext();
                RDN.Library.DataModels.PaymentGateway.Stripe.StripeEventDb even = new RDN.Library.DataModels.PaymentGateway.Stripe.StripeEventDb();
                even.CreatedStripeDate = se.Created.GetValueOrDefault();
                even.StripeId = se.Id;
                even.LiveMode = se.LiveMode.GetValueOrDefault();
                if (se.Data != null)
                {
                    StripeSubscription cust = Stripe.Mapper<StripeSubscription>.MapFromJson(se.Data.Object.ToString());
                    //StripeSubscription cust = (StripeSubscription)se.Data.Object;
                    StripeSubscriptionDb custDb = new StripeSubscriptionDb();
                    even.StripeEventTypeEnum = (byte)StripeEventTypeEnum.customer_subscription_created;
                    custDb.CanceledAt = cust.CanceledAt;
                    custDb.EndedAt = cust.EndedAt;
                    custDb.Customer = dc.StripeCustomers.Where(x => x.Id == cust.CustomerId).FirstOrDefault();
                    custDb.PeriodEnd = cust.PeriodEnd;
                    custDb.PeriodStart = cust.PeriodStart;
                    custDb.Quantity = cust.Quantity;
                    custDb.Start = cust.Start;
                    custDb.Status = cust.Status;
                    if (cust.StripePlan != null)
                    {
                        custDb.StripePlan = dc.StripePlans.Where(x => x.Id == cust.StripePlan.Id).FirstOrDefault();
                        if (custDb.StripePlan == null)
                        {
                            StripePlanDb pl = new StripePlanDb();
                            pl.AmountInCents = cust.StripePlan.AmountInCents;
                            pl.Currency = cust.StripePlan.Currency;
                            pl.Id = cust.StripePlan.Id;
                            pl.Interval = cust.StripePlan.Interval;
                            pl.IntervalCount = cust.StripePlan.IntervalCount;
                            pl.LiveMode = cust.StripePlan.LiveMode;
                            pl.Name = cust.StripePlan.Name;
                            pl.TrialPeriodDays = cust.StripePlan.TrialPeriodDays;
                            custDb.StripePlan = pl;
                            dc.StripePlans.Add(pl);
                        }
                    }
                    DateTime now = DateTime.UtcNow;
                    TimeSpan ts = new TimeSpan();
                    int lengthOfDays = 31;

                    SubscriptionPeriodStripe period = SubscriptionPeriodStripe.Monthly;
                    if (cust.StripePlan.Id == StripePlanNames.Monthly_Plan.ToString())
                    {
                        period = SubscriptionPeriodStripe.Monthly;
                        ts = now.AddMonths(1) - DateTime.UtcNow;
                        lengthOfDays = ts.Days;
                    }
                    else if (cust.StripePlan.Id == StripePlanNames.Six_Month_League_Subscription.ToString())
                    {
                        period = SubscriptionPeriodStripe.Six_Months;
                        ts = now.AddMonths(6) - DateTime.UtcNow;
                        lengthOfDays = ts.Days;
                    }
                    else if (cust.StripePlan.Id == StripePlanNames.Three_Month_League_Subscription.ToString())
                    {
                        period = SubscriptionPeriodStripe.Three_Months;
                        ts = now.AddMonths(3) - DateTime.UtcNow;
                        lengthOfDays = ts.Days;
                    }
                    else if (cust.StripePlan.Id == StripePlanNames.Yearly_League_Subscription.ToString())
                    {
                        period = SubscriptionPeriodStripe.Yearly;
                        ts = now.AddMonths(12) - DateTime.UtcNow;
                        lengthOfDays = ts.Days;
                    }
                    //getting league Id here and subscriptionDate
                    var invoiceFromPast = pg.GetDisplayInvoiceWithStripeCustomerId(cust.CustomerId);
                    Guid leagueId = new Guid();
                    if (invoiceFromPast.Subscription != null)
                    {
                        leagueId = invoiceFromPast.Subscription.InternalObject;
                    }
                    f.SetPaymentProviderId(cust.CustomerId);
                    f.SetSubscription(new InvoiceSubscription
                    {
                        Description = "RDN League portal subscription",
                        DescriptionRecurring = "Fee for RDN League portal subscription",
                        Name = "RDN Member portal",
                        NameRecurring = "RDN Member portal recurring",
                        DigitalPurchaseText = "You have now access to RDN League portal",
                        Price = Convert.ToDecimal(cust.StripePlan.AmountInCents) / Convert.ToDecimal(100),
                        SubscriptionPeriodStripe = period,
                        SubscriptionPeriodLengthInDays = lengthOfDays,
                        //league id is the ownerId
                        InternalObject = leagueId
                    });

                    custDb.TrialEnd = cust.TrialEnd;
                    custDb.TrialStart = cust.TrialStart;

                    dc.StripeSubscriptions.Add(custDb);
                    even.Subscription = custDb;
                }
                dc.StripeEvents.Add(even);
                dc.SaveChanges();

                f.FinalizeInvoice();

                EmailServer.EmailServer.SendEmail(ServerConfig.DEFAULT_EMAIL, ServerConfig.DEFAULT_EMAIL_FROM_NAME, ServerConfig.DEFAULT_ADMIN_EMAIL_ADMIN, "STRIPE: New Subscription About to be charged!!", json);
                return true;
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType(), additionalInformation: json);
            }
            return false;
        }
        public ActionResult PayDuesOnlinePayPal()
        {
            try
            {
                if (HttpContext.Request.InputStream != null)
                {
                    Stream stream = HttpContext.Request.InputStream;
                    var ob = Network.LoadObject<DuesSendParams>(ref stream);
                    var mem = MemberCache.GetMemberDisplay(ob.CurrentMemberId);
                    if (ob.UserId == mem.UserId)
                    {
                        var dues2 = DuesFactory.GetDuesCollectionItem(ob.DuesItemId, ob.DuesId, ob.CurrentMemberId);
                        if (dues2 != null)
                        {
                            PaymentGateway pg = new PaymentGateway();

                            var f = pg.StartInvoiceWizard()
                                .Initalize(ServerConfig.RDNATION_STORE_ID, dues2.Currency, PaymentProvider.Paypal, SiteSingleton.Instance.IsPayPalLive, ChargeTypeEnum.DuesItem)
                                .SetInvoiceId(Guid.NewGuid())
                                .AddDuesItem(new Library.Classes.Payment.Classes.Invoice.InvoiceDuesItem
                                {
                                    BasePrice = (decimal)dues2.DuesFees.FirstOrDefault().TotalPaymentNeededFromMember,
                                    WhoPaysFees = dues2.WhoPaysProcessorFeesEnum,
                                    DuesId = dues2.DuesId,
                                    DuesItemId = dues2.DuesFees.FirstOrDefault().DuesItemId,
                                    MemberPaidId = ob.CurrentMemberId,
                                    Name = "Dues For " + dues2.DuesFees.FirstOrDefault().PayBy.ToString("yyyy/MM/dd"),
                                    PaidForDate = dues2.DuesFees.FirstOrDefault().PayBy,
                                    Description = "Dues Payment",
                                })
                                .SetInvoiceContactData(new Library.Classes.Payment.Classes.Invoice.InvoiceContactInfo
                                {
                                    Email = mem.Email,
                                    FirstName = mem.Firstname,
                                    LastName = mem.LastName,
                                    Phone = mem.PhoneNumber,
                                })
                                                    .FinalizeInvoice();

                            //if (f.Status == InvoiceStatus.Paypal_Email_Not_Confirmed)
                            //    return Redirect(Url.Content("~/dues/member/" + duesModel.LeagueOwnerId.ToString().Replace("-", "") + "/" + memberId.ToString().Replace("-", "")) + "?u=" + SiteMessagesEnum.ppldnc.ToString());
                            //else if (f.Status != InvoiceStatus.Failed)
                            //    return Redirect(f.RedirectLink);
                            return Json(f, JsonRequestBehavior.AllowGet);
                        }

                    }
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, GetType());
            }
            return Json(new CreateInvoiceReturn() { Status = InvoiceStatus.Failed });
        }
    public HttpResponseMessage Put([FromBody]Fund funds, string action)
    {
        try
        {
            //paypal Withdraw
            if (action == "withdrawPP")
            {

                var user = Membership.GetUser(Security.CurrentUser.Identity.Name);
                var localFunds = Fund.GetCurrentFundsInformation((Guid)user.ProviderUserKey);
                if (localFunds.ActiveInUserAccount >= funds.AmountToWithdraw)
                {


                    var mem = SiteCache.GetPublicMemberFull(RDN.Library.Classes.Account.User.GetMemberId());
                    PaymentGateway pg = new PaymentGateway();

                    var f = pg.StartInvoiceWizard()
                        .Initalize(RollinNewsConfig.MERCHANT_ID, "USD", PaymentProvider.Paypal, (PaymentMode)Enum.Parse(typeof(PaymentMode), ConfigurationManager.AppSettings["IsPayPalLive"].ToString()), ChargeTypeEnum.RollinNewsWriterPrePayout)
                        .SetInvoiceId(Guid.NewGuid())
                        .AddWriterPayout(new RDN.Library.Classes.Payment.Classes.Invoice.InvoiceWriterPayout
                        {
                            BasePrice = (decimal)funds.AmountToWithdraw,
                            Name = "Rollin News Payout " + DateTime.UtcNow.ToString("yyyy/MM/dd"),
                            PaymentRequestedDateTime = DateTime.UtcNow,
                            PayoutId = Guid.NewGuid(),
                            UserPaidId = (Guid)user.ProviderUserKey,
                            WhoPaysFees = WhoPaysProcessorFeesEnum.Receiver
                        })
                        .SetInvoiceContactData(new RDN.Library.Classes.Payment.Classes.Invoice.InvoiceContactInfo
                        {
                            Email = user.Email,
                            FirstName = mem.Firstname,
                            LastName = mem.LastName,
                            Phone = mem.PhoneNumber,
                        })
                                            .FinalizeInvoice();
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.NotAcceptable);
                }
            }
            //bitcoinWithdraw
            else if (action == "withdrawBc")
            {

            }
            else if (action == "submitEarnings")
            {
                Security.DemandUserHasRight(Rights.AllowedToSetMonthlyEarnings, false);
                PostRepository repo = new PostRepository();
                var posts = repo.GetPostsAndAuthors();
                List<RDN.Library.Classes.RN.Posts.Classes.Post> PostsTemp = new List<RDN.Library.Classes.RN.Posts.Classes.Post>();
                foreach (var p in posts)
                {
                    try
                    {
                        RDN.Library.Classes.RN.Posts.Classes.Post postTemp = new RDN.Library.Classes.RN.Posts.Classes.Post();
                        postTemp.Id = p.Id;
                        postTemp.AuthorUserId = p.AuthorUserId;
                        PostsTemp.Add(postTemp);
                    }
                    catch (Exception exception)
                    {
                        ErrorDatabaseManager.AddException(exception, GetType());
                    }
                }
                MonthlyStatementsFactory statement = new MonthlyStatementsFactory();
                var state = statement.Initialize(Convert.ToDouble(funds.TotalEarningsForMonth), DateTime.UtcNow)
                    .GetPostsThatHadViews()
                    .SetAuthorsForPosts(PostsTemp)
                    .CalculateAndSavePayouts()
                    .SendEmailsToAuthorsAboutPayouts()
                    .ZeroOutMonthlyViews();


            }
            else
            {
                repository.Update(funds);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (UnauthorizedAccessException)
        {
            return Request.CreateResponse(HttpStatusCode.Unauthorized);
        }
        catch (Exception exception)
        {
            ErrorDatabaseManager.AddException(exception, GetType());
            return Request.CreateResponse(HttpStatusCode.InternalServerError);
        }
    }
        public ActionResult PayDuesOnlinePayPal(DuesPortableModel duesModel)
        {
            try
            {
                if (!String.IsNullOrEmpty(Request.Form["DuesItemId"]))
                {
                    Guid memberId = RDN.Library.Classes.Account.User.GetMemberId();
                    var mem = MemberCache.GetMemberDisplay(memberId);
                    var dues2 = DuesFactory.GetDuesCollectionItem(Convert.ToInt64(Request.Form["DuesItemId"]), duesModel.DuesId, memberId);
                    if (dues2 != null)
                    {
                        PaymentGateway pg = new PaymentGateway();

                        var f = pg.StartInvoiceWizard()
                            .Initalize(ServerConfig.RDNATION_STORE_ID, dues2.Currency, PaymentProvider.Paypal, SiteSingleton.Instance.IsPayPalLive, ChargeTypeEnum.DuesItem)
                            .SetInvoiceId(Guid.NewGuid())
                            .AddDuesItem(new Library.Classes.Payment.Classes.Invoice.InvoiceDuesItem
                            {
                                BasePrice = (decimal)dues2.DuesFees.FirstOrDefault().TotalPaymentNeededFromMember,
                                WhoPaysFees = dues2.WhoPaysProcessorFeesEnum,
                                DuesId = dues2.DuesId,
                                DuesItemId = dues2.DuesFees.FirstOrDefault().DuesItemId,
                                MemberPaidId = memberId,
                                Name = "Dues For " + dues2.DuesFees.FirstOrDefault().PayBy.ToString("yyyy/MM/dd"),
                                PaidForDate = dues2.DuesFees.FirstOrDefault().PayBy,
                                Description = "Dues Payment",
                            })
                            .SetInvoiceContactData(new Library.Classes.Payment.Classes.Invoice.InvoiceContactInfo
                            {
                                Email = mem.Email,
                                FirstName = mem.Firstname,
                                LastName = mem.LastName,
                                Phone = mem.PhoneNumber,
                            })
                                                .FinalizeInvoice();
                        if (f.Status == InvoiceStatus.Paypal_Email_Not_Confirmed)
                            return Redirect(Url.Content("~/dues/member/" + duesModel.LeagueOwnerId.ToString().Replace("-", "") + "/" + memberId.ToString().Replace("-", "")) + "?u=" + SiteMessagesEnum.ppldnc.ToString());
                        else if (f.Status != InvoiceStatus.Failed)
                            return Redirect(f.RedirectLink);
                    }
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, GetType());
            }
            return Redirect(Url.Content("~/dues/league/" + duesModel.LeagueOwnerId.ToString().Replace("-", "")) + "?u=" + SiteMessagesEnum.sww.ToString());
        }
        public ActionResult CheckOut(RDN.Store.Models.CheckOut model)
        {
            try
            {
                var shoppingCartId = StoreGateway.GetShoppingCartId(HttpContext);
                if (!shoppingCartId.HasValue)
                {

                    return Redirect(Url.Action("StoreCart"));
                }

                var sg = new StoreGateway();
                var checkout = sg.GetCheckoutData(shoppingCartId.Value, model.MerchantId);
                if (checkout == null || checkout.ShoppingCart.ItemsCount == 0)
                {
                    return Redirect(Url.Action("StoreCart"));

                }

                PaymentProvider paymentProvider;
                if (!Enum.TryParse(model.PaymentProviderId, out paymentProvider))
                {
                    return Redirect(Url.Action("StoreCart"));

                }

                var pg = new PaymentGateway();

                ShippingType shipType = ShippingType.Postal;
                if (checkout.WillPickUpAtStore)
                    shipType = ShippingType.PickUp;

                var invoice = pg.StartInvoiceWizard()
                    .Initalize(checkout.MerchantId, checkout.Currency, paymentProvider, PaymentMode.Live, ChargeTypeEnum.InStorePurchase)
                    .SetShipping(checkout.TotalShipping, shipType)
                    .SetInvoiceId(Guid.NewGuid())
                    .SetNotes(model.Notes)
                    .SetUserId(RDN.Library.Classes.Account.User.GetUserId())
                    .SetShoppingCartId(shoppingCartId.Value);


                if (paymentProvider == PaymentProvider.Stripe)
                {
                    string token = Request.Form["stripeToken"].ToString();
                    invoice.SetStripeTokenId(token);
                }
                var sellersAddress = new InvoiceContactInfo();
                if (shipType == ShippingType.PickUp)
                {
                    if (checkout.SellersAddress != null)
                    {
                        sellersAddress.City = checkout.SellersAddress.City;
                        sellersAddress.Country = checkout.SellersAddress.Country;
                        sellersAddress.CompanyName = checkout.SellersAddress.CompanyName;
                        sellersAddress.State = checkout.SellersAddress.State;
                        sellersAddress.Street = checkout.SellersAddress.Street;
                        sellersAddress.Street2 = checkout.SellersAddress.Street2;
                        sellersAddress.Zip = checkout.SellersAddress.Zip;
                        invoice.SetSellersAddress(sellersAddress);
                    }
                }

                var billingInfo = new InvoiceContactInfo();
                billingInfo.City = model.BillingAddress_City;
                billingInfo.Country = model.BillingAddress_Country;
                billingInfo.Email = model.BillingAddress_Email;
                billingInfo.FirstName = model.BillingAddress_FirstName;
                billingInfo.LastName = model.BillingAddress_LastName;
                billingInfo.Phone = model.BillingAddress_Phone;
                billingInfo.State = model.BillingAddress_State;
                billingInfo.Street = model.BillingAddress_Street;
                billingInfo.Street2 = model.BillingAddress_Street2;
                billingInfo.Zip = model.BillingAddress_Zip;
                if (User.Identity.IsAuthenticated)
                    RDN.Library.Classes.Account.User.AddContactToMember(RDN.Library.Classes.Account.User.GetMemberId(), billingInfo, AddressTypeEnum.Billing);
                if (model.IsBillingDifferentFromShipping)
                {
                    var shippingInfo = new InvoiceContactInfo();
                    shippingInfo.City = model.ShippingAddress_City;
                    shippingInfo.Country = model.ShippingAddress_Country;
                    shippingInfo.Email = model.ShippingAddress_Email;
                    shippingInfo.FirstName = model.ShippingAddress_FirstName;
                    shippingInfo.LastName = model.ShippingAddress_LastName;
                    shippingInfo.Phone = model.ShippingAddress_Phone;
                    shippingInfo.State = model.ShippingAddress_State;
                    shippingInfo.Street = model.ShippingAddress_Street;
                    shippingInfo.Street2 = model.ShippingAddress_Street2;
                    shippingInfo.Zip = model.ShippingAddress_Zip;
                    invoice.SetInvoiceContactData(billingInfo, shippingInfo);

                    if (User.Identity.IsAuthenticated)
                        RDN.Library.Classes.Account.User.AddContactToMember(RDN.Library.Classes.Account.User.GetMemberId(), shippingInfo, AddressTypeEnum.Shipping);

                }
                else
                    invoice.SetInvoiceContactData(billingInfo, billingInfo);


                foreach (var cartitem in checkout.ShoppingCart.Stores.FirstOrDefault().StoreItems)
                {
                    var item = new InvoiceItem();
                    item.ArticleNumber = cartitem.ArticleNumber;
                    item.Article2Number = cartitem.Article2Number;
                    item.Description = "Tax Included in Price: " + cartitem.Description;
                    item.Name = cartitem.Name;
                    item.BasePrice = cartitem.BasePrice + cartitem.BaseTaxOnItem;
                    item.Price = cartitem.Price;
                    item.TotalShipping = cartitem.Shipping;
                    item.Quantity = cartitem.QuantityOrdered;
                    item.Weight = cartitem.Weight;
                    item.SizeOfItem = cartitem.ItemSizeEnum;
                    item.ColorOfItem = cartitem.ColorAGB;
                    item.StoreItemId = cartitem.StoreItemId;
                    invoice.AddItemTaxIncluded(item);
                }

                var requestResponse = invoice.FinalizeInvoice();
                if (requestResponse.Error != null)
                    throw new Exception(requestResponse.Error);

                this.ClearCart(HttpContext.Session);

                if (requestResponse.Status == InvoiceStatus.Payment_Successful)
                    return Redirect(Url.Content("~/receipt/" + requestResponse.InvoiceId.ToString().Replace("-", "")));
                else if (requestResponse.Status == InvoiceStatus.Pending_Payment_From_Paypal)
                    return Redirect(requestResponse.RedirectLink);
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
        }
        public void CheckOut(CheckOut model)
        {
            var shoppingCartId = GetShoppingCartId();
            if (!shoppingCartId.HasValue)
            {
                Response.Redirect(Url.Action("ViewRDNStore"));
                return;
            }

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

            PaymentProvider paymentProvider;
            if (!Enum.TryParse(model.PaymentProviderId, out paymentProvider))
            {
                Response.Redirect(Url.Action("ViewRDNStore"));
                return;
            }
            int shippingId;
            if (!Int32.TryParse(model.ShippingOptionSelectedId, out shippingId))
            {
                Response.Redirect(Url.Action("ViewRDNStore"));
                return;
            }

            var pg = new PaymentGateway();

            var invoice = pg.StartInvoiceWizard()
                .Initalize(checkout.MerchantId, checkout.Currency, paymentProvider, PaymentMode.Live, ChargeTypeEnum.InvoiceItem)
                .SetShipping(checkout.TotalShipping, ShippingType.Postal)
                .SetInvoiceId(checkout.ShoppingCart.ShoppingCartId);

            var billingInfo = new InvoiceContactInfo();
            billingInfo.City = model.BillingAddress.City;
            billingInfo.CompanyName = model.BillingAddress.CompanyName;
            billingInfo.Country = model.BillingAddress.Country;
            billingInfo.Email = model.BillingAddress.Email;
            billingInfo.Fax = model.BillingAddress.Fax;
            billingInfo.FirstName = model.BillingAddress.FirstName;
            billingInfo.LastName = model.BillingAddress.LastName;
            billingInfo.Phone = model.BillingAddress.Phone;
            billingInfo.State = model.BillingAddress.State;
            billingInfo.Street = model.BillingAddress.Street;
            billingInfo.Street2 = model.BillingAddress.Street2;
            billingInfo.Zip = model.BillingAddress.Zip;

            var shippingInfo = new InvoiceContactInfo();
            shippingInfo.City = model.ShippingAddress.City;
            shippingInfo.CompanyName = model.ShippingAddress.CompanyName;
            shippingInfo.Country = model.ShippingAddress.Country;
            shippingInfo.Email = model.ShippingAddress.Email;
            shippingInfo.Fax = model.ShippingAddress.Fax;
            shippingInfo.FirstName = model.ShippingAddress.FirstName;
            shippingInfo.LastName = model.ShippingAddress.LastName;
            shippingInfo.Phone = model.ShippingAddress.Phone;
            shippingInfo.State = model.ShippingAddress.State;
            shippingInfo.Street = model.ShippingAddress.Street;
            shippingInfo.Street2 = model.ShippingAddress.Street2;
            shippingInfo.Zip = model.ShippingAddress.Zip;
            invoice.SetInvoiceContactData(billingInfo, shippingInfo);

            //foreach (var cartitem in checkout.ShoppingCart.Items)
            //{
            //    var item = new InvoiceItem();
            //    item.ArticleNumber = cartitem.ArticleNumber;
            //    item.Article2Number = cartitem.Article2Number;
            //    item.Description = cartitem.Description;
            //    item.Name = cartitem.Name;
            //    item.BasePrice = cartitem.BasePrice;
            //    item.Price = cartitem.Price;
            //    item.Quantity = cartitem.QuantityOrdered;
            //    item.Weight = cartitem.Weight;
            //    invoice.AddItem(item);
            //}

            invoice.SetTax(checkout.TaxRate);

            var requestResponse = invoice.FinalizeInvoice();
            if (requestResponse.Error != null)
                throw new Exception(requestResponse.Error);

            Response.Redirect(requestResponse.RedirectLink);
        }
        public ActionResult LeagueAddSubscription(AddSubscriptionModel add)
        {
            var memId = RDN.Library.Classes.Account.User.GetMemberId();

            try
            {
                string paymentProvider = Request.Form["PaymentType"].ToString();
                string articleNumberForSubscription = "none";

                PaymentProvider provider = PaymentProvider.None;
                if (paymentProvider == PaymentProvider.Stripe.ToString())
                {
                    provider = PaymentProvider.Stripe;
                    articleNumberForSubscription = Request.Form["stripeToken"].ToString();
                }
                else if (paymentProvider == PaymentProvider.Paypal.ToString())
                {
                    provider = PaymentProvider.Paypal;
                }
                string subType = Request.Form["SubscriptionType"].ToString();
                LeaguePlanTypesEnum sub = (LeaguePlanTypesEnum)Enum.Parse(typeof(LeaguePlanTypesEnum), subType);
                decimal price = 15.99M;
                SubscriptionPeriodStripe subStripe = SubscriptionPeriodStripe.Monthly;
                int lengthOfDays = 31;
                DateTime now = DateTime.UtcNow;
                TimeSpan ts = new TimeSpan();
                if (sub == LeaguePlanTypesEnum.One_Month)
                {
                    price = 15.99M;
                    subStripe = SubscriptionPeriodStripe.Monthly;
                    ts = now.AddMonths(1) - DateTime.UtcNow;
                    lengthOfDays = ts.Days;
                }
                else if (sub == LeaguePlanTypesEnum.Six_Months)
                {
                    price = 71.99M;
                    subStripe = SubscriptionPeriodStripe.Six_Months;
                    ts = now.AddMonths(6) - DateTime.UtcNow;
                    lengthOfDays = ts.Days;
                }
                else if (sub == LeaguePlanTypesEnum.Three_Months)
                {
                    price = 41.99M;
                    subStripe = SubscriptionPeriodStripe.Three_Months;
                    ts = now.AddMonths(3) - DateTime.UtcNow;
                    lengthOfDays = ts.Days;
                }
                else if (sub == LeaguePlanTypesEnum.Twelve_Months)
                {
                    price = 131.99M;
                    subStripe = SubscriptionPeriodStripe.Yearly;
                    ts = now.AddMonths(12) - DateTime.UtcNow;
                    lengthOfDays = ts.Days;
                }


                PaymentGateway pg = new PaymentGateway();
                var f = pg.StartInvoiceWizard().Initalize(ServerConfig.RDNATION_STORE_ID, "USD", provider, SiteSingleton.Instance.IsPayPalLive, ChargeTypeEnum.Subscription)
                    .SetInvoiceId(Guid.NewGuid())
                    .SetSubscription(new InvoiceSubscription
                    {
                        ArticleNumber = articleNumberForSubscription,
                        Description = "RDN League portal subscription",
                        DescriptionRecurring = "Fee for RDN League portal subscription",
                        Name = "RDN Member portal",
                        NameRecurring = "RDN Member portal recurring",
                        DigitalPurchaseText = "You have now access to RDN League portal",
                        Price = price,
                        SubscriptionPeriodStripe = subStripe,
                        SubscriptionPeriodLengthInDays = lengthOfDays,
                        //ValidUntil = subScriptionDate.AddDays(lengthOfDays),
                        //league id is the ownerId
                        InternalObject = add.AddSubscriptionOwnerId
                    })
                    .SetInvoiceContactData(new InvoiceContactInfo
                    {
                        City = add.City,
                        Country = add.Country,
                        Email = add.EmailAddress,
                        FirstName = add.FirstName,
                        LastName = add.LastName,
                        Phone = add.PhoneNumber,
                        State = add.State,
                        Street = add.Address,
                        Zip = add.ZipCode
                    })
                        .FinalizeInvoice();

                //clears the member cache to update all cache repos of the league members.
                MemberCache.ClearLeagueMembersCache(add.AddSubscriptionOwnerId);
                MemberCache.ClearLeagueMembersApiCache(add.AddSubscriptionOwnerId);
                //succesfully charged.
                if (f.Status == InvoiceStatus.Subscription_Running)
                    return Redirect(Url.Content("~/billing/league/receipt/" + f.InvoiceId.ToString().Replace("-", "")));
                else if (f.Status == InvoiceStatus.Pending_Payment_From_Paypal)
                    return Redirect(f.RedirectLink);
                else if (f.Status == InvoiceStatus.Card_Was_Declined)
                {
                    SiteMessage message = new SiteMessage();
                    message.MessageType = SiteMessageType.Error;
                    message.Message = "Your Card has been Declined.  Please check the information and try again.";
                    this.AddMessage(message);
                }


            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            add.AddSubscriptionOwnerId = add.AddSubscriptionOwnerId;
            var league = RDN.Library.Classes.League.LeagueFactory.GetLeague(add.AddSubscriptionOwnerId);
            if (league != null)
                add.AddSubscriptionOwnerName = league.Name;
            Dictionary<int, string> countries = LocationFactory.GetCountriesDictionary();
            add.Countries = countries.Select(item => new SelectListItem { Text = item.Value, Value = item.Key.ToString() }).ToList();
            add.Years = EnumExt.ToSelectListId(YearsEnum.Fourteen);
            add.Months = EnumExt.ToSelectListIdAndName(MonthsEnum.Jan);
            //#if DEBUG
            //                add.StripeKey = "Stripe.setPublishableKey('" + ServerConfig.STRIPE_DEBUG_KEY + "');";
            //#else
            add.StripeKey = "Stripe.setPublishableKey('" + ServerConfig.STRIPE_LIVE_KEY + "');";
            //#endif
            return View(add);
        }
        public ActionResult LeagueCancelSubscription(LeagueBilling add)
        {
            var memId = RDN.Library.Classes.Account.User.GetMemberId();

            try
            {
                var bi = RDN.Library.Classes.Billing.Classes.LeagueBilling.GetCurrentBillingStatus(add.LeagueId);

                PaymentGateway pg = new PaymentGateway();
                var f = pg.StartInvoiceWizard().Initalize(ServerConfig.RDNATION_STORE_ID, "USD", PaymentProvider.Stripe, PaymentMode.Live, ChargeTypeEnum.Cancel_Subscription)
                   .SetInvoiceId(bi.InvoiceId)
                        .FinalizeInvoice();

                //clears the member cache to update all cache repos of the league members.
                MemberCache.ClearLeagueMembersCache(add.LeagueId);
                MemberCache.ClearLeagueMembersApiCache(add.LeagueId);
                //succesfully charged.
                if (f.Status == InvoiceStatus.Cancelled)
                    return Redirect(Url.Content("~/billing/league/" + add.LeagueId.ToString().Replace("-", "") + "?u=" + SiteMessagesEnum.sc));
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            return Redirect(Url.Content("~/?u=" + SiteMessagesEnum.sww));
        }