public async Task<IHttpActionResult> GetMostAactiveUsers(DateTime dateFrom, int page = 1, int itemsPerPage = 20, string sortBy = "CreatedOn", bool reverse = true, string search = null)
        {
            try
            {

                using (var context = new DrNajeeb.EF.Entities())
                {
                    IQueryable<AspNetUser> usersList = null;

                    usersList = context.AspNetUsers
                        .Where(x => x.IsActiveUSer == true && x.Active == true)
                        .Where(user => !context.UserVideoHistories
                            .Any(f => f.UserId == user.Id && f.WatchDateTime > dateFrom) && !context.VideoDownloadhistories
                            .Any(f => f.UserId == user.Id && f.DateTimeDownloaded > dateFrom))
                            .Include(x => x.Country)
                        .Include(x => x.Subscription)
                        .Include(x => x.AspNetRoles)
                        .Include(x => x.IpAddressFilters);

                    // searching
                    if (!string.IsNullOrWhiteSpace(search))
                    {
                        search = search.ToLower();
                        usersList = usersList.Where(x =>
                            x.FullName.ToLower().Contains(search) ||
                            x.UserName.ToLower().Contains(search) ||
                            x.Email.ToLower().Contains(search));
                    }


                    var totalUsers = await usersList.CountAsync();

                    // sorting (done with the System.Linq.Dynamic library available on NuGet)
                    usersList = usersList.OrderBy(sortBy + (reverse ? " descending" : ""));

                    // paging
                    var usersPaged = usersList.Skip((page - 1) * itemsPerPage).Take(itemsPerPage);

                    var users = new List<UserModel>();

                    foreach (var item in usersPaged)
                    {
                        var usermodel = new UserModel();
                        usermodel.CountryID = item.CountryId;
                        usermodel.EmailAddress = item.Email;
                        usermodel.FullName = item.FullName;
                        usermodel.IsActiveUser = item.IsActiveUSer;
                        usermodel.Id = item.Id;
                        usermodel.IsFilterByIP = item.IsFilterByIP;
                        usermodel.NoOfConcurrentViews = item.NoOfConcurentViews;
                        usermodel.SubscriptionID = item.SubscriptionId;
                        if (item.Country != null)
                        {
                            usermodel.Country.CountryCode = item.Country.CountryCode;
                            usermodel.Country.FlagImage = item.Country.FlagImage;
                            usermodel.Country.Name = item.Country.Name;
                        }
                        if (item.AspNetRoles != null)
                        {
                            foreach (var role in item.AspNetRoles)
                            {
                                usermodel.RolesModel.Add(new RoleModel
                                {
                                    Id = role.Id,
                                    Name = role.Name
                                });
                            }
                        }
                        if (item.Subscription != null)
                        {
                            usermodel.Subscription.Name = item.Subscription.Name;
                            usermodel.Subscription.Id = item.Subscription.Id;
                        }
                        if (item.IsFilterByIP)
                        {
                            if (item.IpAddressFilters != null)
                            {
                                usermodel.FilteredIPs = new List<string>();
                                foreach (var ipAddress in item.IpAddressFilters)
                                {
                                    usermodel.FilteredIPs.Add(ipAddress.IpAddress);
                                }
                            }
                        }
                        users.Add(usermodel);
                    }

                    // json result
                    var json = new
                    {
                        count = totalUsers,
                        data = users,
                    };

                    //await LogHelpers.SaveLog(_Uow, "View Ghost Users Report", User.Identity.GetUserId());

                    return Ok(json);
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        public async Task<IHttpActionResult> GetUsersStatsReport(DateTime dateFrom, DateTime dateTo, int page = 1, int itemsPerPage = 20, string sortBy = "CreatedOn", bool reverse = true, string search = null, bool isActiveUser = true, bool isFreeUser = false)
        {
            try
            {
                var usersList = new List<UserModel>();

                IQueryable<AspNetUser> users;

                if (!isFreeUser)
                {
                    users = _Uow._Users.GetAll(x => x.Active == true && x.CreatedOn >= dateFrom && x.CreatedOn <= dateTo && x.IsActiveUSer == isActiveUser)
                        .Include(x => x.Country)
                        .Include(x => x.Subscription)
                        .Include(x => x.AspNetRoles)
                        .Include(x => x.IpAddressFilters);
                }
                else
                {
                    users = _Uow._Users.GetAll(x => x.Active == true && x.CreatedOn >= dateFrom && x.CreatedOn <= dateTo && x.IsFreeUser.Value)
                    .Include(x => x.Country)
                    .Include(x => x.Subscription)
                    .Include(x => x.AspNetRoles)
                    .Include(x => x.IpAddressFilters);
                }

                // searching
                if (!string.IsNullOrWhiteSpace(search))
                {
                    search = search.ToLower();
                    users = users.Where(x =>
                        x.FullName.ToLower().Contains(search) ||
                        x.UserName.ToLower().Contains(search) ||
                        x.Email.ToLower().Contains(search));
                }

                // sorting (done with the System.Linq.Dynamic library available on NuGet)
                users = users.OrderBy(sortBy + (reverse ? " descending" : ""));

                // paging
                var usersPaged = await users.Skip((page - 1) * itemsPerPage).Take(itemsPerPage).ToListAsync();

                foreach (var item in usersPaged)
                {
                    var usermodel = new UserModel();
                    usermodel.CountryID = item.CountryId;
                    usermodel.EmailAddress = item.Email;
                    usermodel.FullName = item.FullName;
                    usermodel.IsActiveUser = item.IsActiveUSer;
                    usermodel.Id = item.Id;
                    usermodel.IsFilterByIP = item.IsFilterByIP;
                    usermodel.NoOfConcurrentViews = item.NoOfConcurentViews;
                    usermodel.SubscriptionID = item.SubscriptionId;
                    if (item.Country != null)
                    {
                        usermodel.Country.CountryCode = item.Country.CountryCode;
                        usermodel.Country.FlagImage = item.Country.FlagImage;
                        usermodel.Country.Name = item.Country.Name;
                    }
                    if (item.AspNetRoles != null)
                    {
                        foreach (var role in item.AspNetRoles)
                        {
                            usermodel.RolesModel.Add(new RoleModel
                            {
                                Id = role.Id,
                                Name = role.Name
                            });
                        }
                    }
                    if (item.Subscription != null)
                    {
                        usermodel.Subscription.Name = item.Subscription.Name;
                        usermodel.Subscription.Id = item.Subscription.Id;
                    }
                    if (item.IsFilterByIP)
                    {
                        if (item.IpAddressFilters != null)
                        {
                            usermodel.FilteredIPs = new List<string>();
                            foreach (var ipAddress in item.IpAddressFilters)
                            {
                                usermodel.FilteredIPs.Add(ipAddress.IpAddress);
                            }
                        }
                    }
                    usermodel.TotalVideosDownloaded = await _Uow._VideoDownloadhistory.CountAsync(x => x.UserId == item.Id);
                    usersList.Add(usermodel);
                }

                // json result
                var json = new
                {
                    count = users.Count(),
                    data = usersList,
                };

                //await LogHelpers.SaveLog(_Uow, "View User Stats Report", User.Identity.GetUserId());

                return Ok(json);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        public async Task<IHttpActionResult> GetManagers()
        {
            try
            {
                var managers = await _Uow._Roles.GetAll(x => x.Name == "Manager")
                    .Include(x => x.AspNetUsers)
                    .Select(x => x.AspNetUsers)
                    .ToListAsync();

                var usersList = new List<UserModel>();

                foreach (var parent in managers)
                {
                    foreach (var item in parent)
                    {
                        if (item.Active)
                        {
                            var usermodel = new UserModel();
                            usermodel.EmailAddress = item.Email;
                            usermodel.FullName = item.FullName;
                            usermodel.Id = item.Id;
                            usersList.Add(usermodel);
                        }
                    }
                }

                await LogHelpers.SaveLog(_Uow, "Get All Managers", User.Identity.GetUserId());

                return Ok(usersList);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        public async Task<IHttpActionResult> UpdateUser(UserModel model)
        {
            try
            {

                if (!string.IsNullOrEmpty(model.Password))
                {
                    ApplicationUser user = await UserManager.FindByEmailAsync(model.EmailAddress);
                    user.PasswordHash = UserManager.PasswordHasher.HashPassword(model.Password);
                    //await UserManager.UpdateSecurityStampAsync(model.EmailAddress);
                    IdentityResult result = await UserManager.UpdateAsync(user);
                    if (result != null && !result.Succeeded)
                    {
                        return GetErrorResult(result);
                    }
                }
                var subscription=await _Uow._Subscription.GetByIdAsync(model.SubscriptionID.GetValueOrDefault());
                var currentUser = await _Uow._Users.GetAll(x => x.Email == model.EmailAddress).FirstOrDefaultAsync();
                currentUser.CountryId = model.CountryID;
                currentUser.UpdatedOn = DateTime.UtcNow;
                currentUser.FullName = model.FullName;
                currentUser.IsActiveUSer = model.IsActiveUser;
                currentUser.IsAllowMobileVideos = true;
                currentUser.IsFilterByIP = model.IsFilterByIP;
                currentUser.IsParentalControl = false;
                currentUser.IsPasswordReset = model.IsPasswordReset;
                currentUser.NoOfConcurentViews = model.NoOfConcurrentViews;
                currentUser.SubscriptionId = model.SubscriptionID;
                currentUser.UpdatedBy = User.Identity.GetUserId();
                currentUser.IsFreeUser = model.IsFreeUser;
                currentUser.IsInstitutionalAccount = model.IsInstitutionalAccount;
                currentUser.ExpirationDate = (subscription == null) ? DateTime.UtcNow.AddDays(30) : DateTime.UtcNow.AddDays(subscription.TimeDuration.GetValueOrDefault());
                if (currentUser.IsFilterByIP)
                {
                    if (model.FilteredIPs != null)
                    {
                        foreach (var item in model.FilteredIPs)
                        {
                            currentUser.IpAddressFilters.Add(new EF.IpAddressFilter
                            {
                                CreatedOn = DateTime.UtcNow,
                                IpAddress = item,
                                UserId = currentUser.Id
                            });
                        }
                    }
                }
                _Uow._Users.Update(currentUser);
                await _Uow.CommitAsync();

                await LogHelpers.SaveLog(_Uow, "Update User : " + currentUser.UserName, User.Identity.GetUserId());
                return Ok();
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        public async Task<IHttpActionResult> GetLatestUsers()
        {
            try
            {
                var usersList = new List<UserModel>();

                var users = await _Uow._Users.GetAll(x => x.Active == true)
                    .Include(x => x.Country)
                    .Include(x => x.Subscription)
                    .Include(x => x.AspNetRoles)
                    .OrderByDescending(x => x.CreatedOn)
                    .Take(10)
                    .ToListAsync();

                foreach (var item in users)
                {
                    var usermodel = new UserModel();
                    usermodel.CountryID = item.CountryId;
                    usermodel.EmailAddress = item.Email;
                    usermodel.FullName = item.FullName;
                    usermodel.IsActiveUser = item.IsActiveUSer;
                    usermodel.Id = item.Id;
                    usermodel.IsFilterByIP = item.IsFilterByIP;
                    usermodel.NoOfConcurrentViews = item.NoOfConcurentViews;
                    usermodel.SubscriptionID = item.SubscriptionId;
                    if (item.Country != null)
                    {
                        usermodel.Country.CountryCode = item.Country.CountryCode;
                        usermodel.Country.FlagImage = item.Country.FlagImage;
                        usermodel.Country.Name = item.Country.Name;
                    }
                    if (item.AspNetRoles != null)
                    {
                        foreach (var role in item.AspNetRoles)
                        {
                            usermodel.RolesModel.Add(new RoleModel
                            {
                                Id = role.Id,
                                Name = role.Name
                            });
                        }
                    }
                    if (item.Subscription != null)
                    {
                        usermodel.Subscription.Name = item.Subscription.Name;
                        usermodel.Subscription.Id = item.Subscription.Id;
                    }
                    usersList.Add(usermodel);
                }

                //await LogHelpers.SaveLog(_Uow, "Check Latest Users", User.Identity.GetUserId());

                return Ok(usersList);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        public async Task<IHttpActionResult> AddUser(UserModel model)
        {
            try
            {
                var subscription=await _Uow._Subscription.GetByIdAsync(model.SubscriptionID.GetValueOrDefault());
                var user = new ApplicationUser()
                {
                    UserName = model.EmailAddress,
                    Email = model.EmailAddress,
                    Active = true,
                    CountryId = (model.CountryID.HasValue) ? model.CountryID.Value : 418,
                    CreatedOn = DateTime.UtcNow,
                    CurrentViews = 0,
                    FullName = model.FullName,
                    IsActiveUser = model.IsActiveUser,
                    IsAllowMobileVideos = true,
                    IsFilterByIP = model.IsFilterByIP,
                    IsParentalControl = false,
                    IsPasswordReset = model.IsPasswordReset,
                    NoOfConcurentViews = model.NoOfConcurrentViews,
                    SubscriptionId = model.SubscriptionID.Value,
                    IsFreeUser = model.IsFreeUser,
                    SubscriptionDate = DateTime.UtcNow,
                    IsInstitutionalAccount = model.IsInstitutionalAccount,
                    ExpirationDate=(subscription==null)?DateTime.UtcNow.AddDays(30):DateTime.UtcNow.AddDays(subscription.TimeDuration.GetValueOrDefault())
                };

                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (!result.Succeeded)
                {
                    return GetErrorResult(result);
                }

                result = await UserManager.AddToRolesAsync(user.Id, model.Roles.ToArray());
                if (!result.Succeeded)
                {
                    return GetErrorResult(result);
                }


                var currentUser = await _Uow._Users.GetAll(x => x.Id == user.Id).FirstOrDefaultAsync();

                if (currentUser.IsFilterByIP)
                {
                    if (model.FilteredIPs != null)
                    {
                        foreach (var item in model.FilteredIPs)
                        {
                            currentUser.IpAddressFilters.Add(new EF.IpAddressFilter
                            {
                                CreatedOn = DateTime.UtcNow,
                                IpAddress = item,
                                UserId = currentUser.Id
                            });
                        }
                    }
                }
                currentUser.CreatedBy = User.Identity.GetUserId();

                _Uow._Users.Update(currentUser);
                await _Uow.CommitAsync();

                await LogHelpers.SaveLog(_Uow, "Add User : " + currentUser.UserName, User.Identity.GetUserId());

                return Ok();
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }