public int Add(CustomerInfos entity)
        {
            using (var transaction = new TransactionScope())
            {
                DayaxeDbContext.CustomerInfos.InsertOnSubmit(entity);
                Commit();

                var customerCredits = new CustomerCredits
                {
                    Amount                 = 0,
                    CreatedDate            = DateTime.UtcNow,
                    CustomerId             = entity.CustomerId,
                    IsActive               = false,
                    IsDelete               = false,
                    FirstRewardForOwner    = 5,
                    FirstRewardForReferral = 5,
                    LastUpdatedDate        = DateTime.UtcNow,
                    ReferralCode           = Helper.RandomString(8),
                    ReferralCustomerId     = 0
                };

                DayaxeDbContext.CustomerCredits.InsertOnSubmit(customerCredits);
                Commit();
                transaction.Complete();

                return(entity.CustomerId);
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            if (PublicCustomerInfos == null)
            {
                var loginLinkButton = (HtmlAnchor)ControlExtensions.FindControlRecursive(Master, "LoginLinkButton");
                loginLinkButton.Visible = false;
                Response.Redirect(string.Format(Constant.SignIpPage, HttpUtility.UrlEncode(Request.Url.PathAndQuery)));
            }
            _customerCredits = _crRepository.GetById(PublicCustomerInfos.CustomerId);

            if (!IsPostBack)
            {
                if (_customerCredits == null)
                {
                    SendToFriendButton.Text = "Add";
                }
                ReferralCodeLit.Text       = _customerCredits != null ? _customerCredits.ReferralCode : "N/A";
                TotalCreditLit.Text        = Helper.FormatPrice(_customerCredits != null ? _customerCredits.Amount : 0);
                EnjoyFreeDayCationLit.Text = string.Format(ErrorMessage.EnjoyDayCations,
                                                           Helper.FormatPrice(_customerCredits != null ? _customerCredits.FirstRewardForOwner : 0),
                                                           Helper.FormatPrice(_customerCredits != null ? _customerCredits.FirstRewardForOwner : 0));

                RebindLogs();
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var multiView = (MultiView)AuthControl.FindControl("AuthMultiView");
                if (Request.Params["sp"] != null &&
                    (Session["UserSession"] == null || (Session["UserSession"] != null && string.Equals(Request.Params["sp"], (string)Session["UserSession"], StringComparison.OrdinalIgnoreCase))) &&
                    multiView != null)
                {
                    ShowAuth = true;
                    multiView.ActiveViewIndex = 3;
                }

                if (Request.Params["reg"] != null &&
                    string.Equals(Request.Params["reg"], "true", StringComparison.OrdinalIgnoreCase) &&
                    Session["UserSession"] == null &&
                    multiView != null)
                {
                    multiView.ActiveViewIndex = 0;
                    ShowAuth = true;
                }
            }

            if (PublicCustomerInfos != null)
            {
                PublicCustomerCredits = _customerCreditRepository.GetById(PublicCustomerInfos.CustomerId);
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            if (Page.RouteData.Values["hotelName"] != null &&
                Page.RouteData.Values["productName"] != null)
            {
                _products = _productRepository.GetProductsByName((string)Page.RouteData.Values["hotelName"],
                                                                 (string)Page.RouteData.Values["productName"],
                                                                 (string)Session["UserSession"]);
                _hotel = _productRepository.HotelList.First(h => h.HotelId == _products.ProductId);
            }

            if (Session[Constant.UpgradeKey] != null)
            {
                int bookingsTempId = int.Parse(Session[Constant.UpgradeKey].ToString());
                _bookingTemp = _productRepository.GetBookingsTempById(bookingsTempId);
            }

            if (!IsPostBack)
            {
                List <Products> availableUpgradeProducts = _productRepository.GetAvailbleUpgradeProducts(_products.ProductId, _bookingTemp.Item1.CheckinDate);
                const String    mixpanelscript           = "MixpanelScript";
                string          strScript = string.Empty;
                availableUpgradeProducts.ForEach(item =>
                {
                    string strUrl = string.Format("/{0}/{1}/{2}/{3}-",
                                                  Page.RouteData.Values["market"],
                                                  Page.RouteData.Values["city"],
                                                  Page.RouteData.Values["hotelName"],
                                                  item.ProductName.Trim().Replace(" ", "-").ToLower());
                    switch (item.ProductType)
                    {
                    case (int)Enums.ProductType.SpaPass:
                        strUrl += "spa-pass";
                        break;

                    case (int)Enums.ProductType.Daybed:
                        strUrl += "daybeds";
                        break;

                    default:
                        strUrl += "cabanas";
                        break;
                    }
                    strScript += Helper.GetMixpanelScriptRedirect(item.ProductId, strUrl);
                });
                if (!string.IsNullOrEmpty(strScript))
                {
                    ScriptManager.RegisterClientScriptBlock(HotelList, typeof(string), mixpanelscript, strScript, true);
                }

                LvHotelRepeater.DataSource = availableUpgradeProducts;
                LvHotelRepeater.DataBind();
            }

            if (PublicCustomerInfos != null)
            {
                _customerCredits = _customerCreditRepository.GetById(PublicCustomerInfos.CustomerId);
            }
        }
        protected void ApplyPromoClick(object sender, EventArgs e)
        {
            rowMessage.Visible = false;
            MessageLabel.Text  = string.Empty;
            if (string.IsNullOrEmpty(PromoText.Text))
            {
                InitDefaultPromo(Message.InvalidOrExpiredPromo, false);
                return;
            }

            if (PublicCustomerCredits == null)
            {
                InitDefaultPromo(ErrorMessage.YouMustLogIn, false);
                return;
            }

            var giftCard = _customerCreditRepository.GetGiftCardByCode(PromoText.Text.Trim());

            if (giftCard != null)
            {
                if (PublicCustomerCredits == null)
                {
                    InitDefaultPromo(ErrorMessage.YouMustLogIn, false);
                    return;
                }

                if (giftCard.Status == (short)Enums.GiftCardType.Used)
                {
                    InitDefaultPromo(ErrorMessage.GiftCardHasBeenUsed, false);
                    return;
                }

                if (!string.IsNullOrEmpty(giftCard.EmailAddress) &&
                    !PublicCustomerInfos.EmailAddress.Equals(giftCard.EmailAddress, StringComparison.OrdinalIgnoreCase))
                {
                    InitDefaultPromo(ErrorMessage.PleaseCheckYourGiftCardWithCurrentAccount, false);
                    return;
                }

                _customerCreditRepository.AddGiftCard(PublicCustomerCredits, PromoText.Text.Trim());
                PublicCustomerCredits = _customerCreditRepository.Refresh(PublicCustomerCredits);
                CacheLayer.Clear(CacheKeys.GiftCardCacheKey);
                CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);
                CacheLayer.Clear(CacheKeys.CustomerCreditLogsCacheKey);
                BindeGiftCardInfos();
                InitDefaultPromo(ErrorMessage.GiftCardHasBeenApplied);
                BookProductUpdatePanel.Update();
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            Session["Active"] = "SearchBookingsList";
            string sessionUser = Session["CurrentUser"] != null ? Session["CurrentUser"].ToString() : string.Empty;

            PublicUser = JsonConvert.DeserializeObject <CustomerInfos>(sessionUser);
            if (PublicUser == null)
            {
                Response.Redirect(Constant.DefaultPage);
            }

            int customerId;

            int.TryParse(Request.Params["id"], out customerId);
            CurrentCustomerId = customerId;
            _currentData      = _customerCreditRepository.GetAllLogsByCustomerId(CurrentCustomerId).ToList();

            _customerCredits = _customerCreditRepository.GetById(CurrentCustomerId);

            if (!IsPostBack)
            {
                Session["CurrentPage"] = 1;
                CustomerInfosDetails   = _customerInfoRepository.GetById(CurrentCustomerId);

                string json = JsonConvert.SerializeObject(CustomerInfosDetails, CustomSettings.SerializerSettings());
                Session["CustomerInfosDetails"] = json;
                BindRepeater(_currentData.Take(10));
            }
            else
            {
                string session = Session["CustomerInfosDetails"] != null ? Session["CustomerInfosDetails"].ToString() : string.Empty;
                CustomerInfosDetails = JsonConvert.DeserializeObject <CustomerInfos>(session);
            }

            if (CustomerInfosDetails == null)
            {
                Response.Redirect(Constant.SearchBookingsAdminpage);
            }

            BindCustomerData();
        }
        public void Update(CustomerInfos entity)
        {
            using (var transaction = new TransactionScope())
            {
                var update = DayaxeDbContext.CustomerInfos.SingleOrDefault(x => x.CustomerId == entity.CustomerId);
                if (update != null)
                {
                    update.IsActive      = entity.IsActive;
                    update.IsAdmin       = entity.IsAdmin;
                    update.IsDelete      = entity.IsDelete;
                    update.FirstName     = entity.FirstName;
                    update.LastName      = entity.LastName;
                    update.Password      = entity.Password;
                    update.EmailAddress  = entity.EmailAddress;
                    update.IsCheckInOnly = entity.IsCheckInOnly;

                    var customerCredit = DayaxeDbContext.CustomerCredits.SingleOrDefault(cc => cc.CustomerId == entity.CustomerId);
                    if (customerCredit == null)
                    {
                        var customerCredits = new CustomerCredits
                        {
                            Amount                 = 0,
                            CreatedDate            = DateTime.UtcNow,
                            CustomerId             = entity.CustomerId,
                            IsActive               = false,
                            IsDelete               = false,
                            FirstRewardForOwner    = 5,
                            FirstRewardForReferral = 5,
                            LastUpdatedDate        = DateTime.UtcNow,
                            ReferralCode           = Helper.RandomString(8),
                            ReferralCustomerId     = 0
                        };

                        DayaxeDbContext.CustomerCredits.InsertOnSubmit(customerCredits);
                    }
                }
                Commit();
                transaction.Complete();
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            if (Page.RouteData.Values["SubscriptionId"] != null)
            {
                int id;
                int.TryParse((string)Page.RouteData.Values["SubscriptionId"], out id);
                PublicSubscription = _subscriptionRepository.GetById(id);
            }

            //goBack.HRef = AppConfiguration.LandingPageSubscription;

            if (!IsPostBack)
            {
                hotelname.Text    = PublicSubscription.Name;
                Neighborhood.Text = PublicSubscription.ProductHighlight;

                var multiView = (MultiView)AuthControl.FindControl("AuthMultiView");
                if (Request.Params["sp"] != null &&
                    (Session["UserSession"] == null || (Session["UserSession"] != null && string.Equals(Request.Params["sp"], (string)Session["UserSession"], StringComparison.OrdinalIgnoreCase))) &&
                    multiView != null)
                {
                    ShowAuth = true;
                    multiView.ActiveViewIndex = 3;
                }

                if (Request.Params["reg"] != null &&
                    string.Equals(Request.Params["reg"], "true", StringComparison.OrdinalIgnoreCase) &&
                    Session["UserSession"] == null &&
                    multiView != null)
                {
                    multiView.ActiveViewIndex = 0;
                    ShowAuth = true;
                }
            }

            if (PublicCustomerInfos != null)
            {
                PublicCustomerCredits = _customerCreditRepository.GetById(PublicCustomerInfos.CustomerId);
            }
        }
        protected void SendToFriendButton_OnClick(object sender, EventArgs e)
        {
            if (_customerCredits == null)
            {
                _customerCredits = new CustomerCredits
                {
                    Amount                 = 0,
                    CreatedDate            = DateTime.UtcNow,
                    CustomerId             = PublicCustomerInfos.CustomerId,
                    FirstRewardForOwner    = 5,
                    FirstRewardForReferral = 5,
                    IsActive               = true,
                    IsDelete               = false,
                    LastUpdatedDate        = DateTime.UtcNow,
                    ReferralCode           = Helper.RandomString(8)
                };

                _crRepository.Add(_customerCredits);
            }

            CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerCreditLogsCacheKey);
        }
        protected void ApplyPromoClick(object sender, EventArgs e)
        {
            rowMessage.Visible      = false;
            msrp.Visible            = false;
            MessageLabel.Text       = string.Empty;
            LitDisclaimer.Text      = string.Format(Message.TermWithPromo, string.Empty);
            discountInfoRow.Visible = false;
            bool isLimit;

            if (string.IsNullOrEmpty(PromoText.Text))
            {
                InitDefaultPromo(Message.InvalidOrExpiredPromo, false);
                return;
            }

            var  giftCard   = _customerCreditRepository.GetGiftCardByCode(PromoText.Text.Trim());
            bool isGiftCard = giftCard != null;

            if (giftCard != null)
            {
                if (PublicCustomerCredits == null)
                {
                    InitDefaultPromo(ErrorMessage.YouMustLogIn, false);
                    return;
                }

                if (giftCard.Status == (short)Enums.GiftCardType.Used)
                {
                    InitDefaultPromo(ErrorMessage.GiftCardHasBeenUsed, false);
                    return;
                }

                if (!string.IsNullOrEmpty(giftCard.EmailAddress) &&
                    !PublicCustomerInfos.EmailAddress.Equals(giftCard.EmailAddress, StringComparison.OrdinalIgnoreCase))
                {
                    InitDefaultPromo(ErrorMessage.PleaseCheckYourGiftCardWithCurrentAccount, false);
                    return;
                }

                _customerCreditRepository.AddGiftCard(PublicCustomerCredits, PromoText.Text.Trim());
                PublicCustomerCredits = _customerCreditRepository.Refresh(PublicCustomerCredits);
                CacheLayer.Clear(CacheKeys.GiftCardCacheKey);
                CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);
                CacheLayer.Clear(CacheKeys.CustomerCreditLogsCacheKey);
                BindSubscriptionInfos();
                InitDefaultPromo(ErrorMessage.GiftCardHasBeenApplied);
                BookProductUpdatePanel.Update();
            }

            if (!isGiftCard)
            {
                var param = new GetDiscountValidByCodeParams
                {
                    Code           = PromoText.Text.Trim(),
                    SubscriptionId = PublicSubscription.Id,
                    CustomerId     = PublicCustomerInfos != null ? PublicCustomerInfos.CustomerId : 0,
                    IsAdmin        = false,
                    BookingId      = 0
                };

                Discounts discounts = _discountRepository.GetDiscountValidByCode(param, out isLimit);
                if (discounts == null)
                {
                    InitDefaultPromo(isLimit ? Message.ExceedLimit : Message.InvalidOrExpiredPromo, false);
                    return;
                }

                if (discounts.MinAmount > PublicSubscription.Price * TotalTickets)
                {
                    InitDefaultPromo(ErrorMessage.MinAmountNotMatch, false);
                    return;
                }

                double actualPrice = NormalPrice;
                actualPrice = Helper.CalculateDiscount(discounts, actualPrice, TotalTickets);

                if (!actualPrice.Equals(NormalPrice))
                {
                    msrp.Visible       = true;
                    msrpPrice.Text     = Helper.FormatPrice(NormalPrice * TotalTickets);
                    LitDisclaimer.Text = string.Format(Message.TermWithPromo, Message.PeriodString);
                }

                moneyPrice.Text    = Helper.FormatPrice(actualPrice * TotalTickets);
                perMoneyPrice.Text = Helper.FormatPrice(actualPrice);

                string json = JsonConvert.SerializeObject(discounts, CustomSettings.SerializerSettings());
                Session[_discountKey] = json;
                BindSubscriptionInfos();
            }
        }
        private int PurchaseSubscription(out bool success)
        {
            // Check customer change their email
            success = true;
            bool isPayByCredit;

            var bookingExists = _subscriptionBookingRepository.GetBookingInLast3Minutes(PublicSubscription.Id,
                                                                                        PublicCustomerInfos != null ? PublicCustomerInfos.EmailAddress : email.Text.Replace(" ", ""));

            if (bookingExists != null)
            {
                success = false;
                newBookingModal.Visible = true;
                return(bookingExists.Id);
            }

            if (PublicCustomerInfos == null)
            {
                PublicCustomerInfos = new CustomerInfos
                {
                    EmailAddress = email.Text.Replace(" ", ""),
                    FirstName    = FirstName.Text.Trim(),
                    LastName     = LastName.Text.Trim(),
                    ZipCode      = txtzipcode.Text.Trim()
                };

                // Create new account with email
                var response = _customerInfoRepository.GetVipAccess(email.Text.Replace(" ", ""), Constant.SearchPageDefault, FirstName.Text.Trim(), LastName.Text.Trim());
                PublicCustomerInfos.CustomerId       = response.CustomerId;
                PublicCustomerInfos.StripeCustomerId = response.StripeCustomerId;

                CacheLayer.Clear(CacheKeys.CustomerInfosCacheKey);
                CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);

                Session["ReferralCode"] = response.ReferralCode;

                string searchPage = !string.IsNullOrEmpty((string)Session["SearchPage"])
                    ? Session["SearchPage"].ToString()
                    : Constant.SearchPageDefault;

                // Send email new account
                var responseEmail = EmailHelper.EmailNewAccount(PublicCustomerInfos.EmailAddress,
                                                                PublicCustomerInfos.FirstName,
                                                                response.Password,
                                                                Helper.ResolveRelativeToAbsoluteUrl(Request.Url,
                                                                                                    string.Format("{0}?sp={1}",
                                                                                                                  searchPage,
                                                                                                                  response.PasswordKey)), // Reset Password Url
                                                                Helper.ResolveRelativeToAbsoluteUrl(Request.Url,
                                                                                                    string.Format("{0}?c={1}",
                                                                                                                  searchPage,
                                                                                                                  response.AccessKey))); // Browse Day Pass
                PublicCustomerCredits = _subscriptionBookingRepository.GetCustomerCredits(response.CustomerId);


                Session["UserSession"]  = response.AccessKey;
                Session["IsRegister"]   = true;
                Session["ReferralCode"] = response.ReferralCode;
            }

            Regex regex = new Regex(@"([\d]+)(\s)?/(\s)?([\d]+)");
            int   month;
            int   year;

            int.TryParse(regex.Match(txtexpdat.Value).Groups[1].Value, out month);
            int.TryParse("20" + regex.Match(txtexpdat.Value).Groups[4].Value, out year);
            string fullName = string.Format("{0} {1}", FirstName.Text, LastName.Text);

            // Check customer has exists with email
            int            customerId     = PublicCustomerInfos.CustomerId;
            StripeCustomer stripeCustomer = null;
            Discounts      discounts      = new Discounts();
            double         actualPrice    = PublicSubscription.Price;
            double         totalPrice;
            bool           hasCoupon      = false;
            string         stripeCouponId = string.Empty;

            // update user info with exists
            if (!string.IsNullOrEmpty(PublicCustomerInfos.StripeCustomerId))
            {
                stripeCustomer = GetCustomerById(PublicCustomerInfos.StripeCustomerId);
            }

            // Use New Card
            if (MVCardInfo.ActiveViewIndex == 0)
            {
                StripeToken stripeToken = CreateToken(cctextbox.Text.Replace(" ", ""), year, month, txtzipcode.Text,
                                                      fullName,
                                                      txtseccode.Value);

                // update new card for customer
                PublicCustomerInfos.StripeTokenId    = stripeToken.Id;
                PublicCustomerInfos.StripeCardId     = stripeToken.StripeCard.Id;
                PublicCustomerInfos.BankAccountLast4 = stripeToken.StripeCard.Last4;
                PublicCustomerInfos.CardType         = Helper.GetCreditCardType(cctextbox.Text.Replace(" ", ""));
                PublicCustomerInfos.ZipCode          = txtzipcode.Text;

                if (stripeCustomer == null)
                {
                    stripeCustomer = CreateCustomer(PublicCustomerInfos.EmailAddress, fullName, stripeToken.Id);
                    PublicCustomerInfos.StripeCustomerId = stripeCustomer.Id;
                }
                else
                {
                    // Update Stripe exists customer with New Card
                    var card = CreateCard(stripeToken.Id, PublicCustomerInfos.StripeCustomerId);
                    UpdateCustomer(PublicCustomerInfos.EmailAddress, fullName,
                                   PublicCustomerInfos.StripeCustomerId, card.Id);
                }
                _customerInfoRepository.Update(PublicCustomerInfos);

                isPayByCredit = IsPayByCreditCheckBox.Checked;
            }
            else
            {
                isPayByCredit = DCreditCheckBox.Checked;
            }

            if (string.IsNullOrWhiteSpace(PromoText.Text))
            {
                Session.Remove(_discountKey);
            }

            // Not available upgrade so checkout with this hotel
            if (Session[_discountKey] != null)
            {
                discounts = JsonConvert.DeserializeObject <Discounts>(Session[_discountKey].ToString());
            }

            // Have Discount
            if (discounts != null && discounts.Id > 0)
            {
                discounts = _discountRepository.VerifyDiscountsSubscription(discounts, customerId, PublicSubscription.Id);

                // Discount Invalid
                if (discounts != null)
                {
                    actualPrice = Helper.CalculateDiscount(discounts, actualPrice, TotalTickets);
                    hasCoupon   = true;
                }
                else
                {
                    InitDefaultPromo(Message.ExceedLimit, false);
                    Session[_discountKey] = null;
                    success = false;
                    return(0);
                }

                if (discounts.BillingCycleNumber > 1)
                {
                    stripeCouponId = string.Format("{0}C{1}", PublicCustomerInfos.CustomerId,
                                                   Helper.RandomString(Constant.BookingCodeLength));
                    if (discounts.PercentOff > 0)
                    {
                        var couponPrice = PublicSubscription.Price - actualPrice;
                        //Create the Coupon
                        var coupon = new StripeCouponCreateOptions
                        {
                            Duration         = "repeating",
                            Id               = stripeCouponId,
                            MaxRedemptions   = discounts.BillingCycleNumber,
                            DurationInMonths = discounts.BillingCycleNumber
                        };


                        if (discounts.PromoType == (int)Enums.PromoType.Fixed)
                        {
                            coupon.AmountOff = (int)(couponPrice * 100);
                            coupon.Currency  = "usd";
                        }

                        if (discounts.PromoType == (int)Enums.PromoType.Percent)
                        {
                            coupon.PercentOff = (int)(discounts.PercentOff);
                        }

                        //coupon.AmountOff - AmountOff is not a property of StripeCouponCreateOptions
                        var          couponService = new StripeCouponService();
                        StripeCoupon createdCoupon = couponService.Create(coupon);

                        //Apply it to the customer
                        var customerOptions = new StripeCustomerUpdateOptions
                        {
                            Coupon = createdCoupon.Id
                        };

                        var customerService = new StripeCustomerService();
                        customerService.Update(PublicCustomerInfos.StripeCustomerId, customerOptions);
                    }
                }
            }

            if (PublicCustomerInfos.FirstName != FirstName.Text.Trim() || PublicCustomerInfos.LastName != LastName.Text.Trim())
            {
                PublicCustomerInfos.FirstName = FirstName.Text.Trim();
                PublicCustomerInfos.LastName  = LastName.Text.Trim();
                _customerInfoRepository.Update(PublicCustomerInfos);

                // Update Stripe exists customer
                UpdateCustomer(PublicCustomerInfos.EmailAddress, fullName, PublicCustomerInfos.StripeCustomerId, string.Empty);
            }

            // Discount 100% ??
            // Price equal 0, so we should not charge with this
            totalPrice = actualPrice * TotalTickets;
            double chargePrice          = totalPrice;
            string creditLogDescription = string.Empty;

            var subscriptionOptions = new StripeSubscriptionCreateOptions
            {
                PlanId = PublicSubscription.StripePlanId
            };

            // Use DayAxe Credit
            if (isPayByCredit && PublicCustomerCredits != null && PublicCustomerCredits.Amount > 0)
            {
                hasCoupon = true;

                chargePrice = totalPrice - PublicCustomerCredits.Amount;
                if (chargePrice <= 0)
                {
                    chargePrice = 0;
                }
            }

            if (hasCoupon && string.IsNullOrEmpty(stripeCouponId))
            {
                var couponPrice = PublicSubscription.Price - chargePrice;
                if (couponPrice > 0)
                {
                    // Create Coupon Id because we used DayAxe Credit
                    stripeCouponId = string.Format("{0}C{1}", PublicCustomerInfos.CustomerId,
                                                   Helper.RandomString(Constant.BookingCodeLength));
                    var couponOptions = new StripeCouponCreateOptions
                    {
                        Id        = stripeCouponId,
                        AmountOff = Convert.ToInt32(couponPrice * 100), // USD
                        Duration  = "once",
                        Currency  = "USD"
                    };

                    // Create Coupon
                    var couponService = new StripeCouponService();
                    var coupon        = couponService.Create(couponOptions);

                    subscriptionOptions.CouponId = stripeCouponId;

                    creditLogDescription = string.Format("{0} – {1}",
                                                         PublicSubscription.Name, coupon.Id);
                }
            }

            // Create Subscription on Stripe
            var subscriptionService         = new StripeSubscriptionService();
            StripeSubscription subscription = subscriptionService.Create(PublicCustomerInfos.StripeCustomerId, subscriptionOptions);

            var booking = new SubscriptionBookings
            {
                SubscriptionId       = PublicSubscription.Id,
                Quantity             = TotalTickets,
                StripeCouponId       = stripeCouponId,
                BookedDate           = DateTime.UtcNow,
                ActivedDate          = subscription.Start,
                StartDate            = subscription.CurrentPeriodStart,
                EndDate              = subscription.CurrentPeriodEnd,
                Status               = (int)Enums.SubscriptionBookingStatus.Active,
                CustomerId           = customerId,
                LastUpdatedDate      = DateTime.UtcNow,
                LastUpdatedBy        = customerId,
                StripeSubscriptionId = subscription.Id
            };

            var param = new AddSubscriptionBookingParams
            {
                SubscriptionBookingsObject = booking,
                CustomerCreditsObject      = PublicCustomerCredits,
                Description                  = creditLogDescription,
                SubscriptionName             = PublicSubscription.Name,
                FirstName                    = PublicCustomerInfos.FirstName,
                LastName                     = PublicCustomerInfos.LastName,
                SubscriptionBookingDiscounts = discounts,
                ActualPrice                  = actualPrice,
                MerchantPrice                = PublicSubscription.Price,
                PayByCredit                  = totalPrice.Equals(chargePrice) ? 0 : totalPrice - chargePrice,
                TotalPrice                   = chargePrice,
                MaxPurchases                 = PublicSubscription.MaxPurchases
            };

            int bookingId = _subscriptionBookingRepository.Add(param);

            //Session.Remove(_discountKey);

            CacheLayer.Clear(CacheKeys.SubscriptionBookingsCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerInfosCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerCreditLogsCacheKey);
            CacheLayer.Clear(CacheKeys.DiscountsCacheKey);
            CacheLayer.Clear(CacheKeys.SubscriptionBookingDiscountsCacheKey);
            CacheLayer.Clear(CacheKeys.SubsciptionDiscountUsedCacheKey);
            CacheLayer.Clear(CacheKeys.SubscriptionDiscountsCacheKey);
            CacheLayer.Clear(CacheKeys.SubscriptionCyclesCacheKey);

            return(bookingId);
        }
        private int PurchaseGiftCard(out bool success)
        {
            // Check customer change their email
            success = true;
            bool isPayByCredit;

            if (PublicCustomerInfos == null)
            {
                PublicCustomerInfos = new CustomerInfos
                {
                    EmailAddress = email.Text.Replace(" ", ""),
                    FirstName    = FirstName.Text.Trim(),
                    LastName     = LastName.Text.Trim(),
                    ZipCode      = txtzipcode.Text.Trim()
                };

                // Create new account with email
                var response = _customerInfoRepository.GetVipAccess(email.Text.Replace(" ", ""), Constant.SearchPageDefault, FirstName.Text.Trim(), LastName.Text.Trim());
                PublicCustomerInfos.CustomerId       = response.CustomerId;
                PublicCustomerInfos.StripeCustomerId = response.StripeCustomerId;

                CacheLayer.Clear(CacheKeys.CustomerInfosCacheKey);
                CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);

                Session["ReferralCode"] = response.ReferralCode;

                string searchPage = !string.IsNullOrEmpty((string)Session["SearchPage"])
                    ? Session["SearchPage"].ToString()
                    : Constant.SearchPageDefault;

                // Send email new account
                var responseEmail = EmailHelper.EmailNewAccount(PublicCustomerInfos.EmailAddress,
                                                                PublicCustomerInfos.FirstName,
                                                                response.Password,
                                                                Helper.ResolveRelativeToAbsoluteUrl(Request.Url,
                                                                                                    string.Format("{0}?sp={1}",
                                                                                                                  searchPage,
                                                                                                                  response.PasswordKey)), // Reset Password Url
                                                                Helper.ResolveRelativeToAbsoluteUrl(Request.Url,
                                                                                                    string.Format("{0}?c={1}",
                                                                                                                  searchPage,
                                                                                                                  response.AccessKey))); // Browse Day Pass
                PublicCustomerCredits = _customerInfoRepository.GetCustomerCredits(response.CustomerId);


                Session["UserSession"]  = response.AccessKey;
                Session["IsRegister"]   = true;
                Session["ReferralCode"] = response.ReferralCode;
            }

            Regex regex = new Regex(@"([\d]+)(\s)?/(\s)?([\d]+)");
            int   month;

            int.TryParse(regex.Match(txtexpdat.Value).Groups[1].Value, out month);
            int year;

            int.TryParse("20" + regex.Match(txtexpdat.Value).Groups[4].Value, out year);
            string fullName = string.Format("{0} {1}", FirstName.Text, LastName.Text);

            // Check customer has exists with email
            StripeCustomer stripeCustomer = null;
            //var discounts = new Discounts();
            double actualPrice;

            // update user info with exists
            if (!string.IsNullOrEmpty(PublicCustomerInfos.StripeCustomerId))
            {
                stripeCustomer = GetCustomerById(PublicCustomerInfos.StripeCustomerId);
            }

            // Use New Card
            if (MVCardInfo.ActiveViewIndex == 0)
            {
                StripeToken stripeToken = CreateToken(cctextbox.Text.Replace(" ", ""), year, month, txtzipcode.Text,
                                                      fullName,
                                                      txtseccode.Value);

                // update new card for customer
                PublicCustomerInfos.StripeTokenId    = stripeToken.Id;
                PublicCustomerInfos.StripeCardId     = stripeToken.StripeCard.Id;
                PublicCustomerInfos.BankAccountLast4 = stripeToken.StripeCard.Last4;
                PublicCustomerInfos.CardType         = Helper.GetCreditCardType(cctextbox.Text.Replace(" ", ""));
                PublicCustomerInfos.ZipCode          = txtzipcode.Text;

                if (stripeCustomer == null)
                {
                    stripeCustomer = CreateCustomer(PublicCustomerInfos.EmailAddress, fullName, stripeToken.Id);
                    PublicCustomerInfos.StripeCustomerId = stripeCustomer.Id;
                }
                else
                {
                    // Update Stripe exists customer with New Card
                    var card = CreateCard(stripeToken.Id, PublicCustomerInfos.StripeCustomerId);
                    UpdateCustomer(PublicCustomerInfos.EmailAddress, fullName,
                                   PublicCustomerInfos.StripeCustomerId, card.Id);
                }
                _customerInfoRepository.Update(PublicCustomerInfos);

                isPayByCredit = IsPayByCreditCheckBox.Checked;
            }
            else
            {
                isPayByCredit = DCreditCheckBox.Checked;
            }

            if (PublicCustomerInfos.FirstName != FirstName.Text.Trim() || PublicCustomerInfos.LastName != LastName.Text.Trim())
            {
                PublicCustomerInfos.FirstName = FirstName.Text.Trim();
                PublicCustomerInfos.LastName  = LastName.Text.Trim();
                _customerInfoRepository.Update(PublicCustomerInfos);

                // Update Stripe exists customer
                stripeCustomer = UpdateCustomer(PublicCustomerInfos.EmailAddress, fullName, PublicCustomerInfos.StripeCustomerId, string.Empty);
            }

            // Discount 100% ??
            // Price equal 0, so we should not charge with this

            double.TryParse(ValueText.Text, out actualPrice);

            double   chargePrice          = actualPrice;
            string   creditLogDescription = string.Format("eGift Cards – {0}", Helper.FormatPrice(actualPrice * -1));
            DateTime deliveryDate;
            string   stripeChargeId = string.Empty;

            // Use DayAxe Credit
            if (isPayByCredit && PublicCustomerCredits != null && PublicCustomerCredits.Amount > 0)
            {
                // Create Coupon Id because we used DayAxe Credit
                chargePrice = actualPrice - PublicCustomerCredits.Amount;
                if (chargePrice <= 0)
                {
                    chargePrice = 0;
                }
            }

            if (chargePrice > 0)
            {
                StripeCharge stripeCharge = CreateCharges(chargePrice, stripeCustomer.Id, creditLogDescription);
                stripeChargeId = stripeCharge.Id;
            }

            DateTime.TryParseExact(DeliveryDateText.Text, "MM/dd/yyyy", null, DateTimeStyles.None, out deliveryDate);

            double userBookedDate;

            double.TryParse(HidUserBookedDate.Value, out userBookedDate);

            var param = new GiftCardBookings
            {
                CustomerId      = PublicCustomerInfos.CustomerId,
                GiftCardId      = 0,
                Price           = chargePrice,
                PayByCredit     = actualPrice - chargePrice,
                TotalPrice      = actualPrice,
                StripeChargeId  = stripeChargeId,
                BookedDate      = DateTime.UtcNow,
                RecipientEmail  = ToText.Text.Trim(),
                RecipientName   = NameText.Text.Trim(),
                Message         = !string.IsNullOrEmpty(MessageText.Text) ? MessageText.Text : "Enjoy the gift of DayAxe from me!",
                DeliveryDate    = deliveryDate.Date.AddHours(9 + 5), // 9AM + EST = 5 hours
                Description     = creditLogDescription,
                LastUpdatedBy   = PublicCustomerInfos.CustomerId,
                LastUpdatedDate = DateTime.UtcNow,
                UserBookedDate  = userBookedDate
            };

            int giftCardBooking = _giftCardBookingRepository.Add(param);

            CacheLayer.Clear(CacheKeys.GiftCardCacheKey);
            CacheLayer.Clear(CacheKeys.GiftCardBookingCacheKey);

            CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerCreditLogsCacheKey);

            return(giftCardBooking);
        }
        public ResponseData GetVipAccess(string username, string browsePassUrl, string firstName = "", string lastName = "")
        {
            using (var transaction = new TransactionScope())
            {
                var response = new ResponseData();
                username = username.Trim().ToLower();

                var customerInfos = DayaxeDbContext.CustomerInfos.FirstOrDefault(x => x.EmailAddress == username);
                if (customerInfos != null)
                {
                    customerInfos.CreateAccountSessionId = Helper.RandomString(20);
                    customerInfos.Password = Helper.RandomString(7);
                    customerInfos.ChangePasswordSessionId = Helper.RandomString(20);
                    customerInfos.IsConfirmed             = false;

                    var customerCredits = DayaxeDbContext.CustomerCredits
                                          .FirstOrDefault(x => x.CustomerId == customerInfos.CustomerId);
                    if (customerCredits != null)
                    {
                        response.ReferralCode = customerCredits.ReferralCode;
                    }
                }
                else
                {
                    customerInfos = new CustomerInfos
                    {
                        EmailAddress           = username,
                        IsConfirmed            = false,
                        CreateAccountSessionId = Helper.RandomString(20),
                        CreatedDate            = DateTime.UtcNow,
                        BrowsePassUrl          = browsePassUrl,
                        Password = Helper.RandomString(7),
                        ChangePasswordSessionId = Helper.RandomString(20),
                        FirstName = firstName,
                        LastName  = lastName
                    };
                    DayaxeDbContext.CustomerInfos.InsertOnSubmit(customerInfos);

                    Commit();

                    var customerCredits = new CustomerCredits
                    {
                        Amount                 = 0,
                        CreatedDate            = DateTime.UtcNow,
                        CustomerId             = customerInfos.CustomerId,
                        IsActive               = false,
                        IsDelete               = false,
                        FirstRewardForOwner    = 5,
                        FirstRewardForReferral = 5,
                        LastUpdatedDate        = DateTime.UtcNow,
                        ReferralCode           = Helper.RandomString(8),
                        ReferralCustomerId     = 0
                    };

                    DayaxeDbContext.CustomerCredits.InsertOnSubmit(customerCredits);

                    response.ReferralCode = customerCredits.ReferralCode;
                }

                var url = string.Format(Constant.KlaviyoListApiUrl, AppConfiguration.KlaviyoListId);
                var addToListKlaviyoRes = Helper.Post(url, username);

                var logs = new Logs
                {
                    LogKey         = "Klaviyo_Register_Response",
                    UpdatedBy      = 1,
                    UpdatedDate    = DateTime.UtcNow,
                    UpdatedContent = string.Format("{0} - {1}", username, addToListKlaviyoRes)
                };

                DayaxeDbContext.Logs.InsertOnSubmit(logs);

                Commit();
                transaction.Complete();

                response.IsSuccessful     = true;
                response.AccessKey        = customerInfos.CreateAccountSessionId.ToLower();
                response.Password         = customerInfos.Password;
                response.PasswordKey      = customerInfos.ChangePasswordSessionId.ToLower();
                response.CustomerId       = customerInfos.CustomerId;
                response.StripeCustomerId = customerInfos.StripeCustomerId;

                return(response);
            }
        }