protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
                string sessionUser = Session["CurrentUser"] != null ? Session["CurrentUser"].ToString() : string.Empty;
                PublicUser        = JsonConvert.DeserializeObject <CustomerInfos>(sessionUser);
                Session["Active"] = "Booking";
                if (PublicUser == null)
                {
                    Response.Redirect(Constant.DefaultPage);
                }

                string sessionHotel = Session["Hotel"] != null ? Session["Hotel"].ToString() : string.Empty;
                _hotels = _hotelRepository.GetById(int.Parse(sessionHotel));

                if (!IsPostBack)
                {
                    InitSearch();
                }
            }
            catch (Exception ex)
            {
                var logs = new Logs
                {
                    LogKey         = "Admin_BookingPage_Error",
                    UpdatedBy      = PublicUser != null ? PublicUser.CustomerId : 1,
                    UpdatedDate    = DateTime.UtcNow,
                    UpdatedContent = string.Format("{0} - {1} - {2}", ex.Message, ex.StackTrace, ex.Source)
                };
                _bookingRepository.AddLog(logs);
            }
        }
Пример #2
0
        protected void Page_Init(object sender, EventArgs e)
        {
            string sessionUser = Session["CurrentUser"] != null ? Session["CurrentUser"].ToString() : string.Empty;

            _users = JsonConvert.DeserializeObject <CustomerInfos>(sessionUser);
            if (_users != null)
            {
                if (_users.IsSuperAdmin)
                {
                    UserHotel.Visible          = true;
                    Markets.Visible            = true;
                    ContentsPage.Visible       = true;
                    PromoList.Visible          = true;
                    SearchBookingsList.Visible = true;
                    GiftCardList.Visible       = true;
                    SubscriptionList.Visible   = true;
                    LogList.Visible            = true;
                    EditPolicy.Visible         = true;
                }
                string dayaxeUrl = Request.Url.AbsoluteUri;
                Uri    baseUri   = new Uri(dayaxeUrl);
                UpdateUrl  = new Uri(baseUri, "/Handler/UpdateHotel.ashx").AbsoluteUri;
                UpdateUrl += "?userName=" + _users.EmailAddress;
            }
        }
Пример #3
0
        protected void Page_Init(object sender, EventArgs e)
        {
            Session["Active"] = "UserHotel";

            if (Request.Params["userId"] != null)
            {
                int userId = int.Parse(Request.Params["userId"]);
                _users = _userRepository.GetById(userId);
            }
            if (!IsPostBack)
            {
                Session["UserHotel"]   = null;
                Session["CurrentPage"] = 1;
                if (Request.Params["userId"] == null)
                {
                    MVUserHotel.ActiveViewIndex = 0;
                    RptUserHotel.DataSource     = _userRepository.GetAll().Take(Constant.ItemPerPage);
                    RptUserHotel.DataBind();
                }
                else
                {
                    MVUserHotel.ActiveViewIndex = 1;
                    int userId = int.Parse(Request.Params["userId"]);
                    if (userId == 0) // Add new
                    {
                        DdlHotels.Visible       = false;
                        BtnAddUserHotel.Visible = false;
                        Deactivebutton.Visible  = false;
                        ActiveButton.Visible    = false;
                    }
                    else
                    {
                        _users = _userRepository.GetById(userId);
                        if (_users == null)
                        {
                            Response.Redirect(Constant.UserHotelPage);
                        }
                        TxtFirstName.Text = _users.FirstName;
                        TxtLastName.Text  = _users.LastName;
                        TxtUsername.Text  = _users.EmailAddress;
                        if (_users.IsActive)
                        {
                            Deactivebutton.Visible        = true;
                            ActiveButton.Visible          = false;
                            btnSendActivationLink.Visible = true;
                        }
                        else
                        {
                            Deactivebutton.Visible = false;
                            ActiveButton.Visible   = true;
                        }
                        RebindHotelsByuser();
                    }
                }
            }
        }
