<?php

namespace App\Presenters;

use Laracasts\Presenter\Presenter;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Cache;

class UserPresenter extends Presenter
{

    protected static $avatarCache = [];
    protected static $canShowIdMartCache = [];
    protected static $businessCommunityCache = [];
    protected static $isCommunityMemberCache = [];
    protected static array $ownCommunityCache = [];
    protected static array $ownCommunityIdCache = [];
    /**
     * Simple per-request caches (avoid repeating repository calls during view rendering).
     */
    protected static array $communityByIdCache = [];
    protected static array $communityCategoryByIdCache = [];
    protected static array $postDraftCache = [];

    protected static array $isOnlineCache = [];
    protected static array $isUserOnlineCache = [];

    protected static array $personalProfileCache = [];
    protected static array $likeToLearnCache = [];
    protected static array $wantToConnectCache = [];

    public function privacy($id, $default = '')
    {
        $user = $this->entity;
        if (empty($user->privacy_info)) {
            return $default;
        }

        if (! function_exists('perfectUnserialize')) {
            require base_path().'/functions/functions.php';
        }

        $privacy = perfectUnserialize($this->privacy_info);
        if (empty($privacy)) {
            $user->privacy_info = '';
            $user->save();
        }

        if (isset($privacy[$id])) {
            return $privacy[$id];
        }

        return $default;
    }

    public function canSendMessage($user = null)
    {

        $privacy = $this->privacy('send-message', 'public');
        // if (!\Auth::check()) return false;

        if (! \Auth::check() and ! $user) {
            return false;
        }
        $user = (empty($user)) ? \Auth::user() : $user;

        if (! $user) {
            return false;
        }

        if ($user->id == $this->entity->id) {
            return false;
        }
        $connection = app('App\\Repositories\\ConnectionRepository');

        if ($privacy == 'public') {
            return true;
        } elseif ($privacy == 'friends') {
            // only friends

            if ($user and $connection->areFriends($this->entity->id, $user->id)) {
                return true;
            }

            return false;

        } elseif ($privacy == 'friend-follower') {
            // only friends and followers
            if ($user and $connection->areFriends($this->entity->id, $user->id)) {
                return true;
            }

            // now check for follower
            if ($user and $connection->isFollowing($user->id, $this->entity->id)) {
                return true;
            }

            return false;

        } elseif ($privacy == 'nobody') {
            return false;
        }

        return false;
    }

    public function canViewMyAddress($user = null)
    {
        $privacy = $this->privacy('view-address', 'nobody');

        if (\Auth::check()) {
            $user = (empty($user)) ? \Auth::user() : $user;
            if ($user->id == $this->entity->id) {
                return true;
            }
        }

        $connection = app('App\\Repositories\\ConnectionRepository');

        if ($privacy == 'public') {
            return true;
        } elseif ($privacy == 'nobody') {
            return false;
        } else {
            $connection = app('App\\Repositories\\ConnectionRepository');

            if ($privacy == 'friends') {
                if ($user and $connection->areFriends($this->entity->id, $user->id)) {
                    return true;
                }

                return false;
            } elseif ($privacy == 'friend-follower') {
                if ($user and $connection->areFriends($this->entity->id, $user->id)) {
                    return true;
                }

                // now check for follower
                if ($user and $connection->isFollowing($user->id, $this->entity->id)) {
                    return true;
                }

                return false;
            }
        }

        return false;
    }

    public function canViewMyCity($user = null)
    {
        $privacy = $this->privacy('view-origin-city', 'nobody');

        if (\Auth::check()) {
            $user = (empty($user)) ? \Auth::user() : $user;
            if ($user->id == $this->entity->id) {
                return true;
            }
        }

        $connection = app('App\\Repositories\\ConnectionRepository');

        if ($privacy == 'public') {
            return true;
        } elseif ($privacy == 'nobody') {
            return false;
        } else {
            $connection = app('App\\Repositories\\ConnectionRepository');

            if ($privacy == 'friends') {
                if ($user and $connection->areFriends($this->entity->id, $user->id)) {
                    return true;
                }

                return false;
            } elseif ($privacy == 'friend-follower') {
                if ($user and $connection->areFriends($this->entity->id, $user->id)) {
                    return true;
                }

                // now check for follower
                if ($user and $connection->isFollowing($user->id, $this->entity->id)) {
                    return true;
                }

                return false;
            }
        }

        return false;
    }

    public function canPost($user = null)
    {
        $privacy = $this->privacy('timeline-post', 'nobody');

        if (! \Auth::check() and ! $user) {
            return false;
        }
        $user = (empty($user)) ? \Auth::user() : $user;

        // if (!\Auth::check()) return false;
        if (! $user) {
            return false;
        }

        if ($user->id == $this->entity->id) {
            return true;
        }

        $connection = app('App\\Repositories\\ConnectionRepository');

        if ($privacy == 'public') {
            return true;
        } elseif ($privacy == 'friends') {
            // only friends

            if ($user and $connection->areFriends($this->entity->id, $user->id)) {
                return true;
            }

            return false;

        } elseif ($privacy == 'friend-follower') {
            // only friends and followers
            if ($user and $connection->areFriends($this->entity->id, $user->id)) {
                return true;
            }

            // now check for follower
            if ($user and $connection->isFollowing($user->id, $this->entity->id)) {
                return true;
            }

            return false;

        } elseif ($privacy == 'nobody') {
            return false;
        }

        return false;
    }

    public function postPrivacyValue()
    {
        return $privacy = $this->privacy('post-privacy-default', 2);
    }

    public function postPrivacyName()
    {
        $privacy = $this->privacy('post-privacy-default', 2);
        switch ($privacy) {
            case 1:
                return trans('global.public');
                break;
            case 2:
                return trans('connection.friends');
                break;
            case 3:
                return trans('connection.followers');
                break;
            case 4:
                return trans('connection.friends-followers');
                break;
            case 5:
                return trans('connection.only-me');
                break;
        }
    }

    public function isUserOnline($communityId = 0)
    {
        $communityId = (int) $communityId;
        $entityId = (int) ($this->entity->id ?? 0);
        $cacheKey = $entityId . ':' . $communityId;
        if ($entityId > 0 && array_key_exists($cacheKey, self::$isUserOnlineCache)) {
            return self::$isUserOnlineCache[$cacheKey];
        }

        $offset = time() - 1000;
        $online = ($this->entity->last_active_time > $offset);

        $result = 0;

        if (! $online) {
            if ($this->entity->online_status == 1) {
                // Avoid hammering DB with repeated "mark offline" updates.
                $offlineMarkKey = 'user:'.$this->entity->id.':offline_marked';
                if (Cache::add($offlineMarkKey, 1, 300)) {
                    // Only update status/privacy for self; for other users this write is
                    // both expensive and can incorrectly affect the current viewer's privacy.
                    if (\Auth::check() && (int) \Auth::user()->id === $entityId) {
                        $this->entity->updateStatus(0);
                    }
                }
            }
            $result = 0;
        } else {
            if (\Auth::check() && (int) \Auth::user()->id === $entityId) {
                $result = 1;
            } elseif ((int) $this->entity->online_community_id === $communityId) {
                $result = 1;
            } else {
                $result = 0;
            }
        }

        if ($entityId > 0) {
            self::$isUserOnlineCache[$cacheKey] = $result;
        }

        return $result;
    }

    public function isOnline($communityId = 0, $categoryId = 0, $app_status = null)
    {
        $communityId = (int) $communityId;
        $categoryId = (int) $categoryId;
        $entityId = (int) ($this->entity->id ?? 0);
        $cacheKey = $entityId . ':' . $communityId . ':' . $categoryId . ':' . (string) $app_status;
        if ($entityId > 0 && array_key_exists($cacheKey, self::$isOnlineCache)) {
            return self::$isOnlineCache[$cacheKey];
        }

        $offset = time() - 1000;
        $online = ($this->entity->last_active_time > $offset);

        if ($communityId == 0 and \Request::segment(1) == 'c') {
            $communityId = \Request::segment(2);
            if (\Request::segment(3) == 'category') {
                $categoryId = \Request::segment(4);
            }
        }

        $result = 0;

        if (! $online) {
            if ($this->entity->online_status == 1) {
                // Avoid hammering DB with repeated "mark offline" updates.
                $offlineMarkKey = 'user:'.$this->entity->id.':offline_marked';
                if (Cache::add($offlineMarkKey, 1, 300)) {
                    if (\Auth::check() && (int) \Auth::user()->id === $entityId) {
                        $this->entity->updateStatus(0);
                    }
                }
            }
            $result = 0;
        } else {
            $onlineStatus = (int) $this->entity->online_status;
            if ($onlineStatus !== 1) {
                $result = $onlineStatus;
            } else {
                if (\Auth::check()) {
                    if ((int) \Auth::user()->id === $entityId) {
                        $result = 1;
                    } elseif ((int) $this->entity->online_community_id === $communityId) {
                        $result = 1;
                    } else {
                        $result = 0;
                    }
                } elseif ($app_status === 'app_status' && (int) $this->entity->online_community_id === $communityId) {
                    $result = 1;
                } else {
                    $result = 0;
                }
            }
        }

        if ($entityId > 0) {
            self::$isOnlineCache[$cacheKey] = $result;
        }

        return $result;
    }

    /**
     * Format user fullname correctly
     *
     * @return string
     */
    public function fullName()
    {
        $name = (string) $this->entity->fullname;

        return ucwords($name);
    }

    /**
     * Format username
     *
     * @return string
     */
    public function atName()
    {
        return '@'.$this->username;
    }

    public function joinedOn()
    {
        // return str_replace(' ', 'T', $this->entity->created_at).'+05:30';

        /*$timeSet="-05:00";
        if(\Session::has('communitTimeZOne')){
             $communitTimeZOne=\Session::get('communitTimeZOne');

             $timeSet=getTimeAgo($communitTimeZOne);
        }
        return str_replace(' ', 'T', $this->entity->created_at).$timeSet;*/

        return str_replace(' ', 'T', $this->entity->created_at).'-08:00';
    }

    public function lastLoginOn()
    {
        // return str_replace(' ', 'T', $this->entity->updated_at).'+05:30';
        /*$timeSet="-05:00";
        if(\Session::has('communitTimeZOne')){
            $communitTimeZOne=\Session::get('communitTimeZOne');

            $timeSet=getTimeAgo($communitTimeZOne);
        }
        return str_replace(' ', 'T', $this->entity->updated_at).$timeSet;*/
        return str_replace(' ', 'T', $this->entity->updated_at).'-08:00';
    }

    /**
     * Privacy setting for profile page
     */
    public function canViewMe($user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;

        if ($user and $this->entity->id == $user->id) {
            return true;
        } // viewer is the owner

        // for admin to be able to view private profile
        if (\Auth::check() and \Auth::user()->isAdmin()) {
            return true;
        }

        $privacy = $this->privacy('view-profile', 'public');

        if ($privacy == 'public') {
            return true;
        } elseif ($privacy == 'nobody') {
            return false;
        } else {
            $connection = app('App\\Repositories\\ConnectionRepository');

            if ($privacy == 'friends') {
                if ($user and $connection->areFriends($this->entity->id, $user->id)) {
                    return true;
                }

                return false;
            } elseif ($privacy == 'friend-follower') {
                if ($user and $connection->areFriends($this->entity->id, $user->id)) {
                    return true;
                }

                // now check for follower
                if ($user and $connection->isFollowing($user->id, $this->entity->id)) {
                    return true;
                }

                return false;
            }
        }
    }

    public function canSeeBirth()
    {
        //        if (\Auth::check() and $this->entity->id == \Auth::user()->id) return true; //viewer is the owner

        // for admin to be able to view private profile
        //        if (\Auth::check() and \Auth::user()->isAdmin()) return true;

        $privacy = $this->privacy('view-birth', 'public');

        if ($privacy == 'public') {
            return true;
        } elseif ($privacy == 'nobody') {
            return false;
        } else {
            $connection = app('App\\Repositories\\ConnectionRepository');

            if ($privacy == 'friends') {
                if (\Auth::check() and $connection->areFriends($this->entity->id, \Auth::user()->id)) {
                    return true;
                }

                return false;
            } elseif ($privacy == 'friend-follower') {
                if (\Auth::check() and $connection->areFriends($this->entity->id, \Auth::user()->id)) {
                    return true;
                }

                // now check for follower
                if (\Auth::check() and $connection->isFollowing(\Auth::user()->id, $this->entity->id)) {
                    return true;
                }

                return false;
            }
        }
    }

    /**
     * Method to get user profile details value
     *
     * @param  string  $name
     * @return mixed
     */
    public function profile($name = null)
    {
        $details = (! empty($this->entity->profile_details)) ? perfectUnserialize($this->entity->profile_details) : [];

        if (empty($name)) {
            return $details;
        }

        if (isset($details[$name])) {
            return $details[$name];
        }

        return null;
    }

    public function fields()
    {
        return app('App\\Repositories\\CustomFieldRepository')->listAll('profile');
    }

    /**
     * User avatar
     *
     * @param  int  $size
     * @return string
     */
    public function getAvatar($size = 100, $default_image = 0)
    {
        $avatar = $this->avatar;
        $avatarType = $this->privacy('avatar_type', 0);
        $realPathToAvatar = base_path(str_replace('%d', 200, $avatar));
        $amazonPath = \Image::url($avatar, $size);

        $entityId = (int) ($this->entity->id ?? 0);
        $cacheKey = $entityId . ':' . (int) $size . ':' . (int) $default_image;
        if ($entityId > 0 && array_key_exists($cacheKey, self::$avatarCache)) {
            return self::$avatarCache[$cacheKey];
        }

        if ($default_image == 1) {
            $result = $this->defaultAvatar($size);
            if ($entityId > 0) {
                self::$avatarCache[$cacheKey] = $result;
            }

            return $result;
        }

        if (! empty($amazonPath) and $avatarType != 0) {
            $result = $amazonPath;
            if ($entityId > 0) {
                self::$avatarCache[$cacheKey] = $result;
            }

            return $result;
        }

        if ($avatarType == 0
            or empty($avatar)
            or (! preg_match('#http:\/\/|https:\/\/|amazon|cdnuploads#', $realPathToAvatar) and ! file_exists($realPathToAvatar))) {
            $result = $this->defaultAvatar($size);
            if ($entityId > 0) {
                self::$avatarCache[$cacheKey] = $result;
            }

            return $result;
        }

        $result = \Image::url($avatar, $size);
        if ($entityId > 0) {
            self::$avatarCache[$cacheKey] = $result;
        }

        return $result;
    }

    /**
     * Get Default avatar for us
     */
    protected function defaultAvatar($size = 100)
    {
        $firstLetter = strtolower(substr($this->entity->fullname, 0, 1));

        if (in_array($firstLetter, [
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
        ])) {
            return \URL::to(\Theme::asset()->img('theme/images/avatar/'.$firstLetter.'/'.$size.'.png'));
        } else {
            return \URL::to(\Theme::asset()->img('theme/images/avatar/default/'.$size.'.png'));
        }

    }

    /**
     * Get user cover image
     */
    public function coverImage()
    {
        return \Image::url($this->entity->cover);
    }

    /**
     * @param  string  $type
     * @param  string  $default
     * @return null
     */
    public function design($key, $type = 'profile', $default = '')
    {
        $design = (! empty($this->entity->design_info)) ? perfectUnserialize($this->entity->design_info) : [];
        if (! $design) {
            return null;
        }
        if (isset($design[$type])) {
            $userDesign = $design[$type];

            return (isset($userDesign[$key])) ? $userDesign[$key] : null;
        }

        return null;
    }

    public function readDesign($type = 'profile')
    {
        $design = ['enable' => false];
        $userDesign = (! empty($this->entity->design_info)) ? perfectUnserialize($this->entity->design_info) : [];
        $userDesign = (! $userDesign) ? [] : $userDesign;
        $design = array_merge($design, $userDesign);

        if (isset($design[$type])) {
            $design = $design[$type];
        }

        /**
         * @var $enable
         * @var $theme
         */
        extract($design);

        if ($enable) {
            $design['bg_image'] = \Image::url($design['bg_image']);
        }

        if (! $enable) {

            // $themeDesign = \Theme::option()->get('design-themes');
            // $themeDesign = (empty($theme) or !isset($themeDesign[$theme])) ? $themeDesign['default'] : $themeDesign[$theme];

            /**
             * Reset the design to this selected one
             */
            /*$design['bg_image'] = $themeDesign['background-image'];
            $design['bg_color'] = $themeDesign['background-color'];
            $design['bg_attachment'] = $themeDesign['background-attachment'];
            $design['bg_position'] = $themeDesign['background-position'];
            $design['bg_repeat'] = $themeDesign['background-repeat'];
            $design['link_color'] = $themeDesign['link-color'];
            $design['content_bg_color'] = $themeDesign['page-content-bg-color'];*/

            if (isset($theme)) {
                if (empty($theme)) {
                    // $design['bg_image'] = "themes/frontend/default/assets/images/design/bg-images/default.png";
                    $design['bg_image'] = '';
                } else {
                    $design['bg_image'] = 'themes/frontend/default/images/design/bg-images/'.$theme;
                }
                $design['bg_color'] = '#E8E7E7';
                $design['bg_attachment'] = 'fixed';
                $design['bg_position'] = 'center';
                $design['bg_repeat'] = 'no-repeat';
                $design['bg_size'] = 'cover';
                $design['link_color'] = '#6C7A89';
                $design['content_bg_color'] = 'rgba(255, 255, 255, 0.3)';
            } else {
                $themeDesign = \Theme::option()->get('design-themes');

                if (empty($themeDesign)) {
                    $design['bg_image'] = '';
                    $design['bg_color'] = '#E8E7E7';
                    $design['bg_attachment'] = 'fixed';
                    $design['bg_position'] = 'center';
                    $design['bg_repeat'] = 'no-repeat';
                    $design['bg_size'] = 'cover';
                    $design['link_color'] = '#6C7A89';
                    $design['content_bg_color'] = 'rgba(255, 255, 255, 0.3)';
                } else {
                    $themeDesign = (empty($theme) or ! isset($themeDesign[$theme])) ? $themeDesign['default'] : $themeDesign[$theme];
                    $design['bg_image'] = $themeDesign['background-image'];
                    $design['bg_color'] = $themeDesign['background-color'];
                    $design['bg_attachment'] = $themeDesign['background-attachment'];
                    $design['bg_position'] = $themeDesign['background-position'];
                    $design['bg_repeat'] = $themeDesign['background-repeat'];
                    $design['link_color'] = $themeDesign['link-color'];
                    $design['content_bg_color'] = $themeDesign['page-content-bg-color'];
                    $design['bg_size'] = 'cover';
                }
            }
        }

        return $design;
    }

    /**
     * check if user is an admin
     *
     * @return bool
     */
    public function isAdmin()
    {
        $group = $this->group;

        if (strtolower($group->category) == 'admin') {
            return true;
        }

        return false;
    }

    /**
     * Check if a user is a moderator
     *
     * @return bool
     */
    public function isModerator()
    {
        if ($this->group->category == 'moderator') {
            return true;
        }

        return false;
    }

    public function url($segment = null)
    {
        /*if(\Request::segment(1)=="c"){
            $communityId=\Request::segment(2);

            $community=app('App\\Repositories\\CommunityRepository')->getById($communityId);

            if($community and ($community->community_access!=1 || $community->owner_community_access!=1)){
                return $url=$community->present()->url('userprofile/'.$this->entity->username);
            }
        }*/

        /*$hasResumeCreated=$this->entity->present()->isResumeCreated($this->entity->id);
        if($hasResumeCreated){
            $url=$this->entity->present()->resumeLink($this->entity->id);
            return $url;
        }else{
            $url = \URL::route('profile', ['id' => (config('profile-url-format') == 1) ? $this->entity->id : $this->entity->username]).(($segment) ? '/'.$segment : null);
            return $url;
        }*/

        $url = \URL::route('profile', ['id' => (config('profile-url-format') == 1) ? $this->entity->id : $this->entity->username]).(($segment) ? '/'.$segment : null);

        return $url;
    }

