public void Update(CustomerCredits entity)
        {
            var customerUpdate = DayaxeDbContext.CustomerCredits.SingleOrDefault(x => x.CustomerId == entity.CustomerId);

            if (customerUpdate != null)
            {
                if (!string.IsNullOrEmpty(entity.LogDescriptionCredits))
                {
                    var creditLogs = new CustomerCreditLogs
                    {
                        Amount                = customerUpdate.Amount,
                        ProductId             = 0,
                        BookingId             = 0,
                        SubscriptionId        = entity.SubscriptionId,
                        CreatedBy             = 0,
                        CreatedDate           = DateTime.UtcNow,
                        CreditType            = (byte)Enums.CreditType.Charge,
                        Description           = entity.LogDescriptionCredits,
                        CustomerId            = entity.CustomerId,
                        ReferralId            = customerUpdate.ReferralCustomerId,
                        SubscriptionBookingId = 0,
                        Status                = true,
                        GiftCardId            = 0
                    };

                    DayaxeDbContext.CustomerCreditLogs.InsertOnSubmit(creditLogs);
                }

                if (entity.LogsItem != null)
                {
                    AddLog(entity.LogsItem);
                }

                customerUpdate.Amount                 = entity.Amount;
                customerUpdate.LastUpdatedDate        = entity.LastUpdatedDate;
                customerUpdate.FirstRewardForOwner    = entity.FirstRewardForOwner;
                customerUpdate.FirstRewardForReferral = entity.FirstRewardForReferral;
                customerUpdate.IsDelete               = entity.IsDelete;
            }
            Commit();
        }
        public double AddGiftCard(CustomerCredits customerCredits, string code)
        {
            using (var transaction = new TransactionScope())
            {
                var credits = DayaxeDbContext.CustomerCredits.FirstOrDefault(cc => cc.CustomerId == customerCredits.CustomerId);
                if (credits != null)
                {
                    var card = DayaxeDbContext.GiftCards.FirstOrDefault(g => g.Code.ToUpper() == code.ToUpper().Trim());
                    var logs = new CustomerCreditLogs
                    {
                        CreatedDate = DateTime.UtcNow,
                        CreditType  = (int)Enums.CreditType.GiftCard,
                        CustomerId  = credits.CustomerId,
                        ReferralId  = credits.CustomerId,
                        Amount      = card.Amount,
                        CreatedBy   = credits.CustomerId,
                        Description = string.Format("{0} - {{0}} - {1}",
                                                    Enums.CreditType.GiftCard.ToDescription(),
                                                    code.ToUpper().Trim()),
                        BookingId  = 0,
                        Status     = true,
                        GiftCardId = card.Id
                    };

                    card.Status = (short)Enums.GiftCardType.Used;

                    DayaxeDbContext.CustomerCreditLogs.InsertOnSubmit(logs);
                    credits.Amount += card.Amount;

                    Commit();
                }

                transaction.Complete();

                return(credits != null ? credits.Amount : 0);
            }
        }
        public int Add(GiftCardBookings entity)
        {
            using (var transaction = new TransactionScope())
            {
                var customerInfos = CustomerInfoList.FirstOrDefault(ci => ci.CustomerId == entity.CustomerId);

                var giftCard = new GiftCards
                {
                    Amount = entity.TotalPrice,
                    Code   = string.Format(Constant.GiftCardFormat,
                                           entity.CustomerId,
                                           Helper.RandomString(7)),
                    Name = string.Format(Constant.GiftCardNameFormat,
                                         customerInfos != null ? customerInfos.EmailAddress : entity.CustomerId.ToString(),
                                         entity.RecipientName,
                                         entity.RecipientEmail),
                    IsDelete = false,
                    Status   = (byte)Enums.GiftCardType.Available
                };

                DayaxeDbContext.GiftCards.InsertOnSubmit(giftCard);
                Commit();

                entity.GiftCardId = giftCard.Id;
                DayaxeDbContext.GiftCardBookings.InsertOnSubmit(entity);
                Commit();

                if (entity.PayByCredit > 0)
                {
                    var creditLogs = new CustomerCreditLogs
                    {
                        Amount      = entity.PayByCredit,
                        CreatedBy   = entity.CustomerId,
                        CreatedDate = DateTime.UtcNow,
                        CreditType  = (byte)Enums.CreditType.Charge,
                        Description = entity.Description,
                        CustomerId  = entity.CustomerId,
                        Status      = true,
                        GiftCardId  = entity.GiftCardId
                    };

                    DayaxeDbContext.CustomerCreditLogs.InsertOnSubmit(creditLogs);

                    var cusCredits = DayaxeDbContext.CustomerCredits
                                     .SingleOrDefault(cc => cc.CustomerId == entity.CustomerId);

                    if (cusCredits != null)
                    {
                        cusCredits.Amount -= entity.PayByCredit;
                    }
                }

                var schedulesAddOn = new Schedules
                {
                    ScheduleSendType  = (int)Enums.ScheduleSendType.IsEmailGiftCardConfirmation,
                    Name              = "Send eGift Card Confirmation",
                    Status            = (int)Enums.ScheduleType.NotRun,
                    GiftCardBookingId = entity.Id
                };
                DayaxeDbContext.Schedules.InsertOnSubmit(schedulesAddOn);

                Commit();
                transaction.Complete();

                return(entity.Id);
            }
        }
        public int Add(AddSubscriptionBookingParams param)
        {
            try
            {
                using (var transaction = new TransactionScope())
                {
                    var bookingCode = Helper.RandomString(Constant.BookingCodeLength);
                    while (IsBookingCodeExists(bookingCode))
                    {
                        bookingCode = Helper.RandomString(Constant.BookingCodeLength);
                    }
                    param.SubscriptionBookingsObject.BookingCode = bookingCode;

                    // Insert New Bookings
                    DayaxeDbContext.SubscriptionBookings.InsertOnSubmit(param.SubscriptionBookingsObject);
                    Commit();

                    if (param.SubscriptionBookingDiscounts != null && param.SubscriptionBookingDiscounts.Id > 0)
                    {
                        var subscriptionDiscount = new SubscriptionBookingDiscounts
                        {
                            DiscountId            = param.SubscriptionBookingDiscounts.Id,
                            SubscriptionBookingId = param.SubscriptionBookingsObject.Id,
                            SubscriptionId        = param.SubscriptionBookingsObject.SubscriptionId
                        };

                        DayaxeDbContext.SubscriptionBookingDiscounts.InsertOnSubmit(subscriptionDiscount);
                    }

                    // Insert to History for First Cycle
                    var cycle = new SubscriptionCycles
                    {
                        SubscriptionBookingId = param.SubscriptionBookingsObject.Id,
                        StartDate             = param.SubscriptionBookingsObject.StartDate,
                        EndDate         = param.SubscriptionBookingsObject.EndDate,
                        CancelDate      = param.SubscriptionBookingsObject.CancelDate,
                        LastUpdatedBy   = param.SubscriptionBookingsObject.LastUpdatedBy,
                        LastUpdatedDate = param.SubscriptionBookingsObject.LastUpdatedDate,
                        Status          = param.SubscriptionBookingsObject.Status,
                        Price           = param.ActualPrice,
                        MerchantPrice   = param.MerchantPrice,
                        PayByCredit     = param.PayByCredit,
                        TotalPrice      = param.TotalPrice,
                        Quantity        = param.SubscriptionBookingsObject.Quantity,
                        StripeChargeId  = string.Empty,
                        StripeCouponId  = param.SubscriptionBookingsObject.StripeCouponId,
                        StripeInvoiceId = string.Empty,
                        CycleNumber     = 1
                    };

                    DayaxeDbContext.SubscriptionCycles.InsertOnSubmit(cycle);

                    // Insert Discount for Current Customer active Subscription
                    var discount = new Discounts
                    {
                        DiscountName = string.Format("{0} - {1} {2}",
                                                     param.SubscriptionName,
                                                     param.FirstName,
                                                     param.LastName),
                        Code          = string.Format("SUP{0}", Helper.RandomString(8)),
                        StartDate     = param.SubscriptionBookingsObject.StartDate,
                        EndDate       = param.SubscriptionBookingsObject.EndDate,
                        CodeRequired  = true,
                        PercentOff    = 100,
                        PromoType     = (byte)Enums.PromoType.SubscriptionPromo,
                        MinAmount     = 0,
                        IsAllProducts = true,
                        MaxPurchases  = (byte)param.MaxPurchases
                    };
                    DayaxeDbContext.Discounts.InsertOnSubmit(discount);
                    Commit();

                    // Add Invoices
                    var subscriptionInvoice = new SubscriptionInvoices
                    {
                        SubscriptionCyclesId = cycle.Id,
                        BookingStatus        = cycle.Status,
                        Quantity             = cycle.Quantity,
                        Price              = cycle.Price,
                        MerchantPrice      = cycle.MerchantPrice,
                        PayByCredit        = cycle.PayByCredit,
                        TotalPrice         = cycle.TotalPrice,
                        InvoiceStatus      = (int)Enums.InvoiceStatus.Charge,
                        StripeChargeId     = cycle.StripeChargeId,
                        ChargeAmount       = cycle.Price,
                        StripeRefundId     = string.Empty,
                        RefundAmount       = 0,
                        RefundCreditAmount = 0,
                        StripeCouponId     = cycle.StripeCouponId,
                        CreatedDate        = DateTime.UtcNow,
                        CreatedBy          = 1
                    };
                    DayaxeDbContext.SubscriptionInvoices.InsertOnSubmit(subscriptionInvoice);

                    var discountUsed = new SubsciptionDiscountUseds
                    {
                        CustomerId            = param.SubscriptionBookingsObject.CustomerId,
                        DiscountId            = discount.Id,
                        SubscriptionBookingId = param.SubscriptionBookingsObject.Id
                    };
                    DayaxeDbContext.SubsciptionDiscountUseds.InsertOnSubmit(discountUsed);

                    var cusCredits = DayaxeDbContext.CustomerCredits
                                     .SingleOrDefault(cc => cc.CustomerId == param.CustomerCreditsObject.CustomerId);

                    // Add Logs when refund by Upgrade to Subscription
                    if (param.RefundCreditByUpgrade > 0)
                    {
                        var creditLogs = new CustomerCreditLogs
                        {
                            Amount                = param.RefundCreditByUpgrade,
                            ProductId             = 0,
                            BookingId             = 0,
                            SubscriptionId        = param.SubscriptionBookingsObject.SubscriptionId,
                            CreatedBy             = param.CustomerCreditsObject.CustomerId,
                            CreatedDate           = DateTime.UtcNow,
                            CreditType            = (byte)Enums.CreditType.PartialPuchaseRefund,
                            Description           = param.RefundCreditDescription,
                            CustomerId            = param.CustomerCreditsObject.CustomerId,
                            ReferralId            = param.CustomerCreditsObject.ReferralCustomerId,
                            SubscriptionBookingId = param.SubscriptionBookingsObject.Id,
                            Status                = true,
                            GiftCardId            = 0
                        };

                        DayaxeDbContext.CustomerCreditLogs.InsertOnSubmit(creditLogs);

                        if (cusCredits != null)
                        {
                            cusCredits.Amount += param.RefundCreditByUpgrade;
                        }
                    }

                    // Add Logs when pay by DayAxe Credit
                    if (param.PayByCredit > 0)
                    {
                        var creditLogs = new CustomerCreditLogs
                        {
                            Amount                = param.PayByCredit,
                            ProductId             = 0,
                            BookingId             = 0,
                            SubscriptionId        = param.SubscriptionBookingsObject.SubscriptionId,
                            CreatedBy             = param.CustomerCreditsObject.CustomerId,
                            CreatedDate           = DateTime.UtcNow,
                            CreditType            = (byte)Enums.CreditType.Charge,
                            Description           = param.Description,
                            CustomerId            = param.CustomerCreditsObject.CustomerId,
                            ReferralId            = param.CustomerCreditsObject.ReferralCustomerId,
                            SubscriptionBookingId = param.SubscriptionBookingsObject.Id,
                            Status                = true,
                            GiftCardId            = 0
                        };

                        DayaxeDbContext.CustomerCreditLogs.InsertOnSubmit(creditLogs);

                        if (cusCredits != null)
                        {
                            cusCredits.Amount -= param.PayByCredit;
                        }
                    }

                    // First Buy of referral
                    if (param.CustomerCreditsObject != null && param.CustomerCreditsObject.ReferralCustomerId > 0 && (
                            DayaxeDbContext.Bookings.Count(x => x.CustomerId == param.SubscriptionBookingsObject.CustomerId) == 1 ||
                            DayaxeDbContext.SubscriptionBookings.Count(x => x.CustomerId == param.SubscriptionBookingsObject.CustomerId) == 1))
                    {
                        var logs = DayaxeDbContext.CustomerCreditLogs
                                   .Where(ccl => ccl.CustomerId == param.CustomerCreditsObject.ReferralCustomerId &&
                                          ccl.ReferralId == param.SubscriptionBookingsObject.CustomerId &&
                                          !ccl.Status)
                                   .ToList();

                        if (logs.Any())
                        {
                            logs.ForEach(log =>
                            {
                                var cus = DayaxeDbContext.CustomerCredits
                                          .FirstOrDefault(cc => cc.CustomerId == log.CustomerId);
                                if (cus != null)
                                {
                                    cus.Amount += log.Amount;
                                }

                                log.Status = true;
                            });
                            Commit();
                        }
                    }

                    // Add to Customer Credit Log
                    var logsReferred = DayaxeDbContext.CustomerCreditLogs
                                       .Where(ccl => ccl.ReferralId == param.SubscriptionBookingsObject.CustomerId && !ccl.Status)
                                       .ToList();
                    if (logsReferred.Any())
                    {
                        logsReferred.ForEach(log =>
                        {
                            var cus = DayaxeDbContext.CustomerCredits
                                      .FirstOrDefault(cc => cc.CustomerId == log.CustomerId);
                            if (cus != null)
                            {
                                cus.Amount += log.Amount;
                            }

                            log.Status = true;
                        });
                    }

                    // Insert Schedule
                    var schedules = new Schedules
                    {
                        ScheduleSendType      = (int)Enums.ScheduleSendType.IsEmailConfirmSubscription,
                        Name                  = "Send Email confirm Subscription",
                        Status                = (int)Enums.ScheduleType.NotRun,
                        SubscriptionBookingId = param.SubscriptionBookingsObject.Id
                    };
                    DayaxeDbContext.Schedules.InsertOnSubmit(schedules);

                    // Maybe not use here because flow upgrade to subscription do not use this
                    if (param.BookingId > 0)
                    {
                        var bookings = DayaxeDbContext.Bookings.FirstOrDefault(b => b.BookingId == param.BookingId);
                        if (bookings != null)
                        {
                            var chargePrice = (int)((bookings.TotalPrice - bookings.HotelPrice) * 100);
                            try
                            {
                                bookings.TotalPrice -= bookings.HotelPrice;
                                bookings.PassStatus  = (int)Enums.BookingStatus.Active;

                                var discounts = new DiscountBookings
                                {
                                    DiscountId = discount.Id,
                                    ProductId  = bookings.ProductId,
                                    BookingId  = bookings.BookingId
                                };

                                DayaxeDbContext.DiscountBookings.InsertOnSubmit(discounts);
                                bookings.IsActiveSubscription = true;

                                string responseString;
                                if (chargePrice > 0)
                                {
                                    var          chargeService = new StripeChargeService();
                                    StripeCharge charge        = chargeService.Capture(bookings.StripeChargeId, chargePrice);
                                    responseString = charge.StripeResponse.ResponseJson;
                                }
                                else
                                {
                                    var refundOptions = new StripeRefundCreateOptions
                                    {
                                        Reason = StripeRefundReasons.RequestedByCustomer
                                    };
                                    var          refundService = new StripeRefundService();
                                    StripeRefund refund        = refundService.Create(bookings.StripeChargeId, refundOptions);
                                    responseString = refund.StripeResponse.ResponseJson;
                                }

                                var logs = new Logs
                                {
                                    LogKey         = "UpgradeSubscriptionCharge",
                                    UpdatedContent = string.Format("Params: {0} - Response: {1}",
                                                                   JsonConvert.SerializeObject(param, CustomSettings.SerializerSettings()),
                                                                   responseString),
                                    UpdatedBy   = param.SubscriptionBookingsObject.CustomerId,
                                    UpdatedDate = DateTime.UtcNow
                                };
                                AddLog(logs);
                            }
                            catch (Exception ex)
                            {
                                var logs = new Logs
                                {
                                    LogKey         = "UpgradeSubscriptionChargeError",
                                    UpdatedContent = string.Format("Params: {0} - {1} - {2} - {3}",
                                                                   JsonConvert.SerializeObject(param, CustomSettings.SerializerSettings()),
                                                                   ex.Message,
                                                                   ex.StackTrace,
                                                                   ex.Source),
                                    UpdatedBy   = param.SubscriptionBookingsObject.CustomerId,
                                    UpdatedDate = DateTime.UtcNow
                                };
                                AddLog(logs);
                            }
                        }
                    }

                    Commit();

                    transaction.Complete();
                }
            }
            catch (Exception ex)
            {
                var logs = new Logs
                {
                    LogKey         = "AddBookingError",
                    UpdatedContent = string.Format("{0} - {1} - {2} - {3}", param.SubscriptionBookingsObject.CustomerId, ex.Message, ex.StackTrace, ex.Source),
                    UpdatedBy      = param.SubscriptionBookingsObject.CustomerId,
                    UpdatedDate    = DateTime.UtcNow
                };
                AddLog(logs);

                throw new Exception(ex.Message, ex);
            }

            return(param.SubscriptionBookingsObject.Id);
        }
        public double AddReferral(CustomerCredits entity, CustomerCredits referralCustomer)
        {
            using (var transaction = new TransactionScope())
            {
                var currentCustomer = DayaxeDbContext.CustomerCredits.FirstOrDefault(cc => cc.Id == entity.Id);
                var referCustomer   = DayaxeDbContext.CustomerCredits.FirstOrDefault(cc => cc.Id == referralCustomer.Id);
                if (currentCustomer != null && currentCustomer.ReferralCustomerId != 0)
                {
                    throw new Exception(ErrorMessage.CanNotReferralTwice);
                }

                if (currentCustomer != null && referCustomer != null)
                {
                    currentCustomer.ReferralCustomerId = referCustomer.CustomerId;

                    var logs = new CustomerCreditLogs
                    {
                        CreatedDate = DateTime.UtcNow,
                        CreditType  = (int)Enums.CreditType.GiftCard,
                        CustomerId  = currentCustomer.CustomerId,
                        ReferralId  = referCustomer.CustomerId,
                        Amount      = referCustomer.FirstRewardForReferral,
                        CreatedBy   = currentCustomer.CustomerId,
                        Description = string.Format("{0} - {{0}} - {1}",
                                                    Enums.CreditType.Referral.ToDescription(),
                                                    referCustomer.ReferralCode),
                        BookingId  = 0,
                        Status     = false, // Pending
                        GiftCardId = 0
                    };

                    var logReferrals = new CustomerCreditLogs
                    {
                        CreatedDate = DateTime.UtcNow,
                        CreditType  = (int)Enums.CreditType.Referral,
                        CustomerId  = referCustomer.CustomerId,
                        ReferralId  = currentCustomer.CustomerId,
                        Amount      = referCustomer.FirstRewardForOwner,
                        CreatedBy   = currentCustomer.CustomerId,
                        Description = string.Format("{0} - {{0}} - {1}",
                                                    Enums.CreditType.Referral.ToDescription(),
                                                    referCustomer.ReferralCode),
                        BookingId  = 0,
                        Status     = false, // Pending
                        GiftCardId = 0
                    };

                    // Referred Customer has bookings
                    if (DayaxeDbContext.Bookings.Any(b => b.CustomerId == currentCustomer.CustomerId))
                    {
                        referCustomer.Amount += referCustomer.FirstRewardForOwner;
                        logReferrals.Status   = true; // Complete
                    }

                    // Current Customer have bookings so referrer can use credit
                    if (DayaxeDbContext.Bookings.Any(b => b.CustomerId == referCustomer.CustomerId))
                    {
                        currentCustomer.Amount += referralCustomer.FirstRewardForReferral;
                        logs.Status             = true; // Complete
                    }

                    DayaxeDbContext.CustomerCreditLogs.InsertOnSubmit(logs);
                    DayaxeDbContext.CustomerCreditLogs.InsertOnSubmit(logReferrals);
                }

                Commit();
                transaction.Complete();

                return(currentCustomer != null ? currentCustomer.Amount : 0);
            }
        }
        protected void CheckInDateLink_OnClick(object sender, EventArgs e)
        {
            int  ticketAvailable;
            bool availableProduct = PublicBooking.CheckinDate == null ||
                                    DateTime.UtcNow.ToLosAngerlesTimeWithTimeZone(PublicHotel.TimeZoneId).AddDays(2).Date <= PublicBooking.CheckinDate.Value;
            var param = new CheckAvailableProductParams
            {
                ProductId   = PublicProduct.ProductId,
                CheckInDate = _selectedCheckInDate,
                TotalTicket = PublicBooking.Quantity,
                BookingId   = PublicBooking.BookingId,
                IsAdmin     = false,
                TimezoneId  = PublicHotel.TimeZoneId
            };

            availableProduct &= _productRepository.CheckAvailableProduct(param, out ticketAvailable);

            if (!availableProduct)
            {
                Session.Remove("CheckInDate" + PublicBooking.BookingId);
                CheckInDateLink.Text     = "SELECT<br/>CHECK-IN DATE";
                CheckInDateLink.CssClass = "select-checkin-date";
                ScriptManager.RegisterStartupScript(CheckInDateChangePanel, CheckInDateChangePanel.GetType(), "Update_Not_Available", "$(function(){$('#updateFail').modal('show');});", true);
                return;
            }

            var  logs     = new CustomerCreditLogs();
            bool isRefund = false;

            try
            {
                if (!PublicBooking.HasInvoice)
                {
                    MaintainOldInvoices();
                }

                var newPrice = _productRepository.GetById(PublicProduct.ProductId, _selectedCheckInDate).ActualPriceWithDate;

                double actualPrice = GetActualPrice(newPrice);

                double diffPrice = actualPrice * PublicBooking.Quantity - PublicBooking.TotalPrice;

                // Charge
                if (diffPrice > 0)
                {
                    Charges(diffPrice, newPrice, actualPrice);

                    PublicBooking.TotalPrice   += diffPrice;
                    PublicBooking.HotelPrice    = actualPrice;
                    PublicBooking.MerchantPrice = newPrice.Price;
                }
                else if (diffPrice < 0) //Refund
                {
                    double payByCard = Math.Abs(diffPrice) - PublicBooking.PayByCredit;
                    if (PublicBooking.PayByCredit > 0)
                    {
                        var market = (from mh in _productRepository.MarketHotelList
                                      join m in _productRepository.MarketList on mh.MarketId equals m.Id
                                      where mh.HotelId == PublicHotel.HotelId
                                      select m).FirstOrDefault();
                        logs = new CustomerCreditLogs
                        {
                            CustomerId = PublicCustomerInfos != null
                                ? PublicCustomerInfos.CustomerId
                                : PublicBooking.CustomerId,
                            ProductId   = PublicBooking.ProductId,
                            Description = string.Format("{0} – {1} – {2} – {3}",
                                                        PublicProduct.ProductName,
                                                        PublicHotel.HotelName,
                                                        market != null ? market.LocationName : "",
                                                        PublicBooking.BookingIdString),
                            CreatedBy   = PublicCustomerInfos != null ? PublicCustomerInfos.CustomerId : 0,
                            CreatedDate = DateTime.UtcNow,
                            CreditType  = payByCard >= 0
                                ? (byte)Enums.CreditType.FullPurchaseRefund
                                : (byte)Enums.CreditType.PartialPuchaseRefund,
                            ReferralId = 0,
                            BookingId  = PublicBooking.BookingId,
                            Status     = true,
                            GiftCardId = 0
                        };
                        PublicBooking.PaymentType = (byte)Enums.PaymentType.DayAxeCredit;

                        // Refund All of Credit Used
                        if (payByCard >= 0)
                        {
                            PublicBooking.PayByCredit = 0;
                        }
                        else
                        {
                            PublicBooking.PayByCredit -= Math.Abs(diffPrice);
                        }
                    }

                    // Refund More with Stripe
                    if (payByCard > 0)
                    {
                        Refund(payByCard, new KeyValuePair <double, double>(PublicBooking.MerchantPrice, 0),
                               PublicBooking.HotelPrice);

                        PublicBooking.PaymentType = (byte)Enums.PaymentType.Stripe;

                        var        cardService = new StripeCardService();
                        StripeCard stripeCard  = cardService.Get(PublicCustomerInfos.StripeCustomerId,
                                                                 PublicCustomerInfos.StripeCardId);
                        StripeCardString = string.Format("{0} {1}", stripeCard.Brand, stripeCard.Last4);
                    }

                    PublicBooking.TotalPrice   += diffPrice;
                    PublicBooking.HotelPrice    = actualPrice;
                    PublicBooking.MerchantPrice = newPrice.Price;
                    isRefund = true;

                    PublicBooking.StripeCardString = StripeCardString;
                    _bookingRepository.RefundBooking(PublicBooking, logs);
                }
                else
                {
                    PublicBooking.TotalPrice   += diffPrice;
                    PublicBooking.HotelPrice    = actualPrice;
                    PublicBooking.MerchantPrice = newPrice.Price;
                }
            }
            catch (Exception ex)
            {
                UpdateNotPossibleLit.Text = ex.Message;
                ScriptManager.RegisterStartupScript(CheckInDateChangePanel, CheckInDateChangePanel.GetType(), "UpdateFail", "$(function(){$('#updateFail').modal('show');});", true);
                return;
            }

            PublicBooking.CheckinDate = _selectedCheckInDate.AddHours(Math.Abs(PublicHotel.TimeZoneOffset));
            PublicBooking.ExpiredDate = _selectedCheckInDate.AddDays(1).AddHours(Math.Abs(PublicHotel.TimeZoneOffset));
            if (isRefund)
            {
                _bookingRepository.Update(PublicBooking);
            }
            else
            {
                _bookingRepository.Update(PublicBooking, 0, logs);
            }

            Session.Remove("CheckInDate" + PublicBooking.BookingId);
            BindExpiredDate();
            CacheLayer.ClearAll();
            updateSuccess.Visible    = true;
            CheckInDateLink.Text     = "SELECT<br/>CHECK-IN DATE";
            CheckInDateLink.CssClass = "select-checkin-date";
            ScriptManager.RegisterStartupScript(CheckInDateChangePanel, CheckInDateChangePanel.GetType(), "ConfirmUpdate", "$(function(){$('#updateSuccess').modal('show');});", true);
        }
        private void CancelBookingClick(object sender, CommandEventArgs e)
        {
            var bookingId = int.Parse(e.CommandArgument.ToString());
            var bookings  = _bookingRepository.GetById(bookingId);
            var products  = _bookingRepository.ProductList.First(x => x.ProductId == bookings.ProductId);
            var hotels    = _bookingRepository.HotelList.First(x => x.HotelId == products.HotelId);
            var market    = (from mh in _bookingRepository.MarketHotelList
                             join m in _bookingRepository.MarketList on mh.MarketId equals m.Id
                             where mh.HotelId == hotels.HotelId
                             select m).FirstOrDefault();

            var dateNow  = DateTime.UtcNow.ToLosAngerlesTimeWithTimeZone(hotels.TimeZoneId).AddDays(2).AddHours(9);
            var bookDate = bookings.BookedDate.ToLosAngerlesTimeWithTimeZone(hotels.TimeZoneId).AddDays(14);

            if ((products.IsCheckedInRequired && bookings.CheckinDate <= dateNow) ||
                (!products.IsCheckedInRequired && bookDate.Date < DateTime.UtcNow.ToLosAngerlesTimeWithTimeZone(hotels.TimeZoneId).Date))
            {
                ClientScript.RegisterStartupScript(GetType(), "Cancel_Not_Available", "$(function(){$('#updateNotPossible').modal('show');});", true);
                return;
            }

            if (!string.IsNullOrEmpty(bookings.StripeChargeId))
            {
                MaintainOldInvoices(bookings);
            }

            var    logs      = new CustomerCreditLogs();
            double payByCard = bookings.TotalPrice - bookings.PayByCredit;

            if (bookings.PayByCredit > 0)
            {
                logs = new CustomerCreditLogs
                {
                    CustomerId  = bookings.CustomerId,
                    ProductId   = bookings.ProductId,
                    Description = string.Format("{0} – {1} – {2} – {3}",
                                                products.ProductName,
                                                hotels.HotelName,
                                                market != null ? market.LocationName : "",
                                                bookings.BookingIdString),
                    Amount      = Math.Abs(bookings.PayByCredit),
                    CreatedBy   = PublicCustomerInfos != null ? PublicCustomerInfos.CustomerId : 0,
                    CreatedDate = DateTime.UtcNow,
                    CreditType  = payByCard >= 0 ? (byte)Enums.CreditType.FullPurchaseRefund : (byte)Enums.CreditType.PartialPuchaseRefund,
                    ReferralId  = 0,
                    BookingId   = bookings.BookingId,
                    Status      = true,
                    GiftCardId  = 0
                };
                bookings.PaymentType        = (byte)Enums.PaymentType.DayAxeCredit;
                bookings.RefundCreditAmount = bookings.PayByCredit;
            }

            if (payByCard > 0)
            {
                Refund(bookings, PublicCustomerInfos, payByCard, bookings.MerchantPrice, bookings.HotelPrice);

                bookings.PaymentType = (byte)Enums.PaymentType.Stripe;
                var        cardService = new StripeCardService();
                StripeCard stripeCard  = cardService.Get(PublicCustomerInfos.StripeCustomerId, PublicCustomerInfos.StripeCardId);
                StripeCardString            = string.Format("{0} {1}", stripeCard.Brand, stripeCard.Last4);
                bookings.StripeRefundAmount = payByCard;
            }

            bookings.TotalRefundAmount = bookings.TotalPrice;
            bookings.StripeCardString  = StripeCardString;
            bookings.CancelDated       = DateTime.UtcNow;
            bookings.PassStatus        = (int)Enums.BookingStatus.Refunded;
            _bookingRepository.RefundBooking(bookings, logs);
            CacheLayer.Clear(CacheKeys.CustomerCreditsCacheKey);
            CacheLayer.Clear(CacheKeys.CustomerCreditLogsCacheKey);

            BindMyDayPassInfo();
        }