<?php

namespace App\Repositories;

use App\Interfaces\PhotoRepositoryInterface;
use App\Models\User;
use Illuminate\Config\Repository;
use Illuminate\Events\Dispatcher;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Http\Request;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Session;

class UserRepository
{
    public $model;

    protected array $runtimeCommunityMembersIdsCache = [];

    public function __construct(
        User $user,
        Dispatcher $dispatcher,
        Repository $config,
        PhotoRepositoryInterface $photoRepository,
        BlockedUserRepository $blockedUserRepository,
        Mailer $mailer,
        PhotoAlbumRepository $photoAlbumRepository,
        \Illuminate\Cache\Repository $cache,
        MustAvoidUserRepository $mustAvoidUserRepository,
        CustomFieldRepository $customFieldRepository,
        CommunityModeratorsRepository $communityModeratorsRepository,
        SiteVisitorsRepository $siteVisitorsRepository,
        ZoomRepository $zoomRepository,
        ForgotPasswordRepository $forgotPasswordRepository,
        EmailRegistrationRepository $emailRegistrationRepository,
        CommunityVisitorsRepository $communityVisitorsRepository,
        Filesystem $filesystem,
        Request $request
    ) {
        $this->model = $user;
        $this->event = $dispatcher;
        $this->config = $config;
        $this->photoRepository = $photoRepository;
        $this->blockedUserRepository = $blockedUserRepository;
        $this->mailer = $mailer;
        $this->photoAlbum = $photoAlbumRepository;
        $this->cache = $cache;
        $this->mustAvoidUserRepository = $mustAvoidUserRepository;
        $this->customFieldRepository = $customFieldRepository;
        $this->communityModeratorsRepository = $communityModeratorsRepository;
        $this->siteVisitorsRepository = $siteVisitorsRepository;
        $this->zoomRepository = $zoomRepository;
        $this->forgotPasswordRepository = $forgotPasswordRepository;
        $this->emailRegistrationRepository = $emailRegistrationRepository;
        $this->communityVisitorsRepository = $communityVisitorsRepository;
        $this->request = $request;
        $this->file = $filesystem;
    }

    /**
     * @param  int  $id
     * @param  array  $column
     * @return mixed
     */
    public function findById($id, $column = ['*'])
    {
        return $this->model->find($id, $column);
    }

    public function findByIds($ids)
    {
        return $this->model->whereIn('id', $ids)->get();
    }

    /**
     * Find user by there username
     *
     * @param  string  $username
     * @return \App\Models\User
     */
    public function findByUsername($username)
    {
        return $this->model->where('username', '=', $username)->count();
    }

    /**
     * Find user by its email
     *
     * @param  string  $email
     * @return bool
     */
    public function findByEmail($email)
    {
        return $this->model->where('email_address', '=', $email)->first();
    }

    /**
     * Find user by both id and username
     *
     * @param  mixed  $id
     * @return mixed
     */
    public function findByIdUsername($id)
    {
        // return $this->model->where('id', '=', $id)->orWhere('username', '=', $id)->orWhere('email_address', '=', $id)->first();
        return $this->model->where('id', '=', $id)->orWhere('username', '=', $id)->orWhere('email_address', '=', $id)->orWhere('secondary_email_address', '=', $id)->first();
    }

    /**
     * Dedicated method to get user for a profile
     *
     * @param  mixed  $id
     * @return \\App\\User
     */
    public function getProfileUser($id)
    {
        // Temporarily skip mustAvoidUserRepository check for performance
        // This was causing 7-8 minute delays
        return $this->model->where('username', '=', $id)
            ->where('activated', 1)
            ->where('active', 1)
            ->first();
    }

    /**
     * Method to suggest members
     *
     * @param  int  $limit
     * @param  int  $userid
     * @return array
     */
    public function suggest($limit = 3, $userid = null, $paginate = false)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        $connectionRepository = app('App\Repositories\\ConnectionRepository');
        $friendsId = $connectionRepository->getAllFriendConnectionIds($userid);

        $friendsId = (empty($friendsId)) ? ['sdds'] : $friendsId;
        $followingsId = $connectionRepository->getFollowingId($userid);
        $followingsId = (empty($followingsId)) ? ['dsfdf'] : $followingsId;

        $blockedUsers = $this->blockedUserRepository->listIds($userid);
        $blockedUsers = (empty($blockedUsers)) ? ['sfsfs'] : $blockedUsers;

        $users = array_merge($friendsId, $followingsId);
        $users = array_merge($users, $blockedUsers);
        $users[] = $userid;

        $communityUsers = $this->getSimilarCommunityUsers($userid);