    /**
     * Helper method to know if a user can follow this user
     *
     * @param  \App\Models\User  $user
     * @return bo
     */
    public function canFollowMe($user)
    {
        $privacy = $this->privacy('follow-me', 1);
        if ($privacy == 1) {
            return true;
        } elseif ($privacy == 2) {
            $friend = app('App\\Repositories\\ConnectionRepository');
            if ($friend->areFriends($this->entity->id, $user->id)) {
                return true;
            }
        }

        return false;
    }

    public function popoverUrl()
    {
        return \URL::route('load-user-popover', ['id' => $this->entity->id]);
    }

    public function businessAdmin()
    {
        return $isAdmin = app('App\\Repositories\\PageAdminRepository')->isBusinessAdmin();
    }

    public function isCommunityOwner()
    {
        return $this->ownCommunityId() > 0;
    }

    public function ownCommunity()
    {
        $entityId = (int) ($this->entity->id ?? 0);
        if ($entityId > 0 && array_key_exists($entityId, self::$ownCommunityCache)) {
            return self::$ownCommunityCache[$entityId];
        }

        $community = app('App\\Repositories\\CommunityRepository')->getExternalByUserId($entityId);
        $result = $community ?: false;

        if ($entityId > 0) {
            self::$ownCommunityCache[$entityId] = $result;
        }

        return $result;
    }

    public function ownCommunityId(): int
    {
        $entityId = (int) ($this->entity->id ?? 0);
        if ($entityId <= 0) {
            return 0;
        }

        if (array_key_exists($entityId, self::$ownCommunityIdCache)) {
            return (int) self::$ownCommunityIdCache[$entityId];
        }

        // Hot-path optimization: only fetch the id with the same semantics as
        // CommunityRepository::getExternalByUserId (avoid repository + model hydration).
        $id = (int) (\App\Models\Community::query()
            ->where('user_id', '=', $entityId)
            ->where('external_community', '=', 1)
            ->where('status', '=', 1)
            ->where(function ($community) {
                $community->where('card_dtls_added', '=', 1)
                    ->orWhere('skip_card_dtls', '=', 1)
                    ->orWhere('free_plan_signup', '=', 1);
            })
            ->value('id') ?? 0);
        self::$ownCommunityIdCache[$entityId] = $id;

        return $id;
    }

    public function isResumeCreated($userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        return Cache::remember('user_resume_created_' . $userid, 60, function() use ($userid) {
            return app('App\\Repositories\\ResumeRepository')->getByUserId($userid);
        });
    }

    public function resumeLink($userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        $resumeCreated = $this->isResumeCreated($userid);

        if ($resumeCreated) {
            if (\Auth::check() and \Auth::user()->id == $this->entity->id) {
                return $url = \URL::route('ip-manage', ['slug' => $resumeCreated->slug]);
            }

            // return $url = \URL::route('ip', ['slug' => $resumeCreated->slug]);
            return generateResumeUrl($resumeCreated->slug);
        }

        if (\Auth::check() and \Auth::user()->id == $this->entity->id) {
            return $url = \URL::route('ip-create');
        }

        return false;
    }

    public function isAssociatedWithCommunity()
    {
        return $associated = app('App\\Repositories\\CommunityRepository')->isUserAssociatedWithCommunity($this->entity->id);
    }

    public function checkUserProfile()
    {
        return app('App\\Repositories\\UserRepository')->checkUserProfile($this->entity->id);
    }

    public function mutualFriendsCount($userid)
    {
        return $mutualFriendsCount = app('App\\Repositories\\ConnectionRepository')->mutualFriendsCount($userid);
    }

    public function profileFieldClassName($name)
    {
        $className = '';
        if ($name == 'State or Province name') {
            $className = 'autoaddress-state';
        } elseif ($name == 'Current city name') {
            $className = 'autoaddress-city';
        } elseif ($name == 'Work organization name') {
            $className = 'user-profile-organization-name';
        } elseif ($name == 'Write about your organization') {
            $className = 'user-profile-organization-about';
        } elseif ($name == 'Country name') {
            $className = 'autoaddress-country';
        } elseif ($name == 'Want to connect with') {
            $className = 'user-profile-want-to-connect';
        } elseif ($name == 'I would like to learn more about') {
            $className = 'user-profile-learn-more';
        } elseif ($name == 'Your city of origin') {
            // $className="user-profile-origin-city";
            $className = 'autoaddress-origin-city';
        } elseif ($name == 'You want to share the name of your company or organization? (optional)') {
            $className = 'user-profile-want-to-share-organization';
        } elseif ($name == 'Brief introduction?') {
            $className = 'user-profile-brief-information';
        } elseif ($name == 'About me') {
            $className = 'user-profile-about-me';
        }

        return $className;
    }

    public function canAccessSite()
    {
        $user = \Auth::user();
        /*$userAssociatedWithCommunity=$user->present()->isAssociatedWithCommunity();
        $profileCompleted=$user->present()->checkUserProfile();
        $isCommunityAdmin=app('App\\Repositories\\CommunityRepository')->getExternalByUserId($user->id);

        if(count($userAssociatedWithCommunity)>0 || $profileCompleted==1 || !empty($isCommunityAdmin) || \Auth::user()->admin==1){
            return true;
        }else{
            return false;
        }*/

        $profileCompleted = $user->present()->checkUserProfile();
        if ($profileCompleted == 1 || \Auth::user()->admin == 1) {
            return true;
        } else {
            return false;
        }
    }

    public function groupInvitationsCnt()
    {
        return $groupInvitationsCnt = app('App\\Repositories\\InvitedMemberRepository')->groupInvitationsCnt($this->entity->id);
    }

    public function canParticipate($community_id, $competition_id)
    {
        // $community_id=33;
        // $competition_id=9;

        $competition = app('App\\Repositories\\CommunityCompetitionRepository')->getById($competition_id, $community_id);

        if (! $competition) {
            return false;
        }

        if ($competition->deadline != '0000-00-00 00:00:00' and time() > strtotime($competition->deadline)) {
            return false;
        } else {
            if ($competition->status == 0 || $competition->deadline == '0000-00-00 00:00:00') {
                return false;
            }
        }

        $hasParticipated = app('App\\Repositories\\FoodRepository')->geByCommunityId($community_id, $competition_id, \Auth::user()->id);

        if (! $hasParticipated) {
            return true;
        }

        return false;
    }

    public function canShowStoreLink()
    {
        static $requestCache = [];
        $userId = \Auth::check() ? (int) \Auth::user()->id : 0;
        if ($userId > 0 && array_key_exists($userId, $requestCache)) {
            return $requestCache[$userId];
        }

        // First: cheap check (no container graph) for owned external community.
        if ($this->ownCommunityId() > 0) {
            return $requestCache[$userId] = true;
        }

        // Second: cache the expensive repository-based checks briefly.
        // This menu is rendered on many pages; avoid repeating heavy container resolutions.
        $cacheKey = 'user:can_show_store_link:' . $userId;
        $result = Cache::remember($cacheKey, now()->addSeconds(30), function () {
            $businessIds = app('App\\Repositories\\PageAdminRepository')->getByUserId();

            $myBusinessIds = app('App\\Repositories\\PageRepository')->getByBusinesIds($businessIds);

            $allIds = array_merge($businessIds, $myBusinessIds);
            if (empty($allIds)) {
                return false;
            }

            $pages = app('App\\Repositories\\PageRepository')->getByIdsMine($allIds);
            return count($pages) > 0;
        });

        return $requestCache[$userId] = (bool) $result;
    }

