public ActionResult Login(LogOnViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (authProvider.Authenticate(model.EmailAddress, model.Password, this.userRepository))
                {
                    var userObj = userRepository.GetUserByEmailAddress(model.EmailAddress);
                    Session["user"] = userObj;
                    var accountObj = accRepository.Accounts.FirstOrDefault(x => x.ID == userObj.AccountID);
                    Session["account"] = accountObj;
                    var timeZone = accRepository.Accounts.Where(aid => aid.ID == userObj.AccountID).FirstOrDefault().TimeZone;
                    Session["timeZone"] = timeZone;
                    Session["SysAdminDetails"] = null;

                    List<NotificationListViewModel> notificationList = new List<NotificationListViewModel>();

                    CronJobController CJC = new CronJobController();
                    Session["account"] = CJC.checkAccountTrialExpiryForAccount(accountObj);

                    //save details into error table
                    //SaveLogonDetails(model.EmailAddress);

                    if ( userObj.UserType == "Admin" || userObj.UserType == "Standard")
                    {
                        if (userObj.EmailVerified == true)
                        {
                            //get the folders
                            var folders = CCFolderRepository.CCFolders.Where(guid => guid.AccountGUID == accountObj.AccountGUID).ToList();
                            Session["folderss"] = folders;

                            HelperFunctions HF = new HelperFunctions();
                            notificationList = HF.generateNotificationList(accountObj);

                            HF.CheckAcccountStatus(accountObj);

                            if(notificationList.Count>0)
                                Session["notifications"] = notificationList;
                            else
                                Session["notifications"] = null;

                            return Redirect(returnUrl ?? Url.Action("Index", "Admin"));
                        }
                        else
                        {
                            return Redirect(returnUrl ?? Url.Action("ResendVerification", "SignUp", new { uid = userObj.ID }));
                        }
                    }
                    else if (userObj.UserType == "SystemAdmin")
                    {
                        HelperFunctions HF = new HelperFunctions();
                        notificationList = HF.generateNotificationList(accountObj);
                        if (notificationList.Count > 0)
                            Session["notifications"] = notificationList;

                        Session["SysAdminDetails"] = userRepository.GetUserByEmailAddress(model.EmailAddress);

                        return Redirect(returnUrl ?? Url.Action("Index", "CorporateContactsAdmin"));
                    }
                    else
                    {
                        return Redirect(returnUrl ?? Url.Action("SetupSync", "User"));
                    }
                }
                else
                {
                    //save details into error table
                    //SaveLogonDetails(model.EmailAddress);
                    ModelState.AddModelError("", "Incorrect username or password");
                    return View();

                }
            }
            else
            {
                return View();
            }
        }
        public ActionResult ImpersonatedAccount(long AccID)
        {
            if (Session["SysAdminDetails"] != null)
            {
                TempData["SelectedMenu"] = "AccImpersontation";

                var userObj = CCUserRepository.GetUserByEmailAddress(CCUserRepository.Users.First(U => U.AccountID == AccID).Email);
                Session["user"] = userObj;
                var accountObj = CCAccRepository.Accounts.FirstOrDefault(x => x.ID == userObj.AccountID);
                Session["account"] = accountObj;
                var timeZone = CCAccRepository.Accounts.Where(aid => aid.ID == userObj.AccountID).FirstOrDefault().TimeZone;
                Session["timeZone"] = timeZone;
                var folders = CCFolderRepository.CCFolders.Where(guid => guid.AccountGUID == accountObj.AccountGUID).ToList();
                Session["folderss"] = folders;

                List<NotificationListViewModel> notificationList = new List<NotificationListViewModel>();

                CronJobController CJC = new CronJobController();
                Session["account"] = CJC.checkAccountTrialExpiryForAccount(accountObj);

                HelperFunctions HF = new HelperFunctions();
                notificationList = HF.generateNotificationList(accountObj);

                HF.CheckAcccountStatus(accountObj);

                if (notificationList.Count > 0)
                    Session["notifications"] = notificationList;
                else
                    Session["notifications"] = null;

                if (((DateTime)(accountObj.TrialEnds) - (DateTime)(DateTime.Now.Date)).TotalDays < CCGlobalValues.trialPeriod)
                {
                    TrialDataModel trialObj = new TrialDataModel();
                    trialObj.hasPurchased = accountObj.HasPurchased;
                    trialObj.createdDate = accountObj.CreatedDate;
                    trialObj.trialEndDate = accountObj.TrialEnds;
                    trialObj.showPurchaseOptions = true;
                    Session["trialData"] = trialObj;
                }

                ImpersonateAccountsSysAdminModel model = new ImpersonateAccountsSysAdminModel();

                var AccountsInfo = CCAccRepository.Accounts.Where(A => A.ID == AccID).FirstOrDefault();

                model.SelectedAccountInfo = AccountsInfo;
                model.FolderCount = CCFolderRepository.CCFolders.Where(F => F.AccountGUID == AccountsInfo.AccountGUID).Count();
                model.ConnectionCount = CCConnectionRepository.CCSubscriptions.Where(C => C.AccountGUID == AccountsInfo.AccountGUID).Count();
                model.UserCount = CCUserRepository.Users.Where(U => U.AccountID == AccountsInfo.ID).Count();
                model.SubscriptionCount = 0;
                model.ItemsCount = CCItemRepository.CCContacts.Where(I => I.AccountGUID == AccountsInfo.AccountGUID).Count();
                model.SelectedAccountOwner = CCUserRepository.Users.First(U => U.AccountID == AccountsInfo.ID).FullName;

                //Sync Graph Data

                List<string> SyncDates = new List<string>();
                List<double> SyncDateUsage = new List<double>();

                DateTime startDate = DateTime.Now.Date.AddDays(-1);

                for (int i = 6; i > -1; i--)
                {
                    SyncDates.Add((startDate.AddDays(-i)).ToShortDateString());
                }

                for (int i = 0; i < SyncDates.Count(); i++)
                {
                    DateTime syncDateStart = DateTime.Parse(SyncDates[i]);
                    DateTime syncDateEnd = syncDateStart.AddHours(23).AddMinutes(59);

                    SyncDateUsage.Add(CCSyncItemsRepository.CCSyncItems.Where(SI => SI.LastUpdated >= syncDateStart && SI.LastUpdated <= syncDateEnd).Count());
                }

                model.SyncDates = SyncDates;
                model.SyncDateUsage = SyncDateUsage;

                return View(model);
            }
            else
            {
                return RedirectToAction("Login", "Login");
            }
        }
        public ActionResult SaveFeatures(string plan, int quantities, string couponID)
        {
            User userObj = (User)Session["user"];
            Account accountObj = (Account)Session["account"];
            int planLevel = Int32.Parse(plan);
            int existingPlanID = accountObj.PlanID;
            string purchaseType = "Upgrade";

            ////Delete old purchasedfeature
            //var purchasedfeatures = purchRepository.Purchases.Where(p => p.AccountGUID == accountObj.AccountGUID).ToList();
            //foreach (var purch in purchasedfeatures)
            //{
            //    bool res = purchRepository.DeleteFPurchasedFeature(purch.ID);

            //}

            //var featuresForPlan = featureRepository.Features.Where(pl => pl.PlanLevel == planLevel).ToList();

            //// save default feature
            //var featuresForDefaultPlan = featureRepository.Features.Where(pl => pl.PlanLevel == planLevel && pl.Price == 0).ToList();

            //foreach (var feat in featuresForDefaultPlan)
            //{
            //    PurchasedFeatures objFeature = new PurchasedFeatures();
            //    objFeature.AccountGUID = accountObj.AccountGUID;
            //    objFeature.FeatureID = feat.ID;
            //    objFeature.ExpiryDate = DateTime.UtcNow;
            //    objFeature.Enabled = true;

            //    if (feat.Type == "Max Items per Folder")
            //    {
            //        objFeature.Quantity = (feat.Quantity) * quantities;
            //    }
            //    else
            //    {
            //        objFeature.Quantity = feat.Quantity;
            //    }

            //    purchRepository.SavePurchase(objFeature);
            //}

            ////Ajust Folder Fields START

            //List<string> needtosave = new List<string>();
            //List<CCFolderField> savedobj = new List<CCFolderField>();
            //List<CCFolderField> activeFields = new List<CCFolderField>();
            //List<CCFolderField> needToInActive = new List<CCFolderField>();

            //List<String> objFields = new List<string>();

            //if(planLevel == 10)
            //    objFields = FieldsConfigHelper.GetFieldForAppointmentSimple();
            //else if(planLevel == 20)
            //    objFields = FieldsConfigHelper.GetFieldForContactBusiness();
            //else
            //    objFields = FieldsConfigHelper.GetFieldForContactFull();

            //var folderListForAccount = CCFolderRepository.CCFolders.Where(F => F.AccountGUID == accountObj.AccountGUID).ToList();

            //foreach (var fold in folderListForAccount)
            //{
            //    needtosave = CCFieldRepository.IsAvailableField(objFields, fold.FolderID);

            //    foreach (var field in needtosave)
            //    {
            //        CCFolderField folderField = new CCFolderField();
            //        folderField.FieldName = FieldsConfigHelper.GetRealName(field);
            //        folderField.FieldType = FieldsConfigHelper.GetVariableType(field);
            //        folderField.FolderID = fold.FolderID;
            //        folderField.FieldCaption = field;
            //        folderField.Restriction = "none";
            //        folderField.AccountGUID = accountObj.AccountGUID;
            //        folderField.isActive = true;
            //        savedobj.Add(folderField);
            //    }

            //    foreach (var field in objFields)
            //    {
            //        CCFolderField folderField = CCFieldRepository.CCFolderFields.Where(f => f.FieldCaption == field & f.AccountGUID == accountObj.AccountGUID & f.FolderID == fold.FolderID).FirstOrDefault();
            //        activeFields.Add(folderField);
            //    }

            //    var resp = CCFieldRepository.SaveFolderFieldsObj(savedobj);

            //    var fieldList = CCFieldRepository.CCFolderFields.Where(f => f.AccountGUID == accountObj.AccountGUID & f.FolderID == fold.FolderID).ToList();

            //    var toInActiveList = fieldList.Except(activeFields).ToList();

            //    int flag = 0;

            //    foreach (var f1 in fieldList)
            //    {
            //        flag = 0;
            //        foreach (var f2 in activeFields)
            //        {
            //            try
            //            {
            //                if (f2.FieldID == f1.FieldID)
            //                {
            //                    if (f1.isActive != false)
            //                    {
            //                        flag = 1;
            //                        break;
            //                    }
            //                    else
            //                    {
            //                        flag = 2;
            //                        break;
            //                    }

            //                }
            //            }
            //            catch (Exception ex)
            //            { }

            //        }

            //        if (flag == 0)
            //        {
            //            f1.isActive = false;
            //            CCFieldRepository.SaveFolderFields(f1);
            //        }

            //        else if (flag == 2)
            //        {
            //            f1.isActive = true;
            //            CCFieldRepository.SaveFolderFields(f1);
            //        }
            //    }

            //    // add field into default group
            //    var defaultGrp = CCGroupRepository.CCGroups.Where(fid => fid.FolderID == fold.FolderID & fid.GroupName == "Default" & fid.AccountGUID == accountObj.AccountGUID).FirstOrDefault();

            //    if (defaultGrp != null)
            //    {
            //        foreach (var field in resp)
            //        {
            //            long grpFieldOrder = 0;
            //            // get group fileds last order
            //            var groupFieldOrder = CCGroupFieldRepository.CCGroupsFields.Where(gid => gid.GroupID == defaultGrp.GroupID & gid.AccountGUID == accountObj.AccountGUID).OrderByDescending(grp => grp.FieldOrder).FirstOrDefault();
            //            if (groupFieldOrder != null) { grpFieldOrder = groupFieldOrder.FieldOrder; }

            //            CCGroupField objgrpfield = new CCGroupField();
            //            objgrpfield.FieldID = field.FieldID;
            //            objgrpfield.FieldOrder = grpFieldOrder + 1;
            //            objgrpfield.FolderID = defaultGrp.FolderID;
            //            objgrpfield.GroupID = defaultGrp.GroupID;
            //            objgrpfield.AccountGUID = accountObj.AccountGUID;
            //            var aa = CCGroupFieldRepository.SaveGroupField(objgrpfield);
            //        }
            //    }
            //}

            ////Ajust Folder Fields END

            //// change the plain id
            var planid = planRepository.Plans.FirstOrDefault(pl => pl.PlanLevel == planLevel).ID;

            var currentAccount = accountRepo.Accounts.FirstOrDefault(ac => ac.ID == userObj.AccountID);

            //Account account = new Account();
            //account = currentAccount;
            //existingPlanID = account.PlanID;
            //account.PlanID = planid;

            var account = saveFeaturesCommon(plan, quantities);

            account.HasPurchased = true;

            if (currentAccount.TrialEnds <= DateTime.Now.Date & currentAccount.HasPurchased == false & currentAccount.isOverFlow == true)
            {
                account.isOverFlow = false;
            }

            Session["trialData"] = null;

            if (existingPlanID > planid)
            {
                purchaseType = "Downgrade";
            }

            if (accountObj.isPaymentIssue == true)
            {
                account.isPaymentIssue = false;
            }

            account = accountRepo.SaveAccount(account);

            LimitationsViewModel limitationsObj = (LimitationsViewModel)Session["limitations"];
            HelperFunctions HF = new HelperFunctions();
            limitationsObj = HF.updateAccountLimitations(account);
            Session["limitations"] = limitationsObj;

            HF.CheckAcccountStatus(account);

            //Reset Sync Times
            var ConnectionList = CCConnectionRepository.CCSubscriptions.Where(con => con.AccountGUID == account.AccountGUID).ToList();

            foreach (var con in ConnectionList)
            {
                con.ResetAtNextSync = true;
                CCConnectionRepository.SaveSubscription(con);
            }

            var folderDetails = CCFolderRepository.CCFolders.Where(f => f.AccountGUID == account.AccountGUID).ToList();

            foreach (var fold in folderDetails)
            {
                if (fold.isOverFlow == true)
                {
                    if (limitationsObj.folderList.Where(f => f.fold.FolderID == fold.FolderID).FirstOrDefault().itemCount <= limitationsObj.maxItemCountPerFolder)
                    {
                        fold.isOverFlow = false;
                        CCFolderRepository.SaveFolder(fold);
                    }
                }
            }

            Session["account"] = account;

            //var featureQuality = featureRepository.Features.Where(pid => pid.PlanLevel == planLevel & pid.Type == "Max Items per Folder").FirstOrDefault();
            //var savedQuality = purchRepository.Purchases.Where(fid => fid.FeatureID == featureQuality.ID && fid.AccountGUID == accountObj.AccountGUID).FirstOrDefault();

            //if (savedQuality != null)
            //{
            //    var quantitySaved = (savedQuality.Quantity) / (featureQuality.Quantity);
            //    limitationsObj.availableCconnectionCount = (int)(quantitySaved * 5) - (int)CCConnectionRepository.CCSubscriptions.Where(C => C.AccountGUID == accountObj.AccountGUID).Count();
            //    limitationsObj.maxItemCountPerFolder = featureQuality.Quantity;
            //    if (featureRepository.Features.Where(pid => pid.PlanLevel == planLevel & pid.Type == "Sync Calendar").FirstOrDefault().Quantity == 0)
            //        limitationsObj.isCalendarSyncAvailable = false;
            //    else
            //        limitationsObj.isCalendarSyncAvailable = true;
            //}

            List<NotificationListViewModel> notificationList = new List<NotificationListViewModel>();
            notificationList = HF.generateNotificationList(account);
            if (notificationList.Count > 0)
                Session["notifications"] = notificationList;
            else
                Session["notifications"] = null;

            var currentAccountDetails = accountRepo.Accounts.FirstOrDefault(aid => aid.ID == userObj.AccountID);

            if (currentAccountDetails.StripeCustomerID != null)
            {
                ChargeFromExistingDetails(existingPlanID, quantities, couponID);
            }

            if (account != null)
            {
                if (currentAccountDetails.StripeCustomerID == null)
                {
                    return Json("SucessNew", JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json("Sucess", JsonRequestBehavior.AllowGet);
                }

            }
            else
            {
                return Json("Fail", JsonRequestBehavior.AllowGet);
            }
        }