private static ShowEntitlement CreateShowEntitlement(EntitlementRequest request, ShowSubscriptionProduct subscription, ProductShow show, DateTime registDt)
 {
     ShowEntitlement entitlement = new ShowEntitlement()
     {
         EndDate = GetEntitlementEndDate(subscription.Duration, subscription.DurationType, registDt),
         Show = (Show)show.Show,
         OfferingId = offeringId,
         LatestEntitlementRequest = request
     };
     return entitlement;
 }
 private static ShowEntitlement CreateShowEntitlement(EntitlementRequest request, ShowSubscriptionProduct subscription, ProductShow show, DateTime registDt)
 {
     var currentDt = registDt;
     if (subscription.BreakingDate != null)
         registDt = (DateTime)subscription.BreakingDate > currentDt ? (DateTime)subscription.BreakingDate : currentDt;
     ShowEntitlement entitlement = new ShowEntitlement()
     {
         EndDate = MyUtility.getEntitlementEndDate(subscription.Duration, subscription.DurationType, registDt),
         Show = (Show)show.Show,
         OfferingId = GlobalConfig.offeringId,
         LatestEntitlementRequest = request
     };
     return entitlement;
 }
        public ActionResult PPS()
        {
            var absnow_context = new ABSNowEntities();
            var context = new IPTV2Entities();
            DateTime registDt = DateTime.Now;

            var customers = absnow_context.TFCNowRetailMigrationTFCTVs.Where(t => t.LicenseEndDate > registDt && t.IsMigrated == 0);
            var customerIds = customers.Select(t => t.Email.ToLower()).ToArray();
            var users = context.Users.Where(u => customerIds.Contains(u.TfcNowUserName.ToLower()));

            var TFCnowUsernames = users.Select(t => t.TfcNowUserName.ToLower()).ToArray();

            var migratedUsers = customers.Where(c => TFCnowUsernames.Contains(c.Email.ToLower())).OrderBy(c => c.Email);
            var ctp = migratedUsers.Count();

            var MigratedUsersWithGoms = migratedUsers.Join(absnow_context.TFCNowRetailMigrationIDs, license => license.TFCnowPackageID, package => package.TFCnowPackageID, (license, package) => new { license, package })
                .Select(m => new { Id = m.license.ID, Email = m.license.Email, LicenseEndDate = m.license.LicenseEndDate, TFCnowPackageId = m.license.TFCnowPackageID, GOMSInternalId = m.package.GOMSInternalID })
                .OrderBy(m => m.Email);

            List<MigratedUser> list = new List<MigratedUser>();
            foreach (var item in MigratedUsersWithGoms)
            {
                var user = context.Users.FirstOrDefault(u => u.TfcNowUserName.ToLower() == item.Email.ToLower());
                if (user == null)
                    throw new TFCtvObjectIsNull("User");
                Product product = context.Products.FirstOrDefault(p => p.GomsProductId == item.GOMSInternalId);
                if (product == null)
                    throw new TFCtvObjectIsNull("Product");

                DateTime endDate = (DateTime)item.LicenseEndDate;
                if (product is ShowSubscriptionProduct)
                {
                    var subscription = (ShowSubscriptionProduct)product;
                    if (subscription.ALaCarteSubscriptionTypeId == 2) // Pay per serye. Extend to 1 year.
                    {
                        endDate = registDt.AddYears(1);
                    }

                    TimeSpan difference = endDate.Subtract(registDt);

                    var category = subscription.Categories.FirstOrDefault();
                    if (category == null)
                        throw new TFCtvObjectIsNull("Category");
                    ShowEntitlement entitlement = null;
                    //Check entitlement for Category/Show
                    var show_entitlement = user.ShowEntitlements.FirstOrDefault(s => s.CategoryId == category.CategoryId);

                    if (show_entitlement != null)
                    {
                        show_entitlement.EndDate = show_entitlement.EndDate.Add(difference);
                        endDate = show_entitlement.EndDate;
                    }
                    else
                    {
                        entitlement = new ShowEntitlement()
                        {
                            EndDate = endDate,
                            Show = category.Show,
                            OfferingId = Global.OfferingId,
                        };
                        user.ShowEntitlements.Add(entitlement);
                    }
                    string reference = String.Format("TNRMTFCTV-{0}", item.Id);

                    EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, category.Product, "cPanel Migration", reference);

                    if (request != null)
                    {
                        if (entitlement != null)
                            entitlement.LatestEntitlementRequest = request;
                        else
                            user.EntitlementRequests.Add(request);
                    }
                    MigrationTransaction transaction = new MigrationTransaction()
                    {
                        Amount = 0,
                        Currency = Global.DefaultCurrency,
                        Date = registDt,
                        OfferingId = Global.OfferingId,
                        Reference = reference,
                        MigratedProductId = (int)product.ProductId
                    };
                    user.Transactions.Add(transaction);

                    list.Add(new MigratedUser()
                    {
                        Id = item.Id,
                        Email = item.Email,
                        LicenseEndDate = item.LicenseEndDate,
                        GOMSInternalId = item.GOMSInternalId,
                        TFCnowPackageId = item.TFCnowPackageId,
                        EntitlementId = show_entitlement != null ? show_entitlement.EntitlementId : entitlement.EntitlementId,
                        EntitlementRequestId = request.EntitlementRequestId,
                        TransactionId = transaction.TransactionId
                    });

                    using (var ctx = new ABSNowEntities())
                    {
                        var taggedLicense = ctx.TFCNowRetailMigrationTFCTVs.FirstOrDefault(t => t.ID == item.Id);
                        if (taggedLicense != null)
                        {
                            taggedLicense.IsMigrated = 1;
                            ctx.SaveChanges();
                        }
                    }
                }
            }

            if (context.SaveChanges() > 0)
            {
                return this.Json(list, JsonRequestBehavior.AllowGet);
            }

            //return this.Json(list, JsonRequestBehavior.AllowGet);
            return this.Json(null, JsonRequestBehavior.AllowGet);
        }
 private static ShowEntitlement CreateShowEntitlement(DateTime startDt, int CategoryId, int Duration, string DurationType, EntitlementRequest request)
 {
     ShowEntitlement entitlement = new ShowEntitlement()
      {
          EndDate = GetEntitlementEndDate(Duration, DurationType, startDt),
          CategoryId = CategoryId,
          OfferingId = offeringId,
          LatestEntitlementRequest = request
      };
     return entitlement;
 }
        public ActionResult _Subscription(FormCollection f)
        {
            Dictionary<string, object> collection = new Dictionary<string, object>();
            collection = MyUtility.SetError(ErrorCode.UnidentifiedError, String.Empty);

            var email = f["EmailAddress"];
            var pId = f["Product"];
            var payment_mode = f["PaymentMode"];
            var reference = f["Reference"];
            var amt = f["Amount"];
            var currency = f["Currency"];
            var edt = f["EndDate"];
            var OverrideDuration = MyUtility.GetCheckBoxValue(Request, "OverrideDuration");
            var isRefund = MyUtility.GetCheckBoxValue(Request, "IsRefund");
            var IncludeWalletLoad = MyUtility.GetCheckBoxValue(Request, "IncludeWalletLoad");
            var registDt = DateTime.Now;
            try
            {
                int Duration = 0;
                string DurationType = String.Empty;
                DateTime endDt = registDt;

                if (String.IsNullOrEmpty(email) || String.IsNullOrEmpty(pId) || String.IsNullOrEmpty(payment_mode) || String.IsNullOrEmpty(reference) || String.IsNullOrEmpty(amt) || String.IsNullOrEmpty(currency))
                    throw new TFCtvMissingRequiredFields();

                if (isRefund && OverrideDuration)
                    throw new TFCtvUnidentifiedError("Is this a refund & Override product's duration can't be checked at the same time.");

                currency = currency.ToUpper();
                reference = reference.ToUpper();

                var context = new IPTV2Entities();
                var user = context.Users.FirstOrDefault(item => item.EMail.ToLower() == email.ToLower());
                if (user == null)
                    throw new TFCtvUserDoesNotExist();

                decimal amount;
                bool amt_result = decimal.TryParse(amt, out amount);
                if (!amt_result)
                    throw new TFCtvUnidentifiedError("Unable to convert Amount to decimal. User input was invalid.");

                int productId;
                bool pId_result = Int32.TryParse(pId, out productId);
                if (!pId_result)
                    throw new TFCtvUnidentifiedError("Unable to convert ProductId to Int32. User input was invalid.");

                if (OverrideDuration)
                {
                    DateTime overridingEndDate;
                    bool overrideDuration_result = DateTime.TryParse(edt, out overridingEndDate);
                    if (!overrideDuration_result)
                        throw new TFCtvUnidentifiedError("Unable to convert End Date to DateTime. User input was invalid.");
                }

                var currency_count = context.Currencies.Count(item => item.Code.ToUpper() == currency);
                if (currency_count == 0)
                    throw new TFCtvUnidentifiedError("Currency does not exist on our list. User input was invalid.");
                if (currency != Global.TrialCurrency)
                    if (user.Country.CurrencyCode.ToUpper() != currency)
                        throw new TFCtvUnidentifiedError("Currency does not match current user's currency.");

                var offering = context.Offerings.Find(Global.OfferingId);
                if (user.HasPendingGomsChangeCountryTransaction(offering))
                    throw new TFCtvUnidentifiedError("Change in location transaction found. Please retry later.");

                var product = context.Products.FirstOrDefault(item => item.ProductId == productId);

                if (product == null)
                    throw new TFCtvProductDoesNotExist();

                if (product is SubscriptionProduct)
                {
                    bool insertTransaction = false;
                    if (product is PackageSubscriptionProduct)
                    {
                        var package_subscription = (PackageSubscriptionProduct)product;
                        Duration = package_subscription.Duration;
                        DurationType = package_subscription.DurationType;

                        if (isRefund) //Refunding a subscription
                            Duration *= -1;

                        //Get Package
                        var package = package_subscription.Packages.FirstOrDefault();
                        if (package == null)
                            throw new TFCtvObjectIsNull("Package");

                        PackageEntitlement entitlement = null;

                        //Check entitlement for package
                        var package_entitlement = user.PackageEntitlements.FirstOrDefault(item => item.PackageId == package.PackageId);

                        if (isRefund) //Refunding a subscription
                            registDt = package_entitlement.EndDate;

                        endDt = MyUtility.GetEntitlementEndDate(Duration, DurationType, registDt);

                        if (package_entitlement != null)
                        {
                            endDt = MyUtility.GetEntitlementEndDate(Duration, DurationType, package_entitlement.EndDate > registDt ? package_entitlement.EndDate : registDt);
                            package_entitlement.EndDate = endDt;
                        }
                        else
                        {
                            entitlement = new PackageEntitlement()
                            {
                                EndDate = endDt,
                                Package = (Package)package.Package,
                                OfferingId = Global.OfferingId,
                            };
                            user.PackageEntitlements.Add(entitlement);
                        }

                        EntitlementRequest request = CreateEntitlementRequest(registDt, endDt, package.Product, "cPanel Settlement", reference);
                        if (request != null)
                        {
                            if (entitlement != null)
                                entitlement.LatestEntitlementRequest = request;
                            else
                                user.EntitlementRequests.Add(request);
                            insertTransaction = true;
                        }
                    }
                    else if (product is ShowSubscriptionProduct)
                    {
                        var show_subscription = (ShowSubscriptionProduct)product;
                        Duration = show_subscription.Duration;
                        DurationType = show_subscription.DurationType;

                        if (isRefund) //Refuding a subscription
                            Duration *= -1;

                        //Get Show
                        var category = show_subscription.Categories.FirstOrDefault();
                        if (category == null)
                            throw new TFCtvObjectIsNull("Category");

                        ShowEntitlement entitlement = null;

                        //Check entitlement for Category/Show
                        var show_entitlement = user.ShowEntitlements.FirstOrDefault(item => item.CategoryId == category.CategoryId);

                        if (isRefund) //Refunding a subscription
                            registDt = show_entitlement.EndDate;

                        endDt = MyUtility.GetEntitlementEndDate(Duration, DurationType, registDt);

                        if (show_entitlement != null)
                        {
                            endDt = MyUtility.GetEntitlementEndDate(Duration, DurationType, show_entitlement.EndDate > registDt ? show_entitlement.EndDate : registDt);
                            show_entitlement.EndDate = endDt;
                        }
                        else
                        {
                            entitlement = new ShowEntitlement()
                            {
                                EndDate = endDt,
                                Show = category.Show,
                                OfferingId = Global.OfferingId,
                            };
                            user.ShowEntitlements.Add(entitlement);
                        }

                        EntitlementRequest request = CreateEntitlementRequest(registDt, endDt, category.Product, "cPanel Settlement", reference);
                        if (request != null)
                        {
                            if (entitlement != null)
                                entitlement.LatestEntitlementRequest = request;
                            else
                                user.EntitlementRequests.Add(request);
                            insertTransaction = true;
                        }
                    }
                    else if (product is EpisodeSubscriptionProduct)
                    {
                        var episode_subscription = (EpisodeSubscriptionProduct)product;
                        Duration = episode_subscription.Duration;
                        DurationType = episode_subscription.DurationType;

                        if (isRefund) //Refuding a subscription
                            Duration *= -1;

                        //Get Episode
                        var episode = episode_subscription.Episodes.FirstOrDefault();
                        if (episode == null)
                            throw new TFCtvObjectIsNull("Episode");

                        EpisodeEntitlement entitlement = null;

                        //Check entitlement for Category/Show
                        var episode_entitlement = user.EpisodeEntitlements.FirstOrDefault(item => item.EpisodeId == episode.EpisodeId);

                        if (isRefund) //Refunding a subscription
                            registDt = episode_entitlement.EndDate;

                        endDt = MyUtility.GetEntitlementEndDate(Duration, DurationType, registDt);

                        if (episode_entitlement != null)
                        {
                            endDt = MyUtility.GetEntitlementEndDate(Duration, DurationType, episode_entitlement.EndDate > registDt ? episode_entitlement.EndDate : registDt);
                            episode_entitlement.EndDate = endDt;
                        }
                        else
                        {
                            entitlement = new EpisodeEntitlement()
                            {
                                EndDate = endDt,
                                Episode = episode.Episode,
                                OfferingId = Global.OfferingId,
                            };
                            user.EpisodeEntitlements.Add(entitlement);
                        }

                        EntitlementRequest request = CreateEntitlementRequest(registDt, endDt, episode.Product, "cPanel Settlement", reference);
                        if (request != null)
                        {
                            if (entitlement != null)
                                entitlement.LatestEntitlementRequest = request;
                            else
                                user.EntitlementRequests.Add(request);
                            insertTransaction = true;
                        }
                    }

                    //Create Purchase & Purchase Items
                    Purchase purchase = null; //CreatePurchase(registDt, "Settlement");
                    PurchaseItem purchase_item = null; //CreatePurchaseItem(user.UserId, product, amount, currency);

                    //user.Purchases.Add(purchase);
                    //user.PurchaseItems.Add(purchase_item);

                    //Insert transaction
                    if (insertTransaction)
                    {
                        switch (Convert.ToInt32(payment_mode))
                        {
                            case 1: // Prepaid Card
                                purchase = CreatePurchase(registDt, "Settlement via Prepaid Card");
                                user.Purchases.Add(purchase);
                                purchase_item = CreatePurchaseItem(user.UserId, product, amount, currency);
                                purchase.PurchaseItems.Add(purchase_item);

                                Ppc Ppc = context.Ppcs.FirstOrDefault(item => item.SerialNumber.ToUpper() == reference);
                                if (Ppc == null)
                                    throw new TFCtvObjectIsNull("Prepaid Card");
                                if (!(Ppc is SubscriptionPpc))
                                    throw new TFCtvEntityFrameworkError("Prepaid Card is not of type: Subscription.");

                                PpcPaymentTransaction pTransaction = new PpcPaymentTransaction()
                                {
                                    Currency = currency,
                                    Reference = reference,
                                    Amount = Convert.ToDecimal(amount),
                                    Product = product,
                                    Purchase = purchase,
                                    SubscriptionPpc = (SubscriptionPpc)Ppc,
                                    Date = registDt,
                                    OfferingId = Global.OfferingId
                                };
                                user.Transactions.Add(pTransaction);
                                break;
                            case 2: // E-Wallet
                                purchase = CreatePurchase(registDt, "Settlement via Wallet");
                                user.Purchases.Add(purchase);
                                purchase_item = CreatePurchaseItem(user.UserId, product, amount, currency);
                                purchase.PurchaseItems.Add(purchase_item);

                                var wallet = user.UserWallets.FirstOrDefault(item => item.IsActive == true);
                                if (IncludeWalletLoad)
                                    wallet.Balance += amount;

                                WalletPaymentTransaction wTransaction = new WalletPaymentTransaction()
                                {
                                    Currency = currency,
                                    Reference = reference,
                                    Amount = Convert.ToDecimal(amount),
                                    Date = registDt,
                                    User = user,
                                    OfferingId = Global.OfferingId
                                };
                                user.Transactions.Add(wTransaction);
                                wallet.WalletPaymentTransactions.Add(wTransaction);
                                break;
                            case 3: // Credit Card
                                purchase = CreatePurchase(registDt, "Settlement via Credit Card");
                                user.Purchases.Add(purchase);
                                purchase_item = CreatePurchaseItem(user.UserId, product, Convert.ToDecimal(amount), currency);
                                purchase.PurchaseItems.Add(purchase_item);

                                CreditCardPaymentTransaction cTransaction = new CreditCardPaymentTransaction()
                                {
                                    Amount = Convert.ToDecimal(amount),
                                    Currency = currency,
                                    Reference = reference,
                                    Date = registDt,
                                    Purchase = purchase,
                                    OfferingId = Global.OfferingId
                                };
                                user.Transactions.Add(cTransaction);
                                break;
                            case 4: // Paypal
                                purchase = CreatePurchase(registDt, "Settlement via Paypal");
                                user.Purchases.Add(purchase);
                                purchase_item = CreatePurchaseItem(user.UserId, product, Convert.ToDecimal(amount), currency);
                                purchase.PurchaseItems.Add(purchase_item);

                                PaypalPaymentTransaction ppTransaction = new PaypalPaymentTransaction()
                                {
                                    Currency = currency,
                                    Reference = reference,
                                    Amount = Convert.ToDecimal(amount),
                                    User = user,
                                    Date = registDt,
                                    OfferingId = Global.OfferingId
                                };
                                user.Transactions.Add(ppTransaction);
                                break;
                            case 5: // Migration
                                MigrationTransaction mTransaction = new MigrationTransaction()
                                {
                                };
                                user.Transactions.Add(mTransaction);
                                break;
                            default: break;
                        }

                        if (context.SaveChanges() > 0)
                        {
                            collection = MyUtility.SetError(ErrorCode.Success, "You have successfully settled a complaint.");
                            // Success
                        }
                    }
                }
            }
            catch (TFCtvException e)
            {
                collection = MyUtility.SetError(e.StatusCode, e.StatusMessage);
            }
            catch (Exception e)
            {
                collection = MyUtility.SetError(ErrorCode.UnidentifiedError, e.Message);
            }

            return Content(MyUtility.BuildJSON(collection), "application/json");
        }
        public ActionResult Migrate()
        {
            if (GlobalConfig.IsTVERegistrationEnabled)
                return RedirectToAction("Index", "Home");

            Dictionary<string, object> collection = new Dictionary<string, object>();
            ErrorCodes errorCode = ErrorCodes.UnknownError;
            string errorMessage = MyUtility.getErrorMessage(ErrorCodes.UnknownError);
            DateTime registDt = DateTime.Now;
            collection = MyUtility.setError(errorCode, errorMessage);

            if (TempData["TFCnowCustomer"] == null)
                return RedirectToAction("Index", "Home");

            if (!MyUtility.isUserLoggedIn())
                return RedirectToAction("Index", "Home");

            Customer customer = (Customer)TempData["TFCnowCustomer"];

            var absnow_context = new ABSNowEntities();

            string TFCnowPackageIds = GlobalConfig.TFCnowPackageIds;
            var packageids = MyUtility.StringToIntList(TFCnowPackageIds);
            var context = new IPTV2Entities();
            var userId = new Guid(User.Identity.Name);
            User user = context.Users.FirstOrDefault(u => u.UserId == userId);
            if (user == null)
                return RedirectToAction("Index", "Migration");



            //Tag account
            user.TfcNowUserName = customer.EmailAddress;
            user.LastUpdated = registDt;
            context.SaveChanges();

            bool isLicenseMigrated = false;
            bool isWalletMigrated = false;
            //Migrate Wallet
            var balance = absnow_context.NCashWalletBalanceTables.FirstOrDefault(u => u.userId.ToLower() == customer.EmailAddress.ToLower());

            if (balance != null)
            {
                if (balance.cashBalance > 0)
                {
                    var transfer_amount = Forex.Convert(context, GlobalConfig.DefaultCurrency, user.Country.CurrencyCode, balance.cashBalance);

                    var userWallet = user.UserWallets.FirstOrDefault(u => u.Currency == user.Country.CurrencyCode && u.IsActive == true);
                    if (userWallet == null)
                    {
                        userWallet = new UserWallet()
                        {
                            Balance = transfer_amount,
                            IsActive = true,
                            Currency = user.Country.CurrencyCode,
                        };
                        user.UserWallets.Add(userWallet);
                    }
                    else
                        userWallet.Balance += transfer_amount;

                    //Create Paypal transaction

                    var ppTransaction = new PaypalReloadTransaction()
                    {
                        Amount = transfer_amount,
                        Currency = user.Country.CurrencyCode,
                        Date = registDt,
                        Reference = String.Format("M-{0}", customer.CustomerID),
                        OfferingId = GlobalConfig.offeringId,
                        UserWallet = userWallet,
                        StatusId = GlobalConfig.Visible
                    };

                    user.Transactions.Add(ppTransaction);
                    if (context.SaveChanges() > 0)
                        isWalletMigrated = true;
                }
            }

            var licenses = absnow_context.LicensePurchaseds.Where(l => l.CustomerID == customer.CustomerID && packageids.Contains(l.PackageID) && l.LicenseEndDate > registDt).OrderByDescending(l => l.LicenseEndDate);

            //Migrate Licenses
            if (licenses.Count() == 0)
            {
                if (isWalletMigrated)
                {
                    user.TfcNowUserName = customer.EmailAddress;
                    context.SaveChanges();
                }

                //  return RedirectToAction("Complete", "Migration");
                //collection = MyUtility.setError(ErrorCodes.UnknownError, "No licenses to migrate.");
            }
            else
            {
                bool isPremiumProcessed = false;
                bool isLiteProcessed = false;
                bool isMovieChannelProcessed = false;
                bool isLiveStreamProcessed = false;

                var TFCnowPremium = MyUtility.StringToIntList(GlobalConfig.TFCnowPremium);
                var TFCnowLite = MyUtility.StringToIntList(GlobalConfig.TFCnowLite);
                var TFCnowMovieChannel = MyUtility.StringToIntList(GlobalConfig.TFCnowMovieChannel);
                var TFCnowLiveStream = MyUtility.StringToIntList(GlobalConfig.TFCnowLiveStream);

                List<LicenseDisplay> display = new List<LicenseDisplay>();

                var premiumLicense = GetLicense(absnow_context, TFCnowPremium, licenses, 1427);
                display.Add(premiumLicense);
                display.Add(GetLicense(absnow_context, TFCnowLite, licenses, 1425));
                display.Add(GetLicense(absnow_context, TFCnowMovieChannel, licenses, 45));
                if (premiumLicense == null)
                    display.Add(GetLicense(absnow_context, TFCnowLiveStream, licenses, 1427));

                display.RemoveAll(item => item == null);

                foreach (var item in display)
                {
                    int TFCtvPackageId = 0;
                    int TFCtvProductId = 0;

                    if (item.LicenseEndDate > registDt)
                    {
                        var difference = item.LicenseEndDate.Subtract(registDt);
                        PackageEntitlement entitlement = null;
                        if (TFCnowPremium.Contains(item.PackageId))
                        {
                            if (!isPremiumProcessed)
                            {
                                entitlement = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == GlobalConfig.premiumId);
                                isPremiumProcessed = true;
                                TFCtvPackageId = GlobalConfig.premiumId;
                            }
                        }
                        else if (TFCnowLite.Contains(item.PackageId))
                        {
                            if (!isLiteProcessed)
                            {
                                if (user.CountryCode == GlobalConfig.DefaultCountry)
                                {
                                    entitlement = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == GlobalConfig.premiumId);
                                    TFCtvPackageId = GlobalConfig.premiumId;
                                }

                                else
                                {
                                    entitlement = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == GlobalConfig.liteId);
                                    TFCtvPackageId = GlobalConfig.liteId;
                                }

                                isLiteProcessed = true;
                            }
                        }
                        else if (TFCnowMovieChannel.Contains(item.PackageId))
                        {
                            if (!isMovieChannelProcessed)
                            {
                                entitlement = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == GlobalConfig.movieId);
                                isMovieChannelProcessed = true;
                                TFCtvPackageId = GlobalConfig.movieId;
                            }
                        }

                        else if (TFCnowLiveStream.Contains(item.PackageId))
                        {
                            if (!isLiveStreamProcessed)
                            {
                                if (!isPremiumProcessed)
                                {
                                    entitlement = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == GlobalConfig.premiumId);
                                    isLiveStreamProcessed = true;
                                    TFCtvPackageId = GlobalConfig.premiumId;
                                }
                            }
                        }

                        else
                        {
                            //Provide load
                        }
                        if (TFCtvPackageId > 0)
                        {
                            ProductPackage package = context.ProductPackages.FirstOrDefault(p => p.PackageId == TFCtvPackageId);
                            TFCtvProductId = package.Product.ProductId;

                            if (entitlement != null)
                            {
                                if (entitlement.EndDate > registDt)
                                    entitlement.EndDate = entitlement.EndDate.Add(difference);
                                else
                                    entitlement.EndDate = registDt.Add(difference);


                                EntitlementRequest request = new EntitlementRequest()
                                {
                                    DateRequested = registDt,
                                    StartDate = item.LicenseStartDate,
                                    EndDate = entitlement.EndDate,
                                    Product = package.Product,
                                    Source = "Entitlement Transfer",
                                    ReferenceId = item.LicensePurchaseId.ToString()
                                };
                                entitlement.LatestEntitlementRequest = request; // ADDED DECEMBER 06, 2012
                                user.EntitlementRequests.Add(request);
                            }

                            else
                            {
                                EntitlementRequest request = new EntitlementRequest()
                                {
                                    DateRequested = registDt,
                                    StartDate = item.LicenseStartDate,
                                    EndDate = item.LicenseEndDate,
                                    Product = package.Product,
                                    Source = "Entitlement Transfer",
                                    ReferenceId = item.LicensePurchaseId.ToString()
                                };

                                user.EntitlementRequests.Add(request);
                                PackageEntitlement pkg_entitlement = new PackageEntitlement()
                                {
                                    EndDate = item.LicenseEndDate,
                                    Package = (IPTV2_Model.Package)package.Package,
                                    OfferingId = GlobalConfig.offeringId,
                                    LatestEntitlementRequest = request
                                };
                                user.PackageEntitlements.Add(pkg_entitlement);
                            }
                        }
                    }

                    if (TFCtvProductId > 0)
                    {
                        MigrationTransaction transaction = new MigrationTransaction()
                        {
                            Amount = 0,
                            Currency = GlobalConfig.DefaultCurrency,
                            Date = registDt,
                            OfferingId = GlobalConfig.offeringId,
                            Reference = item.LicensePurchaseId.ToString(),
                            MigratedProductId = TFCtvProductId,
                            StatusId = GlobalConfig.Visible
                        };
                        user.Transactions.Add(transaction);
                    }
                }
                if (context.SaveChanges() > 0)
                    isLicenseMigrated = true;
            }

            bool isTingiMigrated = false;
            var tingi = absnow_context.TFCNowRetailMigrationIDs.Select(i => new { i.TFCnowPackageID, i.GOMSInternalID });
            var tingi_licenses = absnow_context.LicensePurchaseds.Where(l => l.CustomerID == customer.CustomerID && tingi.Select(i => i.TFCnowPackageID).Contains(l.PackageID) && l.LicenseEndDate > registDt).OrderByDescending(l => l.LicenseEndDate);
            if (tingi_licenses.Count() == 0)
            {
                if (isLicenseMigrated || isWalletMigrated)
                {
                    user.TfcNowUserName = customer.EmailAddress;
                    context.SaveChanges();
                }

                return RedirectToAction("Complete", "Migration");
            }
            else
            {
                foreach (var item in tingi_licenses)
                {
                    var diff = item.LicenseEndDate.Subtract(registDt);

                    var GomsProductId = tingi.FirstOrDefault(t => t.TFCnowPackageID == item.PackageID);
                    var TFCtvProduct = context.Products.FirstOrDefault(p => p.GomsProductId == GomsProductId.GOMSInternalID);

                    if (TFCtvProduct != null)
                    {
                        if (TFCtvProduct is ShowSubscriptionProduct)
                        {
                            var showSubscription = (ShowSubscriptionProduct)TFCtvProduct;
                            ShowEntitlement se = user.ShowEntitlements.FirstOrDefault(s => s.Show.CategoryId == showSubscription.Categories.First().CategoryId);
                            if (se != null)
                            {
                                if (se.EndDate > registDt)
                                    se.EndDate = showSubscription.ALaCarteSubscriptionTypeId == 2 ? se.EndDate.AddYears(1) : se.EndDate.Add(diff);
                                else
                                    se.EndDate = showSubscription.ALaCarteSubscriptionTypeId == 2 ? registDt.AddYears(1) : registDt.Add(diff);

                                EntitlementRequest request = new EntitlementRequest()
                                {
                                    DateRequested = registDt,
                                    EndDate = se.EndDate,
                                    Product = TFCtvProduct,
                                    Source = "Entitlement Transfer",
                                    ReferenceId = item.LicensePurchasedID.ToString()
                                };
                                user.EntitlementRequests.Add(request);
                            }
                            else
                            {
                                EntitlementRequest request = new EntitlementRequest()
                                {
                                    DateRequested = registDt,
                                    EndDate = showSubscription.ALaCarteSubscriptionTypeId == 2 ? registDt.AddYears(1) : registDt.Add(diff),
                                    Product = TFCtvProduct,
                                    Source = "Entitlement Transfer",
                                    ReferenceId = item.LicensePurchasedID.ToString()
                                };

                                user.EntitlementRequests.Add(request);
                                ShowEntitlement show_entitlement = new ShowEntitlement()
                                {
                                    EndDate = showSubscription.ALaCarteSubscriptionTypeId == 2 ? registDt.AddYears(1) : registDt.Add(diff),
                                    Show = showSubscription.Categories.First().Show,
                                    OfferingId = GlobalConfig.offeringId,
                                    LatestEntitlementRequest = request
                                };
                                user.ShowEntitlements.Add(show_entitlement);
                            }

                            MigrationTransaction transaction = new MigrationTransaction()
                            {
                                Amount = 0,
                                Currency = GlobalConfig.DefaultCurrency,
                                Date = registDt,
                                OfferingId = GlobalConfig.offeringId,
                                Reference = item.LicensePurchasedID.ToString(),
                                MigratedProductId = TFCtvProduct.ProductId,
                                StatusId = GlobalConfig.Visible
                            };
                            user.Transactions.Add(transaction);
                        }
                    }
                }
                if (context.SaveChanges() > 0)
                    isTingiMigrated = true;
            }

            if (isLicenseMigrated || isWalletMigrated || isTingiMigrated)
            {
                user.TfcNowUserName = customer.EmailAddress;
                user.LastUpdated = registDt;
            }
            else
            {
                user.TfcNowUserName = customer.EmailAddress;
                user.LastUpdated = registDt;
            }

            if (context.SaveChanges() > 0)
            {
                return RedirectToAction("Complete", "Migration");
            }
            return Content(MyUtility.buildJson(collection), "application/json");
        }