    public function getRedirectUrl($communityUrl = null, $type = null)
    {
        if ($type != 'primarycommunity') {
            $desUrl = \URL::route('user-home');
        } else {
            $desUrl = '';
        }

        $this->userCommunitySettingsRepository = app('App\\Repositories\\UserCommunitySettingsRepository');
        $this->memberRepository = app('App\\Repositories\\CommunityMemberRepository');

        $user = \Auth::user();
		
		app('App\\Repositories\\UserRepository')->saveWeatherLocation($user);
		
        if ($communityUrl and $type != 'primarycommunity') {

            $loggedInCm = $this->getVisitingCommunity();

            if ($user->present()->canAccessSite() || ($loggedInCm and $loggedInCm->present()->canShowCompleteProfilePage() == 0 and $loggedInCm->present()->canShowOrgActivationCodePage() == 0)) {
                $url = \Auth::user()->present()->profileRedirectUrl();
            } else {
               /* $isProfileCompleted = \Auth::user()->present()->checkUserProfile();

                if ($loggedInCm and ($loggedInCm->present()->canShowOrgActivationCodePage() == 0 || $loggedInCm->user_id == $user->id)) {

                    if ($loggedInCm->present()->canShowCompleteProfilePage() == 0 || $isProfileCompleted == 1) {
                        $url = \Auth::user()->present()->profileRedirectUrl();
                    } else {
                        $url = \URL::route('edit-profile');
                    }
                } else {
                    $url = \URL::route('user-associatedcommunity');
                }*/
				
				$url = \Auth::user()->present()->profileRedirectUrl();
				
            }
            $desUrl = $url;
        } else {

			
            \Auth::user()->present()->saveVisitingCommunity(0);
			
            $resumeData = \Auth::user()->present()->isResumeCreated();
            if (! $resumeData) {
                $desUrl = \URL::route('ip-create');
            }else{
				if($resumeData and $resumeData->community_signup==1 and $resumeData->community_activated==0){
					$desUrl= $resumeData->present()->url('manage');
					return $desUrl;
				}
			}
			
			$page_created=app('App\\Repositories\\PageRepository')->findSignupByUserId(\Auth::user()->id);
			if($page_created){
			    $desUrl= $page_created->present()->url();
				return $desUrl;
			}

            /*$incompleteCommunity = app('App\\Repositories\\CommunityRepository')->getExternalByUserIdIncomplete(\Auth::user()->id);
            if ($incompleteCommunity and \Auth::user()->incomplete_org_redirect_count < 3) {
                $desUrl = \URL::route('community-createown-redirect');
            }*/


            $userOwnSettings = app('App\\Repositories\\UserSettingsRepository')->getByUserId();

            /*$redirectPrimary=0;
            if($userOwnSettings and $userOwnSettings->primary_community_redirect){
                $redirectPrimary=$userOwnSettings->primary_community_redirect;
            }*/

            $redirectPrimary = 1;

            /*if ($user->present()->canAccessSite() and $user->present()->isIdentityVerified($user->id) and $type != 'primarycommunity' and $redirectPrimary == 0) {
                $desUrl = \URL::route('user-home');
            } else {*/

                $hasConnectedWithCommunity = $this->hasConnectedWithCommunity();
                if ($hasConnectedWithCommunity) {
                    $favourite_community = \Auth::user()->favourite_community;
                    $community = app('App\\Repositories\\CommunityRepository')->getById($favourite_community);

                    if (! $community) {
                        $community = app('App\\Repositories\\CommunityRepository')->getById(\Auth::user()->community_signup);
                        if ($community and $favourite_community == 0) {
                            app('App\\Repositories\\UserRepository')->setFavouriteCm($community->id);
                        }
                    }

                    if ($community) {

                        if ($community->resume_community == 1) {
                            $resumeData = \Auth::user()->present()->isResumeCreated();
                            if (! $resumeData) {
                                \Auth::user()->present()->saveVisitingCommunity($community->id);

                                if (! isMobile()) {
                                    $resumeCommunityUrl = $community->present()->url('workspace');
                                    $getUrlHostname = getUrlHostnameScheme($resumeCommunityUrl);
                                    $createResumeUrl = $getUrlHostname.'/ip/create';

                                    return $createResumeUrl;
                                } else {
                                    return \URL::route('ip-create');
                                }
                            }
                        }

                        $isMember = $this->memberRepository->isMember($community->id, \Auth::user()->id);
                        $userSettings = $this->userCommunitySettingsRepository->getByUserId($community->id);
                        //if ($user->present()->canAccessSite()) {
                            if ($isMember || $community->present()->isAdmin() || ($community->community_access == 1 and $community->owner_community_access == 1) || isMobile()) {
                                if ($userSettings and $userSettings->community_view == 0) {
                                    $desUrl = $community->present()->url('workspace');
                                } else {
                                    $desUrl = $community->present()->url('cbdashboard');
                                }
                            }
                        /*} else {
                            if (! isMobile()) {
                                $getUrlHostname = getUrlHostnameScheme($community->present()->url());
                                $desUrl = $getUrlHostname.'/o/'.$community->id.'/home';
                            } else {
                                $desUrl = \URL::route('community-home', ['slug' => $community->id]);
                            }
                        }*/
                    }

                } else {
                    $primaryCommunityId = \Auth::user()->community_signup;
                    if ($primaryCommunityId == 0) {
                        $primaryCommunityId = \Auth::user()->primary_community;
                    }

                    if ($primaryCommunityId) {
                        $primaryCommunity = app('App\\Repositories\\CommunityRepository')->getById($primaryCommunityId);

                        if ($primaryCommunity and (\Auth::user()->primary_community_favourite == $primaryCommunity->id || \Auth::user()->primary_community_favourite == '')) {

                            if ($primaryCommunity->resume_community == 1) {
                                $resumeData = \Auth::user()->present()->isResumeCreated();
                                if (! $resumeData) {
                                    \Auth::user()->present()->saveVisitingCommunity($primaryCommunity->id);

                                    if (! isMobile()) {
                                        $resumeCommunityUrl = $primaryCommunity->present()->url('workspace');
                                        $getUrlHostname = getUrlHostnameScheme($resumeCommunityUrl);
                                        $createResumeUrl = $getUrlHostname.'/ip/create';

                                        return $createResumeUrl;
                                    } else {
                                        return \URL::route('ip-create');
                                    }
                                }
                            }

                            $isMember = $this->memberRepository->isMember($primaryCommunity->id, \Auth::user()->id);

                            /*if ($user->present()->canAccessSite()) {*/
                                if ($isMember || $primaryCommunity->present()->isAdmin() || ($primaryCommunity->community_access == 1 and $primaryCommunity->owner_community_access == 1) || isMobile()) {

                                    $userSettings = $this->userCommunitySettingsRepository->getByUserId($primaryCommunity->id);
                                    if ($userSettings and $userSettings->community_view == 0) {
                                        $desUrl = $primaryCommunity->present()->url('workspace');
                                    } else {
                                        $desUrl = $primaryCommunity->present()->url('cbdashboard');
                                    }
                                }
                            /*} else {
                                if (! isMobile()) {
                                    $getUrlHostname = getUrlHostnameScheme($primaryCommunity->present()->url('workspace'));
                                    $desUrl = $getUrlHostname.'/o/'.$primaryCommunity->id.'/home';
                                } else {
                                    $desUrl = \URL::route('community-home', ['slug' => $primaryCommunity->id]);
                                }
                            }*/
                        }
                    //}
                }
            }
        }

        return $desUrl;
    }

    public function profileRedirectUrl()
    {
        // $returnUrl=\URL::route('edit-profile');

        $returnUrl = \URL::route('edit-profile');

        $this->communityRepository = app('App\\Repositories\\CommunityRepository');

        $this->userCommunitySettingsRepository = app('App\\Repositories\\UserCommunitySettingsRepository');

        // if(\Session::has('theNewCommunityId') and \Session::get('theNewCommunityId')!=""  and \Session::get('theNewCommunityId')!=0){
        // $cmId=\Session::get('theNewCommunityId');

        if (getVisitingCommunityId() != 0) {

            $cmId = getVisitingCommunityId();

            if ($cmId == 89) {
                $resumeData = \Auth::user()->present()->isResumeCreated();
                if ($resumeData) {
                    $ipUrl = \URL::to('ip/').'/'.$resumeData->slug.'/manage';
                } else {
                    $ipUrl = \URL::to('ip/').'/create';
                }

                return $returnUrl = $ipUrl;
            } elseif ($cmId == 146) {
                $businessUrl = \URL::to('c').'/'.$cmId.'/createbusiness';

                return $returnUrl = $businessUrl;
            }

            $community = $this->communityRepository->getById($cmId);

            if ($community) {
                $userSettings = $this->userCommunitySettingsRepository->getByUserId($community->id);
                if ($userSettings and $userSettings->community_view == 0) {
                    return $returnUrl = $community->present()->url('workspace');
                } else {
                    return $returnUrl = $community->present()->url('cbdashboard');
                }
            } else {
                return $returnUrl = \URL::route('user-home');
            }
        }

        if (\Auth::user()->favourite_community != 0) {
            $cmId = \Auth::user()->favourite_community;
            $community = $this->communityRepository->getById($cmId);

            if ($community) {
                $userSettings = $this->userCommunitySettingsRepository->getByUserId($community->id);
                if ($userSettings and $userSettings->community_view == 0) {
                    return $returnUrl = $community->present()->url('workspace');
                } else {
                    return $returnUrl = $community->present()->url('cbdashboard');
                }
            } else {
                return $returnUrl = \URL::route('user-home');
            }
        }

        if (getVisitingCommunityId() == 0) {
            $returnUrl = \URL::route('user-home');
        }

        return $returnUrl;
    }

    public function meetingDefaultLocation()
    {
        $zoomDetails = app('App\Repositories\ZoomRepository')->getByUserId($this->entity->id);

        if ($zoomDetails and $zoomDetails->personal_meeting_url != '') {
            return $zoomDetails->personal_meeting_url;
        }

        return '';
    }

    public function canAccessEventVideoMeeting()
    {
        if (\Auth::check() and \Auth::user()->event_video_access == 1) {
            return true;
        }

        return false;
    }

    public function resetUserProfilePicture($size = 200)
    {
        $avatar = $this->avatar;
        $avatarType = $this->privacy('avatar_type', 0);
        $realPathToAvatar = base_path(str_replace('%d', 200, $avatar));
        $amazonPath = \Image::url($avatar, $size);

        if (! empty($amazonPath) and $avatarType != 0) {

            // if(@getimagesize($amazonPath)){
            // return \Image::url($amazonPath);
            // }

            /*if($amazonPath == 'https://lookaside.facebook.com/platform/profilepic/?asid=243525176206894&height=600&width=600&ext=1525967962&hash=AeTbaevKmiZ03fGd' || $amazonPath == 'https://lookaside.facebook.com/platform/profilepic/?asid=992478387565830&height=600&width=600&ext=1525612619&hash=AeQpQn-9vMuqgb4u')
            {
                $userRepository = app('App\\Repositories\\UserRepository');
                $userRepository->savePrivacy(['avatar_type' => 0], $this->entity);
                return $this->defaultAvatar($size);
            }*/

            if (@getimagesize($amazonPath)) {
                return \Image::url($amazonPath, $size);
            } else {
                $userRepository = app('App\\Repositories\\UserRepository');
                $userRepository->savePrivacy(['avatar_type' => 0], $this->entity);

                return $this->defaultAvatar($size);
            }

            return $amazonPath;
        }
    }

    public function isIdentityVerified($user_id)
    {
        static $requestCache = [];
        $user_id = (int) $user_id;

        if ($user_id <= 0) {
            return false;
        }

        if (array_key_exists($user_id, $requestCache)) {
            return $requestCache[$user_id];
        }

        return $requestCache[$user_id] = Cache::remember('user_identity_verified_' . $user_id, 60, function() use ($user_id) {
            $identity = app('App\\Repositories\\UserIdentificationRepository')->getByUserId($user_id);

            if ($identity && (int) ($identity->is_verified ?? 0) === 1) {
                return true;
            }

            return false;
        });
    }

    public function isUserCommunityMember($cmId)
    {
        $community = app('App\\Repositories\\CommunityRepository')->getById($cmId);
        if ($community->present()->canView()) {
            return true;
        }

        return false;
    }

    public function getLoggedInCommunity()
    {
        if (\Session::has('theCommunityId')) {
            $loggedInCmId = \Session::get('theCommunityId');

            return $loggedInCm = app('App\\Repositories\\CommunityRepository')->getById($loggedInCmId);
        }

        return false;
    }

    public function getNewViewsCommunity()
    {
        if (\Session::get('theNewCommunityId') != '' and \Session::get('theNewCommunityId') != 0) {
            $newCmId = \Session::get('theNewCommunityId');

            return $newCmId = app('App\\Repositories\\CommunityRepository')->getById($newCmId);
        }

        return false;
    }

    public function getVisitingCommunity()
    {
        static $requestCache = [];

        $newCmId = (int) getVisitingCommunityId();

        if ($newCmId === 0) {
            return false;
        }

        if (array_key_exists($newCmId, $requestCache)) {
            return $requestCache[$newCmId];
        }

        return $requestCache[$newCmId] = app('App\\Repositories\\CommunityRepository')->getById($newCmId);
    }

    public function canDoCommunityPostActivity($community_id, $user_id, $type = 'post')
    {
        if (! \Auth::check()) {
            return false;
        }

        $selfUserId = \Auth::user()->id;

        // Fast path: you can always do activity on your own post.
        if ($type == 'post' and $user_id == $selfUserId) {
            return true;
        }

        $community_id = (int) $community_id;
        $cacheKey = 'can_do_cm_post_activity:u'.$selfUserId.':c'.$community_id.':t'.$type;
        static $requestCache = [];

        if (array_key_exists($cacheKey, $requestCache)) {
            return $requestCache[$cacheKey];
        }

        return $requestCache[$cacheKey] = Cache::remember($cacheKey, 30, function () use ($community_id, $selfUserId, $type) {
            if ($this->isIdentityVerified($selfUserId) and $this->checkUserProfile() == 1) {
                return true;
            }

            $this->communityRepository = app('App\\Repositories\\CommunityRepository');
            $community = $this->communityRepository->getById($community_id);

            if (! $community) {
                return false;
            }

            if ($community->present()->canView($community_id)) {
                return true;
            } elseif ($community->id == \Auth::user()->community_signup) {
                return true;
            } elseif (app('App\\Repositories\\CommunityPrimaryMembersRepository')->hasAcceptedByCommunity($selfUserId, $community_id)) {
                return true;
            } elseif ($community->race_community == 1) {
                return true;
            }

            $this->communityMemberRepository = app('App\\Repositories\\CommunityMemberRepository');
            $communityMembers = $this->communityMemberRepository->getUserIds($community_id);

            $myFriends = app('App\\Repositories\\ConnectionRepository')->getFriendsId($selfUserId);

            $commonUsers = array_intersect($communityMembers, $myFriends);

            if (count($commonUsers) > 2) {
                return true;
            }

            return false;
        });
    }

    public function canApplyForCommunityPrimaryMember()
    {
        $user = \Auth::user();

        if (\Session::has('theCommunityId') and \Session::get('theCommunityId') != '') { // check if login from organization admin
            return false;
        }

        if ($user->community_signup != 0) { // check if organization signup
            return false;
        }

        if ($user->primary_community != 0) { // check if organization signup
            return false;
        }

        $userAssociatedWithCommunity = $user->present()->isAssociatedWithCommunity(); // check if organization member
        if (count($userAssociatedWithCommunity) > 0) {
            return false;
        }

        // $isCommunityAdmin=app('App\\Repositories\\CommunityRepository')->getExternalByUserId($user->id); // check if organization admin

        $isCommunityAdmin = app('App\\Repositories\\CommunityRepository')->getMyCommunity($user->id);
        if ($isCommunityAdmin) {
            return false;
        }
        /*
        $isIdentityVerified=$user->present()->isIdentityVerified($user->id);
        if($isIdentityVerified){
            return false;
        }*/

        $hasApplied = app('App\\Repositories\\CommunityPrimaryMembersRepository')->hasApplied($user->id);
        if ($hasApplied) {
            return false;
        }

        $profileCompleted = $user->present()->checkUserProfile();
        if ($profileCompleted == 1) {
            return true;
        }

        return false;
    }

    public function primaryCommunityUrl()
    {
        $desUrl = '';
        $hasConnectedWithCommunity = $this->hasConnectedWithCommunity();

        if ($hasConnectedWithCommunity) {
            return false;
        } else {
            $desUrl = \URL::route('user-home');

            $primaryCommunityId = \Auth::user()->community_signup;
            if ($primaryCommunityId == 0) {
                $primaryCommunityId = \Auth::user()->primary_community;
            }

            if ($primaryCommunityId != 0) {
                $primaryCommunity = app('App\\Repositories\\CommunityRepository')->getById($primaryCommunityId);

                if ($primaryCommunity and (\Auth::user()->primary_community_favourite == $primaryCommunity->id || \Auth::user()->primary_community_favourite == '')) {
				
                    //$desUrl = $primaryCommunity->present()->url('workspace');
					
					$userSettings = app('App\\Repositories\\UserCommunitySettingsRepository')->getByUserId($primaryCommunity->id);
					if ($userSettings and $userSettings->community_view == 0) {
						 $desUrl = $primaryCommunity->present()->url('workspace');
					}else{
						$desUrl = $primaryCommunity->present()->url('cbdashboard');
					}  
                }
            }
        }

        return $desUrl;
    }

    public function hasConnectedWithCommunity()
    {
        $communitiesJoined = app('App\\Repositories\\CommunityRepository')->getMyAllJoinedCommunities();
        if (count($communitiesJoined) > 0) {
            return true;
        }

        $isCommunityAdmin = app('App\\Repositories\\CommunityRepository')->getExternalByUserId(\Auth::user()->id); // check if organization admin

        if ($isCommunityAdmin) {
            return true;
        }

        return false;
    }

    public function socialProfilePageURL()
    {
        $user = $this->entity;
        $primaryCommunityId = '';

        if ($user->community_signup != 0) {
            $primaryCommunityId = $user->community_signup;
        } elseif ($user->primary_community != 0) {
            $primaryCommunityId = $user->primary_community;
        }

        $urlDomain = '';
        $urlScheme = 'https://';
        $mainUrl = parse_url(config('app.url'));

        if ($primaryCommunityId and config('community-domains-own-url') == 'yes') {
            $primaryCommunity = app('App\\Repositories\\CommunityRepository')->getById($primaryCommunityId);

            if ($primaryCommunity) {

                if ($primaryCommunity->domain == 1 and $primaryCommunity->domain_name != '') {
                    if ($primaryCommunity->domain_name != \Request::getHost()) {
                        return 'https://'.$primaryCommunity->domain_name.'/'.$user->username;
                    } else {
                        return $user->present()->url();
                    }
                } else {
                    if (isset($mainUrl['host'])) {
                        $urlDomain = $mainUrl['host'];
                    }

                    if (isset($mainUrl['scheme'])) {
                        $urlScheme = $mainUrl['scheme'].'://';
                    }

					return $user->present()->url();
                   // return $urlScheme.$primaryCommunity->slug.'.'.$urlDomain.'/'.$user->username;
                }
            }
        }

        return config('app.url').'/'.$user->username;
    }

    public function saveVisitingCommunity($communityId)
    {
        $communityId = (int) $communityId;
        app('App\\Repositories\\UserRepository')->saveVisitingCommunity($communityId);

        // Keep in-memory user in sync for the current request.
        try {
            if (\Auth::check() && \Auth::user()) {
                \Auth::user()->visiting_community = $communityId;
            }
        } catch (\Throwable $e) {
            // ignore
        }

        // Requirement: language is chosen by user per visiting community.
        // When visiting community changes, apply that community's saved language immediately.
        try {
            if (!\Auth::check()) {
                return;
            }

            $userId = (int) \Auth::id();
            $lang = app('App\\Repositories\\UserLanguageSelectedRepository')
                ->getForUserAndCommunity($userId, $communityId > 0 ? $communityId : 0);

            if (!is_string($lang) || $lang === '') {
                $lang = 'en';
            }

            $lang = strtolower((string) $lang);

            // Validate community activation.
            if ($communityId > 0 && $lang !== 'en') {
                $active = app('App\\Repositories\\CommunityLanguagesRepository')->findByVarActive($lang, $communityId);
                if (!$active) {
                    $lang = 'en';
                }
            }

            if ($communityId > 0) {
                \Session::put('lang_c_' . $communityId, $lang);
                \Session::put('current-language', $lang);
            } else {
                \Session::put('lang', $lang);
                \Session::put('current-language', $lang);
            }

            app()->setLocale($lang);
        } catch (\Throwable $e) {
            // ignore
        }
    }

    public function saveCurrentCommunity($communityId, $category_id)
    {
        app('App\\Repositories\\UserSettingsRepository')->saveCurrentCommunity($communityId, $category_id);
    }

    public function getCurrentCommunity()
    {
        $userData = app('App\\Repositories\\UserSettingsRepository')->getByUserId();

        return $userData;
    }

    public function totalCartCount()
    {
        return app('App\\Repositories\\BusinessProductsCartRepository')->totalCartCount();
    }

    public function canStartMeeting($user_id)
    {
        return app('App\\Repositories\\UserRepository')->canStartMeeting($user_id);
    }

    public function enterToSubmit()
    {
        $userData = app('App\\Repositories\\UserSettingsRepository')->getByUserId();
        if ($userData and $userData->send_message_on_enter == 1) {
            return true;
        }

        return false;
    }

    public function canShowIdhubs()
    {
        if (getVisitingCommunityId() != 0) {
            $cmId = getVisitingCommunityId();

            $this->communityRepository = app('App\\Repositories\\CommunityRepository');

            $community = $this->communityRepository->getById($cmId);

            if ($community and $community->present()->canHaveIdhubsAccess() == 0) {
                return false;
            }
        }

        return true;
    }

    public function canShowIdMart()
    {
        $cmId = (int) getVisitingCommunityId();
        if ($cmId <= 0) {
            return true;
        }

        if (array_key_exists($cmId, self::$canShowIdMartCache)) {
            return self::$canShowIdMartCache[$cmId];
        }

        $this->communityRepository = app('App\\Repositories\\CommunityRepository');
        $community = $this->communityRepository->getById($cmId);

        $can = true;
        if ($community && $community->present()->canHaveIdmartAccess() == 0) {
            $can = false;
        }

        self::$canShowIdMartCache[$cmId] = $can;

        return $can;
    }

    public function personalProfile()
    {
        $userId = (int) ($this->entity->id ?? 0);
        if ($userId > 0 && array_key_exists($userId, self::$personalProfileCache)) {
            return self::$personalProfileCache[$userId];
        }

        $personalProfile = app('App\\Repositories\\UsersOrganizationRepository')->getByUserId($userId);
        if ($userId > 0) {
            self::$personalProfileCache[$userId] = $personalProfile;
        }

        return $personalProfile;
    }

    public function getLikeToLearn()
    {
        $userId = (int) ($this->entity->id ?? 0);
        if ($userId > 0 && array_key_exists($userId, self::$likeToLearnCache)) {
            return self::$likeToLearnCache[$userId];
        }

        $getLikeToLearn = app('App\\Repositories\\UsersWouldLikeToLearnRepository')->getLiketoLearn($userId);
        if ($userId > 0) {
            self::$likeToLearnCache[$userId] = $getLikeToLearn;
        }

        return $getLikeToLearn;
    }

    public function getWantToConnect()
    {
        $userId = (int) ($this->entity->id ?? 0);
        if ($userId > 0 && array_key_exists($userId, self::$wantToConnectCache)) {
            return self::$wantToConnectCache[$userId];
        }

        $getWantToConnect = app('App\\Repositories\\UsersWantToConnectRepository')->getWantToConnect($userId);
        if ($userId > 0) {
            self::$wantToConnectCache[$userId] = $getWantToConnect;
        }

        return $getWantToConnect;
    }

    public function getICanOffer()
    {
        $getICanOffer = app('App\\Repositories\\UsersICanOfferRepository')->getICanOffer($this->entity->id);

        return $getICanOffer;
    }

    public function hasAddedLikeToKeyword($keyword)
    {
        $hasAdded = app('App\\Repositories\\UsersWouldLikeToLearnRepository')->findByName($keyword);

        return $hasAdded;
    }

    public function hasAddedConnectKeyword($keyword)
    {
        $hasAdded = app('App\\Repositories\\UsersWantToConnectRepository')->findByName($keyword);

        return $hasAdded;
    }

    public function hasAddedOfferKeyword($keyword)
    {
        $hasAdded = app('App\\Repositories\\UsersICanOfferRepository')->findByName($keyword);

        return $hasAdded;
    }

    public function getRedirectUrlPrimary()
    {
        $desUrl = '';
        $user = \Auth::user();

        $hasConnectedWithCommunity = $this->hasConnectedWithCommunity();
        if ($hasConnectedWithCommunity) {
            $favourite_community = \Auth::user()->favourite_community;
            $community = app('App\\Repositories\\CommunityRepository')->getById($favourite_community);

            if (! $community) {
                $community = app('App\\Repositories\\CommunityRepository')->getById(\Auth::user()->community_signup);
                if ($community and $favourite_community == 0) {
                    app('App\\Repositories\\UserRepository')->setFavouriteCm($community->id);
                }
            }

            if ($community) {
                $desUrl = $community->present()->url('workspace');
            }

        } else {
            $primaryCommunityId = \Auth::user()->community_signup;
            if ($primaryCommunityId == 0) {
                $primaryCommunityId = \Auth::user()->primary_community;
            }

            if ($primaryCommunityId) {
                $primaryCommunity = app('App\\Repositories\\CommunityRepository')->getById($primaryCommunityId);

                if ($primaryCommunity and (\Auth::user()->primary_community_favourite == $primaryCommunity->id || \Auth::user()->primary_community_favourite == '')) {
                    $desUrl = $primaryCommunity->present()->url('workspace');
                }
            }

        }

        return $desUrl;
    }

    public function getAskIdeaPlanDetails()
    {
        $plan = app('App\\Repositories\\CommunityPricingPlanRepository')->getByType($this->entity->id, 'askidea');

        return $plan;
    }

    public function getIdmeetsPlanDetails()
    {
        $plan = app('App\\Repositories\\CommunityPricingPlanRepository')->getByType($this->entity->id, 'idmeets');

        return $plan;
    }

    public function getPersonalDomainPlanDetails()
    {
        $plan = app('App\\Repositories\\CommunityPricingPlanRepository')->getByType($this->entity->id, 'personaldomain');

        return $plan;
    }

    public function getCardDetails($transaction_payment_type = 'askidea', $add_payment_type = 'askidea')
    {
        $card = app('App\\Repositories\\CommunityPricingPlanPaymentCardsRepository')->checkCard(0, $this->entity->id, $transaction_payment_type, $add_payment_type);

        return $card;
    }

    public function hasRideProfileCompleted($community_id)
    {
        /*$settings=app('App\\Repositories\\UserCommunitySettingsRepository')->getByUserId($community_id);
        if($settings and $settings->ride_profile_completed==1){
            return "yes";
        }else{
            return "no";
        }*/

        $user = \Auth::user();

        $ride_profile_completed = $user->ride_profile_completed;
        $ride_address_completed = $user->ride_address_completed;

        if ($ride_profile_completed == 0) {
            $communityRideProfileRedirect = \URL::route('community-ride-completeprofile', ['slug' => $community_id]);

            return $communityRideProfileRedirect;
        }

        if ($ride_address_completed == 0) {
            // $communityRideProfileRedirect=\URL::route('community-ride-completeaddress',['slug'=>$community_id]);
            $communityRideProfileRedirect = \URL::route('community-ride-completeprofile', ['slug' => $community_id]);

            return $communityRideProfileRedirect;
        }

        return 'yes';
    }

    public function maxPostVideoUploadSize()
    {
        $videoUploadSize = config('max-size-upload-video');
        if (\Auth::check() and \Auth::user()->max_video_uploadsize_inbytes) {
            $videoUploadSize = \Auth::user()->max_video_uploadsize_inbytes;
        }

        return $videoUploadSize;
    }

    public function getLikeMindedPeers()
    {
        $userid = \Auth::user()->id;

        $this->usersICanOfferRepository = app('App\\Repositories\\UsersICanOfferRepository');
        $this->usersWantToConnectRepository = app('App\\Repositories\\UsersWantToConnectRepository');

        $whatICanOffer = $this->usersICanOfferRepository->getICanOffer($userid);
        $offerNames = [];
        if ($whatICanOffer) {
            foreach ($whatICanOffer as $offer) {
                if (! empty($offer->name)) {
                    $offerNames[] = (string) $offer->name;
                }
            }
        }

        $lookingUserIds = $this->usersWantToConnectRepository->getOtherUserIdsByNames($offerNames, (int) $userid);

        $whatIWantToConnect = $this->usersWantToConnectRepository->getWantToConnect($userid);
        $connectNames = [];
        if ($whatIWantToConnect) {
            foreach ($whatIWantToConnect as $connect) {
                if (! empty($connect->name)) {
                    $connectNames[] = (string) $connect->name;
                }
            }
        }

        $offeringUserIds = $this->usersICanOfferRepository->getOtherUserIdsByNames($connectNames, (int) $userid);

        return array_values(array_unique(array_merge($lookingUserIds, $offeringUserIds)));
    }

    public function getLikeMindedPeersCount()
    {
        return count($this->getLikeMindedPeers());
    }

    public function likeMindedPeersMatching($user_id)
    {
        $self_id = \Auth::user()->id;

        $this->usersICanOfferRepository = app('App\\Repositories\\UsersICanOfferRepository');
        $this->usersWantToConnectRepository = app('App\\Repositories\\UsersWantToConnectRepository');

        $whatICanOffer = $this->usersICanOfferRepository->getICanOfferName($self_id);
        $whatOtherWantToConnect = $this->usersWantToConnectRepository->getWantToConnectName($user_id);

        $countOtherWant = count($whatOtherWantToConnect);
        $countIOffer = count($whatICanOffer);
        $countOther = count(array_intersect($whatICanOffer, $whatOtherWantToConnect));
        $totalOfferPercentCount = ($countOther / $countOtherWant) * 100;
        if ($totalOfferPercentCount > 0) {
            $ttlOffer = $totalOfferPercentCount / 2;
            $ttlOffer = round($ttlOffer);
        } else {
            $ttlOffer = 0;
        }

        $whatOtherCanOffer = $this->usersICanOfferRepository->getICanOfferName($user_id);
        $whatIWantToConnect = $this->usersWantToConnectRepository->getWantToConnectName($self_id);

        $countIWant = count($whatIWantToConnect);

        $countOtherOffer = count($whatOtherCanOffer);

        $countOffer = count(array_intersect($whatIWantToConnect, $whatOtherCanOffer));

        $totalConnectPercentCount = ($countOffer / $countIWant) * 100;

        if ($totalConnectPercentCount > 0) {
            $ttlconnect = $totalConnectPercentCount / 2;
            $ttlconnect = round($ttlconnect);
        } else {
            $ttlconnect = 0;
        }

        $totalPercentage = $ttlconnect + $ttlOffer;

        return $totalPercentage;
    }

    public function userMembersSettings($user_id, $community_id)
    {
        return $settings = app('App\\Repositories\\UserCommunitySettingsRepository')->userMembersSettings($user_id, $community_id);
    }

    public function userMemberProfilePhoto($community_id)
    {
        $user = $this->entity;
        $user_id = $user->id;

        $settings = $this->userMembersSettings($user_id, $community_id);
        if ($settings and $settings->profile_photo) {
            return \Image::url($settings->profile_photo);
        } else {
            return $user->present()->getAvatar(600);
        }
    }

    public function getCommunityById($community_id)
    {
        $community_id = (int) $community_id;
        if ($community_id <= 0) {
            return null;
        }

        if (array_key_exists($community_id, self::$communityByIdCache)) {
            return self::$communityByIdCache[$community_id];
        }

        $community = app('App\\Repositories\\CommunityRepository')->getById($community_id);
        self::$communityByIdCache[$community_id] = $community;

        return $community;
    }

    public function getCommunityCategoryById($category_id)
    {
        $category_id = (int) $category_id;
        if ($category_id <= 0) {
            return null;
        }

        if (array_key_exists($category_id, self::$communityCategoryByIdCache)) {
            return self::$communityCategoryByIdCache[$category_id];
        }

        $category = app('App\\Repositories\\CommunityCategoryRepository')->get($category_id);
        self::$communityCategoryByIdCache[$category_id] = $category;

        return $category;
    }

    public function getCommunityCategoryByCmId($category_id, $community_id)
    {
        $category = app('App\\Repositories\\CommunityCategoryRepository')->get($category_id, $community_id);

        return $category;
    }

    public function getPostDraft($draftType, $draftTypeId, $draftCommunityId, $draftPageId, $profileUsr)
    {
        $key = implode(':', [
            (string) $draftType,
            (int) $draftTypeId,
            (int) $draftCommunityId,
            (int) $draftPageId,
            (int) $profileUsr,
        ]);

        if (array_key_exists($key, self::$postDraftCache)) {
            return self::$postDraftCache[$key];
        }

        $draft = app('App\\Repositories\\PostDraftRepository')->getDraft(
            $draftType,
            $draftTypeId,
            $draftCommunityId,
            $draftPageId,
            $profileUsr
        );

        self::$postDraftCache[$key] = $draft;

        return $draft;
    }

    public function getMyJoinedCommunities()
    {
        $communities = app('App\\Repositories\\CommunityRepository')->getMyAllJoinedCommunities();

        return $communities;
    }

    public function getBusinessCommunity()
    {
        if (array_key_exists('v1', self::$businessCommunityCache)) {
            return self::$businessCommunityCache['v1'];
        }

        $community = app('App\\Repositories\\CommunityRepository')->publicBusinessCommunity();
        self::$businessCommunityCache['v1'] = $community;

        return $community;
    }

    public function isCommunityMember($cmId)
    {
        $cmId = (int) $cmId;
        if ($cmId <= 0) {
            return false;
        }

        if (array_key_exists($cmId, self::$isCommunityMemberCache)) {
            return self::$isCommunityMemberCache[$cmId];
        }

        $isMember = app('App\\Repositories\\CommunityMemberRepository')->isMember($cmId);
        self::$isCommunityMemberCache[$cmId] = $isMember;

        return $isMember;
    }

    public function isCommunityMemberApplied($cmId)
    {
        $isMemberApplied = app('App\\Repositories\\CommunityMembersAppliedRepository')->isApplied($cmId);

        return $isMemberApplied;
    }

    public function canShareExperience()
    {
        $community_id = getVisitingCommunityId();
        $community = app('App\\Repositories\\CommunityRepository')->getById($community_id);
        if ($community and $community->enable_share_experience == 1) {
            return true;
        }

        return false;
    }

    public function sharedExpCount()
    {
        $community_id = getVisitingCommunityId();

        return app('App\\Repositories\\ExperienceRepository')->getSharedCount($community_id);
    }

    public function getMatchingExperience($community_id, $experience)
    {
        return app('App\\Repositories\\ExperienceRepository')->getMatchingExperience($community_id, $experience);
    }

    public function getProductRecurringTrans($product_id, $order_id)
    {
        $transactions = app('App\\Repositories\\BusinessProductsOrdersRepository')->getByProductIdSuccess($product_id, $order_id);

        return $transactions;
    }

    public function getStoreById($store_id)
    {
        $store = app('App\\Repositories\\PageRepository')->getById($store_id);

        return $store;
    }

    public function getOrdersByOrderId($order_id)
    {
        $orders = app('App\\Repositories\\BusinessProductsOrdersRepository')->getByBusinessOrderId($order_id);

        return $orders;
    }

    public function getOrdersByOrderBusinessId($order_id, $business_id)
    {
        $orders = app('App\\Repositories\\BusinessProductsOrdersDetailsRepository')->getByBusinessIdAll($order_id, $business_id);

        return $orders;
    }

    public function getUserById($user_id)
    {
        return app('App\\Repositories\\UserRepository')->findByIdUsername($user_id);
    }

    public function getProductOrdersCount($product_id)
    {
        return app('App\\Repositories\\BusinessProductsOrdersRepository')->getProductOrdersCount($product_id);
    }

    public function isExpCategoryDeactivated($catgory_id)
    {
        $community_id = getVisitingCommunityId();
        $category = app('App\\Repositories\\ExperienceCategoriesRepository')->isExpCategoryDeactivated($community_id, $catgory_id);

        return $category;
    }

    public function countFriendsOnline($communityId, $categoryId)
    {
        $communityId = (int) $communityId;
        $categoryId = (int) $categoryId;

        static $requestCache = [];
        $requestKey = $this->entity->id.'|'.$communityId.'|'.$categoryId;

        if (array_key_exists($requestKey, $requestCache)) {
            return $requestCache[$requestKey];
        }

        $cacheKey = 'friends_online:u'.$this->entity->id.':c'.$communityId.':cat'.$categoryId;

        return $requestCache[$requestKey] = Cache::remember($cacheKey, 10, function () use ($communityId, $categoryId) {
            return app('App\\Repositories\\UserRepository')->countFriendsOnline($communityId, $categoryId);
        });
    }

    public function newMessageCount($group_id)
    {
        return app('App\\Repositories\\PostSeenRepository')->newMessageCount(\Auth::user()->id, 'chat_message', $group_id);
    }

    public function newMessageCountGroup($group_id)
    {
        return app('App\\Repositories\\PostSeenRepository')->newMessageCount(\Auth::user()->id, 'group_message', $group_id);
    }

    public function getMessageGroup($groupId)
    {
        return app('App\\Repositories\\MessageGroupsRepository')->getById($groupId);
    }

    public function getCommunityMembersIds($communityId, $group_id)
    {
        return count(app('App\\Repositories\\UserRepository')->getCommunityMembersIds($communityId, $group_id));
    }

    public function countFriendsUsersFavourite()
    {
        return app('App\\Repositories\\UserRepository')->countFriendsUsersFavourite(); // Not used on another place
    }

    public function friendsUsersFavouriteLimit()
    {
        return app('App\\Repositories\\UserRepository')->friendsUsersFavouriteLimit(); // Not used on another place
    }

    public function listFriendsUsersLimitVisiting($communityId, $categoryId, $visiting_gift_app_community_id)
    {
        return app('App\\Repositories\\UserRepository')->listFriendsUsersLimit(null, null, 10, $communityId, $categoryId, $visiting_gift_app_community_id);
    }

    public function listFriendsUsersLimitSkipFav($getUsersCnt)
    {
        return app('App\\Repositories\\UserRepository')->listFriendsUsersLimit(null, 'skipFavourite', $getUsersCnt, 0, 0, 0); // Not used on another place
    }

    public function listFriendsUsersLimitSkipFavLimited($communityId, $categoryId)
    {
        return app('App\\Repositories\\UserRepository')->listFriendsUsers(null, 'skipFavourite', $communityId, $categoryId, \Auth::user()->id, $communityId, 'limited');
    }

    public function getAppointmentsAllByApt($appointment_id)
    {
        return app('App\\Repositories\\AppointmentRepository')->getByAppointmentId($appointment_id);
    }

    public function getAppointmentRespByApt($appointment_id)
    {
        return app('App\\Repositories\\AppointmentResponsesRepository')->getByAppointment($appointment_id);
    }

    public function getUsersFavouriteCommunity($user)
    {
        return app('App\\Repositories\\UserRepository')->getFavouriteCommunity($user);
    }

    public function getApptCatDept($category_dept_id)
    {
        return app('App\\Repositories\\AppointmentCommunityCategoryDeptRepository')->getById($category_dept_id);
    }
	
	public function getSignupFeature()
	{
		$feature_id_data=app('App\\Repositories\\UsersFeaturesSelectedRepository')->signedUpFeature();
		$feature='';
		if($feature_id_data){
		    $feature=app('App\\Repositories\\FeaturesRepository')->getById($feature_id_data->feature_id);
		}
		return $feature;
	}
	
	public function isMyCommunityCreated()
	{
		return app('App\\Repositories\\CommunityRepository')->getMyCommunity($this->entity->id);
		
	  // return app('App\\Repositories\\CommunityRepository')->isMyCommunityCreated($this->entity->id);
	}
	
	public function myCommunityCreated()
	{		
	    return app('App\\Repositories\\CommunityRepository')->isMyCommunityCreated($this->entity->id);
	}
	
	public function getAllActiveFeatures()
	{
		$features=app('App\\Repositories\\FeaturesRepository')->getAllActive();	
		return $features;	
	}
	
	public function getSubscribedFeaturesList()
	{
		$visitingCommunity=$this->getVisitingCommunity();
		if($visitingCommunity){
			$features_ids=app('App\\Repositories\\UsersFeaturesSelectedRepository')->getSubscribedCommunityIds($visitingCommunity->id);
		}else{
			$features_ids=app('App\\Repositories\\UsersFeaturesSelectedRepository')->getSubscribedIds();		
		}
		
		//$features=app('App\\Repositories\\FeaturesRepository')->getSubscribed($features_ids);
		$features=app('App\\Repositories\\PricingPlansFeaturesRepository')->getSubscribed($features_ids);
		return $features;		
	}
	
