public async Task<ActionResult> GetFirstPageData(string contentItemType, string contentItemId)
        {
            Session.ClearPaymentSubmitted();
            var cuponViewModel = new CreateCouponViewModel();
            using (var repository = RepositoryFactory.GetInstance(Session))
            {

                var currencyRetriever = new CurrencyRetriver(HttpContext, Session, repository);
                var stringsManager = new StringsManager(repository);

                var currentCurrency = currencyRetriever.GetCurrent();
                string portalNamePart1;
                string portalNamePart2;
                double price;
                double supportPrice;

                CurrencyDto contentItemCurrency;
                ParseUser teacher;

                if (contentItemType == "lesson")
                {
                    var clipDetailsDto = (repository.FindClipDetails(contentItemId));
                    portalNamePart1 = clipDetailsDto.GetLocalizedField("portalNamePart1");
                    portalNamePart2 = clipDetailsDto.GetLocalizedField("portalNamePart2");

                    teacher = clipDetailsDto.Teacher;

                    price = Convert.ToDouble(clipDetailsDto.Price);
                    supportPrice = Convert.ToDouble(clipDetailsDto.SupportPrice);
                    contentItemCurrency = clipDetailsDto.Currency.ConvertToCurrencyDto();
                    cuponViewModel.ContentItemDetails.ClipId = clipDetailsDto.ObjectId;
                }
                else
                {
                    var bundle = await repository.FindBundleById(contentItemId);
                    portalNamePart1 = bundle.GetLocalizedField("bundleName");
                    portalNamePart2 = string.Empty;

                    teacher = bundle.Teacher;

                    price = bundle.Price;
                    supportPrice = bundle.SupportPrice;
                    contentItemCurrency = bundle.Currency.ConvertToCurrencyDto();
                    cuponViewModel.ContentItemDetails.BundleId = bundle.ObjectId;
                    cuponViewModel.ContentItemDetails.BundleClipIds = bundle.ClipsInBundle.Select(o => o.ObjectId).ToArray();
                }

                cuponViewModel.HelpText = stringsManager.GetLocalizedString(Strings.CouponHelp);
                cuponViewModel.ContentItemDetails.NamePart1 = portalNamePart1;
                cuponViewModel.ContentItemDetails.NamePart2 = portalNamePart2;
                cuponViewModel.TeacherData.TeacherEmailAddress = teacher.GetString("email");
                cuponViewModel.TeacherData.Balance = teacher.GetPointerValue<double>("adminData", "balance");
                cuponViewModel.TeacherData.Currency = (teacher.GetPointerObject<Currency>("currency")).ConvertToCurrencyDto();
                cuponViewModel.TeacherData.LivesInIsrael = teacher.LivesInIsrael(repository);
                var agent = teacher.GetPointerObject<UserAdminData>("adminData").GetPointerObject<ParseUser>("agent");
                cuponViewModel.TeacherData.AgentId =agent != null ? agent.ObjectId : string.Empty;

                await GetCouponDiscountCalculations(price, supportPrice, contentItemCurrency, currentCurrency, teacher, cuponViewModel);
                Session.SetCouponData(cuponViewModel);
                return Json(cuponViewModel, JsonRequestBehavior.AllowGet);
            }
        }
        private void AgentCreditStatement(CreateCouponViewModel createCouponVm, IMyMentorRepository repository, ParseUser agentAccount, ParseUser teacher, ParseUser siteAccount, CommissionsDto globalCommissionsTable, AccountStatementBuilder accountStatementBuilder, List<AccountStatementDto> accountStatements, CurrencyRetriver currencyRetriever)
        {
            if (agentAccount == null)
            {
                //agent user not found ,send email
                //var missingAgent = teacher.GetPointerObject<UserAdminData>("adminData").GetPointerObject<ParseUser>("agent");
                SendErrorEmail(createCouponVm,MyMentorResources.couponErrAgentNotFound);
               // Mailer.SendAgentNotFound(missingAgent.Username,teacher.Username,createCouponVm.EventId);
                return;
            }

            var userAdminData = agentAccount.GetPointerObject<UserAdminData>("adminData");
            var acpAgentCommission = userAdminData.AcpTeacherCommission == Global.NoCommission ? 
                globalCommissionsTable.AgentCommission :
                userAdminData.AcpTeacherCommission;

            var agentSugOsek         = agentAccount.GetPointerObject<SugOsek>("sugOsek");
            var agentGetVat          = agentSugOsek.GetVat ? 1: 0;
            var agentPayVat          = agentSugOsek.PayVat ? 1 :0;
          
            var teacherSugOsek       = teacher.GetPointerObject<SugOsek>("sugOsek");
            var teacherPayVat        = teacherSugOsek.PayVat? 1: 0;            
            var maamFlag             = teacherPayVat == agentGetVat  ? 0 : 1;
            var teachertCurrency     = teacher.GetPointerObject<Currency>("currency").ConvertToCurrencyDto();
            var agentCurrency        = agentAccount.GetPointerObject<Currency>("currency").ConvertToCurrencyDto();
            var emlatHamaraFlag      = agentCurrency.ObjectId != teachertCurrency.ObjectId;
            var conversionCommission = globalCommissionsTable.ConversionCommission;
            var maam                 = globalCommissionsTable.Maam;
            var gapToPay             = createCouponVm.TeacherData.GapToPay;
            var totalCommission      = (gapToPay + (maamFlag * ((-gapToPay/(100 +maam)* maam * teacherPayVat)+(gapToPay*maam/100 *agentGetVat)))) * acpAgentCommission;            
            var agentIncludingVat    = agentSugOsek.GetVat ? maam : 0;
            double emlatHamara;
            
            // זיכוי סוכן
            var agentCreditAccountStatement = accountStatementBuilder.SetAccountStatement(
                agentAccount,
                totalCommission,
                0,
                TransactionType.CouponAgentCommission,
                DateTime.Now,
                currencyRetriever.GetCurrent(),
                includingVAT: agentIncludingVat);
            accountStatements.Add(agentCreditAccountStatement);
            createCouponVm.AgentBalance = agentAccount.GetPointerObject<UserAdminData>("adminData").Balance;

            // חיוב סוכן בעמלת המרה
            if (emlatHamaraFlag)
            {
                emlatHamara = totalCommission*conversionCommission;
                var agentDebitAccountStatement = accountStatementBuilder.SetAccountStatement(
                    agentAccount,
                    0,
                    emlatHamara,
                    TransactionType.CouponAgentExCommission,
                    DateTime.Now,
                    currencyRetriever.GetCurrent(),
                    includingVAT: agentIncludingVat);

                accountStatements.Add(agentDebitAccountStatement);
                createCouponVm.AgentBalance = agentAccount.GetPointerObject<UserAdminData>("adminData").Balance;
            }

            //חיוב האתר בעמלת הסוכן
            maamFlag = 0 == teacherPayVat ? 0 : 1;
            totalCommission = (gapToPay + (maamFlag * ((-gapToPay / (100 + maam) * maam * teacherPayVat) + (gapToPay * maam / 100 * 0)))) * acpAgentCommission;
            var siteAccountDebitStatement = accountStatementBuilder.SetAccountStatement(
                siteAccount,
                0,
                totalCommission,
                TransactionType.CouponAgentCommission,
                DateTime.Now,
                currencyRetriever.GetCurrent());
            accountStatements.Add(siteAccountDebitStatement);
            createCouponVm.SiteAccountBalance = siteAccount.GetPointerObject<UserAdminData>("adminData").Balance;

            if (emlatHamaraFlag)
            {
                //זיכוי האתר בעמלת המרה של הסוכן
                emlatHamara = totalCommission*conversionCommission;
                siteAccountDebitStatement = accountStatementBuilder.SetAccountStatement(
                    siteAccount,
                    emlatHamara,
                    0,
                    TransactionType.CouponAgentExCommission,
                    DateTime.Now,
                    currencyRetriever.GetCurrent());
                accountStatements.Add(siteAccountDebitStatement);
                createCouponVm.SiteAccountBalance = siteAccount.GetPointerObject<UserAdminData>("adminData").Balance; ;
            }
        }
        public async Task<ActionResult> SubmitFirstPage(string email, double discountPrice, string contentItemId, string contentItemType, bool includesSupport)
        {
            using (var repository = RepositoryFactory.GetInstance(Session))
            {
                var currencyRetriever = new CurrencyRetriver(HttpContext, Session, repository);
                var currentCurrency = currencyRetriever.GetCurrent();
                var createCouponVm = await GetSubmitFirstPageViewData(email, repository);
                var teachersBalance = Convert.ToSingle(createCouponVm.TeacherData.Balance);
                var teacherCurrency = createCouponVm.TeacherData.Currency;
               
                createCouponVm.IncludesSupport = includesSupport;
                createCouponVm.CouponDiscountPrice = discountPrice;
                CheckThatDiscountPriceIsValid(discountPrice, createCouponVm);
               
                if (createCouponVm.CouponErrors.HasErrors)
                {
                    return Json(createCouponVm, JsonRequestBehavior.AllowGet);
                }
                
                createCouponVm.TeacherData.FormattedBalance = CurrencyConverter.Convert(teachersBalance,teacherCurrency, currentCurrency).ToCurrency(currentCurrency);
               
                var discountType = GetDiscountType(createCouponVm, discountPrice);

                switch (discountType)
                {
                    case CouponDiscountType.Admin:
                        await CreateAdminOrSelfCoupons(discountPrice, createCouponVm, discountType, repository);
                        break;

                    case CouponDiscountType.Regular:
                        createCouponVm.DiscountType                                     = discountType.ToString();
                        createCouponVm.TeacherData.FormattedGapToPay                    = 0.0.ToCurrency(currentCurrency);
                        createCouponVm.TeacherData.FormattedWillBeChargedFromAccount    = 0.0.ToCurrency(currentCurrency);
                        createCouponVm.TeacherData.FormattedAmountForPayment            = 0.0.ToCurrency(currentCurrency);
                        createCouponVm.TeacherData.AmountForPayment = 0;
                        break;

                    case CouponDiscountType.Special:
                        createCouponVm.DiscountType                                     = discountType.ToString();
                        createCouponVm.TeacherData.GapToPay                             = createCouponVm.GetGapToPay(discountPrice);
                        createCouponVm.TeacherData.AmountForPayment                     = createCouponVm.GetAmountForPayment(currentCurrency,repository);
                        createCouponVm.TeacherData.WillBeChargedFromAccount             = createCouponVm.GetWillBeChargedFromAccount();
                        createCouponVm.TeacherData.FormattedGapToPay                    = createCouponVm.TeacherData.GapToPay.ToCurrency(currentCurrency);
                        createCouponVm.TeacherData.FormattedWillBeChargedFromAccount    = createCouponVm.TeacherData.WillBeChargedFromAccount.ToCurrency(currentCurrency);
                        createCouponVm.TeacherData.FormattedAmountForPayment            = createCouponVm.TeacherData.AmountForPayment.ToCurrency(currentCurrency);
                        break;
                }

                createCouponVm.SelectedCurrency = currentCurrency;
                createCouponVm.CouponExists = repository.FindCoupon(createCouponVm.ContentItemDetails.ClipId, createCouponVm.ContentItemDetails.BundleId, createCouponVm.TeacherData.TeacherId, createCouponVm.CouponStudentDetails.StudentUserId) != null;
                Session.SetCouponData(createCouponVm);
                return Json(createCouponVm, JsonRequestBehavior.AllowGet);
            }
        }
        private async Task StartPaymentProcess(double amountForPayment, string currentUrl, CreateCouponViewModel createCuponVm, ParseRepository repository)
        {
            var currencyRetriever = new CurrencyRetriver(HttpContext, Session, repository);
            var paymentOk = true;
            try
            {
                var itemNameLabel = string.IsNullOrEmpty(createCuponVm.ContentItemDetails.BundleId)
                    ? MyMentorResources.paypalCuponFor
                    : MyMentorResources.paypalCuponForBundle;
                var itemName = string.Concat(itemNameLabel, createCuponVm.ContentItemDetails.NamePart1, " ", createCuponVm.ContentItemDetails.NamePart2);
                var ppManager = new ExpressCheckoutManager(currentUrl);
               
                var paypalCurrencyCode = createCuponVm.TeacherData.Currency.PaypalCode;
                amountForPayment = CurrencyConverter.Convert(amountForPayment,currencyRetriever.GetCurrent(),createCuponVm.TeacherData.Currency);
                var validationResponse = ppManager.CouponSpecialDiscountPaymentValidation(itemName, amountForPayment, paypalCurrencyCode);
                
                createCuponVm.PaymentApprovalUrl = validationResponse.ValidationUrl;
                createCuponVm.PaymentId = validationResponse.PaymentId;

                //update paymentid in the event record
                createCuponVm.EventId =
                    await
                        CreateUpdateEvent(createCuponVm, EventStatus.EventStarted, repository);
            }
            catch (Exception ex)
            {
                paymentOk = false;
                mLogger.Log(LogLevel.Error, ex);
            }

            if (!paymentOk)
            {
                await DeleteCoupon(createCuponVm, repository);
                await CreateUpdateEvent(createCuponVm, EventStatus.EventErrorResolved, repository);
            }
        }
 private double ConvertToNis(double amountToConvert, out CurrencyDto currentCurrency)
 {
     using (var repository = RepositoryFactory.GetInstance(Session))
     {
         var currencyRetriever = new CurrencyRetriver(HttpContext, Session, repository);
         currentCurrency = currencyRetriever.GetCurrent();
         var defaultCurrency = repository.FindDefaultCurrency();
         return CurrencyConverter.Convert(amountToConvert, currentCurrency, defaultCurrency);
     }
 }
        public string GetConvertedCurrency(string sourceCurrencyId, float amount = 0)
        {
            if (string.IsNullOrEmpty(sourceCurrencyId))
            {
                return "0";
            }
            using (var repository = RepositoryFactory.GetInstance(Session))
            {
                var currencyRetriver = new CurrencyRetriver(HttpContext, Session, repository);
                var sourceCurrency = repository.FindAllCurrencies().First(item => item.ObjectId == sourceCurrencyId);

                return CurrencyConverter.Convert(amount, sourceCurrency, currencyRetriver.GetCurrent()).ToString("0.00");
            }
        }
        private  void GetContentItems(LessonsViewModel model, ContentItemsRequest contentItemsRequest)
        {
            using (var repository = RepositoryFactory.GetInstance(Session))
            {
                var currencyRetriver = new CurrencyRetriver(HttpContext, Session, repository);
                var defaultCurrency = repository.FindDefaultCurrency();
                var currentUserId = Session.GetLoggedInUser() != null
                    ? Session.GetLoggedInUser().ObjectId
                    : string.Empty;

                contentItemsRequest.WorldId = _worldId;
                var lessonsData = repository.FindAggregatedBundlesAndClips(contentItemsRequest);
                model.ContentItems = lessonsData.Items;
                model.ItemsCount = lessonsData.Count;
                foreach (var contentItem in model.ContentItems)
                {
                    CurrencyDto source = contentItem.Currency ?? defaultCurrency;
                    CurrencyDto target = currencyRetriver.GetCurrent();
                    contentItem.ConvertedPrice = CurrencyConverter.Convert(float.Parse(contentItem.Price), source, target).ToCurrency(currencyRetriver.GetCurrent());
                    contentItem.ConvertedPriceWithSupport =CurrencyConverter.Convert(float.Parse(contentItem.PriceWithSupport), source, target).ToCurrency(currencyRetriver.GetCurrent());
                    SetDisplayIncludeInActiveBundle(contentItem, currentUserId);
                }
            }
            //  model.ItemsCount = lessonsData.Count;
        }
        private  AccountStatementDto TeacherAccountCreditStatement(CreateCouponViewModel createCouponVm, AccountStatementBuilder accountStatementBuilder, 
            double paymentTransaction, List<AccountStatementDto> accountStatements, ParseUser teacher, CurrencyRetriver currencyRetriever)
        {
            var currentCurrencyDto = currencyRetriever.GetCurrent();
            // add creding + debit record for teacher            
            var teacherAccountCreditStatement =  accountStatementBuilder.SetAccountStatement(
                teacher,
                paymentTransaction, 
                0,
                TransactionType.CouponBuyerPayment,
                DateTime.Now,
                currentCurrencyDto);

            var teacherAccountDebitStatement =  accountStatementBuilder.SetAccountStatement(
                teacher, 
                0,
                createCouponVm.TeacherData.GapToPay, 
                TransactionType.CouponBuyerDebit,
                DateTime.Now,
                currentCurrencyDto);

            createCouponVm.TeacherData.Balance = teacher.GetPointerObject<UserAdminData>("adminData").Balance;
            accountStatements.AddRange(new[]
            {
                teacherAccountCreditStatement,
                teacherAccountDebitStatement,
            });
            return teacherAccountCreditStatement;
        }
        private async Task UpdateBundle(BundleUpdateViewModel model)
        {
            using (var repository = RepositoryFactory.GetInstance(Session))
            {
                var currencyRetriver = new CurrencyRetriver(HttpContext, Session, repository);
                var existingBundle = await repository.FindBundleById(model.ObjectId);
                var bundle = model.GetBundle();
                var activeStatusString =
                    repository.FindClipStatuses()
                        .Single(o => o.Status == LessonStatus.Active.ToLower())
                        .GetLocalizedField("status");

                var statusChanged = existingBundle.Status.ObjectId != bundle.Status.ObjectId;
                if (statusChanged)
                {
                    var hasInactiveClips = model.BundleClips.Any(o => o.Status != activeStatusString);
                    ClipStatus newStatus = null;
                    newStatus = Task.Run(() => bundle.Status.FetchIfNeededAsync()).Result;


                    if (newStatus.Status == LessonStatus.Active.ToLower())
                    {
                        if (hasInactiveClips)
                        {
                            throw new StatusChangeException(MyMentorResources.updateBundleInactiveLessonInBundle);
                        }
                    }
                }
                bundle.Currency = currencyRetriver.GetCurrent().ConvertToDomain();
                await repository.UpdateBundle(bundle);
            }
        }
        public ActionResult SearchLessons(ContentItemsRequest request = null)
        {
            using (var repository = RepositoryFactory.GetInstance(Session))
            {
                var bundleStatusId = Request["StatusId"];
                var teacherName = Request["TeacherName"];
                var bundleStatus = repository.FindClipStatuses().SingleOrDefault(o => o.ObjectId == bundleStatusId);
                var isBundleActive = bundleStatus != null && bundleStatus.Status_en_us == BL.Consts.LessonStatus.Active;

                if (request != null)
                {
                    request.PageSize = -1;
                    request.ActiveStatusOnly = isBundleActive;
                    request.WorldId = _worldId;
                    request.category5 = teacherName;
                }

                var clips = repository.FindAllClips(request);
                var defaultCurrency = repository.FindDefaultCurrency();
                var minimalData = clips.Items.ToMinimalData().ToArray();
                var currencyRetriver = new CurrencyRetriver(HttpContext, Session, repository);

                foreach (var data in minimalData)
                {
                    CurrencyDto source = data.Currency ?? defaultCurrency;
                    CurrencyDto target = currencyRetriver.GetCurrent();
                    data.Price = CurrencyConverter.Convert(float.Parse(data.Price), source, target).ToString("0.00");
                }

                return PartialView("LessonsSearchResults", minimalData);
            }
        }
 private async Task<string> AddBundle(BundleUpdateViewModel model, string worldContentTypeId)
 {
     using (var repository = RepositoryFactory.GetInstance(Session))
     {
         var currencyRetriver = new CurrencyRetriver(HttpContext, Session, repository);
         var bundle = model.GetBundle();
         bundle.Teacher = ParseObject.CreateWithoutData<ParseUser>(model.TeacherId);
         bundle.Currency = currencyRetriver.GetCurrent().ConvertToDomain();
         bundle.ContentType = new WorldContentType();
         bundle.ContentType.ObjectId = worldContentTypeId;
         return await repository.AddBundle(bundle);
     }
 }
        public async Task<ActionResult> GetBundleEditData(string bundleId)
        {
            using (var repository = RepositoryFactory.GetInstance())
            {
                var selectedBundle = await repository.FindBundleById(bundleId);
                CurrencyDto defaultCurrency = null;
                defaultCurrency = repository.FindDefaultCurrency();

                var currencyRetriver = new CurrencyRetriver(HttpContext, Session, repository);
                CurrencyDto sourceCurrency = selectedBundle.Currency.ConvertToCurrencyDto() ?? defaultCurrency;
                CurrencyDto targetCurrency = currencyRetriver.GetCurrent();

                var model = GetBundleInitViewModel(selectedBundle);
                model.SelectedCategory1Value = selectedBundle.Category1 != null ? selectedBundle.Category1.ObjectId : "";
                model.SelectedCategory2Value = selectedBundle.Category2 != null ? selectedBundle.Category2.ObjectId : "";
                model.SelectedCategory3Value = selectedBundle.Category3 != null ? selectedBundle.Category3.ObjectId : "";
                model.SelectedCategory4Value = selectedBundle.Category4 != null ? selectedBundle.Category4.ObjectId : "";
                model.SelectedStatus = selectedBundle.Status.ObjectId;
                model.ObjectId = selectedBundle.ObjectId;
                model.Remarks_en_us = selectedBundle.Remarks_en_us ?? string.Empty;
                model.Remarks_he_il = selectedBundle.Remarks_he_il ?? string.Empty;
                model.Description_en_us = selectedBundle.Description_en_us ?? string.Empty;
                model.Description_he_il = selectedBundle.Description_he_il ?? string.Empty;
                model.TeacherName = selectedBundle.Teacher.GetFullName(Language.CurrentLanguageCode);
                model.Price =CurrencyConverter.Convert(selectedBundle.Price, sourceCurrency, targetCurrency).ToString("0.00");
                model.SupportPrice =CurrencyConverter.Convert(selectedBundle.SupportPrice, sourceCurrency, targetCurrency).ToString("0.00");
                model.FirstName = selectedBundle.Teacher.GetLocalizedField("firstName");
                model.LastName = selectedBundle.Teacher.GetLocalizedField("lastName");
                model.CityOfResidence = selectedBundle.Teacher.GetLocalizedField("cityOfResidence");

                if (selectedBundle.CreatedAt.HasValue)
                {
                    model.Created = selectedBundle.CreatedAt.Value.ToString("dd/MM/yyyy");
                }
                if (selectedBundle.UpdatedAt.HasValue)
                {
                    model.Updated = selectedBundle.UpdatedAt.Value.ToString("dd/MM/yyyy");
                }
                if (selectedBundle.ClipsInBundle != null)
                {
                    foreach (var clipDetails in selectedBundle.ClipsInBundle)
                    {
                        sourceCurrency = clipDetails.Currency.ConvertToCurrencyDto() ?? defaultCurrency;
                        SetClipViewModelInBunde(model, clipDetails, sourceCurrency, targetCurrency);
                    }
                }
                model.MinimumPrice = GetBundleMinimumPriceInternal(model.BundleClips).ToString("0.00");
                return Json(model, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult GetBundleCreateData(string clipId)
        {
            if (string.IsNullOrEmpty(clipId))
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }

            using (var repository = RepositoryFactory.GetInstance(Session))
            {
                var currencyRetriver = new CurrencyRetriver(HttpContext, Session, repository);
                CurrencyDto defaultCurrency = null;
                defaultCurrency = repository.FindDefaultCurrency();

                var clipDetails = repository.FindClipDetails(clipId);
                var model = GetBundleInitViewModel(null);

                CurrencyDto sourceCurrency = clipDetails.Currency.ConvertToCurrencyDto() ?? defaultCurrency;
                CurrencyDto targetCurrency = currencyRetriver.GetCurrent();

                SetClipViewModelInBunde(model, clipDetails, sourceCurrency, targetCurrency);
                model.TeacherName = clipDetails.Teacher.GetFullName(Language.CurrentLanguageCode);
                model.TeacherId = clipDetails.Teacher.ObjectId;

                model.SelectedCategory1Value = clipDetails.Category1 != null ? clipDetails.Category1.ObjectId : "";
                model.SelectedCategory2Value = clipDetails.Category2 != null ? clipDetails.Category2.ObjectId : "";
                model.SelectedCategory3Value = clipDetails.Category3 != null ? clipDetails.Category3.ObjectId : "";
                model.SelectedCategory4Value = clipDetails.Category4 != null ? clipDetails.Category4.ObjectId : "";
                //model.SelectedStatus = clipDetails.Status.ObjectId;
                model.Remarks_he_il = string.Empty;
                model.Remarks_he_il = string.Empty;
                model.Description_en_us = string.Empty;
                model.Description_he_il = string.Empty;

                model.FirstName = clipDetails.Teacher.GetLocalizedField("firstName");
                model.LastName = clipDetails.Teacher.GetLocalizedField("lastName");
                model.CityOfResidence = clipDetails.Teacher.GetLocalizedField("cityOfResidence");
                 return Json(model, JsonRequestBehavior.AllowGet);
            }
        }
        private static void VatCreditStatement(CreateCouponViewModel createCouponVm, double maamPaymentCredit, AccountStatementBuilder accountStatementBuilder, List<AccountStatementDto> accountStatements, AccountStatementDto teacherAccountCreditStatement, double maam, double maamFromBalance, ParseUser maamAccount, ParseUser maamBalanceAccount, CurrencyRetriver currencyRetriever)
        {
            if (maamPaymentCredit > 0)
            {
                // add record for mamm account
                var maamAccountCreditStatement =  accountStatementBuilder.SetAccountStatement(
                   maamAccount,
                    maamPaymentCredit,
                    0,
                    TransactionType.CouponVatCredit,
                    DateTime.Now,
                    currencyRetriever.GetCurrent());
                
                accountStatements.Add(maamAccountCreditStatement);
                createCouponVm.MaamAccountBalance = maamAccount.GetPointerObject<UserAdminData>("adminData").Balance;
                if (teacherAccountCreditStatement != null)
                {
                    teacherAccountCreditStatement.IncludingVat = maam;
                }
            }

            if (maamFromBalance > 0)
            {
                // add record for mamm balance account מעמ יתרות
                var maamBalanceAccountCreditStatement =  accountStatementBuilder.SetAccountStatement(
                   maamBalanceAccount,
                    maamFromBalance,
                    0,
                    TransactionType.CouponVatCredit,
                    DateTime.Now,
                    currencyRetriever.GetCurrent());

                accountStatements.Add(maamBalanceAccountCreditStatement);
                createCouponVm.MaamBalanceAccountBalance = maamBalanceAccount.GetPointerObject<UserAdminData>("adminData").Balance;
            }
        }
        private  void GetBundles(ContentItemsRequest request, LessonsViewModel model, IMyMentorRepository repository)
        {
            var currencyRetriver = new CurrencyRetriver(HttpContext, Session, repository);
            var defaultCurrency = repository.FindDefaultCurrency();
            var currentUserId = Session.GetLoggedInUser() != null ? Session.GetLoggedInUser().ObjectId : string.Empty;

            model.LessonDisplayMode = LessonDisplayMode.Bundles;
            var findBundlesResult =  repository.FindBundlesByClipId(request.clipId);
            if (!findBundlesResult.ClipToBundle.Any())
            {
                request.clipId = null;
                GetLessons(request, model, repository);
                return;
            }

            model.BundlesViewModel.ContentItem = findBundlesResult.SelectedClip.ToDto();
            model.BundlesViewModel.Bundles = findBundlesResult.ClipToBundle.Select(o => o.Key).ToDto().ToArray();

            CurrencyDto sourceCurrency = model.BundlesViewModel.ContentItem.Currency ?? defaultCurrency;
            CurrencyDto targetCurrency = currencyRetriver.GetCurrent();

            model.BundlesViewModel.ContentItem.ConvertedPrice = CurrencyConverter.Convert(float.Parse(model.BundlesViewModel.ContentItem.Price), sourceCurrency, targetCurrency).ToCurrency(currencyRetriver.GetCurrent());
            model.BundlesViewModel.ContentItem.ConvertedPriceWithSupport = CurrencyConverter.Convert(float.Parse(model.BundlesViewModel.ContentItem.PriceWithSupport), sourceCurrency, targetCurrency).ToCurrency(currencyRetriver.GetCurrent());

            foreach (var bundleViewModel in model.BundlesViewModel.Bundles)
            {
                sourceCurrency = bundleViewModel.Currency.ConvertToCurrencyDto() ?? defaultCurrency;
                Bundle bundle = findBundlesResult.ClipToBundle.First(ctb => ctb.Key.ObjectId == bundleViewModel.ObjectId).Key;
                bundleViewModel.Clips = findBundlesResult.ClipToBundle[bundle].ToDto();
                bundleViewModel.ConvertedPrice = CurrencyConverter.Convert(float.Parse(bundleViewModel.Price), sourceCurrency, targetCurrency).ToCurrency(currencyRetriver.GetCurrent());
                bundleViewModel.ConvertedSupportPrice = CurrencyConverter.Convert(float.Parse(bundleViewModel.SupportPrice), sourceCurrency, targetCurrency).ToCurrency(currencyRetriver.GetCurrent());
                bundleViewModel.IsActive = bundle.GetPointerObject<ClipStatus>("status").Status == LessonStatus.Active.ToLower();

                float allClipsPrices = 0;
                foreach (var clip in bundleViewModel.Clips)
                {
                    sourceCurrency = clip.Currency ?? defaultCurrency;
                    var convertedClipPrice = CurrencyConverter.Convert(float.Parse(clip.Price), sourceCurrency, targetCurrency);
                    clip.ConvertedPrice = convertedClipPrice.ToCurrency(currencyRetriver.GetCurrent());
                    clip.ConvertedPriceWithSupport = CurrencyConverter.Convert(float.Parse(clip.PriceWithSupport), sourceCurrency, targetCurrency).ToCurrency(currencyRetriver.GetCurrent());
                    allClipsPrices += convertedClipPrice;
                    clip.ExistsInMultipleBundles = findBundlesResult.ClipToBundle.Count(x => x.Value.Select(_ => _.ObjectId).Contains(clip.ObjectId)) > 1;
                    clip.SelectedContentItem = clip.ObjectId == model.BundlesViewModel.ContentItem.ObjectId;
                    SetDisplayIncludeInActiveBundle(clip, currentUserId);
                }
                bundleViewModel.ConvertedPriceWithoutDiscount = allClipsPrices.ToCurrency(currencyRetriver.GetCurrent());
            }
        }
        private void SiteAccountCreditStatement(CreateCouponViewModel createCouponVm, AccountStatementBuilder accountStatementBuilder, double amountForSiteAccountCredit, List<AccountStatementDto> accountStatements, ParseUser siteAccount, CurrencyRetriver currencyRetriever)
        {
            var siteAccountCreditStatement =  accountStatementBuilder.SetAccountStatement(
                siteAccount,
                amountForSiteAccountCredit,
                0,
                TransactionType.CouponSiteCredit,
                DateTime.Now,
                currencyRetriever.GetCurrent());

            createCouponVm.SiteAccountBalance = siteAccount.GetPointerObject<UserAdminData>("adminData").Balance;
            accountStatements.Add(siteAccountCreditStatement);
        }
        public ActionResult GetContentItemMetaData(string itemId)
        {
            var model = new LessonUpdateViewModel();
            var retriever = CategoryRetrieverFactory.GetInstance(_worldId);
            var categories =  retriever.GetCategories();
            using (var repository = RepositoryFactory.GetInstance(Session))
            {
                var clipDetails = repository.FindClipDetails(itemId);
                var currencyRetriver = new CurrencyRetriver(HttpContext, Session, repository);
                var stringManager = new StringsManager(repository);

                CurrencyDto defaultCurrency = repository.FindDefaultCurrency();
                CurrencyDto targetCurrency = currencyRetriver.GetCurrent();
                CurrencyDto sourceCurrency = clipDetails.Currency.ConvertToCurrencyDto() ?? defaultCurrency;
                var teacherFirstName = clipDetails.GetLocalizedPointerValue("teacher", "firstName");
                var teacherLastName = clipDetails.GetLocalizedPointerValue("teacher", "lastName");
                var teacherCityOfResidence = clipDetails.GetLocalizedPointerValue("teacher", "cityOfResidence");
                var clipStatusName = clipDetails.GetLocalizedPointerValue("status", "status");
                var teacherPublishingStatus =
                    (Session.GetLoggedInUser().GetPointerObject<UserAdminData>("adminData")).GetPointerObjectId(
                        "userPublishingStatus");

                var showReadingDates = (repository.FindWorlds(_worldId)).Single().ReadingDates;

                model.ShowReadingDates = showReadingDates;
                model.PortalNamePart1 = clipDetails.GetLocalizedField("portalNamePart1");
                model.PortalNamePart2 = clipDetails.GetLocalizedField("portalNamePart2");
                model.CategoryName1 = categories[0].Label;
                model.CategoryName2 = categories[1].Label;
                model.CategoryName3 = categories[2].Label;
                model.CategoryName4 = categories[3].Label;

                model.Category1Values = categories[0].Values.ToArray();
                model.Category2Values = categories[1].Values.ToArray();
                model.Category3Values = categories[2].Values.ToArray();
                model.Category4Values = categories[3].Values.ToArray();

                model.SelectedCategory1Value = clipDetails.Category1 != null ? clipDetails.Category1.ObjectId : "";
                model.SelectedCategory2Value = clipDetails.Category2 != null ? clipDetails.Category2.ObjectId : "";
                model.SelectedCategory3Value = clipDetails.Category3 != null ? clipDetails.Category3.ObjectId : "";
                model.SelectedCategory4Value = clipDetails.Category4 != null ? clipDetails.Category4.ObjectId : "";

                model.Created = clipDetails.CreatedAt.HasValue?clipDetails.CreatedAt.Value.ToString("dd/MM/yyyy"):string.Empty;
                model.Updated = clipDetails.UpdatedAt.HasValue ? clipDetails.UpdatedAt.Value.ToString("dd/MM/yyyy") : string.Empty;
                model.Version = clipDetails.Version;

                model.Remarks_he_il = clipDetails.Remarks_he_il;
                model.Remarks_en_us = clipDetails.Remarks_en_us;

                model.Performer_he_il = clipDetails.Performer_he_il;
                model.Performer_en_us = clipDetails.Performer_en_us;

                model.Description_he_il = clipDetails.Description_he_il;
                model.Description_en_us = clipDetails.Description_en_us;

                var lessonPrice = CurrencyConverter.Convert(clipDetails.Price, sourceCurrency, targetCurrency);
                var lessonPriceWithSupport = CurrencyConverter.Convert(clipDetails.SupportPrice, sourceCurrency,
                    targetCurrency);

                model.LessonPrice = lessonPrice.ToString("0.00");
                model.SupportPrice = lessonPriceWithSupport.ToString("0.00");
                model.MinimumPrice =
                    CurrencyConverter.Convert(clipDetails.GetPointerValue<double>("category3", "minPrice"),
                        sourceCurrency, targetCurrency).ToString("0.00");

                model.TeacherFirstName = string.IsNullOrEmpty(teacherFirstName) ? string.Empty : teacherFirstName;
                model.TeacherLastName = string.IsNullOrEmpty(teacherLastName) ? string.Empty : teacherLastName;

                model.TeacherResidence = teacherCityOfResidence;
                model.SelectedStatus = clipDetails.Status.ObjectId;
                model.CalendarRegional = Language.Direction == LanguageDirection.RTL ? "he" : "";

                model.IsRTL = Language.Direction == LanguageDirection.RTL;
                model.CurrencyId = clipDetails.Currency != null ? clipDetails.Currency.ObjectId : string.Empty;
                model.DefaultCurrencyId = repository.FindDefaultCurrency().ObjectId;

                model.LessonTitleTemplatePart1 = stringManager.GetTemplate(_worldId, StringTemplates.TitlePart1,
                    Language.CurrentLanguageCode);
                model.LessonTitleTemplatePart2 = stringManager.GetTemplate(_worldId, StringTemplates.TitlePart2,
                    Language.CurrentLanguageCode);

                model.StatusValues =
                    repository.FindStatusOptionsByTeacherPublishingStatusAndClipStatus(teacherPublishingStatus,
                        clipDetails.Status.ObjectId, Session.GetLoggedInUserRoleName() == RoleNames.ADMINISTRATORS);
                if (!model.StatusValues.Any(item => item.Key == clipDetails.Status.ObjectId))
                {
                    var statusValuesList = new List<KeyValuePair<string, string>>(model.StatusValues);
                    statusValuesList.Insert(0,
                        new KeyValuePair<string, string>(clipDetails.Status.ObjectId, clipStatusName));
                    model.StatusValues = statusValuesList.ToArray();
                }

                if (clipDetails.ReadingDates != null)
                {
                    foreach (var readingDate in clipDetails.ReadingDates)
                    {
                        model.ReadingDates.Add(((DateTime) readingDate).ToString("dd/MM/yyyy"));
                    }
                }

                return Json(model, JsonRequestBehavior.AllowGet);
            }
        }
        private  string GetEmailTemplate(CreateCouponViewModel createCouponVm,IMyMentorRepository repository)
        {
            var currenctUserFullName = Session.GetLoggedInUser().GetFullName(Language.CurrentLanguageCode);
            var teacherFullName = createCouponVm.TeacherData.TeacherFullName;

            var currencyRetriever = new CurrencyRetriver(HttpContext, Session, repository);

            var itemType = repository.FindEntities().Single(x => x.EntityCode == EntityKeys.Coupons.ToString());
            var mailTemplate = new MailTemplate(Language.CurrentCulture);
          
            var emailData = new CouponEmailData();
            emailData.TeacherFullName =currenctUserFullName == teacherFullName ? createCouponVm.TeacherData.TeacherFullName:currenctUserFullName;
            emailData.CouponNumber = createCouponVm.CouponId;
            emailData.Event = createCouponVm.EventId;
            emailData.ItemNamePart1 = createCouponVm.ContentItemDetails.NamePart1;
            emailData.ItemNamePart2 = createCouponVm.ContentItemDetails.NamePart2;
            emailData.ItemType = itemType.GetLocalizedField("EntityName");
            emailData.OriginalPriceWithCurrency = createCouponVm.ContentItemDetails.FormattedOriginalPrice;
            emailData.StudentPriceWithCurrency = createCouponVm.CouponDiscountPrice.ToCurrency(currencyRetriever.GetCurrent());
            emailData.ValidUntil = createCouponVm.CouponValidUntil;
            emailData.PurchaseDate = DateTime.Now.ToString("dd/MM/yyyy");
            if (!string.IsNullOrEmpty(createCouponVm.EventId))
            {
                emailData.Event = string.Format(MyMentorResources.couponLetterEventPlaceholder, createCouponVm.EventId);
            }            
           
            var mailForStudent = mailTemplate.GetCouponEmail(emailData);
            return mailForStudent;
        }
 private double ConvertToContentItemCurrency(CurrencyDto contentItemCurrency, double amountToConvert)
 {
     using (var repository = RepositoryFactory.GetInstance(Session))
     {
         var currencyRetriever = new CurrencyRetriver(HttpContext, Session, repository);
         return CurrencyConverter.Convert(amountToConvert, currencyRetriever.GetCurrent(), contentItemCurrency);    
     }
     
 }
 public string GetUserCurrencySymbol()
 {
     using (var repository = RepositoryFactory.GetInstance(Session))
     {
         var currencyRetriever = new CurrencyRetriver(HttpContext, Session, repository);
         var current = currencyRetriever.GetCurrent();
         return current.CurrencySymbol;
     }
 }
        public ActionResult FixTransactionErrors(string eventId)
        {
            IMyMentorRepository repository = RepositoryFactory.GetInstance(Session);
            try
            {
                var currencyRetriever = new CurrencyRetriver(HttpContext, Session, repository);
                var currentCurrency = currencyRetriever.GetCurrent();
                IEnumerable<EventDto> eventsDtos = null;

                eventsDtos = repository.FindPendingCouponPurchaseEvents(eventId);

                foreach (var eventsDto in eventsDtos)
                {
                    bool couponCreated = !string.IsNullOrEmpty(eventsDto.CouponId);
                    if (!couponCreated)
                    {
                        eventsDto.EventStatus = EventStatus.EventErrorResolved;
                        repository.CreateUpdateEvent(eventsDto);
                        continue;
                    }
                    var createCouponVm = CreateCouponViewModel(eventsDto);
                    HandlePaymentRequiredRecovery(createCouponVm, eventsDto, repository, currencyRetriever, currentCurrency);
                }
            }
            finally
            {
                repository.Dispose();
            }

            return Redirect("TransactionErrors");
        }