Пример #4
0
        protected void Page_Init(object sender, EventArgs e)
        {
            _customerInfo = _customerInfoRepository.GetCustomerInfoBySessionId(Session["UserSession"].ToString());
            if (!IsPostBack)
            {
                if (_customerInfo != null)
                {
                    FullNameHeader.InnerText = string.Format("{0} {1}", _customerInfo.FirstName, _customerInfo.LastName);

                    FirstNameText.Text    = _customerInfo.FirstName;
                    LastNameText.Text     = _customerInfo.LastName;
                    EmailAddressText.Text = _customerInfo.EmailAddress;
                }
            }
        }
        private StripeCustomer UpdateStripeCustomer(CustomerInfos customerInfos)
        {
            var myCustomer = new StripeCustomerUpdateOptions
            {
                Email       = customerInfos.EmailAddress,
                Description = string.Format("{0} {1} ({2})",
                                            customerInfos.FirstName,
                                            customerInfos.LastName,
                                            customerInfos.EmailAddress)
            };

            var            customerService = new StripeCustomerService();
            StripeCustomer stripeCustomer  = customerService.Update(customerInfos.StripeCustomerId, myCustomer);

            return(stripeCustomer);
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            string dayaxeUrl = Request.Url.AbsoluteUri;
            Uri    baseUri   = new Uri(dayaxeUrl);

            UploadUrl = new Uri(baseUri, "/Handler/Upload.ashx").AbsoluteUri;
            if (Request.Params["id"] != null)
            {
                UploadUrl += "?id=" + Request.Params["id"];
            }
            string sessionUser = Session["CurrentUser"] != null ? Session["CurrentUser"].ToString() : string.Empty;

            _users = JsonConvert.DeserializeObject <CustomerInfos>(sessionUser);
            if (_users != null)
            {
                UploadUrl += "&userName=" + _users.EmailAddress;
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            var currentSession = Session["UserSession"];

            if (currentSession != null && _customerInfos == null)
            {
                _customerInfos = _helper.GetCustomerInfoBySessionId(currentSession.ToString());
                if (_customerInfos != null && !string.IsNullOrEmpty(_customerInfos.BrowsePassUrl))
                {
                    HomeLink.NavigateUrl = _customerInfos.BrowsePassUrl;
                }
                else if (!string.IsNullOrEmpty((string)Session["SearchPage"]))
                {
                    HomeLink.NavigateUrl = Session["SearchPage"].ToString();
                }
            }
            else
            {
                HomeLink.NavigateUrl = Constant.SearchPageDefault;
            }
        }
        private void BindMyDayPassInfo()
        {
            var daypassRepeater = ControlExtensions.FindControlRecursive(ContentPlaceHolder, "DayPassRepeater") as Repeater;

            if (daypassRepeater != null)
            {
                if (Session["UserSession"] == null)
                {
                    throw new HttpException(401, "UnAuthorized");
                }

                CustomerInfos customerInfos = _bookingRepository.GetCustomerInfoBySessionId((string)Session["UserSession"]);
                if (customerInfos == null)
                {
                    throw new HttpException(401, "UnAuthorized");
                }

                daypassRepeater.ItemDataBound += DaypassRepeaterOnItemDataBound;
                var daypasses = _bookingRepository.GetBookingsByCustomerId(customerInfos.CustomerId);
                daypassRepeater.DataSource = daypasses;
                daypassRepeater.DataBind();
            }
        }
Пример #9
0
        protected void BtnAddUserHotel_OnClick(object sender, EventArgs e)
        {
            int hotelId;

            int.TryParse(DdlHotels.SelectedValue, out hotelId);
            if (hotelId != 0)
            {
                int userId = int.Parse(Request.Params["userId"]);
                _users = _userRepository.GetById(userId);
                var hotel = _hotelRepository.GetHotel(hotelId, _users.EmailAddress);
                if (hotel == null)
                {
                    var userHotels = new CustomerInfosHotels
                    {
                        HotelId    = hotelId,
                        CustomerId = _users.CustomerId
                    };
                    _userHotelRepository.Add(userHotels);

                    _userHotelRepository.ResetCache();
                }
                RebindHotelsByuser(true);
            }
        }
Пример #10
0
        protected void Page_Init(object sender, EventArgs e)
        {
            ScriptAnalyticsHeader.Visible = AppConfiguration.EnableTracking;
            if (Session["IsLogOut"] != null)
            {
                Session["IsLogOut"] = null;
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "resetMixpanel", "if (window.mixpanel) { window.mixpanel.reset(); }", true);
            }
            RequestUrl = Request.Url.AbsoluteUri.ToLower();
            if (RequestUrl.Contains("reviews"))
            {
                body.Attributes["class"] += " reviews-page";
            }
            if (RequestUrl.Contains("membership"))
            {
                body.Attributes["class"] += " membership-page";
            }

            if (RequestUrl.Contains("credits"))
            {
                body.Attributes["class"] += " credits-page";
            }

            var createSession = Request.Params["c"];

            if (Session["UserSession"] == null && createSession != null)
            {
                Session["UserSession"] = createSession;
            }

            partnerLink.HRef = AppConfiguration.ForPartnerLink;

            var currentSession = Session["UserSession"];

            if (currentSession != null)
            {
                using (var customerInfoRepository = new CustomerInfoRepository())
                {
                    _customerInfos = customerInfoRepository.GetCustomerInfoBySessionId(currentSession.ToString());
                    if (_customerInfos != null)
                    {
                        string firstName = string.IsNullOrEmpty(_customerInfos.FirstName)
                            ? _customerInfos.EmailAddress.Split('@')[0]
                            : _customerInfos.FirstName;
                        FirstnameLiteral.Text                 = firstName;
                        FirstnameMobileLiteral.Text           = firstName;
                        LoginLinkButton.Attributes["class"]  += " hidden-sm hidden-xs";
                        LoginLinkButton.Attributes["onclick"] = "";
                        if (Request.Browser["IsMobileDevice"] == "true")
                        {
                            LoginLinkButton.Visible = false;
                        }
                        hiw.Visible       = false;
                        mdp.Visible       = true;
                        MyAccount.Visible = true;
                        if (_customerInfos.IsAdmin)
                        {
                            partnerLink.InnerText = "Host";
                            partnerLink.HRef      = String.Format("{0}?e={1}",
                                                                  AppConfiguration.HostLink,
                                                                  HttpUtility.UrlEncode(Algoritma.Encrypt(_customerInfos.EmailAddress, Constant.EncryptPassword)));
                            partnerLink.Attributes["class"] = "is-host";
                        }
                    }
                }
            }
        }
Пример #11
0
        protected void SaveUserClick(object sender, EventArgs e)
        {
            try
            {
                int    userId   = int.Parse(Request.Params["userId"]);
                string userName = TxtUsername.Text.Trim();
                if (userId == 0)
                {
                    if (string.IsNullOrEmpty(userName))
                    {
                        LblMessage.Visible = true;
                        LblMessage.Text    = "Username is required";
                        return;
                    }

                    if (!Helper.IsValidEmail(userName))
                    {
                        LblMessage.Visible = true;
                        LblMessage.Text    = "Please use valid email address";
                        return;
                    }

                    _users = _userRepository.GetCustomerByEmailAddress(userName);
                    if (_users == null)
                    {
                        string salt     = Algoritma.GenerateSalt();
                        string password = Algoritma.EncryptHMACSHA512("~new_dayaxe-user!", salt);

                        _users = new CustomerInfos
                        {
                            FirstName     = TxtFirstName.Text,
                            LastName      = TxtLastName.Text,
                            EmailAddress  = userName,
                            Password      = password,
                            Salt          = salt,
                            CreatedDate   = DateTime.UtcNow,
                            IsActive      = true,
                            IsAdmin       = true,
                            IsCheckInOnly = DdlRole.SelectedValue == "3" // Checkin Only
                        };
                        userId = _userRepository.Add(_users);
                    }
                    else
                    {
                        _users.FirstName     = TxtFirstName.Text;
                        _users.LastName      = TxtLastName.Text;
                        _users.EmailAddress  = userName;
                        _users.IsActive      = true;
                        _users.IsAdmin       = true;
                        _users.IsDelete      = false;
                        _users.IsCheckInOnly = DdlRole.SelectedValue == "3"; // Checkin Only

                        _userRepository.Update(_users);
                        userId = _users.CustomerId;
                    }
                }
                else
                {
                    _users               = _userRepository.GetById(userId);
                    _users.FirstName     = TxtFirstName.Text;
                    _users.LastName      = TxtLastName.Text;
                    _users.EmailAddress  = userName;
                    _users.IsCheckInOnly = DdlRole.SelectedValue == "3"; // Checkin Only

                    _userRepository.Update(_users);
                }

                _userHotelRepository.ResetCache();

                Response.Redirect(Constant.UserHotelPage + "?userId=" + userId);
            }
            catch (Exception ex)
            {
                LblMessage.Visible = true;
                LblMessage.Text    = ex.Message;
                return;
            }
        }
        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);
        }
        private void Refund(Bookings booking, CustomerInfos customerInfos, double diffPrice, double merchantPrice, double actualPrice)
        {
            var bookingInvoices = _bookingRepository.GetInvoicesByBookingId(booking.BookingId).ToList();
            var chargeInvoices  = bookingInvoices
                                  .Where(x => x.InvoiceStatus == (int)Enums.InvoiceStatus.Charge)
                                  .OrderBy(x => x.TotalPrice)
                                  .ToList();

            while (diffPrice > 0)
            {
                var currentCharge = chargeInvoices.FirstOrDefault();
                if (currentCharge != null)
                {
                    var refundOfCurrentCharge = bookingInvoices
                                                .Where(x => (x.InvoiceStatus == (int)Enums.InvoiceStatus.PartialRefund || x.InvoiceStatus == (int)Enums.InvoiceStatus.FullRefund) &&
                                                       x.StripeChargeId == currentCharge.StripeChargeId)
                                                .ToList();

                    var oldRefund    = refundOfCurrentCharge.Sum(x => x.RefundAmount);
                    var newDiffPrice = currentCharge.ChargeAmount - oldRefund;

                    if (newDiffPrice > 0)
                    {
                        double newRefundPrice = diffPrice;
                        diffPrice -= newDiffPrice;
                        var chargeInvoice = new Invoices
                        {
                            BookingId      = booking.BookingId,
                            PassStatus     = booking.PassStatus,
                            StripeChargeId = currentCharge.StripeChargeId,
                            ChargeAmount   = currentCharge.ChargeAmount,
                            CreatedDate    = DateTime.UtcNow,
                            CreatedBy      = customerInfos != null ? customerInfos.CustomerId : 0,
                            HotelPrice     = actualPrice,
                            MerchantPrice  = merchantPrice,
                            Quantity       = booking.Quantity,
                            TotalPrice     = booking.TotalPrice
                        };

                        if (diffPrice >= 0)
                        {
                            newRefundPrice = newDiffPrice;
                            chargeInvoice.InvoiceStatus = (int)Enums.InvoiceStatus.FullRefund;
                        }
                        else
                        {
                            chargeInvoice.InvoiceStatus = (int)Enums.InvoiceStatus.PartialRefund;
                        }
                        var refund = CallStripeRefund(currentCharge.StripeChargeId, newRefundPrice);
                        chargeInvoice.RefundAmount       = (double)refund.Amount / 100;
                        chargeInvoice.StripeRefundId     = refund.Id;
                        chargeInvoice.StripeRefundStatus = refund.Status;

                        string requestObj = JsonConvert.SerializeObject(refund, CustomSettings.SerializerSettings());
                        string message    = string.Format("{0} Refund Response: {1}, Refund Post Data: {2}",
                                                          booking.BookingCode,
                                                          refund.StripeResponse.ResponseJson,
                                                          requestObj);
                        _bookingRepository.AddInvoices(chargeInvoice, message);
                    }
                    chargeInvoices.Remove(currentCharge);
                }
            }
        }