	public function getSubscribedFeaturesListCm($community_id)
	{
		$features_ids=app('App\\Repositories\\UsersFeaturesSelectedRepository')->getSubscribedCommunityIds($community_id);		
		//$features=app('App\\Repositories\\FeaturesRepository')->getSubscribed($features_ids);
		$features=app('App\\Repositories\\PricingPlansFeaturesRepository')->getSubscribed($features_ids);
		return $features;		
	}
	
	public function getSubscribedFeaturesListCmIds($community_id,$pricing_plan=0)
	{
		/*if($pricing_plan){
			$features_ids=app('App\\Repositories\\PlansFeaturesSelectedRepository')->getSelectedFeatureIdsForPlan($pricing_plan);		
			$features=app('App\\Repositories\\PricingPlansFeaturesRepository')->getSubscribedIds($features_ids);
			return $features;		
		}else{
			$features_ids=app('App\\Repositories\\UsersFeaturesSelectedRepository')->getSubscribedCommunityIds($community_id);		
			$features=app('App\\Repositories\\PricingPlansFeaturesRepository')->getSubscribedIds($features_ids);
			return $features;		
		}	*/
		
		$features_ids=app('App\\Repositories\\UsersFeaturesSelectedRepository')->getSubscribedCommunityIds($community_id);
		
		if($pricing_plan){
            $planFeatureIds = app('App\\Repositories\\PlansFeaturesSelectedRepository')->getSelectedFeatureIdsForPlan($pricing_plan);
            $features_ids = collect($features_ids)->merge($planFeatureIds)->unique()->values();
		}
		
		$features=app('App\\Repositories\\PricingPlansFeaturesRepository')->getSubscribedIds($features_ids);
		return $features;
	}
	
	public function getSubscribedFeatures()
	{
		$features_ids=app('App\\Repositories\\UsersFeaturesSelectedRepository')->getSubscribedIds();		
		//$features=app('App\\Repositories\\FeaturesRepository')->getSubscribed($features_ids);
		$features=app('App\\Repositories\\PricingPlansFeaturesRepository')->getSubscribed($features_ids);
		return $features;		
	}
	
	public function myCommunityMenuUrl($pageName)
	{	
		//$myCommunity=\Auth::user()->present()->isMyCommunityCreated();
		
		$user=\Auth::user();
		
		$myCommunity=$this->getVisitingCommunity();
		
		if($myCommunity){	
		   $isOwner=$myCommunity->isOwner($user->id);
		   $isMember=$myCommunity->present()->isMember($user->id);
			  
		   $domainUrl=$myCommunity->present()->getCommunityDomainUrl();		   
		   $urlDomain="";
		   $mainUrl=parse_url($domainUrl);
		   if(isset($mainUrl['host'])){
				$urlDomain=$mainUrl['host'];
		   }		   
		   
		   $currentHost = Request::getHost();		   
		   $menuUrlLink='';
		   
		   if($urlDomain==$currentHost){
		   		if($pageName=='custom_website_creation' and $isOwner){
		   			$menuUrlLink=$myCommunity->present()->url('homepagecontents');
				}elseif($pageName=='secure_web_address' and $isOwner){
		   			$menuUrlLink=$myCommunity->present()->url('pannelsetting');
				}elseif($pageName=='task_dashboard' and ($isOwner || $isMember)){
		   			$menuUrlLink=$myCommunity->present()->url('alltasks');
				}elseif($pageName=='document_sharing' and $isOwner){
		   			$menuUrlLink=$myCommunity->present()->url('documentsdashboard');
				}elseif($pageName=='create_forms' and ($isOwner || $isMember)){
		   			$menuUrlLink=$myCommunity->present()->url('cmsurveys');
				}elseif($pageName=='data_analytics' and ($isOwner || $isMember)){
		   			$menuUrlLink=$myCommunity->present()->url('longforms');
				}elseif($pageName=='event_management' and ($isOwner || $isMember)){
		   			$menuUrlLink=$myCommunity->present()->url('allpostevents');
				}elseif($pageName=='crowdfunding_management' and ($isOwner || $isMember)){
		   			$menuUrlLink=$myCommunity->present()->url('allcrowdfunding');
				}elseif($pageName=='customer_relationship' and ($isOwner || $isMember)){
		   			$menuUrlLink=$myCommunity->present()->url('campaigntemplates');
				}elseif($pageName=='team_collaboration' and ($isOwner || $isMember)){
		   			$menuUrlLink=$myCommunity->present()->url('members');
				}elseif($pageName=='organizational_intranet' and ($isOwner || $isMember)){
		   			$menuUrlLink=$myCommunity->present()->url('workspace');
				}elseif($pageName=='video_conferencing' and ($isOwner || $isMember)){
		   			$menuUrlLink=$myCommunity->present()->url('workspace');
				}elseif($pageName=='idhubs_ecosystem'){
					$redirectUrl=\Config::get('app.url');
					$getUrlHostname=\Config::get('app.url');					
		   			$menuUrlLink=$getUrlHostname.'/cmownpage?lgkey='.\Auth::user()->login_key."&lgurl=".$redirectUrl;		
				}		
		   }else{		   
		   		$getUrlHostname=getUrlHostnameScheme($domainUrl);
				$redirectUrl='';
				if($pageName=='custom_website_creation' and $isOwner){
           			$redirectUrl=$getUrlHostname."/c/33/homepagecontents";           
           		}elseif($pageName=='secure_web_address' and $isOwner){
           			$redirectUrl=$getUrlHostname."/c/33/pannelsetting";           
           		}elseif($pageName=='task_dashboard' and ($isOwner || $isMember)){
           			$redirectUrl=$getUrlHostname."/c/33/alltasks";           
           		}elseif($pageName=='document_sharing' and $isOwner){
           			$redirectUrl=$getUrlHostname."/c/33/documentsdashboard";           
           		}elseif($pageName=='create_forms' and ($isOwner || $isMember)){
           			$redirectUrl=$getUrlHostname."/c/33/cmsurveys";           
           		}elseif($pageName=='data_analytics' and ($isOwner || $isMember)){
           			$redirectUrl=$getUrlHostname."/c/33/longforms";           
           		}elseif($pageName=='event_management' and ($isOwner || $isMember)){
           			$redirectUrl=$getUrlHostname."/c/33/allpostevents";           
           		}elseif($pageName=='crowdfunding_management' and ($isOwner || $isMember)){
           			$redirectUrl=$getUrlHostname."/c/33/allcrowdfunding";           
           		}elseif($pageName=='customer_relationship' and ($isOwner || $isMember)){
           			$redirectUrl=$getUrlHostname."/c/33/campaigntemplates";           
           		}elseif($pageName=='team_collaboration' and ($isOwner || $isMember)){
           			$redirectUrl=$getUrlHostname."/c/33/members";           
           		}elseif($pageName=='organizational_intranet' and ($isOwner || $isMember)){
           			$redirectUrl=$getUrlHostname."/c/33";           
           		}elseif($pageName=='video_conferencing' and ($isOwner || $isMember)){
           			$redirectUrl=$getUrlHostname."/c/33";           
           		}elseif($pageName=='idhubs_ecosystem'){
		   			$redirectUrl=\Config::get('app.url');
					$getUrlHostname=\Config::get('app.url');
				}
				
				$menuUrlLink=$getUrlHostname.'/cmownpage?lgkey='.\Auth::user()->login_key."&lgurl=".$redirectUrl;		   
			}	
			return $menuUrlLink;	   
		}
		return '';
	}	
	
	public function getTimelinePosts()
	{
		return app('App\\Repositories\\PostRepository')->getMyLatestTimelinePosts(\Auth::user()->id);
	}
	
	public function getMyCommunityAppUrl()
	{
		$myCommunity=\Auth::user()->present()->ownCommunity();
		if($myCommunity){
			$domainUrl=$myCommunity->present()->getCommunityDomainUrl();		   
			$urlDomain="";
			$mainUrl=parse_url($domainUrl);
			if(isset($mainUrl['host'])){
				$urlDomain=$mainUrl['host'];
			}		   
		   
			$currentHost = Request::getHost();	
			
			if($urlDomain==$currentHost){
				$menuUrlLink=$myCommunity->present()->url('featureslisting');
			}else{
				$getUrlHostname=getUrlHostnameScheme($domainUrl);
				$redirectUrl=$getUrlHostname."/c/33/featureslisting";   
				$menuUrlLink=$getUrlHostname.'/cmownpage?lgkey='.\Auth::user()->login_key."&lgurl=".$redirectUrl;	        
			}
			return $menuUrlLink;
		}	
	}
	
	public function getAgreementsCount()
	{
        $user = $this->entity;
        $uid = (int) ($user->id ?? 0);
        if ($uid <= 0) {
            return 0;
        }

        $email = '';
        try {
            $email = strtolower(trim((string) ($user->email ?? '')));
        } catch (\Throwable $e) {
            $email = '';
        }

        $cacheKey = 'agreements_count_u' . $uid;
        $queryCount = function () use ($uid, $email) {
            return (int) \DB::table('pdf_sign_documents as d')
                ->where(function ($q) use ($uid, $email) {
                    $q->where('d.user_id', $uid)
                        ->orWhereExists(function ($sub) use ($uid, $email) {
                            $sub->select(\DB::raw(1))
                                ->from('pdf_sign_recipients as r')
                                ->whereColumn('r.document_id', 'd.id')
                                ->where(function ($qr) use ($uid, $email) {
                                    $qr->where('r.user_id', $uid);
                                    if ($email !== '') {
                                        $qr->orWhere('r.email', $email);
                                    }
                                });
                        });
                })
                ->count();
        };

        try {
            return (int) Cache::remember($cacheKey, now()->addSeconds(30), function () use ($queryCount) {
                return (int) $queryCount();
            });
        } catch (\Throwable $e) {
            try {
                return (int) $queryCount();
            } catch (\Throwable $e2) {
                return 0;
            }
        }
	}
}