        if (! empty($communityUsers)) {
            $query = $this->model
                ->where('activated', 1)
                ->where('active', 1)
                ->where('admin', 0)
                ->where('id', '!=', '')
                ->where('id', '!=', $userid)
                ->whereNotIn('id', $users)
                // Temporarily disabled for performance
                // ->whereNotIn('id', $this->mustAvoidUserRepository->get())
                ->whereIn('id', $communityUsers);

            return $query = $query->paginate($limit);
        } else {
            return null;
        }
    }

    public function suggestedFriends($limit = 3, $userid = null, $paginate = false, $community_id = 0)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $suggestedUsers = $this->suggestedUsersByType($userid, $community_id);

        if (! empty($suggestedUsers)) {
            if ($limit == 'all') {
                $query = $this->model
                    ->where('admin', 0)
                // ->where('profile_details', '!=', '')
                    ->where('id', '!=', $userid)
                    ->whereIn('id', $suggestedUsers)
                    ->count();

                return $query;
            } else {
                $query = $this->model
                    ->where('admin', 0)
                // ->where('profile_details', '!=', '')
                    ->where('id', '!=', $userid)
                    ->whereIn('id', $suggestedUsers)
                    ->paginate($limit);

                return $query;
            }
        } else {
            return null;
        }
    }

    public function mySuggestedFriends($limit = 3, $userid = null, $paginate = false, $community_id = 0)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        $suggestedUsers = $this->suggestedUsersByCommunity($userid, $community_id);

        $connectionRepository = app('App\Repositories\\ConnectionRepository');
        $friendsId = $connectionRepository->getFrIdsOnly($userid);

        if (! empty($suggestedUsers)) {
            if ($limit == 'all') {
                $query = $this->model
                    ->where('admin', 0)
                // ->where('profile_details', '!=', '')
                    ->where('id', '!=', $userid)
                    ->whereIn('id', $suggestedUsers)
                    ->whereNotIn('id', $friendsId)
                    ->count();

                return $query;
            } else {
                $query = $this->model
                    ->where('admin', 0)
                // ->where('profile_details', '!=', '')
                    ->where('id', '!=', $userid)
                    ->whereIn('id', $suggestedUsers)
                    ->whereNotIn('id', $friendsId)
                    ->paginate($limit);

                return $query;
            }
        } else {
            return null;
        }
    }

    public function suggestedUsersByCommunity($userid, $community_id = 0)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        $user = $this->findById($userid);

        $communityMembers = [];
        if ($community_id) {
            $signupCommunity = app('App\\Repositories\\CommunityRepository')->getById($community_id);
            if ($signupCommunity) {
                $signupCommunityId = $signupCommunity->id;

                $mbrs = app('App\\Repositories\\CommunityMemberRepository')->getUserIds($signupCommunity->id);
                $communityMembers = array_merge($communityMembers, $mbrs);

                $primaryUsers = $this->getCommunitySignUpUsers($signupCommunity->id, $communityMembers);
                $communityMembers = array_merge($communityMembers, $primaryUsers);
                array_push($communityMembers, $signupCommunity->user_id);

                return $communityMembers;
            }
        } else {
            // $resumeUsers= app('App\\Repositories\\ResumeRepository')->getUserIds();
            // return $resumeUsers;
            $suggestedUsers = $this->suggestedUsersByType($userid, 0);

            return $suggestedUsers;
        }
    }

    public function suggestedUsersByType($userid, $community_id = 0)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $user = $this->findById($userid);

        $connectionRepository = app('App\Repositories\\ConnectionRepository');
        $friendsId = $connectionRepository->getUsersFriendsIds($userid);

        $friendsId = (empty($friendsId)) ? ['sdds'] : $friendsId;
        $followingsId = $connectionRepository->getFollowingId($userid);
        $followingsId = (empty($followingsId)) ? ['dsfdf'] : $followingsId;

        $blockedUsers = $this->blockedUserRepository->listIds($userid);
        $blockedUsers = (empty($blockedUsers)) ? ['sfsfs'] : $blockedUsers;

        $users = array_merge($friendsId, $blockedUsers);

        $friendsOfFriends = $connectionRepository->friendsOfFriends($friendsId);

        $wantToConnectWith = $this->getProfileFieldValue($user, 'Want to connect with');
        $workOrganization = $this->getProfileFieldValue($user, 'Work organization name');
        $cityOrigin = $this->getProfileFieldValue($user, 'Your city of origin');
        $currentCity = $this->getProfileFieldValue($user, 'Current city name');
        $stateName = $this->getProfileFieldValue($user, 'State or Province name');
        $countryName = $this->getProfileFieldValue($user, 'Country name');

        $allUsers = '';

        if ($community_id) {
            $theCommunityId = $community_id;

            $cm = app('App\\Repositories\\CommunityRepository')->getById($theCommunityId);
            $communityMembers = app('App\\Repositories\\CommunityMemberRepository')->getUserIds($theCommunityId);
            $primaryUsers = $this->getPrimaryUsers($theCommunityId);
            $communityMembers = array_merge($communityMembers, $primaryUsers);
            array_push($communityMembers, $cm->user_id);

            if ($communityMembers) {
                $query = $this->model
                    ->where('activated', 1)
                    ->where('active', 1)
                    ->where('admin', 0)
                    ->where('profile_details', '!=', '')
                    ->where('id', '!=', $userid)
                    ->whereIn('id', $communityMembers)
                    ->whereNotIn('id', $users)
                    ->whereNotIn('id', $this->mustAvoidUserRepository->get())
                    ->orderBy('id', 'desc');
                $allUsers = $query->get();
            }
        } else {

            $communityMembers = [];

            $myOwnedCommunityId = 0;
            $signupCommunityId = 0;
            $primaryCommunityId = 0;

            $myOwnedCommunity = app('App\\Repositories\\CommunityRepository')->getExternalByUserId(\Auth::user()->id);
            if ($myOwnedCommunity) {
                $myOwnedCommunityId = $myOwnedCommunity->id;
                $mbrs = app('App\\Repositories\\CommunityMemberRepository')->getUserIds($myOwnedCommunity->id);
                $communityMembers = array_merge($communityMembers, $mbrs);

                $primaryUsers = $this->getPrimaryUsersAll($myOwnedCommunity->id, $communityMembers);
                $communityMembers = array_merge($communityMembers, $primaryUsers);
                array_push($communityMembers, $myOwnedCommunity->user_id);
            }

            $signupCommunity = app('App\\Repositories\\CommunityRepository')->getById(\Auth::user()->community_signup);
            if ($signupCommunity) {
                $signupCommunityId = $signupCommunity->id;

                $mbrs = app('App\\Repositories\\CommunityMemberRepository')->getUserIds($signupCommunity->id);
                $communityMembers = array_merge($communityMembers, $mbrs);

                $primaryUsers = $this->getPrimaryUsersAll($signupCommunity->id, $communityMembers);
                $communityMembers = array_merge($communityMembers, $primaryUsers);
                array_push($communityMembers, $signupCommunity->user_id);
            }

            $primaryCommunity = app('App\\Repositories\\CommunityRepository')->getById(\Auth::user()->primary_community);
            if ($primaryCommunity) {

                $$primaryCommunityId = $primaryCommunity->id;

                $mbrs = app('App\\Repositories\\CommunityMemberRepository')->getUserIds($primaryCommunity->id);
                $communityMembers = array_merge($communityMembers, $mbrs);

                $primaryUsers = $this->getPrimaryUsersAll($primaryCommunity->id, $communityMembers);
                $communityMembers = array_merge($communityMembers, $primaryUsers);
                array_push($communityMembers, $primaryCommunity->user_id);
            }

            // Same community users start
            $communitiesJoined = app('App\\Repositories\\CommunityRepository')->getMyAllJoinedCommunities();
            if (count($communitiesJoined) > 0) {
                foreach ($communitiesJoined as $cm) {
                    $myCommunity = $cm->community;
                    if ($myCommunity and $myCommunity->external_community == 1 and $myCommunity->eventmeeting == 0) {
                        if ($myCommunity->id != $myOwnedCommunityId and $myCommunity->id != $signupCommunityId and $myCommunity->id != $primaryCommunityId) {

                            $mbrs = app('App\\Repositories\\CommunityMemberRepository')->getUserIds($myCommunity->id);
                            $communityMembers = array_merge($communityMembers, $mbrs);

                            $primaryUsers = $this->getPrimaryUsersAll($myCommunity->id, $communityMembers);
                            $communityMembers = array_merge($communityMembers, $primaryUsers);
                            array_push($communityMembers, $myCommunity->user_id);
                        }
                    }
                }
            }

            $friendsOfFriends = array_intersect($friendsOfFriends, $communityMembers);
            // Same community users end

            $query = $this->model
                ->where('activated', 1)
                ->where('active', 1)
                ->where('admin', 0)
                ->where('profile_details', '!=', '')
                ->where('id', '!=', $userid)
                ->whereIn('id', $communityMembers)
                ->whereNotIn('id', $users)
                ->whereNotIn('id', $this->mustAvoidUserRepository->get())
                // ->orderBy(\DB::raw('rand()'));
                ->orderBy('id', 'desc');
            $allUsers = $query->get();
        }

        $allMyConnections = [];

        $myConnectionPreference = $user->present()->privacy('connection-preferences');

        if ($allUsers) {
            foreach ($allUsers as $usr) {

                if ($wantToConnectWith != '' and ($myConnectionPreference == 1 || $myConnectionPreference == '' || $myConnectionPreference == 6)) {
                    $wantToConnectWithOtherUser = $this->getProfileFieldValue($usr, 'Want to connect with');
                    if ($wantToConnectWithOtherUser == $wantToConnectWith) {
                        $wantToConnectWithUsers[] = $usr->id;
                    }
                }

                if ($workOrganization != '' and ($myConnectionPreference == 2 || $myConnectionPreference == '' || $myConnectionPreference == 6)) {
                    $workOrganizationOtherUser = $this->getProfileFieldValue($usr, 'Work organization name');
                    if ($workOrganizationOtherUser == $workOrganization) {
                        $workOrganizationUsers[] = $usr->id;
                    }
                }

                if ($cityOrigin != '' and ($myConnectionPreference == 5 || $myConnectionPreference == '' || $myConnectionPreference == 6)) {
                    $cityOriginOtherUser = $this->getProfileFieldValue($usr, 'Your city of origin');
                    if ($cityOriginOtherUser == $cityOrigin) {
                        $cityOriginUsers[] = $usr->id;
                    }
                }

                if ($currentCity != '' and ($myConnectionPreference == 4 || $myConnectionPreference == '' || $myConnectionPreference == 6)) {
                    $currentCityOtherUser = $this->getProfileFieldValue($usr, 'Current city name');
                    if ($currentCityOtherUser == $currentCity) {
                        $currentCityUsers[] = $usr->id;
                    }
                }

                /*if($stateName!="" and ($myConnectionPreference=="" || $myConnectionPreference==6)){
                    $stateNameOtherUser =  $this->getProfileFieldValue($usr,'State or Province name');
                    if($stateNameOtherUser == $stateName){
                        $stateNameUsers[]=$usr->id;
                    }
                }

                if($countryName!="" and ($myConnectionPreference=="" || $myConnectionPreference==6)){
                    $countryNameOtherUser =  $this->getProfileFieldValue($usr,'Country name');
                    if($countryNameOtherUser == $countryName){
                        $countryNameUsers[]=$usr->id;
                    }
                }*/
            }

            if (isset($wantToConnectWithUsers)) {
                $allMyConnections = array_merge($allMyConnections, $wantToConnectWithUsers);
            }

            if (isset($workOrganizationUsers)) {
                $allMyConnections = array_merge($allMyConnections, $workOrganizationUsers);
            }

            if (isset($cityOriginUsers)) {
                $allMyConnections = array_merge($allMyConnections, $cityOriginUsers);
            }

            if (count($friendsOfFriends) and ($myConnectionPreference == 3 || $myConnectionPreference == '' || $myConnectionPreference == 6)) {
                $allMyConnections = array_merge($allMyConnections, $friendsOfFriends);
            }

            if (isset($currentCityUsers)) {
                $allMyConnections = array_merge($allMyConnections, $currentCityUsers);
            }

            /*if(isset($stateNameUsers)){
                $allMyConnections = array_merge($allMyConnections, $stateNameUsers);
            }

            if(isset($countryNameUsers)){
                $allMyConnections = array_merge($allMyConnections, $countryNameUsers);
            }*/
        }

        return $allMyConnections;
    }

    public function getProfileFieldValue($user, $fieldName)
    {
        $data = $this->customFieldRepository->getByNameType('profile', $fieldName);
        if ($data) {
            if ($user) {
                return $user->present()->profile($data->id);
            }
        } else {
            return false;
        }
    }

    public function getBirthState($user)
    {
        $data = $this->customFieldRepository->getByNameType('profile', 'Birth State');
        if ($data) {
            return $user->present()->profile($data->id);
        } else {
            return false;
        }
    }

    public function gatherFriendsOfFriend($userid)
    {
        $connectionRepository = app('App\Repositories\\ConnectionRepository');
        $friendsId = $connectionRepository->getAllFriendConnectionIds($userid);
        $users = ['empty'];

        foreach ($friendsId as $friendId) {
            $thisUserFriends = $connectionRepository->getFriendsId($friendId);
            foreach ($thisUserFriends as $f) {
                $users[] = $friendId;
            }
        }

        $this->cache->put('user-friends-of-friends-'.$userid, $users, 3600);

        return $users;
    }

    /**
     * Search users with a term
     *
     * @param  string  $term
     * @param  int  $limit
     * @return array
     */
    public function search($term = '', $limit = null, $community_id = 0)
    {

        $limit = (empty($limit)) ? $this->config->get('user-listing') : $limit;
        $term = str_replace('@', '', $term);
        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->where('username', '!=', 'admin')
            ->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', '=', $term);
            });
            // Temporarily disabled for performance - was causing 7+ minute delays
            // ->whereNotIn('id', $this->mustAvoidUserRepository->get());
        $country = request()->get('country');
        $gender = request()->get('gender');
        $city = request()->get('city');

        if ($country and $country != 'all') {
            $users = $users->where('country', '=', $country);
        }
        if ($gender and $gender != 'both') {
            $users = $users->where('genre', '=', $gender);
        }
        if ($city) {
            $users = $users->where('city', '=', $city);
        }

        if ($community_id) {
            $result = $this->model
                ->where('activated', 1)
                ->where('active', 1)
                ->where('community_signup', '=', $community_id)
                ->pluck('id');
            $community_signup_users = is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;

            $communityMembers = app('App\\Repositories\\CommunityMemberRepository')->getUserIds($community_id);

            $cm_usr_ids = array_unique(array_merge($community_signup_users, $communityMembers));

            $users = $users->whereIn('id', $cm_usr_ids);
        }

        if (\Auth::check()) {
            $blockedUsers = $this->blockedUserRepository->listIds(\Auth::user()->id);
            $users->whereNotIn('id', $blockedUsers);
        }

        return $users = $users->paginate($limit);
    }

    public function searchUsers($term = '', $limit = null)
    {
        $userid = \Auth::user()->id;

        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->where('username', '!=', 'admin')
            ->where('id', '!=', $userid)
            ->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', 'LIKE', '%'.$term.'%');
            });
            // Temporarily disabled for performance
            // ->whereNotIn('id', $this->mustAvoidUserRepository->get());

        return $users = $users->paginate(10);
    }

    public function searchAllUsers($term = '', $limit = null)
    {
        $userid = \Auth::user()->id;

        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->where('username', '!=', 'admin')
            ->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', 'LIKE', '%'.$term.'%');
            })
            ->whereNotIn('id', $this->mustAvoidUserRepository->get());

        return $users = $users->paginate(10);
    }

    public function searchByIds($term, $userIds, $limit = 5, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->whereIn('id', $userIds)
            ->whereNotIn('id', $this->mustAvoidUserRepository->get())
            ->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', '=', $term);
            });

        // if (\Auth::check()) {
        if ($userid) {
            $blockedUsers = $this->blockedUserRepository->listIds($userid);
            $users->whereNotIn('id', $blockedUsers);
        }

        return $users = $users->paginate($limit);
    }

    public function listByIds($onlyIds = ['0'], $skipIds = [0], $limit = 10, $offset = 0, $term = '')
    {
        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->whereIn('id', $onlyIds)
            ->whereNotIn('id', $skipIds)
            ->whereNotIn('id', $this->mustAvoidUserRepository->get());

        if (! empty($term)) {
            $users->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', '=', $term);
            });
        }

        if (\Auth::check()) {
            $blockedUsers = $this->blockedUserRepository->listIds(\Auth::user()->id);
            $users->whereNotIn('id', $blockedUsers); // always ignore is blocked users
        }

        return $users->skip($offset)
            ->take($limit)
            ->get();

    }

    public function listByIdsAll($onlyIds = ['0'], $term = '')
    {
        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->whereIn('id', $onlyIds)
            ->whereNotIn('id', $this->mustAvoidUserRepository->get());

        if (! empty($term)) {
            $users->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', '=', $term);
            });
        }

        return $users->get();
    }

    public function friendsSuggest($term, $limit = 5, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $friendsId = app('App\\Repositories\\ConnectionRepository')->getFriendsId($userid);

        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->whereIn('id', $friendsId)
            ->whereNotIn('id', $this->mustAvoidUserRepository->get())
            ->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', '=', $term);
            });

        if (\Auth::check()) {
            $blockedUsers = $this->blockedUserRepository->listIds(\Auth::user()->id);
            $users->whereNotIn('id', $blockedUsers);
        }

        return $users = $users->paginate($limit);
    }

    public function latestUsers($limit = 10)
    {
        return $this->model->where('activated', 1)->where('active', 1)->where('avatar', '!=', '')->orderBy('id', 'desc')->paginate($limit);
    }

    /**
     * Search users base on search term
     *
     * @param  string  $term
     * @param  int  $limit
     * @return array
     */
    public function searchByUsername($term, $limit = null, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $limit = (empty($limit)) ? $this->config->get('user-listing') : $limit;
        $users = $this->model
            ->whereNotIn('id', $this->mustAvoidUserRepository->get())
            ->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%');
            });

        if ($userid) {
            $blockedUsers = $this->blockedUserRepository->listIds($userid);
            $users->whereNotIn('id', $blockedUsers);
        }

        return $users = $users->paginate($limit);
    }

    public function searchByUsernameCommunity($term, $userids, $limit = null)
    {
        $userid = \Auth::user()->id;

        $limit = (empty($limit)) ? $this->config->get('user-listing') : $limit;
        $users = $this->model
            ->whereIn('id', $userids)
            ->whereNotIn('id', $this->mustAvoidUserRepository->get())
            ->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%');
            });

        return $users = $users->paginate($limit);
    }

    /**
     * Getstarted members suggestion
     *
     * @return array
     */
    public function getstartedMembers()
    {
        return $this->suggest(10);
    }

    /**
     * Get User limit per page
     *
     * @param  int  $limit
     * @return array
     */
    public function getPerPage($limit = null)
    {
        $limit = (empty($limit)) ? $this->config->get('user-per-page') : $limit;

        return $this->model->paginate($limit);
    }

    /**
     * @return mixed
     */
    public function login($val, $adminlogin = null)
    {
        $credential = [
            'username' => '',
            'password' => '',
            'keep' => '',
        ];

        /**
         * @var $username
         * @var $password
         * @var $keep
         */
        extract($credential = array_merge($credential, $val));

        $keep = (empty($keep)) ? false : true;
        unset($credential['keep']);
        $loggedin = false;
        /**
         * first try using username
         */
        if (! $adminlogin and ($username == 'admin' || $username == 'admin@idhubs.com')) {
            return false;
        }

        if ($this->request->is('api/v1/*')) {
            if ($loggedin = \Auth::attempt($credential, $keep, false)) {
                return $loggedin = true;
            } else {
                $credential = [
                    'email_address' => $username,
                    'password' => $password,
                ];
                $loggedin = (\Auth::attempt($credential, $keep, false)) ? true : false;

                if (! $loggedin) {
                    $credential = [
                        'secondary_email_address' => $username,
                        'password' => $password,
                    ];
                    $loggedin = (\Auth::attempt($credential, $keep, false)) ? true : false;
                }

                return $loggedin;
            }
        } elseif ($loggedin = \Auth::attempt($credential, $keep)) {
            $loggedin = true;
        } else {
            $credential = [
                'email_address' => $username,
                'password' => $password,
            ];
            $loggedin = \Auth::attempt($credential, $keep);

            if (! $loggedin) {
                $credential = [
                    'secondary_email_address' => $username,
                    'password' => $password,
                ];
                $loggedin = \Auth::attempt($credential, $keep);
            }
        }

        if ($loggedin) {
            $user = \Auth::user();

            // if ($user->login_key == "") {
            $user->login_key = substr(hash('sha256', mt_rand().microtime()), 0, 30);
            $user->save();
            // }

            if ($adminlogin and $user->admin == 0) {
                \Auth::logout();

                return false;
            }

            if ($user->banned == 1) {
                \Auth::logout();

                return 'banned';
            } elseif ($user->activated == 0) {
                \Auth::logout();

                return 'activate';
            } else {
                $user->online_status = 1;
                $this->savePrivacy(['self-offline' => 0], $user);
                $user->save();

                /* ---Set cookie to store username and password --- */
                if ($keep) {
                    $hour = time() + 31536000;
                    setcookie('remember_me_user', $username, $hour, '/', '.'.$_SERVER['SERVER_NAME']);
                    setcookie('remember_me_pass', $password, $hour, '/', '.'.$_SERVER['SERVER_NAME']);
                } else {
                    $remember_me_user = 'remember_me_user';
                    unset($_COOKIE['remember_me_user']);

                    $remember_me_pass = 'remember_me_pass';
                    unset($_COOKIE['remember_me_pass']);
                }
                /* Set cookie end */

                return 'valid';
            }

        }

        return $loggedin;
    }

    /**
     * Log In user using their id
     *
     * @param  int  $id
     * @return mixed
     **/
    public function loginUsingId($id)
    {
        $loggedin = false;
        if ($loggedin = \Auth::loginUsingId($id)) {
            $user = \Auth::user();
            if ($user->banned == 1) {
                \Auth::logout();

                return 'banned';
            } elseif ($user->activated == 0) {
                \Auth::logout();

                return 'activate';
            } else {
                $user->online_status = 1;
                $this->savePrivacy(['self-offline' => 0], $user);
                $user->login_key = substr(hash('sha256', mt_rand().microtime()), 0, 30);
                $user->save();

                return 'valid';
            }
        }

        return $loggedin;
    }

    /**
     * Register new member
     *
     * @param  array  $val
     * @param  bool  $active
     * @return bool
     */
    public function signup($val, $active = false)
    {
        $credential = [
            'username' => '',
            'password' => '',
            'email_address' => '',
            'fullname' => '',
            'genre' => '',
            'country' => '',
            'birth_day' => 0,
            'birth_month' => 0,
            'birth_year' => 0,
            'role_id' => 1,
            'city' => '',
            'community_name' => '',
            'community_description' => '',
            'searchable' => 0,
            'moderator_action' => 1,
            'domain' => '',
            'domain_name' => '',
            'community_slug' => '',
            'community_full_address' => '',
            'state' => '',
            'zip' => '',
            'pricing_plan' => 1,
            'signup_type' => '',
            'signup_type_id' => 0,
        ];

        /**
         * @var $username
         * @var $password
         * @var $email_address
         * @var $fullname
         * @var $genre
         * @var $country
         * @var $birth_day
         * @var $birth_month
         * @var $birth_year
         * @var $role_id
         */
        extract($credential = array_merge($credential, $val));

        $user = $this->model->newInstance();
        // $user->username = sanitizeText($username, 100);
        $user->username = $this->generateUsername($username);
        $user->email_address = $email_address;
        $user->fullname = sanitizeText($fullname, 100);
        $user->genre = sanitizeText($genre);
        $user->country = sanitizeText($country);
        $user->city = sanitizeText($city);
        $user->password = \Hash::make($password);
        $user->online_status = 1;
        $user->last_active_time = time();
        $user->birth_day = sanitizeText($birth_day);
        $user->birth_month = sanitizeText($birth_month);
        $user->birth_year = sanitizeText($birth_year);
        $user->role_id = sanitizeText($role_id); // for content admin - media provider
        $user->signup_type = $signup_type;
        $user->signup_type_id = $signup_type_id;
		$user->currency="USD";
        $user->active = 0;
        $user->activated = 0;

        $user->fully_started = 1;

        $userIpAddress = getUserClientIpAddr();
        if ($userIpAddress) {
            $ipInfo = $this->siteVisitorsRepository->getIpInfo($userIpAddress);
            if ($ipInfo and is_array($ipInfo) and $ipInfo['status'] == 'success') {
                if (isset($ipInfo['country'])) {
                    $user->country = $ipInfo['country'];
                }

                if (isset($ipInfo['city'])) {
                    $user->city = $ipInfo['city'];
                }

                if (isset($ipInfo['state'])) {
                    $user->state = $ipInfo['state'];
                }
            }
        }

        $user->ip_address = $userIpAddress;
        $user->save();

        $this->setUserRoleUUID($user);

        app('App\\Repositories\\NotificationRepository')->sendCalNotification($user); // Show event notification
        $externalCommunity = app('App\\Repositories\\CommunityRepository')->addExternalCommunity($user->id, $community_name, $community_description, $searchable, $moderator_action, $domain, $domain_name, $community_slug, 0, 0, $community_full_address, $city, $state, $country, $zip, $email_address, $pricing_plan); // Get and save comunity data

        if ($externalCommunity) {
            $user->external_community = $externalCommunity->id;
            $user->favourite_community = $externalCommunity->id;
            $user->save();

            try {
                $this->mailer->send('emails.auth.community-registered', [
                    'username' => $user->username,
                    'fullname' => $user->fullname,
                    'email_address' => $user->email_address,
                    'community_title' => $externalCommunity->title,
                ], function ($mail) {
                    $mail->to('info@idhubs.com', 'admin')
                        ->subject('New community registered');
                });
            } catch (\Exception $e) {

            }
        }
        /***
         * Send a welcome email to our new user
         */
        try {
            $this->mailer->send('emails.auth.welcome-community', [
                'username' => $user->username,
                'fullname' => $user->fullname,
                'email_address' => $user->email_address,
                'password' => $password,
                'profileUrl' => $user->present()->url(),
                'site_name' => config('site_title'),
            ], function ($mail) use ($user) {
                $mail->to($user->email_address, $user->fullname)
                    ->subject(trans('mail.welcome-mail-subject'));
            });
        } catch (\Exception $e) {

        }

        $this->event->dispatch('user.register', [$user, $val]);

        return $user;
    }

    /**
     * Register new member
     *
     * @param  array  $val
     * @param  bool  $active
     * @return bool
     */
    public function registeruser($val, $active = false)
    {
        $credential = [
            'username' => '',
            'password' => '',
            'email_address' => '',
            'fullname' => '',
            'genre' => '',
            'country' => '',
            'birth_day' => 0,
            'birth_month' => 0,
            'birth_year' => 0,
            'role_id' => 1,
            'communityId' => 0,
            'signup_type' => '',
            'signup_type_id' => 0,
        ];

        /**
         * @var $username
         * @var $password
         * @var $email_address
         * @var $fullname
         * @var $genre
         * @var $country
         * @var $birth_day
         * @var $birth_month
         * @var $birth_year
         * @var $role_id
         */
        extract($credential = array_merge($credential, $val));

        // If registration is initiated from a PDF-sign invite flow, force the user to be
        // an IDHubs user (communityId = 0) so welcome email is not community-branded.
        $forceGlobalCommunity = false;
        try {
            $forceGlobalCommunity = (int) \Session::get('pdfsign_force_global_community', 0) === 1;
        } catch (\Throwable $e) {
        }

        if (! $forceGlobalCommunity) {
            try {
                $returnUrl = '';
                if (isset($val['returnUrl'])) {
                    $returnUrl = (string) $val['returnUrl'];
                } elseif (isset($returnUrl)) {
                    $returnUrl = (string) $returnUrl;
                }

                if ($returnUrl !== '' && stripos($returnUrl, 'pdf-sign/invite/') !== false) {
                    $forceGlobalCommunity = true;
                }
            } catch (\Throwable $e) {
            }
        }

        if ($forceGlobalCommunity) {
            $communityId = 0;
            try {
                \Session::forget('pdfsign_force_global_community');
            } catch (\Throwable $e) {
            }
        }

        $user = $this->model->newInstance();
        // $user->username = sanitizeText($username, 100);
        $user->username = $this->generateUsername($username);
        $user->email_address = $email_address;
        $user->fullname = sanitizeText($fullname, 100);
        $user->genre = sanitizeText($genre);
        $user->country = sanitizeText($country);
        $user->password = \Hash::make($password);
        $user->online_status = 1;
        $user->last_active_time = time();
        $user->birth_day = sanitizeText($birth_day);
        $user->birth_month = sanitizeText($birth_month);
        $user->birth_year = sanitizeText($birth_year);
        $user->role_id = sanitizeText($role_id); // for content admin - media provider
        $user->community_signup = $communityId;
        $user->external_community = sanitizeText($communityId);
        $user->signup_type = $signup_type;
        $user->signup_type_id = $signup_type_id;
		$user->currency="USD";
		
		$userfullName=$fullname;						
		$firstName = $userfullName;
		$lastName = "";
		
		$fullNameExp=explode(" ",$userfullName);
		
		if(isset($fullNameExp[0])){
			$firstName=$fullNameExp[0];
		}
		
		if(isset($fullNameExp[1])){
			$lastName=$fullNameExp[1];
		}else{
			$lastName=$firstName;
		}
		
		$user->first_name=$firstName;
		$user->last_name=$lastName;
		
        $community = app('App\\Repositories\\CommunityRepository')->getById($communityId); // Get community

        $autoActivation = '';
        if ($community) {
            if ($community->auto_signon == 1) {
                $autoActivation = 'yes';
            }
        }

        if (\Session::has('inviteUrl')) {
            $autoActivation = 'yes';
        }

        if ($autoActivation == 'yes') {
            $user->active = 1;
            $user->activated = 1;
        } else {
            if ($active or ! config('user-activation')) {
                $user->active = 1;
                $user->activated = 1;
            }
        }

        if (! config('user-getstarted')) {
            $user->fully_started = 1;
        }

        $userIpAddress = getUserClientIpAddr();
        if ($userIpAddress) {
            $ipInfo = $this->siteVisitorsRepository->getIpInfo($userIpAddress);
            if ($ipInfo and is_array($ipInfo) and $ipInfo['status'] == 'success') {
                if (isset($ipInfo['country'])) {
                    $user->country = $ipInfo['country'];
                }

                if (isset($ipInfo['city'])) {
                    $user->city = $ipInfo['city'];
                }

                if (isset($ipInfo['state'])) {
                    $user->state = $ipInfo['state'];
                }
            }
        }

        $user->ip_address = $userIpAddress;
        $user->save();

        $this->setUserRoleUUID($user);

        if ($community and ($community->eventmeeting == 1 || $community->id == 75)) {
            $community = app('App\\Repositories\\CommunityRepository')->getResumeCommunity();
            if ($community) {
                $user->community_signup = $community->id;
                $user->external_community = $community->id;
            }
        }

        app('App\\Repositories\\NotificationRepository')->sendCalNotification($user); // Show event notification

        /***
         * Send a welcome email to our new user
         */

        if ($community) {

            //if ($user->active == 1 and $user->activated == 1) {
                $followOwner = app('App\\Repositories\\ConnectionRepository')->add($user->id, $community->user_id, 1);
				
				$getInfluencers=app('App\\Repositories\\CommunityInfluencersRepository')->getInfluencersByCommunity($community->id);
				if($getInfluencers){
					foreach($getInfluencers as $inId){
						app('App\\Repositories\\ConnectionRepository')->add($user->id, $inId, 1);
					}
				}
            //}

            $email_subject = 'Welcome at '.$community->title;
            if ($community->welcome_email_subject) {
                $email_subject = $community->welcome_email_subject;
            }

            if ($community->welcome_email) {

                $email_body = $community->welcome_email;
                $replaceString1 = $user->email_address;
                $new_email_body = str_replace("'user_email_address'", $replaceString1, $email_body);

                $mail_from_email = $community->present()->getFromEmailAddress();

                try {
                    $this->mailer->send('emails.email-body', [
                        'email_body' => $new_email_body,
                    ], function ($mail) use ($user, $community, $email_subject, $mail_from_email) {
                        $mail->to($user->email_address, $user->fullname)
                            ->subject($email_subject)
                            ->from($mail_from_email, $community->title);
                    });
                } catch (\Exception $e) {

                }
            } else {

                $mail_from_email = $community->present()->getFromEmailAddress();

                try {
                    $this->mailer->send('emails.auth.welcome-member', [
                        'username' => $user->username,
                        'site_name' => $community->title,
                        'fullname' => $user->fullname,
                        'email_address' => $user->email_address,
                        'community_name' => $community->title,
                        'siteName' => $community->title,
                        'community_url' => $community->present()->url(),
                        'community_email' => $community->email,
                        'community_phone' => $community->contact,
                        'community_id' => $community->id,
                    ], function ($mail) use ($user, $community, $email_subject, $mail_from_email) {
                        $mail->to($user->email_address, $user->fullname)
                            ->subject($email_subject)
                            ->from($mail_from_email, $community->title);
                    });
                } catch (\Exception $e) {

                }
            }
        } else {

            if($signup_type=='email_signup_feature'){
				try {
					$this->mailer->send('emails.auth.welcome-feature', [
						'username' => $user->username,
						'fullname' => $user->fullname,
						'email_address' => $user->email_address,
						'password' => $password,
						'profileUrl' => $user->present()->url(),
						'site_name' => config('site_title'),
						'feature_id'=>$signup_type_id
					], function ($mail) use ($user) {
						$mail->to($user->email_address, $user->fullname)
							->subject(trans('mail.welcome-mail-subject'));
					});
				} catch (\Exception $e) {
	
				}
			}else{ 
				try {
					$this->mailer->send('emails.auth.welcome', [
						'username' => $user->username,
						'fullname' => $user->fullname,
						'email_address' => $user->email_address,
						'password' => $password,
						'profileUrl' => $user->present()->url(),
						'site_name' => config('site_title'),
					], function ($mail) use ($user) {
						$mail->to($user->email_address, $user->fullname)
							->subject(trans('mail.welcome-mail-subject'));
					});
				} catch (\Exception $e) {
	
				}
			}	
        }

        $this->event->dispatch('user.register', [$user, $val]);

        return $user;
    }

    /**
     * Send Activation code
     *
     * @param  \App\Models\User  $user
     * @return bool
     */
    public function sendActivation($user, $siteName = null)
    {
        $hash = md5($user->username.$user->password);
        $user->hash = $hash;
        $user->save();

        if ($siteName == 'wakhal_tv') {
            $site_title = 'Wakhal Tv';
            $subject = 'Wakhal Tv Account activation';
        } else {
            $site_title = config('site_title');
            $subject = trans('mail.activation-mail-subject');
        }

        $community = app('App\\Repositories\\CommunityRepository')->getById($user->community_signup); // Get community

        if ($community) {

            $email_subject = 'Account activation';
            if ($community->activation_email_subject) {
                $email_subject = $community->activation_email_subject;
            }

            if ($community->activation_email) {

                $email_body = $community->activation_email;

                $replaceString = 'accountactivate?email='.$user->email_address;

                $new_email_body = str_replace('accountactivate?email=', $replaceString, $email_body);

                $replaceString1 = 'code='.$hash;

                $new_email_body1 = str_replace('code=', $replaceString1, $new_email_body);

                $mail_from_email = $community->present()->getFromEmailAddress();

                try {
                    $this->mailer->send('emails.email-body', [
                        'email_body' => $new_email_body1,
                    ], function ($mail) use ($user, $community, $email_subject, $mail_from_email) {
                        $mail->to($user->email_address, $user->fullname)
                            ->subject($email_subject)
                            ->from($mail_from_email, $community->title);
                    });
                } catch (\Exception $e) {

                }
            } else {

                $mail_from_email = $community->present()->getFromEmailAddress();

                try {
                    $this->mailer->send('emails.auth.activation-community', [
                        'hash' => $hash,
                        'site_name' => $community->title,
                        'username' => $user->username,
                        'fullname' => $user->fullname,
                        'email_address' => $user->email_address,
                        'profileUrl' => $user->present()->url(),
                        'siteName' => $community->title,
                        'community_name' => $community->title,
                        'community_acivation_url' => $community->present()->url('accountactivate'),
                    ], function ($mail) use ($user, $community, $email_subject, $mail_from_email) {
                        $mail->to($user->email_address, $user->fullname)
                            ->subject($email_subject)
                            ->from($mail_from_email, $community->title);
                    });
                } catch (\Exception $e) {

                }
            }
        } else {

            try {
                $this->mailer->send('emails.auth.activation', [
                    'hash' => $hash,
                    'site_name' => config('site_title'),
                    'username' => $user->username,
                    'fullname' => $user->fullname,
                    'email_address' => $user->email_address,
                    'profileUrl' => $user->present()->url(),
                    'siteName' => $siteName,
                ], function ($mail) use ($user, $subject) {
                    $mail->to($user->email_address, $user->fullname)
                        ->subject($subject); /*subject(trans('mail.activation-mail-subject', [
                            'name' => $user->username,
                            'site_title' => $site_title
                        ])*/
                });
            } catch (\Exception $e) {

            }
        }

        return true;
    }

    /**
     * Find user by its activation hash
     *
     * @param  array  $val
     * @return \App\Models\User
     */
    public function findByHash($val, $withEmail = true)
    {
        /**
         * @var $email
         * @var $code
         */
        extract($val);

        if (! $withEmail) {
            return $this->model->where('hash', '=', $code)->first();
        }

        return $this->model->where('hash', '=', $code)->where('email_address', '=', $email)->first();
    }

    /**
     * Activate account
     *
     * @param  array  $val
     * @return bool
     */
    public function activate($val, $user = null)
    {
        if (! $user) {
            $user = $this->findByHash($val);

            if (! $user) {
                return false;
            }

            \Auth::login($user);

            if ($user->activated) {
                return $user;
            }

            $user->activated = 1;
            $user->active = 1;
            $user->is_email_verified = 1;
            $user->save();
        }

        $communityId = $user->community_signup;

        if ($communityId > 0) {
            $community = app('App\\Repositories\\CommunityRepository')->getById($communityId); // Get community
            if ($community) {

                $email_subject = 'Your account has been activated successfully';
                if ($community->activation_successfull_email_subject) {
                    $email_subject = $community->activation_successfull_email_subject;
                }

                if ($community->activation_successfull_email) {

                    $email_body = $community->activation_successfull_email;

                    $replaceString = $user->fullname;

                    $new_email_body = str_replace("'user_fullname'", $replaceString, $email_body);

                    $replaceString1 = $user->email_address;

                    $new_email_body1 = str_replace("'user_email_address'", $replaceString1, $new_email_body);

                    $mail_from_email = $community->present()->getFromEmailAddress();

                    try {
                        $this->mailer->send('emails.email-body', [
                            'email_body' => $new_email_body1,
                        ], function ($mail) use ($user, $community, $email_subject, $mail_from_email) {
                            $mail->to($user->email_address, $user->fullname)
                                ->subject($email_subject)
                                ->from($mail_from_email, $community->title);
                        });
                    } catch (\Exception $e) {

                    }
                } else {
                    $mail_from_email = $community->present()->getFromEmailAddress();
                    try {
                        $this->mailer->send('emails.auth.activated_successfully', [
                            'username' => $user->username,
                            'fullname' => $user->fullname,
                            'email_address' => $user->email_address,
                            'site_name' => config('site_title'),
                            'profileUrl' => $user->present()->url(),
                            'community_url' => $community->present()->url(),
                            'community_title' => $community->title,
                            'community_id' => $community->id,
                        ], function ($mail) use ($user, $community, $email_subject, $mail_from_email) {
                            $mail->to($user->email_address, $user->fullname)
                                ->subject($email_subject)
                                ->from($mail_from_email, $community->title);
                        });
                    } catch (\Exception $e) {

                    }
                }
            }
        }

        $this->mustAvoidUserRepository->remove($user->id); // remove from avoided users

        return $user;
    }

    /**
     * Send password retrieval message
     *
     * @param  string  $email
     * @return bool
     */
    public function retrievePassword($email, $siteName = null)
    {
        // $user = $this->findByEmail($email);
        $user = $this->findByUsernameEmail($email);

        if (! $user) {
            return false;
        }

        if ($user->activated == 0 || $user->active == 0) {
            return false;
        }

        $hash = md5($user->username.$user->password);
        $user->hash = $hash;
        $user->save();

        try {
            $this->mailer->send('emails.auth.password', [
                'hash' => $hash,
                'username' => $user->username,
                'fullname' => $user->fullname,
                'email_address' => $user->email_address,
                'site_name' => config('site_title'),
                'profileUrl' => $user->present()->url(),
                'siteName' => $siteName,
            ], function ($mail) use ($user) {
                $mail->to($user->email_address, $user->fullname)
                    ->subject(trans('mail.forgot-pass-mail-subject'));
            });
        } catch (\Exception $e) {

        }

        return true;
    }

    /**
     * Save user settings
     *
     * @param  $user
     * @param  array  $val
     * @param  bool  $isAdmin
     * @return string
     */
    public function forgetPassword($email, $siteName = null)
    {
        $user = $this->findByUsernameEmail($email);

        if (! $user) {
            return false;
        }

        $hash = md5($user->username.$user->password);
        $user->hash = $hash;
        $user->save();

        $new_hash = $this->forgotPasswordRepository->add($user, 0);

        try {
            $this->mailer->send('emails.auth.password', [
                'hash' => $new_hash,
                'username' => $user->username,
                'fullname' => $user->fullname,
                'email_address' => $user->email_address,
                'site_name' => config('site_title'),
                'profileUrl' => $user->present()->url(),
                'siteName' => $siteName,
            ], function ($mail) use ($user) {
                $mail->to($user->email_address, $user->fullname)
                    ->subject('Password Retrieval');
            });
        } catch (\Exception $e) {

        }

        return true;
    }

    public function forgetPasswordCommunity($email, $communityId)
    {
        $user = $this->findByUsernameEmail($email);

        $community = app('App\\Repositories\\CommunityRepository')->getById($communityId);

        if (! $user || ! $community) {
            return false;
        }

        if ($user->activated == 0 || $user->active == 0) {
            return false;
        }

        $hash = md5($user->username.$user->password);
        $user->hash = $hash;
        $user->save();

        $new_hash = $this->forgotPasswordRepository->add($user, $communityId);

        $mail_from_email = $community->present()->getFromEmailAddress();

        try {
            $this->mailer->send('emails.auth.community-password', [
                'hash' => $new_hash,
                'username' => $user->username,
                'fullname' => $user->fullname,
                'email_address' => $user->email_address,
                'site_name' => config('site_title'),
                'profileUrl' => $user->present()->url(),
                'communityId' => $communityId,
            ], function ($mail) use ($user, $community, $mail_from_email) {
                $mail->to($user->email_address, $user->fullname)
                    ->subject('Password Retrieval')
                    ->from($mail_from_email, $community->title);
            });
        } catch (\Exception $e) {

        }

        return true;
    }

    public function saveByUserIdProfile($user, $val, $isAdmin = false)
    {
        $expected = [
            'like_to_learn' => '',
            'connect_with' => '',
            'origin_city' => '',
            'genre' => '',
            'avatar_type' => 0,
            'about_me' => '',
			'birth_day' => 0,
            'birth_month' => 0,
            'birth_year' => 0,
        ];
        $val = array_merge($expected, $val);
        extract($val);

        $this->savePrivacy(['avatar_type' => $avatar_type], $user);

        $user->like_to_learn = $like_to_learn;
        $user->connect_with = $connect_with;
        $user->origin_city = $origin_city;
        $user->about_me = $about_me;
        if (! empty($genre)) {
            $user->genre = sanitizeText($genre);
        }
		
		$user->birth_day = sanitizeText($birth_day);
        $user->birth_month = sanitizeText($birth_month);
        $user->birth_year = sanitizeText($birth_year);

        $user->save();

        return $user;
    }

    public function saveSettings($user, $val, $isAdmin = false)
    {
        $expected = [
            'username' => '',
            'fullname' => '',
            'currentpassword' => '',
            'newpassword' => '',
            // 'genre' => '',
            'activated' => '',
            'active' => '',
            'group' => '',
            'country' => '',
            'city' => '',
            'email' => '',
            'bio' => 'bio',
            // 'avatar_type' => 0,
            'language' => '',
            'birth_day' => 0,
            'birth_month' => 0,
            'birth_year' => 0,
            'currency' => '',
            'secondary_email_address' => '',
            'bring_all_posts' => 0,
            'first_name' => '',
            'last_name' => '',
            'phone_number' => '',
            // 'like_to_learn' => '',
            // 'connect_with' => '',
            // 'origin_city' => '',
        ];

        $val = array_merge($expected, $val);

        /**
         * @var $username
         * @var $fullname
         * @var $currentpassword
         * @var $newpassword
         * @var $genre
         * @var $activated
         * @var $active
         * @var $group
         * @var $country
         * @var $city
         * @var $email
         * @var $bio
         * @var $avatar_type
         * @var $language
         * @var $birth_day
         * @var $birth_month
         * @var $birth_year
         */
        extract($val);

        $message = null;

        $fullname = $first_name.' '.$last_name;

        $user->currency = $currency;

        $user->fullname = sanitizeText($fullname, 100);
        $user->first_name = sanitizeText($first_name, 100);
        $user->last_name = sanitizeText($last_name, 100);

        // $user->phone_number = $phone_number;

        // $user->like_to_learn = $like_to_learn;
        // $user->connect_with = $connect_with;
        // $user->origin_city = $origin_city;

        // if (!empty($genre)) $user->genre = sanitizeText($genre);

        if ($isAdmin) {
            if (\Auth::user()->id != 1) {
                return false;
            }
            $user->activated = $activated;
            $user->active = $active;
            $user->user_group = $group;
            // $user->country = sanitizeText($country);
            $user->email_address = $email;
        } else {
            $user->bio = sanitizeText($bio);
            // $user->country = sanitizeText($country);
            // $user->city = sanitizeText($city, 70);
           
		    //$user->birth_day = sanitizeText($birth_day);
            //$user->birth_month = sanitizeText($birth_month);
            //$user->birth_year = sanitizeText($birth_year);

            $this->savePrivacy(['lang' => $language], $user);
        }

        $validatorRules = [];

        if (! empty($username) and $username != $user->username) {
            $validatorRules['username'] = 'required|alpha_num|slug|min:5|unique:users,username,'.$user->id;
        }

        if (! $isAdmin and $email != $user->email_address) {
            $validatorRules['email'] = 'required|email|unique:users,email_address,'.$user->id.'|unique:users,secondary_email_address,'.$user->secondary_email_address;
        }

        if (! $isAdmin and $secondary_email_address != '' and $secondary_email_address != $user->secondary_email_address) {
            /* $validatorRules['secondary_email_address'] = 'required|email|unique:users,email_address,'.$user->id.'|unique:users,secondary_email_address,'.$user->secondary_email_address; */
        }

        /**
         * Check for new password
         */
        if (! empty($newpassword)) {
            $validatorRules['currentpassword'] = 'required';
            $validatorRules['newpassword'] = 'required|min:6';

            if (! \Hash::check($currentpassword, $user->password)) {
                $message = trans('user.password-does-not-match');
            } else {
                $user->password = \Hash::make($newpassword);
                $message = 'You password has been changed successfully.';

                $user->social_pass = '';
            }

        }

        // update user avatar type
        // $this->savePrivacy(['avatar_type' => $avatar_type], $user);

        if ($email == $secondary_email_address) {
            return $message = 'Privide different email addresses.';
        }
        if (! empty($validatorRules)) {

            $validator = \Validator::make($val, $validatorRules);

            if ($validator->fails()) {
                $message = $message.' '.$validator->messages()->first();
            }

            /**
             * Saving username from here if it doesnot have the error message
             */
            if (config('can-change-username') and ! $validator->messages()->has('username') and $username != $user->username) {
                $user->username = sanitizeText($username, 100);

                if ($user->verified == 1 and config('remove-verify-badge-username')) {
                    $user->verified = 0;
                }
            }

            /**
             * Checking for validity of emails
             */
            if (! $isAdmin and ! $validator->messages()->has('email')) {
                $user->email_address = $email;
            }

            /*if (!$isAdmin and !$validator->messages()->has('secondary_email_address')) {
                $user->secondary_email_address = $secondary_email_address;
            }*/
        }

        if ($secondary_email_address == '') {
            $user->secondary_email_address = '';
        }

        /**
         * Save and update user details
         */
        $user->social_posts_on_community = $bring_all_posts;
        $user->save();

        $this->event->dispatch('user.setting.update', [$user, $val]);

        $this->updateCRMUser($user->id);

        return $message;
    }
	
	 public function saveMembersSettings($user, $val, $isAdmin = false)
    {
        $expected = [
            'username' => '',
            'fullname' => '',
            'currentpassword' => '',
            'newpassword' => '',
            'genre' => '',
            'activated' => '',
            'active' => '',
            'group' => '',
            'country' => '',
            'city' => '',
            'email' => '',
            'bio' => 'bio',            
            'language' => '',
            'birth_day' => 0,
            'birth_month' => 0,
            'birth_year' => 0,
            'currency' => '',
            'secondary_email_address' => '',
            'bring_all_posts' => 0,
            'first_name' => '',
            'last_name' => '',
            'phone_number' => '',
        ];

        $val = array_merge($expected, $val);

        extract($val);

        $message = "Settings saved successfully";
        
		$user->birth_day = sanitizeText($birth_day);
		$user->birth_month = sanitizeText($birth_month);
		$user->birth_year = sanitizeText($birth_year);

		$this->savePrivacy(['lang' => $language], $user);       

        $validatorRules = [];
       
        if (! empty($newpassword)) {
            $validatorRules['currentpassword'] = 'required';
            $validatorRules['newpassword'] = 'required|min:6';

            if (! \Hash::check($currentpassword, $user->password)) {
                $message = trans('user.password-does-not-match');
            } else {
                $user->password = \Hash::make($newpassword);
                $message = 'You password has been changed successfully.';

                $user->social_pass = '';
            }
        }
		
		if (! empty($genre)) {
            $user->genre = sanitizeText($genre);
        }

        $user->save();

        $this->event->dispatch('user.setting.update', [$user, $val]);

        return $message;
    }

    /**
     * Update Basic Profile
     *
     * @param  array  $val
     * @param  bool  $isAdmin
     * @return string
     */
    public function updateBasicProfile($user, $val)
    {
        $expected = [
            'fullname' => '',
            'currentpassword' => '',
            'newpassword' => '',
            'country' => '',
        ];

        $val = array_merge($expected, $val);

        /**
         * @var $fullname
         * @var $currentpassword
         * @var $newpassword
         * @var $genre
         * @var $country
         */
        extract($val);

        $message = null;

        $user->fullname = sanitizeText($fullname, 100);
        if (! empty($genre)) {
            $user->genre = sanitizeText($genre);
        }

        $user->country = sanitizeText($country, 70);

        /**
         * Check for new password
         */
        if (! empty($newpassword)) {
            $validatorRules['currentpassword'] = 'required';
            $validatorRules['newpassword'] = 'required|min:6';

            if (! \Hash::check($currentpassword, $user->password)) {
                $message = trans('user.password-does-not-match');
            } else {
                $user->password = \Hash::make($newpassword);
            }
        }

        /**
         * Save and update user details
         */
        $user->save();

        $this->event->dispatch('user.setting.update', [$user, $val]);

        return $message;
    }

    /**
     * Change user avatar
     *
     * @param  string  $image
     * @param \App\Models\ $user
     * @return \iDwakhalweb\Image\ImageProcessor
     */
    public function changeAvatar($image, $user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;
        $album = $this->photoAlbum->add('profile photos', $user->id, true);
        $slug = 'album-'.$album->id;
        // $image = sanitizeText($image);

        // $image = $this->photoRepository->add($image, $user->id, $slug);

        $param = [
            'path' => 'users/'.$user->id,
            'slug' => ($album) ? 'album-'.$album->id : 'posts',
            'userid' => $user->id,
            'url' => true, // Reverted back to true since $image is a file path, not an uploaded file object
        ];

        $image = $this->photoRepository->upload($image, $param);

        if (! $image) {
            return false;
        }

        $this->photoRepository->deleteFilesFromLocal($image); // delete files from local

        if ($image and $album) {
            if (isset($album->default_photo) and empty($album->default_photo)) {
                $album->default_photo = $image;
                $album->save();
            }
        }

        /**
         * Now save user avatar
         */
        $user->avatar = $image;

        $user->save();

        // automatically update this user avatar type
        $this->savePrivacy(['avatar_type' => 1], $user);

        $this->event->dispatch('user.avatar', [$user, $image]);

        // return $user;

        return $image;
    }

    /**
     * Method to update user cover
     *
     * @param  string  $image
     * @param  \App\Models\User  $user
     * @return bool
     */
    public function updateCover($image, $user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;

        $album = $this->photoAlbum->add('cover photos', $user->id, true);
        $slug = 'album-'.$album->id;

        $user->cover = sanitizeText($image);
        $user->save();

        if ($image and $album) {
            if (isset($album->default_photo) and empty($album->default_photo)) {
                $album->default_photo = $image;
                $album->save();
            }
        }

        /**
         * Let help user to keep record of profile covers upload
         */
        $this->photoRepository->add($image, $user->id, $slug);

        $this->event->dispatch('user.update.cover', [$user, $image]);

        return true;
    }

    /**
     * Method to update user profile details
     *
     * @param  array  $val
     * @param  \App\Models\User  $user
     * @return bool
     */
    public function updateProfile($val, $user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;
        $newVal = [];
        foreach ($val as $id => $value) {
            $newVal[$id] = sanitizeText($value);
        }

        // return $newVal;

        $user->profile_details = perfectSerialize($newVal);
        $user->save();
        $this->event->dispatch('user.update.profile', [$user, $val]);

        return true;
    }

    /**
     * @param  string  $current
     * @param  null  $user
     * @return mixed
     */
    public function changeDesignBg($file, $current = '', $user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;
        $image = $this->photoRepository->upload($file, [
            'path' => 'users/'.$user->id.'/design',
            'slug' => 'design',
            'userid' => $user->id,
            'resize' => false,
        ]);

        if (! $image) {
            return false;
        }
        if ($current) {
            $this->photoRepository->delete($current);
        }

        return $image;

    }

    /**
     * @param  null  $user
     * @return bool
     */
    public function saveDesign($val, $user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;

        $expected = [
            'type' => 'profile',
            'theme' => 'default',
            'enable' => false,
            'bg_image' => '',
            'bg_color' => '',
            'bg_position' => '',
            'bg_attachment' => '',
            'bg_repeat' => '',
            'link_color' => '',
            'content_bg_color' => '',
        ];

        /**
         * @var $type,
         */
        extract($val = array_merge($expected, $val));

        $designs = perfectUnserialize($user->design_info);
        $designs[$type] = sanitizeUserInfo($val);
        $user->design_info = perfectSerialize($designs);
        $user->save();

        $this->event->dispatch('user.update.design', [$user, $val]);

        return true;
    }

    /**
     * Change password
     *
     * @param  array  $val
     * @param  \App\Models\User  $user
     * @return bool
     */
    public function changePassword($val, $user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;

        extract($val);

        /*
         * @var $password
         */

        $user->password = \Hash::make($password);

        /**
         * Once user can use his/her email to retrieve password means the email is verified
         * to check if account is activated or not
         */
        $user->activated = 1;
        $user->active = 1;

        $user->save();

        $this->event->dispatch('retrieve-password', [$user]);

        return true;
    }

    /**
     * Save user bio
     *
     * @param  string  $bio
     * @param  \App\Models\User  $user
     * @return bool
     */
    public function saveBio($bio, $user = null, $city = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;
        $user->bio = sanitizeText($bio);
        if ($city) {
            // $user->city = sanitizeText($city);
        }
        $user->save();

        return $user;
    }

    /**
     * Save user api token
     *
     * @param  string  $token
     * @param  \App\Models\User  $user
     * @return bool
     */
    public function saveApiToken($token, $user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;
        $user->api_token = sanitizeText($token);
        $user->save();

        return $user;
    }

    /**
     * get user api token
     *
     * @param  \App\Models\User  $user
     * @return string api_token
     */
    public function getApiToken($user)
    {
        $user = (empty($user)) ? \Auth::user() : $user;

        return $user->api_token;
    }

    /**
     * save user privacy info
     *
     * @param  array  $val
     * @param  \App\Models\User  $user
     * @return bool
     */
    public function savePrivacy($val, $user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;

        $privacy = (empty($user->privacy_info)) ? [] : perfectUnserialize($user->privacy_info);
        $privacy = array_merge($privacy, $val);

        $user->privacy_info = perfectSerialize(sanitizeUserInfo($privacy));
        $user->save();

        $this->event->dispatch('user.save.privacy', [$user]);

        return true;
    }

    /**
     * Finish getstarted
     *
     * @param  \App\Models\User  $user
     * @return \App\Models\User
     */
    public function finishGetstarted($user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;
        $user->fully_started = 1;
        $user->save();

        return $user;

    }

    /**
     * Method to list all users neccessary on admincp
     *
     * @return array
     */
    public function listAll($term = null)
    {
        $users = $this->model
            ->where('active', '!=', 0)
            ->where('banned', '!=', 1)
            ->where('activated', '!=', 0);

        if ($term) {
            $users = $users->where('fullname', 'LIKE', '%'.$term.'%')
                ->orWhere('username', 'LIKE', '%'.$term.'%')
                ->orWhere('email_address', 'LIKE', '%'.$term.'%');
        }

        return $users = $users->orderBy('updated_at', 'desc')->paginate(10);
    }

    public function listAllByCommunity($term = null, $community_id = null, $order = null)
    {
        $users = $this->model
            ->where('active', '!=', 0)
            ->where('banned', '!=', 1)
            ->where('activated', '!=', 0);

        if ($community_id != '') {
            $users = $users->where('admin', '=', 0)->where('community_signup', '=', $community_id);
        }

        if ($term) {
            $users = $users->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', '=', $term);
            });
        }

        if ($order) {
            return $users = $users->orderBy('created_at', 'desc')->paginate(10);
        } else {
            return $users = $users->orderBy('updated_at', 'desc')->paginate(10);
        }
    }

    public function countByCommunity($community_id)
    {
        $users = $this->model
            ->where('active', '!=', 0)
            ->where('banned', '!=', 1)
            ->where('activated', '!=', 0);

        $users = $users->where('admin', '=', 0)->where('community_signup', '=', $community_id);

        return $users = $users->count();
    }

    public function listBanned($term = null)
    {
        $users = $this->model
            ->where('banned', '=', 1);

        if ($term) {
            $users = $users->where('fullname', 'LIKE', '%'.$term.'%')
                ->orWhere('username', 'LIKE', '%'.$term.'%')
                ->orWhere('email_address', 'LIKE', '%'.$term.'%');
        }

        return $users = $users->orderBy('id', 'desc')->paginate(10);
    }

    public function listBannedIds($term = null)
    {
        $cacheKey = 'user_banned_ids';
        
        return $this->cache->remember($cacheKey, 1440, function () {
            $result = $this->model
                ->where('banned', '=', 1)
                ->pluck('id');
            $bannedUsers = is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;

            return $bannedUsers;
        });
    }
    public function listInactiveIds()
    {
        $cacheKey = 'user_inactive_ids';

        return $this->cache->remember($cacheKey, 1440, function () {
            $result = $this->model
                ->where('active', '=', 0)
                ->pluck('id');
            $inactiveUsers = is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;

            return $inactiveUsers;
        });
    }

    public function listMediaContibutor($term = null)
    {
        $users = $this->model
            ->where('role_id', '=', 1);

        if ($term) {
            $users = $users->where('fullname', 'LIKE', '%'.$term.'%')
                ->orWhere('username', 'LIKE', '%'.$term.'%')
                ->orWhere('email_address', 'LIKE', '%'.$term.'%');
        }

        return $users = $users->orderBy('id', 'desc')->paginate(10);
    }

    public function getAll()
    {
        return $this->model->orderBy('id', 'desc')->get();
    }

    public function getAllByAuthType($type)
    {
        return $this->model->where('auth', '=', $type)->orderBy('id', 'desc')->get();
    }

    public function listOnlineUsers($communityId = 0, $categoryId = 0)
    {
        $offset = time() - 1000;
        $userid = \Auth::user()->id;

        if ($communityId == 0) {
            $friends = app('App\\Repositories\\ConnectionRepository')->getFriendsId();
        } else {

            $friends = [];
            $visiting_gift_app_community_id = 0;
            if ($communityId != 0) {
                $current_cm_view = app('App\\Repositories\\CommunityRepository')->getById($communityId);
                if ($current_cm_view and $current_cm_view->gift_app_community == 1) {
                    $visiting_gift_app_community_id = $current_cm_view->id;
                }
            }

            if ($visiting_gift_app_community_id != 0) {
                $friends_contacts = app('App\\Repositories\\GiftsSendRepository')->getMyContactUserIds($visiting_gift_app_community_id, $userid);

                $nonFriendUserIds = app('App\\Repositories\\MessageRepository')->getNonFriendsUserIds($visiting_gift_app_community_id);

                $friends = array_merge($friends_contacts, $nonFriendUserIds);
            } else {
                $friends = $this->getCommunityMembersIds($communityId, $categoryId);
            }
        }

        return $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->whereIn('id', $friends)
            ->whereNotIn('id', $this->mustAvoidUserRepository->get())
            ->where('last_active_time', '>', $offset)
            ->where('online_status', '!=', 0)
            ->where('id', '!=', $userid)
            ->orderBy('fullname', 'asc')
            ->where('online_community_id', '=', $communityId)
            ->get();
    }

    public function listOnlineUsersChat($communityId = 0, $categoryId = 0)
    {
        $offset = time() - 1000;
        $userid = \Auth::user()->id;

        if ($communityId == 0) {
            $friends = app('App\\Repositories\\ConnectionRepository')->getFriendsId();
        } else {

            $friends = [];
            $visiting_gift_app_community_id = 0;
            if ($communityId != 0) {
                $current_cm_view = app('App\\Repositories\\CommunityRepository')->getById($communityId);
                if ($current_cm_view and $current_cm_view->gift_app_community == 1) {
                    $visiting_gift_app_community_id = $current_cm_view->id;
                }
            }

            if ($visiting_gift_app_community_id != 0) {
                $friends_contacts = app('App\\Repositories\\GiftsSendRepository')->getMyContactUserIds($visiting_gift_app_community_id, $userid);

                $nonFriendUserIds = app('App\\Repositories\\MessageRepository')->getNonFriendsUserIds($visiting_gift_app_community_id);

                $friends = array_merge($friends_contacts, $nonFriendUserIds);
            } else {
                $friends = $this->getCommunityMembersIds($communityId, $categoryId);

                $current_cm_view = app('App\\Repositories\\CommunityRepository')->getById($communityId);
                if ($current_cm_view) {
                    array_push($friends, $current_cm_view->user_id);
                }
            }
        }

        return $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->whereIn('id', $friends)
            ->whereNotIn('id', $this->mustAvoidUserRepository->get())
            // ->where('last_active_time', '>', $offset)
            // ->where('online_status', '!=', 0)
            ->where('id', '!=', $userid)
            ->orderBy('fullname', 'asc')
            // ->where('online_community_id','=',$communityId)
            ->get();
    }

    public function listFriendsUsers($term = null, $skipFavourite = null, $communityId = 0, $categoryId = 0, $userid = null, $cmId = 0, $get_type = 'all')
    {
        // $userid = \Auth::user()->id;

        $userid = ($userid) ? $userid : \Auth::user()->id;

        $visiting_gift_app_community_id = 0;
        if ($cmId != 0) {
            $current_cm_view = app('App\\Repositories\\CommunityRepository')->getById($cmId);
            if ($current_cm_view and $current_cm_view->gift_app_community == 1) {
                $visiting_gift_app_community_id = $current_cm_view->id;
            }
        }

		//return $visiting_gift_app_community_id;
			
        if ($visiting_gift_app_community_id != 0) {
            if ($term != '') {
                $friends = app('App\\Repositories\\CommunityVisitorsRepository')->getUidByCommunityId($visiting_gift_app_community_id);
            } else {
                $friends = app('App\\Repositories\\GiftsSendRepository')->getMyContactUserIds($visiting_gift_app_community_id, $userid);
            }

            $favouriteFriends = [0];
            if ($skipFavourite) {
                $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIds('favourite_friend', $userid);
            }
        } else {
		   // return $cmId;
            if ($communityId == 0 || $communityId=="") {
                if ($cmId != 0 and $term != '') {
				    
                    $communityMembers = $this->getCommunityMembersIds($cmId);

                    $primaryUsers = $this->getPrimaryUsersAll($cmId, $communityMembers);
                    $friends = array_merge($communityMembers, $primaryUsers);

                    $favouriteFriends = [0];
                    if ($skipFavourite) {
                        $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIdsOrganization('favourite_friend', $userid, $friends);
                    }
                } else {
				    
                    $friends = app('App\\Repositories\\ConnectionRepository')->getFriendsId($userid, $cmId);

                    $favouriteFriends = [0];
                    if ($skipFavourite) {
                        $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIds('favourite_friend', $userid);
                    }
                }
            } else {
                $friends = $this->getCommunityMembersIds($communityId, $categoryId);

                $favouriteFriends = [0];
                if ($skipFavourite) {
                    $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIdsOrganization('favourite_friend', $userid, $friends);
                }
            }
        }

        if ($term != '' and ($communityId == 0 || $communityId=="") and $cmId == 0) {
            
			$users = $this->model
                ->where('activated', 1)
                ->where('active', 1)
                ->whereNotIn('id', $this->mustAvoidUserRepository->get())
                ->where('id', '!=', $userid);

            if ($term != '') {
                $users = $users->where(function ($users) use ($term) {
                    $users->where('username', 'LIKE', '%'.$term.'%')
                        ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                        ->orWhere('email_address', '=', $term);

                });
            }

            $users = $users->orderBy('fullname', 'asc')
                ->paginate(10);

            return $users;
        } else {
			//return $favouriteFriends;
            $users = $this->model
                ->where('activated', 1)
                ->where('active', 1)
                ->whereIn('id', $friends)
                ->whereNotIn('id', $this->mustAvoidUserRepository->get())
                ->whereNotIn('id', $favouriteFriends)
                ->where('id', '!=', $userid);

            if ($term != '') {
                $users = $users->where(function ($users) use ($term) {
                    $users->where('username', 'LIKE', '%'.$term.'%')
                        ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                        ->orWhere('email_address', '=', $term);

                });
            }

            if ($get_type == 'all') {
                $users = $users->orderBy('fullname', 'asc')->get();
            } else {
                $users = $users->orderBy('fullname', 'asc')->paginate(10);
            }

            return $users;
        }
    }

    public function listFriendsUsersLimit($term, $skipFavourite, $limit, $communityId, $categoryId, $cmIds)
    {
        $userid = \Auth::user()->id;

        $visiting_gift_app_community_id = 0;
        if ($cmIds != 0) {
            $current_cm_view = app('App\\Repositories\\CommunityRepository')->getById($cmIds);
            if ($current_cm_view and $current_cm_view->gift_app_community == 1) {
                $visiting_gift_app_community_id = $current_cm_view->id;
            }
        }

        if ($visiting_gift_app_community_id != 0) {
            $friends = app('App\\Repositories\\GiftsSendRepository')->getMyContactUserIds($visiting_gift_app_community_id, $userid);

            $favouriteFriends = [0];
            if ($skipFavourite) {
                $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIds('favourite_friend', $userid);
            }
        } else {
            if ($communityId == 0) {
                $friends = app('App\\Repositories\\ConnectionRepository')->getFriendsId($userid, $cmIds);

                $favouriteFriends = [0];
                if ($skipFavourite) {
                    $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIds('favourite_friend', $userid);
                }
            } else {

                $friends = $this->getCommunityMembersIds($communityId, $categoryId);

                $favouriteFriends = [0];
                if ($skipFavourite) {
                    $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIdsOrganization('favourite_friend', $userid, $friends);
                }
            }
        }
        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->whereIn('id', $friends)
            ->whereNotIn('id', $this->mustAvoidUserRepository->get())
            ->whereNotIn('id', $favouriteFriends)
            ->where('id', '!=', $userid)
            ->orderBy('fullname', 'asc')
            ->paginate($limit);

        return $users;
    }

    public function listFriendsUsersFavourite($term = null, $communityId = 0, $categoryId = 0, $userid = null)
    {
        // $userid = \Auth::user()->id;

        $userid = ($userid) ? $userid : \Auth::user()->id;

        if ($communityId == 0 || $communityId=="") {
            $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIds('favourite_friend', $userid);
        } else {
            $friends = $this->getCommunityMembersIds($communityId, $categoryId);
            $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIdsOrganization('favourite_friend', $userid, $friends);
        }

        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->whereIn('id', $favouriteFriends)
            ->whereNotIn('id', $this->mustAvoidUserRepository->get())
            ->where('id', '!=', $userid);

        if ($term != '') {
            $users = $users->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', '=', $term);
            });
        }

        $users = $users->orderBy('fullname', 'asc')->get();

        return $users;
    }

    public function countFriendsUsersFavourite($communityId = 0, $categoryId = 0)
    {
        $userid = \Auth::user()->id;

        if ($communityId == 0) {

            $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIds('favourite_friend', $userid);

            $users = $this->model
                ->where('activated', 1)
                ->where('active', 1)
                ->whereIn('id', $favouriteFriends)
                ->whereNotIn('id', $this->mustAvoidUserRepository->get())
                ->where('id', '!=', $userid);
            $users = $users->count();

            return $users;
        } else {

            $communityUsers = $this->getCommunityMembersIds($communityId, $categoryId);

            $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIdsOrganization('favourite_friend', $userid, $communityUsers);

            $users = $this->model
                ->where('activated', 1)
                ->where('active', 1)
                ->whereIn('id', $favouriteFriends)
                ->whereNotIn('id', $this->mustAvoidUserRepository->get())
                ->where('id', '!=', $userid);
            $users = $users->count();

            return $users;
        }
    }

    public function friendsUsersFavouriteLimit($communityId = 0, $categoryId = 0)
    {
        $userid = \Auth::user()->id;

        if ($communityId == 0) {
            $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIds('favourite_friend', $userid);

            $users = $this->model
                ->where('activated', 1)
                ->where('active', 1)
                ->whereIn('id', $favouriteFriends)
                ->whereNotIn('id', $this->mustAvoidUserRepository->get())
                ->where('id', '!=', $userid);

            $users = $users->orderBy('fullname', 'asc')->paginate(10);

            // $users=$users->orderBy('online_status', 'desc')->paginate(10);
            return $users;
        } else {

            $communityUsers = $this->getCommunityMembersIds($communityId, $categoryId);

            $favouriteFriends = app('App\\Repositories\\LikeRepository')->favouriteFriendsIdsOrganization('favourite_friend', $userid, $communityUsers);

            $users = $this->model
                ->where('activated', 1)
                ->where('active', 1)
                ->whereIn('id', $favouriteFriends)
                ->whereNotIn('id', $this->mustAvoidUserRepository->get())
                ->where('id', '!=', $userid);

            $users = $users->orderBy('fullname', 'asc')->paginate(10);

            // $users=$users->orderBy('online_status', 'desc')->paginate(10);
            return $users;
        }
    }

    public function countFriendsOnline($communityId = 0, $categoryId = 0)
    {
        if ($communityId == 0) {
            return count($this->listOnlineUsers());
        } else {
            $offset = time() - 1000;
            $userid = \Auth::user()->id;

            $friends = $communityUsers = $this->getCommunityMembersIds($communityId, $categoryId);

            return $this->model
                ->where('activated', 1)
                ->where('active', 1)
                ->whereIn('id', $friends)
                ->whereNotIn('id', $this->mustAvoidUserRepository->get())
                ->where('last_active_time', '>', $offset)
                ->where('online_status', '!=', 0)
                ->where('id', '!=', $userid)
                ->orderBy('fullname', 'asc')
                ->where('online_community_id', '=', $communityId)
                ->count();
        }
    }

    public function listUnvalidatedUsers($term = null, $community_id = null)
    {
        $users = $this->model->where('activated', '=', 0)->where('deactivated', '=', 0)->where('admin', '=', 0);

        if ($community_id != '') {
            $users = $users->where('community_signup', '=', $community_id);
        }

        if ($term) {
            $users = $users->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', '=', $term);
            });
        }

        $users = $users->orderBy('id', 'desc')->paginate(10);

        return $users;
    }

    public function listDeactivatedUsers($term = null)
    {
        $users = $this->model->where('deactivated', '=', 1)->where('banned', '=', 0)->where('admin', 0);

        if ($term) {
            $users = $users->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', '=', $term);
            });
        }

        $users = $users->orderBy('id', 'desc')->paginate(10);

        return $users;
    }

    public function listUnverifiedUsers($term = null, $community_id = null)
    {
        $users = $this->model
            ->where('active', '=', 1)
            ->where('activated', '=', 1)
            ->where('deactivated', '=', 0)
            ->where('is_email_verified', '=', 0)
            ->where('admin', 0);

        if ($community_id != '') {
            $users = $users->where('community_signup', '=', $community_id);
        }

        if ($term) {
            $users = $users->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', '=', $term);
            });
        }

        $users = $users->orderBy('id', 'desc')->paginate(10);

        return $users;
    }

    public function communityUnverifiedUsersCount($community_id = 0)
    {
        return $users = $this->model
            ->where('active', '=', 1)
            ->where('activated', '=', 1)
            ->where('deactivated', '=', 0)
            ->where('is_email_verified', '=', 0)
            ->where('admin', 0)
            ->where('community_signup', '=', $community_id)
            ->count();
    }

    /**
     * Admincp update a user
     *
     * @param  array  $val
     * @param  \App\Models\User  $user
     * @return bool
     */
    public function adminUpdate($val, $user)
    {
	
        // if (\Auth::user()->id != 1) return false;
        $expected = [
            'fullname' => '',
            'username' => '',
            'email' => '',
            'genre' => '',
            'verified' => '',
            'activated' => '',
            'admin' => 0,
            'quiz_admin' => 0,
            'contest_admin' => 0,
            'contest_id' => 0,
            'image' => '',
            'password' => '',
            'statistics_admin' => 0,
            'program_admin' => 0,
            'community_moderator_admin' => 0,
            'game_manager' => 0,
            'community_signup' => '',
            'event_video_access' => 0,
            'appointment_video_access' => 0,
            'identity_admin' => 0,
            'identity_access' => 0,
            'campaign_access' => 0,
            'ban_campaign' => 0,
            'send_welcome_email' => 0,
            'can_start_meeting' => 2,
            'post_nomination' => 0,
            'campaign_community_create' => 0,
            'post_comment_admin' => 0,
            'max_video_uploadsize_inbytes' => '',
            'shipping_api' => 0,
            'avatar_type' => '',
        ];

        /**
         * @var $fullname
         * @var $username
         * @var $email
         * @var $genre
         * @var $verified
         * @var $activated
         * @var $admin
         * @var $password
         * @var $contest_admin
         * @var $quiz_admin
         * @var $contest_id
         */
        extract($val = array_merge($expected, $val));

		$findByEmail=$this->findByBothEmail($email);
		
        if($findByEmail and $user->id!=$findByEmail->id){
		     $message='This email address already taken by other user';
			 \Session::flash('warning', $message);
			 return $message;
		}
		
		$findByUsername=$this->findByUsernameOnly($username);
		
		if($findByUsername and $user->username!=$findByUsername->username){
		     $message='This username already taken by other user';
			 \Session::flash('warning', $message);
			 return $message;
		}

        if (request()->hasFile('image')) {

            $fileMaxSize = config('max-upload-files');
            $mainFile = request()->file('image');
            $fileExt = $mainFile->getClientOriginalExtension();

            if ($mainFile->getSize() > $fileMaxSize or ! in_array(strtolower($fileExt), ['jpg', 'gif', 'png', 'jpeg'])) {
                return false;
            }

            $filePath = 'uploads/contest/judges/'.$contest_id.'/';

            // ensure the folder exists

            $CDNRepository = app('App\\Repositories\\CDNRepository');

            $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);
            $fileName = md5($mainFile->getClientOriginalName().time()).'.'.$fileExt;
            $image = $filePath.$fileName;

            $file_path_name = $mainFile->getClientOriginalName();
            $mainFile->move(public_path().'/'.$filePath, $fileName);

            $newFileName = $CDNRepository->upload(public_path().'/'.$image, $image);
            // if ($newFileName != $image) {
            // that means file has been successfully uploaded to a CDN Server so
            $CDNRepository->deleteThisFile(public_path().'/'.$image);
            $image = $newFileName;
            // }
        }

        $this->savePrivacy(['avatar_type' => $avatar_type], $user);

        $user->email_address = $email;
        $user->fullname = sanitizeText($fullname, 100);
        $user->username = sanitizeText($username);
        $user->genre = $genre;
        $user->verified = $verified;
        $user->activated = $activated;
        $user->contest_admin = $contest_admin;
        $user->quiz_admin = $quiz_admin;
        $user->contest_id = $contest_id;
        $user->contest_admin_photo = $image;
        if ($password) {
            $user->password = \Hash::make($password);
        }

        if ($activated) {
            $user->active = 1;
			$user->activated = 1;
            $this->mustAvoidUserRepository->remove($user->id);
        }else{
			$user->active = 0;
			$user->activated = 0;
		}

            // Ensure inactive-id cache is refreshed immediately.
            try {
                \Cache::forget('user_inactive_ids');
            } catch (\Throwable $e) {
            }
		
        $user->admin = $admin;
        $user->statistics_admin = $statistics_admin;
        $user->program_admin = $program_admin;
        $user->community_moderator_admin = $community_moderator_admin;
        $user->game_manager = $game_manager;

        if ($community_signup != '') {
            if ($user->primary_community) {
                if ($user->primary_community == $user->primary_community_favourite) {
                    $user->primary_community_favourite = $community_signup;
                }
                $user->primary_community = $community_signup;
            } else {
                $user->external_community = $community_signup;
                $user->community_signup = $community_signup;
            }
        }

        $user->event_video_access = $event_video_access;
        $user->appointment_video_access = $appointment_video_access;
        $user->identity_admin = $identity_admin;
        $user->identity_access = $identity_access;
        $user->campaign_access = $campaign_access;
        $user->ban_campaign = $ban_campaign;
        $user->post_nomination = $post_nomination;
        $user->campaign_community_create = $campaign_community_create;
        $user->post_comment_admin = $post_comment_admin;
        $user->max_video_uploadsize_inbytes = $max_video_uploadsize_inbytes;

        // Only super admin can toggle shipping API access
        if (\Auth::check() && (int) \Auth::user()->id === 1) {
            $user->shipping_api = (int) $shipping_api;
        }
        $user->save();

        // Ensure inactive-id cache is refreshed immediately.
        try {
            \Cache::forget('user_inactive_ids');
        } catch (\Throwable $e) {
        }

        $this->updateCRMUser($user->id);

        if ($send_welcome_email == 1) {
            $this->activate([], $user);
        }

        if ($user->admin == 0) {

            $roleId = $can_start_meeting;

            $hasRole = \DB::select("SELECT * FROM id_immodel_has_roles WHERE model_type='App\\\\Models\\\\User' AND model_id='".$user->id."' ");
            if (count($hasRole) > 0) {
                \DB::select("Update id_immodel_has_roles set role_id='".$roleId."' WHERE model_type='App\\\\Models\\\\User' AND model_id='".$user->id."' ");
            } else {
                $date = date('Y-m-d H:i:s');
                $modalType = 'App\\\\Models\\\\User';

                \DB::insert('insert into id_immodel_has_roles (role_id,model_type, 	model_id,created_at,updated_at)'
                ." values ('"
                .$roleId."',
				'".$modalType."',
				'".$user->id."',
				'".$date."',
				'".$date."')");
            }
        }

        //return 'User information saved successfully';
		 $message='User information saved successfully';
		 \Session::flash('success', $message);
		 return $message;
        //return $user;
    }

    public function postNominationUsers()
    {
        $result = $this->model->where('post_nomination', '=', 1)
            ->where('activated', 1)
            ->where('active', 1)
            ->pluck('id');
        return is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;
    }

    public function deactivate($val, $parseUser = null)
    {
        // if (\Auth::user()->id != 1) return false;
        $expected = [
            'userid' => '',
            'permanent' => 0,
        ];

        /**
         * @var $userid
         * @var $permanent
         */
        extract(array_merge($expected, $val));

        $user = (empty($parseUser)) ? \Auth::user() : $parseUser;
        $user->activated = 0;
        $user->active = 0;
        $user->deactivated = 1;
        $user->save();

        // Ensure inactive-id cache is refreshed immediately.
        try {
            \Cache::forget('user_inactive_ids');
        } catch (\Throwable $e) {
        }

        $this->mustAvoidUserRepository->add($user->id);

        if ($permanent) {
            $this->delete($user->id, $user); // sorry we are deleting the user completely
        }

        if (! $parseUser) {
            \Auth::logout();
        }

        return true;
    }

    public function resendActivation($email)
    {
        // if (\Auth::user()->id != 1) return false;
        $user = $this->findByEmail($email);

        if (! $user or $user->activated == 1) {
            return false;
        }
        $this->sendActivation($user);

        return true;
    }

    public function ban($val, $user)
    {
        // if (\Auth::user()->id != 1) return false;
        $expected = [
            'action' => 'ban',
            'message' => '',
        ];

        /**
         * @var $action
         * @var $message
         */
        extract(array_merge($expected, $val));

        if ($action == 'unban') {
            $user->activated = 1;
            $user->active = 1;
            $user->banned = 0;
            $user->deactivated = 0;
            $user->save();

            // Ensure banned-id cache is refreshed immediately.
            try {
                \Cache::forget('user_banned_ids');
            } catch (\Throwable $e) {
            }

            // Ensure inactive-id cache is refreshed immediately.
            try {
                \Cache::forget('user_inactive_ids');
            } catch (\Throwable $e) {
            }

            $this->mustAvoidUserRepository->remove($user->id); // remove from avoided users

            // send a mail to user
            try {
                \Mail::queue('emails.user.unban', [
                    'message' => $message,
                    'site_name' => config('site_title'),
                    'username' => $user->username,
                    'fullname' => $user->fullname,
                    'email_address' => $user->email_address,
                    'profileUrl' => $user->present()->url(),
                ], function ($mail) use ($user) {
                    $mail->to($user->email_address, $user->fullname)
                        ->subject(trans('mail.user-unban', [
                            'name' => $user->username,
                            'site_title' => config('site_title'),
                        ]));
                });
            } catch (\Exception $e) {
            }
        } else {
            $this->deactivate([], $user);
            $user->banned = 1;
            $user->save();

            // Ensure banned-id cache is refreshed immediately.
            try {
                \Cache::forget('user_banned_ids');
            } catch (\Throwable $e) {
            }

            // Ensure inactive-id cache is refreshed immediately.
            try {
                \Cache::forget('user_inactive_ids');
            } catch (\Throwable $e) {
            }

            // send a mail to user
            try {
                \Mail::queue('emails.user.ban', [
                    'message' => $message,
                    'site_name' => config('site_title'),
                    'username' => $user->username,
                    'fullname' => $user->fullname,
                    'email_address' => $user->email_address,
                    'profileUrl' => $user->present()->url(),
                ], function ($mail) use ($user) {
                    $mail->to($user->email_address, $user->fullname)
                        ->subject(trans('mail.user-ban', [
                            'name' => $user->username,
                            'site_title' => config('site_title'),
                        ]));
                });
            } catch (\Exception $e) {
            }
        }
    }

    /**
     * @return bool
     */
    public function delete($userid, $user = null)
    {
        // if (\Auth::user()->id != 1) return false;
        $user = $this->findById($userid);
        // $loggedUser = \Auth::user();

        $loggedUser = (empty($user)) ? \Auth::user() : $user;

        if ($user and $user->admin == 1) {
            return false;
        }

        if ($user and ($loggedUser->id == $userid or $loggedUser->isAdmin())) {

            $email_address = $user->email_address;

            // this is when we call delete this user
            $user->delete();

            foreach ([
                'App\\Repositories\\PostRepository',
                'App\\Repositories\\BlockedUserRepository',
                'App\\Repositories\\CommentRepository',
                'App\\Repositories\\LikeRepository',
                'App\\Repositories\\PhotoRepository',
                'App\\Repositories\\NotificationReceiverRepository',
                'App\\Repositories\\ConnectionRepository',
                'App\\Repositories\\NotificationRepository',
                'App\\Repositories\\CommunityRepository',
                'App\\Repositories\\CommunityMemberRepository',
                'App\\Repositories\\PageRepository',
                'App\\Repositories\\GameRepository',
                'App\\Repositories\\MessageRepository',
                'App\\Repositories\\ReportRepository',
                'App\\Repositories\\MessageConversationRepository',
                'App\\Repositories\\CommunityCategoryMembersRepository',
            ] as $object) {
                app($object)->deleteAllByUser($userid);
            }

            app('App\\Repositories\\EmailRegistrationRepository')->deleteAllByUser($email_address);
            app('App\\Repositories\\CommunityMembersEmailsRepository')->changeStatusByEmail($email_address);

            return true;
        }
    }

    public function total()
    {
        return $this->model->count();
    }

    public function totalOnline()
    {
        // online users totalonline
        return $this->model->where('last_active_time', '>', time() - 1000)->count() + 479;
    }

    public function getOnlineUsers()
    {
        /*$users = $this->model->where('last_active_time', '>', time() - 1000);
        return $users = $users->orderBy('id', 'desc')->paginate(10);*/

        $usersOnline = $this->model->where('last_active_time', '>', time() - 1000);
        $result1 = $usersOnline->orderBy('id', 'desc')->pluck('id');
        $userIdsOnline = is_object($result1) && method_exists($result1, 'toArray') ? $result1->toArray() : $result1;

        $randomUsers = $this->model->where('activated', 1);
        $randomUsers = $this->model->where('active', 1);
        $randomUsers = $this->model->whereNotIn('id', $userIdsOnline);
        $result2 = $randomUsers->orderBy(\DB::raw('rand()'))->take(479)->pluck('id');
        $userIdsRandom = is_object($result2) && method_exists($result2, 'toArray') ? $result2->toArray() : $result2;

        $allIds = array_merge($userIdsOnline, $userIdsRandom);

        return $users = $this->model
            ->whereIn('id', $allIds)
            ->orderBy('last_active_time', 'desc')
            ->paginate(10);
    }

    public function findByUsernameToken($username, $api_token)
    {
        return $this->model->where('username', '=', $username)->where('api_token', '=', $api_token)->first();
    }
	
	public function findByUsernameOnly($username)
    {
        return $this->model->where('username', '=', $username)->first();
    }

    public function get_contest_judges($contest_id)
    {
        return $this->model->where('contest_id', '=', $contest_id)->where('contest_admin', '=', 1)->get();
    }

    public function checkUserAccount($userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        $user = $this->findByIdUsername($userid);

        $status = 1;

        if ($user) {
            $fullname = $user->fullname;
            $username = $user->username;
            $email_address = $user->email_address;
            $genre = $user->genre;
            $country = $user->country;
            $city = $user->city;
            $bio = $user->bio;

            // if($fullname=='' ||  $username=='' || $email_address=='' || $genre=='' || $country=='' || $city=='0' || $city=='' || $bio==''){
            if ($fullname == '' || $username == '' || $email_address == '') {
                // $status = 0; //do not check for account complete
                $status = 1;
            }
        }

        return $status;
    }

    public function checkUserProfile($userid = null)
    {
		//return 0;
		$user=\Auth::user();
		
		$status = 1;
		$hasWouldLiketoCount=count($user->present()->getLikeToLearn());
		$hasWantTocntCount=count($user->present()->getWantToConnect());
		$hasICanOfferCount=count($user->present()->getICanOffer());
		
		if($hasWouldLiketoCount < 3){
			$status = 0;
		}
		
		if($hasWantTocntCount < 3){
			$status = 0;
		}
		
		if($hasICanOfferCount < 3){
			$status = 0;
		}
		
		return $status;
		
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        $fields = $this->customFieldRepository->listAll('profile');

        $status = 1;

        $user = $this->findById($userid);

        if ($user->first_name == '' and $user->fullname == '') {
            $status = 0;
        }

        if ($user->last_name == '') {
            $status = 0;
        }

        return $status;

        $wantToShareOrg = '';
        $wantToAbout = '';
        if ($fields) {
            $user = $this->findById($userid);
            // $isCommunityOwner=$user->present()->isCommunityOwner();
            foreach ($fields as $field) {
                /*if(!$isCommunityOwner || ($isCommunityOwner and $field->name!="Current City Name" and $field->name!="Gender"))
                {
                    $fieldValue=$user->present()->profile($field->id);
                    if($fieldValue==''){
                        $status = 0;
                    }
                }*/

                $fieldValue = $user->present()->profile($field->id);

                if ($field->name == 'You want to share the name of your company or organization? (optional)') {
                    $wantToShareOrg = $fieldValue;
                }

                if ($field->name == 'Brief introduction?') {
                    $wantToAbout = $fieldValue;
                }

                if ($field->name == 'Work organization name' || $field->name == 'Write about your organization') {
                    if ($wantToShareOrg == 'Yes') {
                        if ($fieldValue == '') {
                            $status = 0;
                        }
                    }
                } elseif ($field->name == 'About me') {
                    if ($wantToAbout == 'Yes') {
                        if ($fieldValue == '') {
                            $status = 0;
                        }
                    }
                } else {
                    if ($fieldValue == '') {
                        $status = 0;
                    }
                }
            }
        }

        return $status;
    }

    /**
     * Dedicated method to get user for a profile
     *
     * @param  mixed  $id
     * @return \\App\\User
     */
    public function getProfileUserById($id)
    {

        return $this->model->where('id', '=', $id)
            ->whereNotIn('id', $this->mustAvoidUserRepository->get())
            ->where('activated', 1)
            ->where('active', 1)
            ->first();
    }

    public function totalFromDate()
    {
        return $this->model->where('created_at', '>', '2018-02-02 11:00:00')->count();
    }

    public function getFavouriteCommunity($user)
    {
        $data = $this->customFieldRepository->getByNameType('profile', 'Interested Community');
        if ($data) {
            if ($user) {
                return $user->present()->profile($data->id);
            }
        } else {
            return false;
        }
    }

    public function getSimilarCommunityUsers($userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $user = $this->findById($userid);
        $userCommunity = $this->getFavouriteCommunity($user);

        if (empty($userCommunity)) {
            return false;
        }

        $userCmId = $user->external_community;

        $query = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->where('admin', 0)
            ->where('profile_details', '!=', '')
            ->where('id', '!=', $userid)
            ->where('id', '!=', '')
            ->where('external_community', $userCmId)
            ->whereNotIn('id', $this->mustAvoidUserRepository->get())
            ->orderBy(\DB::raw('rand()'));

        $allUsers = $query->get();

        if ($allUsers) {
            foreach ($allUsers as $usr) {
                $communities = $this->getFavouriteCommunity($usr);
                if ($communities == $userCommunity) {
                    $usrIds[] = $usr->id;
                }
            }

            if (! empty($usrIds)) {
                $usrIds = array_filter($usrIds);
                if (count($usrIds)) {
                    return $usrIds;
                }
            } else {
                return null;
            }
        }
    }

    public function getUsersByCommunity($communityName, $limit = 10)
    {
        $query = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->where('admin', 0)
            ->where('profile_details', '!=', '');

        $allUsers = $query->get();

        if ($allUsers) {
            foreach ($allUsers as $usr) {
                $communities = $this->getFavouriteCommunity($usr);
                if ($communities == $communityName) {
                    $usrIds[] = $usr->id;
                }
            }

            if (! empty($usrIds)) {
                $usrIds = array_filter($usrIds);
                if (count($usrIds)) {
                    $query = $this->model
                        ->where('activated', 1)
                        ->where('active', 1)
                        ->where('admin', 0)
                        ->whereIn('id', $usrIds);

                    // return $query = $query->paginate($limit);
                    return $query = $query->get();
                }
            } else {
                return null;
            }
        }
    }

    public function isCommunityModerator($postUser, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        // $user = $this->findById($userid);
        // $userCommunity = $this->getFavouriteCommunity($user);

        $postUser = $this->findById($postUser);
        $postUserCommunity = $this->getFavouriteCommunity($postUser);

        $isUserModerator = $this->communityModeratorsRepository->isCommunityModerator($userid, $postUserCommunity);

        // if(($userCommunity!='' and $postUserCommunity!='') and ($userCommunity==$postUserCommunity) and ($user->community_moderator==1))
        if ($postUserCommunity != '' and $isUserModerator == 1) {
            return true;
        } else {
            return false;
        }
    }

    public function isCommunityModeratorActive($postUser, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        // $user = $this->findById($userid);
        // $userCommunity = $this->getFavouriteCommunity($user);

        $postUser = $this->findById($postUser);
        $postUserCommunity = $this->getFavouriteCommunity($postUser);

        $isUserModerator = $this->communityModeratorsRepository->isCommunityModeratorActive($userid, $postUserCommunity);

        // if(($userCommunity!='' and $postUserCommunity!='') and ($userCommunity==$postUserCommunity) and ($user->community_moderator==1))
        if ($postUserCommunity != '' and $isUserModerator == 1) {
            return true;
        } else {
            return false;
        }
    }

    public function countModeratorsByCommunity($userid)
    {
        $user = $this->findById($userid);
        $userCommunity = $this->getFavouriteCommunity($user);

        /*$query = $this->model
        ->where('activated', 1)
        ->where('active', 1)
        ->where('admin', 0)
        ->where('profile_details', '!=', '')
        ->where('id', '!=', '')
        ->whereNotIn('id', $this->mustAvoidUserRepository->get());

        $allUsers = $query->get();

        if($userCommunity!=''){
            if($allUsers){
                foreach($allUsers as $usr){
                    $communities =  $this->getFavouriteCommunity($usr);
                    if($communities == $userCommunity){
                        $usrIds[]=$usr->id;
                    }
                }

                if(!empty($usrIds)){
                    return count($usrIds);
                }else{
                    return 0;
                }
            }else{
                return 0;
            }
        }else{
            return 0;
        }*/

        $allusers = $this->communityModeratorsRepository->getModeratorsByCommunity($userCommunity);
        if ($allusers) {
            return $this->findByIds($allusers);
        } else {
            return false;
        }
    }

    public function activeUsersByCommunity($communityName)
    {
        $query = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->where('admin', 0)
            ->where('profile_details', '!=', '');

        $allUsers = $query->get();
        $activeUsers = [];

        if ($allUsers) {
            foreach ($allUsers as $usr) {
                $communities = $this->getFavouriteCommunity($usr);
                if ($communities == $communityName) {
                    $likes = count(app('App\\Repositories\\LikeRepository')->getAllByUserId($usr->id));
                    $comments = count(app('App\\Repositories\\CommentRepository')->getAllByUserId($usr->id));
                    $reposted = count(app('App\\Repositories\\PostRepository')->getAllRepostedByUserId($usr->id));

                    $activities = $likes + $comments + $reposted;
                    $activeUsers[$usr->id] = $activities;
                }
            }
            arsort($activeUsers);

            $usrIds = [];
            $i = 0;
            foreach ($activeUsers as $key => $val) {
                $i++;
                $usrIds[] = $key;
                if ($i == 10) {
                    break;
                }
            }

            return $usrIds;
        }
    }

    public function searchCommunityUsers($communityName, $keyword = null, $limit = 10)
    {
        $query = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->where('admin', 0)
            ->where('profile_details', '!=', '')
            ->where('username', 'LIKE', '%'.$keyword.'%')
            ->orWhere('fullname', 'LIKE', '%'.$keyword.'%')
            ->orWhere('email_address', 'LIKE', '%'.$keyword.'%');

        return $allUsers = $query->get();
    }

    public function findByUsernameEmail($id)
    {
        return $this->model->where('username', '=', $id)->orWhere('email_address', '=', $id)->first();
    }

    public function accountActivate($email, $code)
    {
        $user = $this->model->where('hash', '=', $code)->where('email_address', '=', $email)->first();

        if (! $user) {
            return false;
        }

        $user->activated = 1;
        $user->active = 1;
        $user->save();

        $this->mustAvoidUserRepository->remove($user->id); // remove from avoided users

        return $user;
    }

    public function changeMyPassword($password, $user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;
        $user->password = \Hash::make($password);
        $user->activated = 1;
        $user->save();

        return true;
    }

    public function resetTvLogin($userid)
    {
        $user = $this->findById($userid);
        $user->last_session_time = '';
        $user->last_session = '';
        $user->save();

        return true;
    }

    public function externalCommunityUserAction($value, $communityId, $userId)
    {
        $user = $this->model->where('id', '=', $userId)->first();

        if (! empty($user)) {

            if ($value == 1 and $user->active == 0) {
                $user->active = $value;
                $user->activated = $value;
                $user->save();
            }

            if ($value == 1) {
                $community = app('App\\Repositories\\CommunityRepository')->getById($communityId);

                $urlDomain = config('community-domain.domain-url');
                $scheme = 'https';
                $mainUrl = parse_url(config('app.url'));
                if (isset($mainUrl['host'])) {
                    $urlDomain = $mainUrl['host'];
                    $scheme = $mainUrl['scheme'];
                }

                $cmUrl = $scheme.'://'.$community->slug.'.'.$urlDomain;
                $community_login_url = $cmUrl.'/c/'.$community->id.'/login';
                $community_forgot_link = $cmUrl.'/c/'.$community->id.'/forgotpass';

                $mail_from_email = $community->present()->getFromEmailAddress();

                try {
                    $this->mailer->send('emails.community-activated', [
                        'fullname' => $user->fullname,
                        'email_address' => $user->email_address,
                        'community_title' => $community->title,
                        'community_url' => $cmUrl,
                        'community_login_url' => $community_login_url,
                        'community_forgot_link' => $community_forgot_link,
                    ], function ($mail) use ($user, $community, $mail_from_email) {
                        $mail->to($user->email_address, $user->fullname)
                            ->subject('Your account has been activated successfully')
                            ->from($mail_from_email, $community->title);
                    });
                } catch (\Exception $e) {

                }
            }
        }
    }

    public function addSportUser($val, $countryManager = 0, $gameSubAdmin = 0)
    {
        $credential = [
            'first_name' => '',
            'last_name' => '',
            'fullname' => '',
            'email_address' => '',
            'genre' => '',
            'dob' => '',
            'role_id' => 1,
            'country' => '',
            'role' => '',
            'functional_area' => '',
            'bio' => '',
            'phone_number' => '',
            'tshirt_size' => '',
            'birth_day' => '',
            'birth_month' => '',
            'birth_year' => '',
            'category' => '',
        ];

        extract($credential = array_merge($credential, $val));

        $findUser = $this->findByEmail($email_address);

        if (! empty($findUser)) {
            return false;
        }

        /*$birth_day = "";
        $birth_month = "";
        $birth_year = "";*/

        if (! empty($dob)) {
            $db = explode('-', $dob);
            if (isset($db[0])) {
                $birth_day = $db[0];
            }
            if (isset($db[1])) {
                $birth_month = $db[1];
            }
            if (isset($db[2])) {
                $birth_year = $db[2];
            }
        }

        // $sportsCommunity = $this->getSportsCommunity();
        $sportsCommunity = \Auth::user()->external_community;
        $fullname = $first_name.' '.$last_name;
        $username = $this->generateUsername($first_name.$last_name);
        $password = substr(md5(time()), 0, 8);
        $user = $this->model->newInstance();
        $user->username = sanitizeText($username, 100);
        $user->email_address = $email_address;
        $user->fullname = sanitizeText($fullname, 100);
        $user->genre = sanitizeText($genre);
        $user->country = sanitizeText($country);
        $user->password = \Hash::make($password);
        $user->online_status = 1;
        $user->last_active_time = time();
        $user->birth_day = sanitizeText($birth_day);
        $user->birth_month = sanitizeText($birth_month);
        $user->birth_year = sanitizeText($birth_year);
        $user->role_id = sanitizeText($role_id);
        $user->bio = sanitizeText($bio);
        $user->sport_user = 1;
        $user->active = 1;
        $user->activated = 1;
        $user->fully_started = 1;
        $user->first_name = $first_name;
        $user->last_name = $last_name;
        $user->game_subadmin = $gameSubAdmin;
        $user->country_manager = $countryManager;
        $user->external_community = $sportsCommunity;
        $user->community_signup = $sportsCommunity;
        $user->signup_type = 'add_sport_user';
        $user->phone_number = $phone_number;
		$user->currency="USD";
        $user->save();

        $this->setUserRoleUUID($user);

        // if($gameSubAdmin==0){
        $userData = app('App\\Repositories\\SportsUserDataRepository')->addUserData($user->id, $role, $functional_area, $tshirt_size, $category); // Get and save comunity data
        // }

        if ($sportsCommunity != 0 and ! empty($user)) {
            $community = app('App\\Repositories\\CommunityRepository')->getById($sportsCommunity); // Get community
            if ($community) {
                if ($countryManager == 1) {

                    $mail_from_email = $community->present()->getFromEmailAddress();

                    try {
                        $this->mailer->send('emails.auth.welcome-sport', [
                            'site_name' => $community->title,
                            'username' => $user->username,
                            'first_name' => $user->first_name,
                            'last_name' => $user->last_name,
                            'password' => $password,
                            'email_address' => $user->email_address,
                            'siteName' => $community->title,
                            'country' => ucfirst($user->country),
                            'community_name' => $community->title,
                            'community_url' => $community->present()->url(),
                            'loggedIn_fullname' => \Auth::user()->fullname,
                        ], function ($mail) use ($user, $community, $mail_from_email) {
                            $mail->to($user->email_address, $user->fullname)
                                ->subject('Welcome to '.$community->title)
                                ->from($mail_from_email, $community->title);
                        });
                    } catch (\Exception $e) {

                    }
                }

                if ($gameSubAdmin == 1) {

                    $mail_from_email = $community->present()->getFromEmailAddress();

                    try {
                        $this->mailer->send('emails.auth.welcome-sport-subadmin', [
                            'site_name' => $community->title,
                            'username' => $user->username,
                            'first_name' => $user->first_name,
                            'last_name' => $user->last_name,
                            'password' => $password,
                            'email_address' => $user->email_address,
                            'siteName' => $community->title,
                            'country' => ucfirst($user->country),
                            'community_name' => $community->title,
                            'community_url' => $community->present()->url(),
                            'loggedIn_fullname' => \Auth::user()->fullname,
                        ], function ($mail) use ($user, $community, $mail_from_email) {
                            $mail->to($user->email_address, $user->fullname)
                                ->subject('Welcome to '.$community->title)
                                ->from($mail_from_email, $community->title);
                        });
                    } catch (\Exception $e) {

                    }
                }
            }
        }

        $this->event->dispatch('user.register', [$user, $val]);

        return $user;
    }

    public function generateUsername($name)
    {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '', $name)));

        $data = $this->getByUsername($slug);

        $_newslug = $slug;

        if (! is_null($data) > 0) {
            $n = 1;
            $max_index = 9999;
            while ($n < $max_index) { // just to be safe
                $_newslug = $slug.$n;
                $findnewslug = $this->getByUsername($_newslug);
                if (! is_null($findnewslug) == 0) {
                    break;
                }
                $n++;
            }
        }

        return $_newslug;
    }

    public function getByUsername($username)
    {
        return $this->model->where('username', '=', $username)->first();
    }

    /**
     * Method to list all country managers
     *
     * @return array
     */
    public function listAllCountryManagers($term = null)
    {
        $users = $this->model
            ->where('active', '!=', 0)
            ->where('banned', '!=', 1)
            ->where('country_manager', '!=', 0)
            ->where('activated', '!=', 0);

        if ($term) {
            $users = $users->where('fullname', 'LIKE', '%'.$term.'%')
                ->orWhere('username', 'LIKE', '%'.$term.'%')
                ->orWhere('email_address', 'LIKE', '%'.$term.'%');
        }

        return $users = $users->orderBy('id', 'desc')->paginate(10);
    }

    // public function countryManagerUpdate($val, $user)
    public function sportUserUpdate($val, $user, $sportSubAdmin = 0)
    {
        $credential = [
            'first_name' => '',
            'last_name' => '',
            'email_address' => '',
            'genre' => '',
            'dob' => '',
            'country' => '',
            'role' => '',
            'functional_area' => '',
            'bio' => '',
            'phone_number' => '',
            'tshirt_size' => '',
            'category' => '',
        ];

        extract($credential = array_merge($credential, $val));

        $db = explode('-', $dob);

        $findUser = $this->findByEmail($email_address);

        if (! empty($findUser) and $findUser->id != $user->id) {
            return false;
        }

        $birth_day = '';
        $birth_month = '';
        $birth_year = '';

        if (isset($db[0])) {
            $birth_day = $db[0];
        }
        if (isset($db[1])) {
            $birth_month = $db[1];
        }
        if (isset($db[2])) {
            $birth_year = $db[2];
        }

        $fullname = $first_name.' '.$last_name;

        $user->email_address = $email_address;
        $user->fullname = sanitizeText($fullname, 100);
        $user->genre = sanitizeText($genre);
        $user->country = sanitizeText($country);
        $user->birth_day = sanitizeText($birth_day);
        $user->birth_month = sanitizeText($birth_month);
        $user->birth_year = sanitizeText($birth_year);
        $user->bio = sanitizeText($bio);
        $user->first_name = $first_name;
        $user->last_name = $last_name;
        $user->phone_number = $phone_number;
        $user->save();

        if ($sportSubAdmin == 0) {
            $userData = app('App\\Repositories\\SportsUserDataRepository')->addUserData($user->id, $role, $functional_area, $tshirt_size, $category);
        }
    }

    public function getSportsCommunity()
    {
        $gameManager = $this->model->where('game_manager', 1)->where('external_community', '!=', 0)->first();
        if ($gameManager) {
            return $gameManager->external_community;
        } else {
            return 0;
        }
    }

    /**
     * Method to list all team members
     *
     * @return array
     */
    public function listAllTeamMembers($term = null)
    {
        $users = $this->model
            ->where('active', '!=', 0)
            ->where('banned', '!=', 1)
            ->where('sport_user', 1)
            /* ->where('country', \Auth::user()->country) */
            ->where('country_manager', '!=', 1)
            ->where('activated', '!=', 0);

        if (\Auth::user()->country_manager == 1) {
            $users = $users->where('country', \Auth::user()->country);
        }

        if ($term) {
            $users = $users->where('fullname', 'LIKE', '%'.$term.'%')
                ->orWhere('username', 'LIKE', '%'.$term.'%')
                ->orWhere('email_address', 'LIKE', '%'.$term.'%');
        }

        return $users = $users->orderBy('id', 'desc')->paginate(10);
    }

    public function listAllParticipants($term = null, $country = null, $role = null, $functional_area = null, $venue = null, $venueTwo = null, $ceremony = null, $zone = null, $zoneTwo = null, $transport = null, $dining = null, $category = null, $getType = null)
    {
        $users = $this->model
            ->where('active', '!=', 0)
            ->where('banned', '!=', 1)
            ->where('sport_user', 1)
            // ->where('country_manager', 0)
            /* ->where('game_subadmin', '!=', 1) */
            ->where('activated', '!=', 0);

        if ($country != '' and $term == '') {
            $users = $users->where('country', 'LIKE', '%'.$country.'%');
        }

        if ($term != '' and $country == '') {

            $users = $users->where(function ($users) use ($term) {
                $users = $users->where('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('last_name', 'LIKE', '%'.$term.'%')
                    ->orWhere('first_name', 'LIKE', '%'.$term.'%')
                    ->orWhere('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', 'LIKE', '%'.$term.'%');
            });
        }

        if ($country != '' and $term != '') {
            $users = $users->where(function ($users) use ($term) {
                $users->where('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', 'LIKE', '%'.$term.'%');
            })->where(function ($users) use ($country) {
                $users = $users->where('country', 'LIKE', '%'.$country.'%');
            });
        }

        if ($role != '' || $functional_area != '' || $venue != '' || $venueTwo != '' || $ceremony != '' || $zone != '' || $zoneTwo != '' || $transport != '' || $dining != '' || $category != '') {
            $zoneUsers = app('App\\Repositories\\SportsUserDataRepository')->getByData($role, $functional_area, $venue, $venueTwo, $ceremony, $zone, $zoneTwo, $transport, $dining, $category);
            $userIds = [];
            if (! empty($zoneUsers)) {
                foreach ($zoneUsers as $usr) {
                    array_push($userIds, $usr->user_id);
                }
            }

            $users = $users->whereIn('id', $userIds);
        }

        if ($getType == '') {
            return $users = $users->orderBy('id', 'desc')->paginate(10);
        } else {
            return $users = $users->orderBy('id', 'desc')->get();
        }
        // return $users = $users->orderBy('id', 'desc')->get(); //To get all records
    }

    // public function countryManagerUpdate($val, $user)
    public function sportUserParticipantUpdate($val, $user)
    {
        $credential = [
            'first_name' => '',
            'last_name' => '',
            'email_address' => '',
            'genre' => '',
            'dob' => '',
            'country' => '',
            'role' => '',
            'functional_area' => '',
            'bio' => '',
            'phone_number' => '',
            'venue1' => '',
            'venue2' => '',
            'ceremony' => '',
            'zone1' => '',
            'zone2' => '',
            'transport' => '',
            'dining' => '',
            'tshirt_size' => '',
            'category' => '',
        ];

        extract($credential = array_merge($credential, $val));

        $db = explode('-', $dob);

        $findUser = $this->findByEmail($email_address);

        if (! empty($findUser) and $findUser->id != $user->id) {
            return false;
        }

        $birth_day = '';
        $birth_month = '';
        $birth_year = '';

        if (isset($db[0])) {
            $birth_day = $db[0];
        }
        if (isset($db[1])) {
            $birth_month = $db[1];
        }
        if (isset($db[2])) {
            $birth_year = $db[2];
        }

        $fullname = $first_name.' '.$last_name;

        $user->email_address = $email_address;
        $user->fullname = sanitizeText($fullname, 100);
        $user->genre = sanitizeText($genre);
        $user->country = sanitizeText($country);
        $user->birth_day = sanitizeText($birth_day);
        $user->birth_month = sanitizeText($birth_month);
        $user->birth_year = sanitizeText($birth_year);
        $user->bio = sanitizeText($bio);
        $user->first_name = $first_name;
        $user->last_name = $last_name;
        $user->phone_number = $phone_number;
        $user->save();

        $userData = app('App\\Repositories\\SportsUserDataRepository')->addUserAllData($user->id, $role, $functional_area, $venue1, $venue2, $ceremony, $zone1, $zone2, $transport, $dining, $tshirt_size, $category);
    }

    public function checkEmailExist($email_address, $user_id)
    {
        $findUser = $this->findByEmail($email_address);

        if (! empty($findUser)) {

            if ($user_id) {
                $user = $this->findById($user_id);

                if (! empty($user) and $findUser->id != $user->id) {
                    return 1;
                } else {
                    return 0;
                }
            } else {
                return 1;
            }
        } else {
            return 0;
        }
    }

    public function listAllSportSubAdmin($term = null)
    {
        $users = $this->model
            ->where('active', '!=', 0)
            ->where('banned', '!=', 1)
            ->where('game_subadmin', '!=', 0)
            ->where('activated', '!=', 0);

        if ($term) {
            $users = $users->where('fullname', 'LIKE', '%'.$term.'%')
                ->orWhere('username', 'LIKE', '%'.$term.'%')
                ->orWhere('email_address', 'LIKE', '%'.$term.'%');
        }

        return $users = $users->orderBy('id', 'desc')->paginate(10);
    }

    public function externalCommunityMembers($community_id, $term = null)
    {
        $users = $this->model
           // ->where('active', '!=', 0)
            ->where('banned', '!=', 1)
            // ->where('activated', '!=', 0)
            // ->where('business_user', '=', 0)
            ->where('business_user', '!=', 1)
            ->where('external_community', $community_id);
        if ($term) {
            $users = $users->where('fullname', 'LIKE', '%'.$term.'%')
                ->orWhere('username', 'LIKE', '%'.$term.'%')
                ->orWhere('email_address', 'LIKE', '%'.$term.'%');
        }

        return $users = $users->orderBy('id', 'desc')->paginate(10);
    }
	
	public function externalCommunityMembersAll($community_id, $term = null)
    {
        $users = $this->model
            ->where('banned', '!=', 1)
            ->where('business_user', '!=', 1)
            ->where('external_community', $community_id);

		return $users = $users->orderBy('id', 'asc')->get();
    }

    public function externalCommunityInactiveMembers($community_id, $term = null)
    {
        $users = $this->model
            ->where('active', '=', 0)
            ->where('business_user', '!=', 1)
            ->where('community_signup', $community_id);
        if ($term) {
            $users = $users->where('fullname', 'LIKE', '%'.$term.'%')
                ->orWhere('username', 'LIKE', '%'.$term.'%')
                ->orWhere('email_address', 'LIKE', '%'.$term.'%');
        }

        return $users = $users->orderBy('id', 'desc')->paginate(50);
    }

    public function deleteCommunityInactiveMembers($community_id, $usr_ids)
    {
        if (! empty($usr_ids)) {
            foreach ($usr_ids as $usr_id) {
                $user = $this->model->where('external_community', $community_id)->where('id', $usr_id)->first();
                if ($user) {
                    $email_address = $user->email;
                    $userid = $user->id;

                    $user->delete();

                    foreach ([
                        'App\\Repositories\\PostRepository',
                        'App\\Repositories\\BlockedUserRepository',
                        'App\\Repositories\\CommentRepository',
                        'App\\Repositories\\LikeRepository',
                        'App\\Repositories\\PhotoRepository',
                        'App\\Repositories\\NotificationReceiverRepository',
                        'App\\Repositories\\ConnectionRepository',
                        'App\\Repositories\\NotificationRepository',
                        'App\\Repositories\\CommunityRepository',
                        'App\\Repositories\\CommunityMemberRepository',
                        'App\\Repositories\\PageRepository',
                        'App\\Repositories\\GameRepository',
                        'App\\Repositories\\MessageRepository',
                        'App\\Repositories\\ReportRepository',
                        'App\\Repositories\\MessageConversationRepository',
                        'App\\Repositories\\CommunityCategoryMembersRepository',
                    ] as $object) {
                        app($object)->deleteAllByUser($userid);
                    }

                    app('App\\Repositories\\EmailRegistrationRepository')->deleteAllByUser($email_address);
                    app('App\\Repositories\\CommunityMembersEmailsRepository')->changeStatusByEmail($email_address);
                }
            }
        }
    }

    public function businessCommunityMembers($community_id, $term = null)
    {
        $users = $this->model
            ->where('active', '!=', 0)
            ->where('banned', '!=', 1)
            ->where('activated', '!=', 0)
            ->where('business_user', '=', 1)
            ->where('external_community', $community_id);
        if ($term) {
            $users = $users->where('fullname', 'LIKE', '%'.$term.'%')
                ->orWhere('username', 'LIKE', '%'.$term.'%')
                ->orWhere('email_address', 'LIKE', '%'.$term.'%');
        }

        return $users = $users->orderBy('id', 'desc')->paginate(10);
    }

    public function totalPlayers()
    {
        $users = app('App\\Repositories\\SportsUserDataRepository')->totalPlayers();
        $userIds = [];
        if (! empty($users)) {
            foreach ($users as $usr) {
                array_push($userIds, $usr->user_id);
            }
        }

        $users = $this->model->whereIn('id', $userIds);

        return $users = $users->count();
    }

    public function totalVolunteers()
    {
        $users = app('App\\Repositories\\SportsUserDataRepository')->totalVolunteers();
        $userIds = [];
        if (! empty($users)) {
            foreach ($users as $usr) {
                array_push($userIds, $usr->user_id);
            }
        }

        $users = $this->model->whereIn('id', $userIds);

        return $users = $users->count();
    }

    public function isSportuser($userid)
    {
        $users = $this->model
            ->where('active', '!=', 0)
            ->where('banned', '!=', 1)
            ->where('sport_user', 1)
            ->where('activated', '!=', 0)
            ->where('id', $userid);

        return $users->first();
    }

    public function applyToJoinCommunity()
    {
        $user = \Auth::user();
        $user->applied_to_join = 1;
        $user->save();
    }

    public function addBusinessUser($val, $communityId = 0)
    {
        $credential = [
            'fullname' => '',
            'email_address' => '',
            'genre' => '',
        ];

        extract($credential = array_merge($credential, $val));

        $findUser = $this->findByEmail($email_address);

        if (! empty($findUser)) {
            return false;
        }

        /*$birth_day = "";
        $birth_month = "";
        $birth_year = "";*/

        // $sportsCommunity = $this->getSportsCommunity();
        $sportsCommunity = \Auth::user()->external_community;
        $username = $this->generateUsername($fullname);
        $password = substr(md5(time()), 0, 8);
        $user = $this->model->newInstance();
        $user->username = sanitizeText($username, 100);
        $user->email_address = $email_address;
        $user->fullname = sanitizeText($fullname, 100);
        $user->password = \Hash::make($password);
        $user->active = 1;
        $user->activated = 1;
        $user->fully_started = 1;
        $user->business_user = 1;
        $user->external_community = $communityId;
        $user->community_signup = $communityId;
        $user->signup_type = 'community_business_import';
		$user->currency="USD";
        $user->save();

        $this->setUserRoleUUID($user);

        return $user;
    }

    public function setFavouriteCm($communityId, $user = null)
    {
        // $user = \Auth::user();
        $user = (empty($user)) ? \Auth::user() : $user;
        $user->favourite_community = $communityId;
        $user->save();
    }

    public function setFavoutriteCmByUserId($communityId, $userid)
    {
        $user = $this->findByIdUsername($userid);
        if ($user and $user->favourite_community == 0) {
            $user->favourite_community = $communityId;
            $user->save();
        }
    }

    public function setPrimaryCmByUserId($communityId, $userid)
    {
        $user = $this->findByIdUsername($userid);
        if ($user) {
            $user->primary_community = $communityId;
            $user->save();
            $this->setFavoutriteCmByUserId($communityId, $userid);
        }
    }

    public function getUsersByIds($mutualFriendsIds, $limit = 10, $term = null)
    {
        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->whereIn('id', $mutualFriendsIds)
            ->whereNotIn('id', $this->mustAvoidUserRepository->get());

        if ($term) {
            $users = $users->where(function ($q) use ($term) {
                $q->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', '=', $term);
            });
        }

        return $users->paginate($limit);
    }

    public function findByLoginKey($login_key)
    {
        return $this->model->where('login_key', '=', $login_key)->first();
    }

    public function updateLoginKey()
    {
        $user = \Auth::user();
        $user->login_key = substr(hash('sha256', mt_rand().microtime()), 0, 30);
        $user->save();
    }

    public function savePushNotificationId($player_Id, $user)
    {
        if ($user->push_notification_id) {
            $notificationKey = explode(',', $user->push_notification_id);

            if (in_array($player_Id, $notificationKey)) {
                $player_Id = $user->push_notification_id;
            } else {
                $player_Id = $user->push_notification_id.','.$player_Id;
            }
        }

        $user->push_notification_id = $player_Id;
        $user->save();

        return $user;
    }

    public function totalCoummunitySignup($community_id)
    {
        // online users totalonline
        return $this->model->where('community_signup', '=', $community_id)->count();
    }

    public function totalOnlineCommunityMembers($community_id)
    {
        $communityMembers = app('App\\Repositories\\CommunityMemberRepository')->getUserIds($community_id);

        return $this->model->where('last_active_time', '>', time() - 1000)->whereIn('id', $communityMembers)->count();
    }

    public function getOnlineUsersByCommunity($community_id)
    {
        $communityMembers = app('App\\Repositories\\CommunityMemberRepository')->getUserIds($community_id);

        $users = $this->model->where('last_active_time', '>', time() - 1000);

        return $users = $users->whereIn('id', $communityMembers)->orderBy('id', 'desc')->paginate(10);
    }

    public function updateLastUrl($currentUrl)
    {
        $protocol = ((! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
        $url = $protocol.$_SERVER['HTTP_HOST'];
        $urlParams = str_replace($url, '', $currentUrl);
        $user = \Auth::user();
        $user->last_url = $urlParams;
        $user->save();
    }

    public function saveMeetingId($user)
    {
        $user->meeting_id = mt_rand(100000, 999999);
        $user->meeting_pass = substr(hash('sha256', mt_rand().microtime()), 0, 6);
        $user->save();

        return $user;
    }

    public function searchMemberForChat($term, $existingMembers, $communityId = 0, $categoryId = 0)
    {
        if ($term) {
            $userid = (empty($userid)) ? \Auth::user()->id : $userid;

            $users = $this->model
                ->where('activated', 1)
                ->where('active', 1)
                ->where('id', '!=', $userid);

            if ($existingMembers) {
                $users = $users->whereNotIn('id', $existingMembers);
            }

            if ($communityId != 0) {
                $communityMembers = $this->getCommunityMembersIds($communityId, $categoryId);
                $users = $users->whereIn('id', $communityMembers);
            }

            $users = $users->where(function ($users) use ($term) {
                $users->where('username', 'LIKE', '%'.$term.'%')
                    ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                    ->orWhere('email_address', '=', $term);
            });

            return $users = $users->paginate(10);
        }
    }

    public function searchByIdTerm($term, $ids)
    {
        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->whereIn('id', $ids);

        $users = $users->where(function ($users) use ($term) {
            $users->where('username', 'LIKE', '%'.$term.'%')
                ->orWhere('fullname', 'LIKE', '%'.$term.'%')
                ->orWhere('email_address', '=', $term);
        });

        $result = $users->pluck('id');
        return is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;
    }

    public function getCommunityMembersIds($community_id = 0, $category_id = 0)
    {

        $community_id = (int) $community_id;
        $category_id = (int) $category_id;

        $cacheKey = 'community_member_ids_' . $community_id . '_' . $category_id;

        if (isset($this->runtimeCommunityMembersIdsCache[$cacheKey])) {
            return $this->runtimeCommunityMembersIdsCache[$cacheKey];
        }

        $membersId = $this->cache->remember($cacheKey, 1, function () use ($community_id, $category_id) {

        $this->communityRepository = app('App\\Repositories\\CommunityRepository');

        $this->communityCategoryRepository = app('App\\Repositories\\CommunityCategoryRepository');

        $this->communityCategoryMembersRepository = app('App\\Repositories\\CommunityCategoryMembersRepository');

        $this->communityMemberRepository = app('App\\Repositories\\CommunityMemberRepository');

            $community = $this->communityRepository->getById($community_id);

            if ($category_id > 0) {
                $category = $this->communityCategoryRepository->get($category_id, $community_id);
                if ($category) {
                    // When a category is selected, list only that category's members.
                    $categoryMembers = $this->communityCategoryMembersRepository->getMembersIds($community_id, (int) $category->id);

                    // Always include community owner as a member of all groups.
                    if ($community && isset($community->user_id)) {
                        $categoryMembers[] = (int) $community->user_id;
                    }

                    return array_values(array_unique($categoryMembers));
                }
            }

            // Community-only view: list community members only (not category members).
            $membersId = $this->communityMemberRepository->getMembersIds($community_id);

            // Fix: Add null safety check for $community
            if ($community && isset($community->user_id)) {
                $membersId[] = $community->user_id;
            }

            return array_values(array_unique($membersId));
        });

        $this->runtimeCommunityMembersIdsCache[$cacheKey] = $membersId;

        return $membersId;
    }

    public function lastOnlineCommunity($communityId)
    {
        $user = \Auth::user();
        $user->online_community_id = $communityId;
        $user->save();
    }

    // if admin deactivate any langauage then check which user has used this lanagauge and changed there langauge with english
    public function makeDefaultForDeactiveLang($var)
    {
        $all = $this->getAll();
        foreach ($all as $eachUser) {
            if (! empty($eachUser->privacy_info)) {
                $privacy = perfectUnserialize($eachUser->privacy_info);
                if (isset($privacy['lang'])) {
                    if ($var == $privacy['lang']) {
                        // make his active langauage english
                        $this->savePrivacy(['lang' => 'en'], $eachUser);
                        \Artisan::call('cache:clear');
                        \Artisan::call('view:clear');
                        \Session::put('lang', 'en');
                        // notification
                    }
                }

            }
        }
    }

    public function deletePushNotificationId($player_Id, $user)
    {
        if ($user->push_notification_id) {
            $notificationKey = explode(',', $user->push_notification_id);

            $allKeys = '';

            foreach ($notificationKey as $key) {

                if ($key != $player_Id) {
                    if ($allKeys == '') {
                        $allKeys = $key;
                    } else {
                        $allKeys = $allKeys.','.$key;
                    }
                }
            }

            $user->push_notification_id = $allKeys;
            $user->save();

            return $user->push_notification_id;
        }
    }

    public function setCommunityToUsers()
    {
        $date = '2021-01-10';

        /*$users=$this->model->where('created_at','>',$date)->where('community_signup', '=', 0)->where('external_community', '=', 0)->get();
        if($users){
            foreach($users as $user){
                $isCommunityOwner=app('App\\Repositories\\CommunityRepository')->getExternalByUserId($user->id);
                if(!$isCommunityOwner){
                    $user->external_community=89;
                    $user->community_signup=89;

                    if($user->favourite_community==0){
                        $user->favourite_community=89;
                    }

                    $user->save();
                }
            }
        }	*/
    }

    public function getCommunitySignUpUsers($community_id)
    {
        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->where('admin', 0);

        $users = $users->where(function ($users) use ($community_id) {
            $users->where('community_signup', '=', $community_id);
        });

        $result = $users->pluck('id');
        return is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;
    }
	
	public function getAllCommunitySignUpUsersIds($community_id)
    {
        $community_id = (int) $community_id;
        if ($community_id <= 0) {
            return [];
        }

        $result = $this->model
            ->newQuery()
            ->where('community_signup', '=', $community_id)
            ->pluck('id');

        $ids = is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : (is_array($result) ? $result : []);
        return array_values(array_filter(array_map('intval', $ids)));
    }

    public function getPrimaryUsers($community_id)
    {
        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->where('admin', 0)
            ->where('profile_details', '!=', '');

        $users = $users->where(function ($users) use ($community_id) {
            $users->where('community_signup', '=', $community_id)
                ->orWhere('primary_community', '=', $community_id);
        });

        $result = $users->pluck('id');
        return is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;
    }

    public function getPrimaryUsersAll($community_id, $usersIds)
    {
        $users = $this->model
            ->where('activated', 1)
            ->where('active', 1)
            ->where('admin', 0)
            ->where('profile_details', '!=', '')
            ->whereNotIn('id', $usersIds);

        $users = $users->where(function ($users) use ($community_id) {
            $users->where('community_signup', '=', $community_id)
                ->orWhere('primary_community', '=', $community_id);
        });

        $result = $users->pluck('id');
        $users = is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;

        return $users;
    }

    public function setPrimaryFavourite($communityId, $user = null)
    {
        // $user = \Auth::user();
        $user = (empty($user)) ? \Auth::user() : $user;
        $user->primary_community_favourite = $communityId;
        $user->save();
    }

    public function saveVisitingCommunity($communityId)
    {
        $user = \Auth::user();
        if (! $user) {
            return;
        }

        $communityId = (int) $communityId;
        $currentVisitingCommunity = (int) ($user->visiting_community ?? 0);

        // Avoid a DB write if nothing changed
        if ($currentVisitingCommunity !== $communityId) {
            $user->visiting_community = $communityId;
            $user->save();
        }

        // Throttle mapping writes/checks: ensure the (user,community) row exists
        // without doing a DB query on every request.
        $cacheKey = 'community_visitors_mapped_u' . $user->id . '_c' . $communityId;
        if (! $this->cache->has($cacheKey)) {
            $this->communityVisitorsRepository->addVisitor($user->id, $communityId);
            $this->cache->put($cacheKey, 1, now()->addHours(12));
        }
    }

    public function updateEmail($user, $email_address)
    {
        $findByEmail = $this->findByEmail($email_address);
        if ($findByEmail and $findByEmail->id != $user->id) {
            return false;
        } else {
            $user->email_address = $email_address;
            $user->save();

            return $user;
        }
    }

    public function appointmentSignup($val, $active = false)
    {
        $credential = [
            'username' => '',
            'email_address' => '',
            'fullname' => '',
            'communityId' => 0,
            'type' => 'appointment',
            'is_active' => 1,
            'self_action' => 0,
            'email_type' => '',
            'signup_type' => '',
            'signup_type_id' => 0,
			'postUrl'=>''
        ];

        extract($credential = array_merge($credential, $val));

        $password = hash('crc32', $username.time());

        $user = $this->model->newInstance();
        $user->username = $this->generateUsername($username);
        $user->password = \Hash::make($password);
        $user->email_address = $email_address;
        $user->fullname = sanitizeText($fullname, 100);
        $user->role_id = 1; // for content admin - media provider
        $user->community_signup = $communityId;
        $user->external_community = $communityId;
        $user->signup_type = $signup_type;
        $user->signup_type_id = $signup_type_id;
        $user->business_user = 2;
		$user->currency="USD";
        $user->login_key = substr(hash('sha256', mt_rand().microtime()), 0, 30);

        if ($is_active == 1) {
            $user->active = 1;
            $user->activated = 1;
            $user->fully_started = 1;
        } else {
            $user->active = 0;
            $user->activated = 0;
            $user->fully_started = 0;
        }
        // $user->save();

        if ($self_action == 1) {
            $userIpAddress = getUserClientIpAddr();
            if ($userIpAddress) {
                $ipInfo = $this->siteVisitorsRepository->getIpInfo($userIpAddress);
                if ($ipInfo and is_array($ipInfo) and $ipInfo['status'] == 'success') {
                    if (isset($ipInfo['country'])) {
                        $user->country = $ipInfo['country'];
                    }

                    if (isset($ipInfo['city'])) {
                        $user->city = $ipInfo['city'];
                    }

                    if (isset($ipInfo['state'])) {
                        $user->state = $ipInfo['state'];
                    }
                }
            }

            $user->ip_address = $userIpAddress;
            $user->save();
        }

        if ($user->active == 0) {
            $hash = md5($user->username.$user->password);
            $user->hash = $hash;
            $user->save();
        }

        $userHash = $user->hash;
        $isActive = $user->active;

        $this->setUserRoleUUID($user);

        if ($communityId > 0) {

            $fileName = 'emails.auth.appointment-signup';
            if ($type == 'autosignup') {
                $fileName = 'emails.auth.auto-signup';
            }

            $community = app('App\\Repositories\\CommunityRepository')->getById($communityId); // Get community

            if ($community) {
                $mail_from_email = $community->present()->getFromEmailAddress();

                if ($email_type == 'document_invite') {
                    $fileName = 'emails.auth.auto-signup-document-invite';

                    try {
                        $this->mailer->send($fileName, [
                            'username' => $user->username,
                            'site_name' => $community->title,
                            'fullname' => $user->fullname,
                            'email_address' => $user->email_address,
                            'password' => $password,
                            'community_id' => $community->id,
                            'userHash' => $userHash,
                            'isActive' => $isActive,
                            'community_acivation_url' => $community->present()->url('accountactivate'),
                        ], function ($mail) use ($user, $community, $mail_from_email) {
                            $mail->to($user->email_address, $user->fullname)
                                ->subject('Welcome to '.$community->title)
                                ->from($mail_from_email, $community->title);
                        });
                    } catch (\Exception $e) {
                        // return $e;
                        // error_log($e);
                    }
                } else {
                    try {
                        $this->mailer->send($fileName, [
                            'username' => $user->username,
                            'site_name' => $community->title,
                            'fullname' => $user->fullname,
                            'email_address' => $user->email_address,
                            'password' => $password,
                            'community_id' => $community->id,
                            'userHash' => $userHash,
                            'isActive' => $isActive,
                            'community_acivation_url' => $community->present()->url('accountactivate'),
                        ], function ($mail) use ($user, $community, $mail_from_email) {
                            $mail->to($user->email_address, $user->fullname)
                                ->subject('Welcome to '.$community->title)
                                ->from($mail_from_email, $community->title);
                        });
                    } catch (\Exception $e) {
                        // return $e;
                        // error_log($e);
                    }
                }
            }
        } else {
            if ($type == 'documentsignup') {
                $fileName = 'emails.auth.document-signup';

                $mainBaseUrl = config('app.url');
                $getUrlHostname = getUrlHostnameScheme($mainBaseUrl);
                $redirectUrlResume = \URL::to('ipdocumentredirectlink');
                $create_doc_url = $getUrlHostname.'/cmownpagebyid?lgkey='.base64_encode($user->id).'&lgurl='.$redirectUrlResume;

                try {
                    $this->mailer->send($fileName, [
                        'username' => $user->username,
                        'site_name' => 'idhubs',
                        'fullname' => $user->fullname,
                        'email_address' => $user->email_address,
                        'password' => $password,
                        'userHash' => $userHash,
                        'isActive' => $isActive,
                        'resume_id' => $signup_type_id,
                        'create_doc_url' => $create_doc_url,
                    ], function ($mail) use ($user) {
                        $mail->to($user->email_address, $user->fullname)
                            ->subject('Welcome to idhubs')
                            ->from(config('site_email'), 'idhubs');
                    });
                } catch (\Exception $e) {
                    // return $e;
                }
            } elseif ($type == 'invoicesignup') {
                $invoiceId = $signup_type_id;
                $fileName = 'emails.auth.invoice-signup';

                $from_user = \Auth::user();

                try {
                    $this->mailer->send($fileName, [
                        'username' => $user->username,
                        'site_name' => 'idhubs',
                        'fullname' => $user->fullname,
                        'email_address' => $user->email_address,
                        'password' => $password,
                        'userHash' => $userHash,
                        'isActive' => $isActive,
                        'invoiceId' => $invoiceId,
                        'from_user_fullname' => $from_user->fullname,
                        'from_user_link' => $from_user->present()->url(),
                        'communityId' => 0,
                        'user_id' => $user->id,
                    ], function ($mail) use ($user) {
                        $mail->to($user->email_address, $user->fullname)
                            ->subject('Welcome to idhubs')
                            ->from(config('site_email'), 'idhubs');
                    });
                } catch (\Exception $e) {
                    // return $e;
                }
			}elseif($type == 'autosignup' and ($signup_type=='like_on_post' || $signup_type == 'like_on_post_comment' || $signup_type == 'like_on_comment_of_comment'  || $signup_type == 'comment_on_post' || $signup_type == 'comment_on_post_comment')) {
					try {
						$this->mailer->send('emails.auth.autosignup-like-comment', [
							'username' => $user->username,
							'site_name' => 'idhubs',
							'fullname' => $user->fullname,
							'email_address' => $user->email_address,
							'password' => $password,
							'userHash' => $userHash,
							'isActive' => $isActive,
							'postUrl'=>$postUrl
						], function ($mail) use ($user) {
							$mail->to($user->email_address, $user->fullname)
								->subject('Welcome to idhubs')
								->from(config('site_email'), 'idhubs');
						});
					} catch (\Exception $e) {
						// return $e;
					}
            } else {
                $fileName = 'emails.auth.ip-appointment-signup';
                if ($type == 'autosignup') {
                    $fileName = 'emails.auth.autosignup';
                }

                try {
                    $this->mailer->send($fileName, [
                        'username' => $user->username,
                        'site_name' => 'idhubs',
                        'fullname' => $user->fullname,
                        'email_address' => $user->email_address,
                        'password' => $password,
                        'userHash' => $userHash,
                        'isActive' => $isActive,
                    ], function ($mail) use ($user) {
                        $mail->to($user->email_address, $user->fullname)
                            ->subject('Welcome to idhubs')
                            ->from(config('site_email'), 'idhubs');
                    });
                } catch (\Exception $e) {
                    // return $e;
                }
            }
        }

        $this->event->dispatch('user.register', [$user, $val]);

        return $user;
    }

    public function makeEmailPrimary()
    {
        $user = \Auth::user();

        if ($user->email_address != '' and $user->secondary_email_address != '') {

            $primary = $user->email_address;
            $secondary = $user->secondary_email_address;

            $user->secondary_email_address = $primary;
            $user->email_address = $secondary;
            $user->save();
        }
    }

    public function findByBothEmail($email)
    {
        return $this->model
            ->where('email_address', '=', $email)
            ->orWhere('secondary_email_address', '=', $email)->first();
    }

    public function sendSecondayEmail($email)
    {
        $user = \Auth::user();
        try {
            $this->mailer->send('emails.user.secondary-email', [
                'username' => $user->username,
                'fullname' => $user->fullname,
                'email_address' => base64_encode($email),
                'user_id' => $user->id,
            ], function ($mail) use ($user, $email) {
                $mail->to($email, $user->fullname)
                    ->subject('Update Secondary Email');
            });
        } catch (\Exception $e) {
            // return $e;
        }

        return 'Verification link sent on '.$email.'. Check your email and click the link in received email.';
    }

    public function updateSecondaryEmail($user_id, $uid, $email)
    {
        return $this->model
            ->where('id', '=', $user_id)
            ->where('id', '=', $uid)
            ->update(['secondary_email_address' => $email]);
    }

    public function getCrmUser($user_id, $community_id)
    {
        $crmUser = \DB::select("SELECT * FROM id_crm_users WHERE idhubs_id='".$user_id."' and community_id='".$community_id."' ");

        return $crmUser;
    }

    public function updateCRMUser($user_id)
    {
        $user = $this->findByIdUsername($user_id);

        \DB::table('crm_users')
            ->where('idhubs_id', $user_id)
            ->update(['first_name' => $user->fullname, 'email' => $user->email_address, 'password' => $user->password]);
    }

    public function getById($id)
    {
        return $this->model->where('id', '=', $id)->first();
    }

    public function setUserRoleUUID($user)
    {
        if ($user) {
            $date = date('Y-m-d H:i:s');
            $roleId = 2;
            $modalType = 'App\\\\Models\\\\User';

            if (empty($user->uuid)) {
                $user->uuid = generateUUID();
                $user->status = 'activated';
                $user->save();
            }

            $hasRole = \DB::select("SELECT * FROM id_immodel_has_roles WHERE model_type='App\\\\Models\\\\User' AND model_id='".$user->id."' ");

            if (count($hasRole) == 0) {
                \DB::insert('insert into id_immodel_has_roles (role_id,model_type, 	model_id,created_at,updated_at)'
                ." values ('"
                .$roleId."',
				'".$modalType."',
				'".$user->id."',
				'".$date."',
				'".$date."')");
            }
        }
    }

    public function canStartMeeting($user_id)
    {
        $hasRole = \DB::select("SELECT * FROM id_immodel_has_roles WHERE model_type='App\\\\Models\\\\User' AND model_id='".$user_id."' ");
        if (count($hasRole) > 0) {
            return $hasRole[0]->role_id;
        }

        return 2;
    }

    public function createZoomMeeting($userid, $appointment, $password)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $zoomDetails = $this->zoomRepository->getByUserId($userid);

        if ($zoomDetails) {
            // require_once app_path().'/library/zoom/vendor/autoload.php';

            $client = new \GuzzleHttp\Client(['base_uri' => 'https://api.zoom.us']);

            $arr_token = $this->zoomRepository->get_access_token($userid);

            if ($arr_token) {

                $arr_token = json_decode($arr_token, true);

                $accessToken = $arr_token['access_token'];

                $new_time = \DateTime::createFromFormat('h:i A', $appointment->master_start_time);
                $time_24 = $new_time->format('H:i:s');
                $start_time = $appointment->appointment_date.'T';
                $start_time_new = $start_time.$time_24;

                try {
                    $response = $client->request('POST', '/v2/users/me/meetings', [
                        'headers' => [
                            'Authorization' => "Bearer $accessToken",
                        ],
                        'json' => [
                            'topic' => $appointment->description,
                            'type' => 2,
                            'start_time' => $start_time_new,
                            'duration' => $appointment->totalmins, // 30 mins
                            'timezone' => $appointment->master_timezone,
                            'settings' => ['use_pmi' => true],
                            'password' => $password,
                        ],
                    ]);
                    $data = json_decode($response->getBody());

                    return $data;

                } catch (\Exception $e) {
                    if ($e->getCode() == 401) {

                        $refresh_token = $this->zoomRepository->get_refersh_token($userid);

                        $client = new \GuzzleHttp\Client(['base_uri' => 'https://zoom.us']);
                        try {
                            $response = $client->request('POST', '/oauth/token', [
                                'headers' => [
                                    'Authorization' => 'Basic '.base64_encode($zoomDetails->client_id.':'.$zoomDetails->client_secret),
                                ],
                                'form_params' => [
                                    'grant_type' => 'refresh_token',
                                    'refresh_token' => $refresh_token,
                                ],
                            ]);

                            if ($response) {
                                $this->zoomRepository->update_access_token($response->getBody(), $userid);

                                return $this->createZoomMeeting($userid, $appointment, $password);
                            }

                        } catch (\Exception $e) {

                        }
                    }
                }
            }
        }
    }

    public function registration($fullname, $first_name, $last_name, $email_address, $phone, $password, $username, $phone_number, $signup_type)
    {
        $birth_day = 0;
        $birth_month = 0;
        $birth_year = 0;
        $genre = '';
        $role_id = 1;

        $user = $this->model->newInstance();
        $user->username = $this->generateUsername($username);
        $user->email_address = $email_address;
        $user->fullname = sanitizeText($fullname, 100);
        $user->first_name = sanitizeText($first_name, 100);
        $user->last_name = sanitizeText($last_name, 100);
        $user->genre = sanitizeText($genre);
        $user->password = \Hash::make($password);
        $user->online_status = 1;
        $user->last_active_time = time();
        $user->birth_day = sanitizeText($birth_day);
        $user->birth_month = sanitizeText($birth_month);
        $user->birth_year = sanitizeText($birth_year);
        $user->role_id = sanitizeText($role_id); // for content admin - media provider
        $user->phone_number = $phone_number;
        $user->signup_type = $signup_type;
		$user->currency="USD";
        $user->active = 1;
        $user->activated = 1;

        $user->fully_started = 1;

        $userIpAddress = getUserClientIpAddr();
        if ($userIpAddress) {
            $ipInfo = $this->siteVisitorsRepository->getIpInfo($userIpAddress);
            if ($ipInfo and is_array($ipInfo) and $ipInfo['status'] == 'success') {
                if (isset($ipInfo['country'])) {
                    $user->country = $ipInfo['country'];
                }

                if (isset($ipInfo['city'])) {
                    $user->city = $ipInfo['city'];
                }

                if (isset($ipInfo['state'])) {
                    $user->state = $ipInfo['state'];
                }
            }
        }
        $user->login_key = substr(hash('sha256', mt_rand().microtime()), 0, 30);
        $user->ip_address = $userIpAddress;
        $user->save();

        $this->setUserRoleUUID($user);

        app('App\\Repositories\\NotificationRepository')->sendCalNotification($user);

        try {
            $this->mailer->send('emails.register.welcome', [
                'username' => $user->username,
                'fullname' => $user->fullname,
                'email_address' => $user->email_address,
                'password' => $password,
                'profileUrl' => $user->present()->url(),
                'site_name' => config('site_title'),
            ], function ($mail) use ($user) {
                $mail->to($user->email_address, $user->fullname)
                    ->subject('Welcome aboard idhubs');
            });
        } catch (\Exception $e) {

        }

        return $user;
    }

    public function getGiftReferralIds($user_id)
    {
        $result = $this->model
            ->where('gift_referred_by', '=', $user_id)
            ->groupBy('id')
            ->pluck('id');
        return is_object($result) && method_exists($result, 'toArray') ? $result->toArray() : $result;
    }

    public function findByIdsLimit($ids, $limit)
    {
        return $this->model->whereIn('id', $ids)->paginate($limit);
    }

    public function emailRegistration($email_address)
    {
        $message = 'Check your email and click on the link to activate and proceed';

        $emailDataExist = $this->emailRegistrationRepository->findByEmail($email_address);
        if ($emailDataExist) {
            if ($emailDataExist) {
                try {
                    $this->mailer->send('emails.register.complete-profile', [
                        'hash_key' => $emailDataExist->hash_key,
                        'email_address' => $email_address,
                    ], function ($mail) use ($email_address) {
                        $mail->to($email_address, $email_address)
                            ->subject('Re-activation Email from idhubs');
                    });
                } catch (\Exception $e) {
                    $message = $e;
                }
            }
        } else {
            $emailData = $this->emailRegistrationRepository->addEmail($email_address);

            if ($emailData) {
                try {
                    $this->mailer->send('emails.register.email-register', [
                        'hash_key' => $emailData->hash_key,
                        'email_address' => $email_address,
                    ], function ($mail) use ($email_address) {
                        $mail->to($email_address, $email_address)
                            ->subject('Activation Email from idhubs');
                    });
                } catch (\Exception $e) {
                    $message = $e;
                }
            }
        }

        return $message;
    }

    public function sendRideCouponCode($user, $communityId)
    {
        if ($user and $user->ride_coupon == '' and $user->ride_coupon_redeemed == 0) {
            $couponCode = generate_random_string(10);

            $user->ride_coupon = $couponCode;
            $user->ride_profile_completed_on = date('Y-m-d');
            $user->save();

            $community = app('App\\Repositories\\CommunityRepository')->getById($communityId); // Get community
            if ($community) {
                $mail_from_email = $community->present()->getFromEmailAddress();
                try {
                    $this->mailer->send('emails.community.ride-coupon-send', [
                        'username' => $user->username,
                        'site_name' => $community->title,
                        'fullname' => $user->fullname,
                        'email_address' => $user->email_address,
                        'community_id' => $community->id,
                        'couponCode' => $couponCode,
                    ], function ($mail) use ($user, $community, $mail_from_email) {
                        $mail->to($user->email_address, $user->fullname)
                            ->subject('Coupon Code Received')
                            ->from($mail_from_email, $community->title);
                    });
                } catch (\Exception $e) {

                }
            }
        }
    }

    public function sendVerificationEmail($user)
    {
        $verification_key = substr(hash('sha256', mt_rand().microtime()), 0, 30);
        $user->email_verification_code = $verification_key;
        $user->save();

        $email = $user->email_address;

        $community = '';
        if ($user->community_signup || $user->primary_community) {
            $community = app('App\\Repositories\\CommunityRepository')->getById($user->community_signup);
            if (! $community) {
                $community = app('App\\Repositories\\CommunityRepository')->getById($user->primary_community);
            }
        }

        if ($community) {
            $mail_from_email = $community->present()->getFromEmailAddress();

            try {
                $this->mailer->send('emails.user.verify-email-community', [
                    'username' => $user->username,
                    'fullname' => $user->fullname,
                    'email_address' => base64_encode($email),
                    'user_id' => $user->id,
                    'community_id' => $community->id,
                    'email_verification_code' => $verification_key,
                    'community_acivation_url' => $community->present()->url('accountverify'),
                ], function ($mail) use ($user, $email, $community, $mail_from_email) {
                    $mail->to($email, $user->fullname)
                        ->subject('Email Verification')
                        ->from($mail_from_email, $community->title);
                });
            } catch (\Exception $e) {
                // return $e;
            }
        } else {
            try {
                $this->mailer->send('emails.user.verify-email', [
                    'username' => $user->username,
                    'fullname' => $user->fullname,
                    'email_address' => base64_encode($email),
                    'user_id' => $user->id,
                    'email_verification_code' => $verification_key,
                    'acivation_url' => \URL::route('user-accountverify'),
                ], function ($mail) use ($user, $email) {
                    $mail->to($email, $user->fullname)
                        ->subject('Email Verification');
                });
            } catch (\Exception $e) {
                // return $e;
            }
        }

        return 'Verification link sent to '.$email.'. Check email, including junk, and click link. Email may take minutes depending on your internet region.';
    }

    public function getPaymentsUsersByIds($user_ids, $limit = 10)
    {
        $userIds = $this->model
            ->whereIn('id', $user_ids)
            ->paginate($limit);

        return $userIds;
    }

    public function sendEmailLoginLink($user, $community)
    {
        $email_login_code = substr(hash('sha256', mt_rand().microtime()), 0, 30);
        $user->email_login_code = $email_login_code;
        $user->save();

        $mail_from_email = $community->present()->getFromEmailAddress();

        try {
            $this->mailer->send('emails.user.community-email-login', [
                'username' => $user->username,
                'fullname' => $user->fullname,
                'email_address' => $user->email_address,
                'user_id' => $user->id,
                'email_login_code' => $email_login_code,
                'communityId' => $community->id,
            ], function ($mail) use ($user, $community, $mail_from_email) {
                $mail->to($user->email_address, $user->fullname)
                    ->subject('Permission to Access the Event')
                    ->from($mail_from_email, $community->title);
            });
        } catch (\Exception $e) {
            // return $e;
        }
    }

    public function sendPaymentAlertEmail($type, $amount, $transaction_id, $from_name, $from_email, $from_url)
    {
        $send_alert_email = config('payment-alert-send-to-email');

        if ($send_alert_email) {
            try {
                $this->mailer->send('emails.payment-alert', [
                    'type' => $type,
                    'amount' => $amount,
                    'transaction_id' => $transaction_id,
                    'from_name' => $from_name,
                    'from_email' => $from_email,
                    'from_url' => $from_url,
                ], function ($mail) use ($send_alert_email) {
                    $mail->to($send_alert_email)
                        ->subject('New Payment Received');
                });
            } catch (\Exception $e) {
                // return $e;
            }
        }
    }
	
	public function saveWeatherLocation($user)
	{
		//if($user->weather_location=="" || $user->weather_location==null){
			
		$visitor_ip = getUserClientIpAddr();
		//$visitor_ip='106.215.176.170';
		$ipInfo = app('App\\Repositories\\SiteVisitorsRepository')->getIpInfo($visitor_ip);

		// Default fallback coordinates for Toronto, Canada
		$visitorsCountry = 'Canada';
		$visitorsCity = 'Toronto';
		$visitorsState = 'Ontario';
		$lat = 43.6532;
		$lon = -79.3832;

		$address_fetched='';
		
		if ($ipInfo and is_array($ipInfo) and $ipInfo['status'] == 'success') {
			// Only update location info if we have coordinates
			if (isset($ipInfo['latitude']) && isset($ipInfo['longitude']) && 
				is_numeric($ipInfo['latitude']) && is_numeric($ipInfo['longitude'])) {
				
				$lat = floatval($ipInfo['latitude']);
				$lon = floatval($ipInfo['longitude']);
				
				// Only update city/state/country if we have valid coordinates
				if (isset($ipInfo['country'])) {
					$visitorsCountry = $ipInfo['country'];
				}

				if (isset($ipInfo['city'])) {
					$visitorsCity = $ipInfo['city'];
				}

				if (isset($ipInfo['state'])) {
					$visitorsState = $ipInfo['state'];
				}
				
				$address_fetched='yes';
			}
			// If no coordinates available, keep Toronto defaults for everything
		}

		// Create weather location data in the format expected by weather widget
		
		//return $address_fetched;
		
		if($address_fetched=='yes'){
			$locationData = [
				'currentLocation' => [
					'lat' => $lat,
					'lon' => $lon
				],
				'selectedLocationName' => $visitorsCity . ', ' . $visitorsState,
				'userCountry' => $visitorsCountry,
				'savedAt' => date('c') // ISO 8601 format
			];
			
			$user->weather_location = json_encode($locationData);
			$user->save();  
			
			return json_encode($locationData);
		}else{
			if($user->weather_location==""){
				$locationData = [
					'currentLocation' => [
						'lat' => $lat,
						'lon' => $lon
					],
					'selectedLocationName' => $visitorsCity . ', ' . $visitorsState,
					'userCountry' => $visitorsCountry,
					'savedAt' => date('c') // ISO 8601 format
				];
				
				$user->weather_location = json_encode($locationData);
				$user->save(); 
				
				return json_encode($locationData);
			}
		}		
		
		return $user->weather_location;	          
	//}
	}
}
