<?php

namespace App\Presenters;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Laracasts\Presenter\Presenter;

class CommunityPresenter extends Presenter
{
    protected const AUTH_STATE_CACHE_PREFIX = 'community_auth_state:';

    public function url($segment = null)
    {
        $segment = (empty($segment)) ? '' : '/'.$segment;
        /*$domainData = explode('.', \Request::getHost());
        if(isset($domainData[2])){
            return $segment;
        }else{
            return \URL::route('community-page', ['slug' => $this->entity->slug]).$segment;
        }*/

        if (isMobile()) {
            return \URL::route('community-page', ['slug' => $this->entity->id]).$segment;
        } else {
            if (config('community-domains-own-url') == 'no') {
                return \URL::route('community-page', ['slug' => $this->entity->id]).$segment;
            } else {
                if ($segment) {
                    $communityDomainUrl = $this->getCommunityDomainUrl('https').'/c/'.$this->entity->id.$segment;
                } else {
                    if (\Auth::check()) {
                        $communityDomainUrl = $this->getCommunityDomainUrl().'/c/'.$this->entity->id;
                    } else {
                        $communityDomainUrl = $this->getCommunityDomainUrl();
                    }
                }

                return \URL::to($communityDomainUrl);
            }
        }
    }

    /**
     * Build a community auth URL (login/signup) with a compact query.
     *
     * By default this stores the full params server-side and returns a short URL like:
     *   /c/{id}/login?s=Ab12CdEfGh
     */
    public function authUrl($segment, array $params = [], bool $useStateToken = true, bool $useShortKeys = true)
    {
        $baseUrl = $this->url($segment);

        $params = $this->normalizeAuthParams($params);
        $params = array_filter($params, static function ($value) {
            return ! (is_null($value) || $value === '');
        });

        if (empty($params)) {
            return $baseUrl;
        }

        if ($useStateToken) {
            $token = $this->storeAuthState($params);

            return $baseUrl.'?'.http_build_query(['s' => $token], '', '&', PHP_QUERY_RFC3986);
        }

        if ($useShortKeys) {
            $params = $this->shortenAuthParams($params);
        }

        return $baseUrl.'?'.http_build_query($params, '', '&', PHP_QUERY_RFC3986);
    }

    /**
     * Convenience wrapper to pick up known auth params from the current request.
     */
    public function authUrlFromRequest($segment, array $overrides = [], bool $useStateToken = true, bool $useShortKeys = true)
    {
        $requestParams = \Request::only([
            'type',
            'linktype',
            'returnUrl',
            'returnUrlMeeting',
            'urltype',
            'urltypeid',
            // short keys support
            't',
            'lt',
            'ru',
            'rum',
            'ut',
            'ui',
        ]);

        $params = array_merge($requestParams, $overrides);

        return $this->authUrl($segment, $params, $useStateToken, $useShortKeys);
    }

    protected function normalizeAuthParams(array $params)
    {
        $map = [
            't' => 'type',
            'lt' => 'linktype',
            'ru' => 'returnUrl',
            'rum' => 'returnUrlMeeting',
            'ut' => 'urltype',
            'ui' => 'urltypeid',
        ];

        foreach ($map as $shortKey => $longKey) {
            if (! array_key_exists($longKey, $params) && array_key_exists($shortKey, $params)) {
                $params[$longKey] = $params[$shortKey];
            }
            unset($params[$shortKey]);
        }

        return $params;
    }

    protected function shortenAuthParams(array $params)
    {
        $map = [
            'type' => 't',
            'linktype' => 'lt',
            'returnUrl' => 'ru',
            'returnUrlMeeting' => 'rum',
            'urltype' => 'ut',
            'urltypeid' => 'ui',
        ];

        $out = $params;
        foreach ($map as $longKey => $shortKey) {
            if (array_key_exists($longKey, $out)) {
                $out[$shortKey] = $out[$longKey];
                unset($out[$longKey]);
            }
        }

        return $out;
    }

    protected function storeAuthState(array $params)
    {
        // Short, URL-safe token. Collision extremely unlikely, but we guard anyway.
        for ($i = 0; $i < 5; $i++) {
            $token = Str::random(12);
            $cacheKey = static::AUTH_STATE_CACHE_PREFIX.$token;

            if (! Cache::has($cacheKey)) {
                Cache::put($cacheKey, $params, now()->addMinutes(30));
                return $token;
            }
        }

        // Fallback (should never happen)
        $token = Str::random(20);
        Cache::put(static::AUTH_STATE_CACHE_PREFIX.$token, $params, now()->addMinutes(30));

        return $token;
    }

    public function urlWithId($segment = null)
    {
        $segment = (empty($segment)) ? '' : '/'.$segment;

        return \URL::route('community-page', ['slug' => $this->entity->id]).$segment;
    }

    public function domainUrl()
    {
		$schemeName = config('community-domains-scheme', 'http');
        $scheme = $schemeName.'://';
		
		if (!\Auth::check()){
			if ($this->entity->domain_name != '' and $this->entity->domain == 1) {
				return $scheme.$this->entity->domain_name;
			}else{
				return \URL::route('community-page', ['slug' => $this->entity->id]);
			}
		}else{
			if ($this->entity->domain_name != '' and $this->entity->domain == 1) {
				//return $scheme.$this->entity->domain_name."/w";
				return $scheme.$this->entity->domain_name;
			}else{
				return \URL::route('community-page', ['slug' => $this->entity->id])."/w";
			}
		}	
    }

    public function readDesign()
    {
        return $this->entity->user->present()->readDesign('community-'.$this->entity->id);
    }

    public function getPrivacy()
    {
        return ($this->entity->privacy == 1) ? 'Public' : 'Private';
    }

    public function isAdmin()
    {
        if (! \Auth::check()) {
            return false;
        }

        return $this->entity->user_id == \Auth::user()->id;
    }

    public function canReceiveNotification($userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $check = app('App\\Repositories\\NotificationReceiverRepository')->exists($userid, 'community', $this->entity->id);

        return ($check) ? 1 : 0;
    }

    public function field($id = null)
    {
        $details = (! empty($this->entity->info)) ? perfectUnserialize($this->entity->info) : [];

        if (empty($id)) {
            return $details;
        }

        if (isset($details[$id])) {
            return $details[$id];
        }

        return 'Nill';
    }

    public function fields()
    {
        return app('App\\Repositories\\CustomFieldRepository')->listAll('community');
    }

    public function createdOn()
    {
        return str_replace(' ', 'T', $this->entity->created_at).'+05:30';
    }

    public function canJoin($userid = null)
    {
        // if (!\Auth::check()) return false;

        if (! \Auth::check() and ! $userid) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        if (! $userid) {
            return false;
        }

        if ($this->entity->privacy == 0 and ! $this->isInvited($userid)) {
            return false;
        }

        return true;
    }

    public function canView()
    {
        static $requestCache = [];
        $communityId = (int) ($this->entity->id ?? 0);
        $userId = \Auth::check() ? (int) \Auth::user()->id : 0;

        $requestKey = $userId . '|' . $communityId;
        if (array_key_exists($requestKey, $requestCache)) {
            return $requestCache[$requestKey];
        }

        $cacheKey = $userId
            ? 'community_can_view_u' . $userId . '_c' . $communityId
            : 'community_can_view_guest_c' . $communityId;

        $ttlSeconds = $userId ? 15 : 60;

        return $requestCache[$requestKey] = Cache::remember($cacheKey, now()->addSeconds($ttlSeconds), function () {
            if (! \Auth::check()) {
                if ($this->privacy == 1 or $this->external_community == 1) {
                    return true;
                }
            } else {

                if ($this->eventmeeting == 1 || $this->gift_app_community == 1) {
                    return true;
                }

                if ($this->entity->present()->canSignInToCommunity(\Auth::user()->id)) {
                    if ($this->privacy == 1 or $this->entity->isOwner() or $this->isMember()/* or $this->isInvited() */ or $this->eventmeeting == 1) {
                        return true;
                    }
                }

            }

            return false;
        });
    }

    public function isInvited($userid = null)
    {
        // if (!\Auth::check()) return false;

        if (! \Auth::check() and ! $userid) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        if (! $userid) {
            return false;
        }

        $isInvitedByEmail = app('App\\Repositories\\InvitedMemberRepository')->isInvitedByEmail('community', $this->entity->id);

        $invited = app('App\\Repositories\\InvitedMemberRepository')->isInvited('community', $this->entity->id, $userid);
        if ($invited) {
            return true;
        }

        return false;
    }

    public function canPost($userid = null)
    {
        if (! \Auth::check() and ! $userid) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        if (! $userid or ! $this->isMember($userid)) {
            return false;
        }

        if ($this->entity->isOwner($userid) or ($this->entity->can_post == 1)) {
            return true;
        }

        return false;
    }

    public function canManage($userid = null)
    {
        if (! \Auth::check() and ! $userid) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        if (! $userid) {
            return false;
        }

        if ($this->entity->isOwner($userid)) {
            return true;
        }

        if ($this->isModerator($userid)) {
            return true;
        }

        return false;
    }

    public function canInvite($userid = null)
    {
        // if (!\Auth::check()) return false;
        if (! \Auth::check() and ! $userid) {
            return false;
        }
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        if (! $userid) {
            return false;
        }

        return ($this->isMember($userid) and $this->entity->can_invite == 1) or $this->entity->isOwner($userid);
    }

    public function isMember($userid = null)
    {
        if ($this->entity->isOwner($userid)) {
            return true;
        }

        return app('App\\Repositories\\CommunityMemberRepository')->isMember($this->entity->id, $userid);
    }

    public function isModerator($userid = null)
    {
        // if (!\Auth::check()) return false;

        if (! \Auth::check() and ! $userid) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        if (! $userid) {
            return false;
        }

        $moderators = $this->entity->getModerators();

        // $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        return in_array($userid, $moderators);
    }

    public function getLogo()
    {
        if (empty($this->entity->logo)) {
            return \Theme::asset()->img('theme/images/community/logo-replace.png');
        }

        return \Image::url($this->entity->logo,600);
    }

    public function getFooterLogo()
    {
        if (empty($this->entity->footer_logo)) {
            return $this->getLogo();
        }

        return \Image::url($this->entity->footer_logo);
    }

    public function getEventAppLogo()
    {
        if (empty($this->entity->event_app_logo)) {
            return $this->getLogo();
        }

        return \Image::url($this->entity->event_app_logo);
    }

    public function memberStatus($userid)
    {
        if ($this->isMember($userid)) {
            return 'member';
        }

        $invited = app('App\\Repositories\\InvitedMemberRepository')->isInvited('community', $this->entity->id, $userid);
        if ($invited) {
            return 'invited';
        }

        return false;
    }

    public function pendingCommunityActions()
    {
        return count(app('App\\Repositories\\PostRepository')->communityMembersPosts($this->entity->id, $this->entity->user_id));
    }

    public function pendingCommunityActionsCount()
    {
        return app('App\\Repositories\\PostRepository')->pendingCommunityActionsCount($this->entity->id, $this->entity->user_id);
    }

    public function myPendingCommunityActionsCount()
    {
        return app('App\\Repositories\\PostRepository')->myPendingCommunityActionsCount($this->entity->id);
    }

    public function myScheduledPostCount()
    {
        return app('App\\Repositories\\PostRepository')->myScheduledPostCount($this->entity->id);
    }

	public function pendingStoresCount()
	{
		return app('App\\Repositories\\PageRepository')->myBusinessesPendingReviewCount($this->entity->id);
	}

    public function communityMembersIgnoredPosts()
    {
        return app('App\\Repositories\\PostRepository')->communityMembersIgnoredPostsCount($this->entity->id, $this->entity->user_id);
    }

    public function eventAction()
    {
        return count(app('App\\Repositories\\CommunityRepository')->getPendingEventsCount($this->entity->id));
    }

    public function canAddEvent()
    {
        $status = true;
        $this->userRepository = app('App\\Repositories\\USerRepository');
        $account = $this->userRepository->checkUserAccount(\Auth::user()->id);
        $profile = $this->userRepository->checkUserProfile(\Auth::user()->id);

        if ($account == 0 || $profile == 0) {
            $status = false;
        }
        $status = true;

        return $status;
    }

    public function canPublishFeeds()
    {
        $scoailFeeds = app('App\\Repositories\\CommunitySocialFeedRepository')->getByCommunityId($this->entity->id);

        if (isset($scoailFeeds) and $scoailFeeds->publish_feeds == 1) {
            return true;
        } else {
            return false;
        }
    }

    public function isGroupMember($userid, $categoryId)
    {
        return $isGroupMember = app('App\\Repositories\\CommunityCategoryMembersRepository')->isGroupMember($userid, $categoryId, $this->entity->id);
    }

    public function canViewCategory($categoryId, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        // Allow callers to pass the category model to avoid extra DB lookups.
        if (is_object($categoryId) && isset($categoryId->id)) {
            $category = $categoryId;
            $categoryId = (int) $category->id;
        } else {
            $categoryId = (int) $categoryId;
            $category = app('App\\Repositories\\CommunityCategoryRepository')->get($categoryId);
        }

        $canView = 'no';
        if ($userid == $this->entity->user_id) {
            // return true;
            $canView = 'yes';
        } elseif ($category->group_type == 1 && $category->status == 1) {
            $canView = 'yes';
        } else {

            $isGroupMember = app('App\\Repositories\\CommunityCategoryMembersRepository')->isGroupMember($userid, $categoryId, $this->entity->id);
            if ($isGroupMember && $category->status == 1) {
                // return true;
                $canView = 'yes';
            }
            // return false;
        }

        if ($canView == 'yes' and $category->meeting_topic == 0) {
            return true;
        } elseif ($canView == 'yes' and $category->meeting_topic == 1) {
            // return false;

            $event = app('App\\Repositories\\PostEventsRepository')->getByTopicId($category->id, $this->entity->id);

            if ($event and $event->web_meeting == 1 and $event->fund_nature == 0 and $event->idmeet_meeting == 1) {

                $timeZone = 'America/New_York';

                if ($event->timezone != '') {
                    $timeZone = $event->timezone;
                } elseif ($event->type == 'community') {
                    $communityData = $event->community;

                    if ($communityData and $communityData->timezone) {
                        $timeZone = $communityData->timezone;
                    }
                }

                date_default_timezone_set($timeZone);

                if (time() >= strtotime($event->starttime) and time() <= strtotime($event->endtime)) {
                    return true;
                }

                if (time() > strtotime($event->endtime)) {
                    $category->expired = 1;
                    $category->save();
                }

                $communityTimeZone = 'America/New_York';
                if ($this->entity->timezone) {
                    $communityTimeZone = $this->entity->timezone;
                }
                date_default_timezone_set($communityTimeZone);
            } else {
                $category->expired = 1;
                $category->save();
            }
        } elseif ($category->meeting_topic == 2) {

            $appointments = app('App\\Repositories\\AppointmentRepository')->getByTopicIdAll($category->id, $this->entity->id);

            if (count($appointments) > 0) {
                foreach ($appointments as $appointment) {
                    if ($appointment and $appointment->idmeet_meeting == 1) {

                        $timeZoneCm = 'America/New_York';

                        $timeZone = $appointment->master_timezone;
                        date_default_timezone_set($timeZone);

                        $fullDate = $appointment->appointment_date.' '.$appointment->master_end_time;

                        if (time() <= strtotime($fullDate)) {
                            $canViewAppointment = app('App\\Repositories\\AppointmentRepository')->canViewAppointment($appointment);

                            if ($canViewAppointment) {
                                return true;
                            }
                        }

                        if (time() > strtotime($fullDate)) {
                            $category->expired = 1;
                            $category->save();
                        }

                        if ($this->entity->timezone) {
                            $timeZoneCm = $this->entity->timezone;
                        }
                        date_default_timezone_set($timeZoneCm);
                    }
                }
            } else {
                $category->expired = 1;
                $category->save();
            }
        }

        return false;
    }

    public function categoryMembersCount($categoryId)
    {
        $categoryId = (int) $categoryId;
        $cacheKey = 'cm:'.$this->entity->id.':category_members_count:'.$categoryId;

        return Cache::remember($cacheKey, 30, function () use ($categoryId) {
            return app('App\\Repositories\\CommunityCategoryMembersRepository')->countMembers($categoryId, $this->entity->id);
        });
    }

    public function getDocumentUrl($path)
    {
        $file = URL::to($path);
        $CDNRepository = app('App\\Repositories\\CDNRepository');
        if ($CDNRepository->has($path)) {

            /*if (strpos($path, 'media/appvideo/') !== false) {
                $file = $CDNRepository->getVideoOutpuLinkMp4($path);
            } else {
                $file = $CDNRepository->getLink($path);
            }*/
			
			$extension = strtolower(pathinfo(parse_url($path, PHP_URL_PATH), PATHINFO_EXTENSION));

			if ($extension === 'mp4') {
				$file = $CDNRepository->getVideoOutpuLinkMp4($path);
			} else {
				$file = $CDNRepository->getLink($path);
			}
        }

        return $file;
    }

    public function getDocumentDownloadCount($document_id)
    {
        $downloads = app('App\\Repositories\\CommunityDocumentsDownloadRepository')->countDownloads($document_id);

        return $downloads;
    }

    public function getDocumentCopyCount($document_id)
    {
        $copy = app('App\\Repositories\\CommunityDocumentsCopyRepository')->countCopy($document_id);

        return $copy;
    }

    public function getDocumentsCount($category_id)
    {
        $count = app('App\\Repositories\\CommunityDocumentsRepository')->countDocuments($category_id);

        return $count;
    }

    public function getDocumentsSpaceCount($category_id)
    {
        $space = app('App\\Repositories\\CommunityDocumentsRepository')->getDocumentsSpaceCount($category_id);

        return $space;
    }

    public function newPosts($category_id)
    {
        if (! \Auth::check()) {
            return 0;
        }

        $communityId = (int) $this->entity->id;
        $categoryId = (int) $category_id;
        $userId = (int) \Auth::id();

        if ($communityId <= 0 || $categoryId <= 0 || $userId <= 0) {
            return 0;
        }

        // Per-request bulk cache to avoid calling newPostsNotSeen() in loops.
        static $bulkByCommunityAndUser = [];
        $bulkKey = $communityId.':'.$userId;

        if (! array_key_exists($bulkKey, $bulkByCommunityAndUser)) {
            $categoryIds = [];

            // Prefer already-loaded relation (common in menus/lists).
            if (isset($this->entity->categories) && is_iterable($this->entity->categories)) {
                foreach ($this->entity->categories as $cat) {
                    if ($cat && isset($cat->id)) {
                        $categoryIds[] = (int) $cat->id;
                    }
                }
            }

            $categoryIds = array_values(array_unique(array_filter($categoryIds, static fn ($id) => $id > 0)));

            if (! empty($categoryIds)) {
                $bulkByCommunityAndUser[$bulkKey] = app('App\\Repositories\\PostSeenRepository')
                    ->newPostsNotSeenBulk($communityId, $categoryIds, $userId);
            } else {
                $bulkByCommunityAndUser[$bulkKey] = [];
            }
        }

        if (array_key_exists($categoryId, $bulkByCommunityAndUser[$bulkKey])) {
            return (int) $bulkByCommunityAndUser[$bulkKey][$categoryId];
        }

        // Fallback (e.g. if categories relation wasn't available).
        return (int) app('App\\Repositories\\PostSeenRepository')->newPostsNotSeen($communityId, $categoryId, $userId);
    }

    public function getHomeContents()
    {
        $homeContents = app('App\\Repositories\\CommunityHomeContentsRepository')->getByCommunityId($this->entity->id);
        if ($homeContents) {
            return $homeContents;
        } else {
            $arrVal = ['hometheme' => 3];

            $homeContents = app('App\\Repositories\\CommunityHomeContentsRepository')->addContents($arrVal, $this->entity->id, $this->entity->user_id);

            return $homeContents;
        }
    }

    public function getTopBanners()
    {
        return app('App\\Repositories\\CommunityTopbannerRepository')->getByCommunityId($this->entity->id);
    }

    public function getPages()
    {
        return app('App\\Repositories\\CommunityPagesRepository')->getAllPublishedByCommunityId($this->entity->id);
    }

    public function getAllPages()
    {
        return app('App\\Repositories\\CommunityPagesRepository')->getAllCommunityPages($this->entity->id);
    }

    public function newForms()
    {
        $newposts = app('App\\Repositories\\CommunityFormsSeenRepository')->newFormsNotSeen($this->entity->id, 'form');

        return $newposts;
    }

    public function getMenuHeaderColor()
    {
        $community = $this->entity;
        $homecontents = $community->present()->getHomeContents();

        $menuHeaderColor = 'rgb(243, 243, 243)';
        if ($homecontents) {
            if ($homecontents->use_own_header_color == 1) {
                $menuHeaderColor = $homecontents->own_header_color;
            } else {
                $menuHeaderColor = $homecontents->header_color;
            }
        }

        return $menuHeaderColor;
    }

    public function getMenuColor()
    {
        $community = $this->entity;
        $homecontents = $community->present()->getHomeContents();

        $menuTextColor = '#5d5d5c';
        if ($homecontents) {
            if ($homecontents->use_own_menu_color == 1) {
                $menuTextColor = $homecontents->own_menu_color;
            } else {
                $menuTextColor = $homecontents->menu_color;
            }
        } elseif ($community->slug == 'durhamrtds') {
            $menuTextColor = '#FFFFFF';
        }

        return $menuTextColor;
    }

    public function getMenuBackGroundcolor()
    {
        $community = $this->entity;
        $menuBoxColor = '#F00';

        $homecontents = $community->present()->getHomeContents();
        if ($homecontents) {
            if ($homecontents->use_own_menu_background_color == 1) {
                $menuBoxColor = $homecontents->own_menu_background_color;
            } else {
                $menuBoxColor = $homecontents->menu_background_color;
            }
        } elseif ($community->slug == 'durhamrtds') {
            $menuBoxColor = '#cc101e';
        }

        return $menuBoxColor;
    }

    public function getFooterBackGroundcolor()
    {
        $community = $this->entity;
        $footerColor = '#666';

        $homecontents = $community->present()->getHomeContents();
        if ($homecontents) {
            if ($homecontents->use_own_footer_color == 1) {
                $footerColor = $homecontents->own_footer_color;
            } else {
                $footerColor = $homecontents->footer_color;
            }
        } elseif ($community->slug == 'durhamrtds') {
            $footerColor = '#cc101e';
        }

        return $footerColor;
    }

    public function getLogoAvatar()
    {
        if (empty($this->entity->logo_avatar)) {
            return $this->defaultAvatar($this->entity->title, 100);
        }

        return \Image::url($this->entity->logo_avatar);
    }

    public function getFeviconAvatar()
    {
        if (empty($this->entity->fevicon_image)) {
            return $this->getLogoAvatar();
        }

        return \Image::url($this->entity->fevicon_image);
    }

    public function defaultAvatar($title, $size = 100)
    {
        $firstLetter = strtolower(substr($title, 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'));
        }
    }

    public function facebookRedirectUrl()
    {
        $community = $this->entity;
        if ($community->domain_name != '') {
            return $facebookRedirectUrl = 'https://'.$community->domain_name.'/c/'.$community->id.'/auth/facebook/callback';
        } else {
            $urlDomain = '';
            $mainUrl = parse_url(config('app.url'));
            if (isset($mainUrl['host'])) {
                $urlDomain = $mainUrl['host'];
            }

            return $facebookRedirectUrl = 'https://'.$community->slug.'.'.$urlDomain.'/c/'.$community->id.'/auth/facebook/callback';
        }
    }

    public function facebookLoginUrl()
    {
        $community = $this->entity;
        if ($community->domain_name != '') {
            return $facebookRedirectUrl = 'https://'.$community->domain_name.'/c/'.$community->id.'/auth/facebook';
        } else {
            $urlDomain = '';
            $mainUrl = parse_url(config('app.url'));
            if (isset($mainUrl['host'])) {
                $urlDomain = $mainUrl['host'];
            }

            return $facebookRedirectUrl = 'https://'.$community->slug.'.'.$urlDomain.'/c/'.$community->id.'/auth/facebook';
        }
    }

    public function googleRedirectUrl()
    {
        $community = $this->entity;
        if ($community->domain_name != '') {
            return $facebookRedirectUrl = 'https://'.$community->domain_name.'/c/'.$community->id.'/auth/google';
        } else {
            $urlDomain = '';
            $mainUrl = parse_url(config('app.url'));
            if (isset($mainUrl['host'])) {
                $urlDomain = $mainUrl['host'];
            }

            return $facebookRedirectUrl = 'https://'.$community->slug.'.'.$urlDomain.'/c/'.$community->id.'/auth/google';
        }
    }

    public function linkedinRedirectUrl()
    {
        $community = $this->entity;
        if ($community->domain_name != '') {
            return $facebookRedirectUrl = 'https://'.$community->domain_name.'/c/'.$community->id.'/auth/linkedin';
        } else {
            $urlDomain = '';
            $mainUrl = parse_url(config('app.url'));
            if (isset($mainUrl['host'])) {
                $urlDomain = $mainUrl['host'];
            }

            return $facebookRedirectUrl = 'https://'.$community->slug.'.'.$urlDomain.'/c/'.$community->id.'/auth/linkedin';
        }
    }

    public function countDirectSignupMembers()
    {
        $users = app('App\\Repositories\\UserRepository')->totalCoummunitySignup($this->entity->id);

        return $users;
    }

    public function communityBusinessTotal()
    {
        $users = app('App\\Repositories\\PageRepository')->communityBusinessTotal($this->entity->id);

        return $users;
    }

    public function canManageGroup($categoryId, $userid = null)
    {
        if (! \Auth::check() and ! $userid) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        if (! $userid) {
            return false;
        }

        $categoryId = (int) $categoryId;
        $userid = (int) $userid;

        $cacheKey = 'cm:'.$this->entity->id.':can_manage_group:cat'.$categoryId.':u'.$userid;
        return Cache::remember($cacheKey, 30, function () use ($categoryId, $userid) {
            if ($this->entity->isOwner($userid)) {
                return true;
            }

            return (bool) app('App\\Repositories\\CommunityCategoryMembersRepository')->isGroupAdmin($this->entity->id, $categoryId, $userid);
        });
    }

    public function businessPageSettings()
    {
        return app('App\\Repositories\\CommunityBusinessSettingsRepository')->getByCommunityId($this->entity->id);
    }

    public function marketplaceTitle()
    {
        $homecontents = $this->getHomeContents();
        $marketplaceTitle = 'Community eMarketplace';
        if ($homecontents and $homecontents->marketplace_title) {
            $marketplaceTitle = $homecontents->marketplace_title;
        }

        return $marketplaceTitle;
    }

    public function categoryCompetitionCount($category_id)
    {
        return app('App\\Repositories\\CommunityCompetitionRepository')->getByCommunityCategory($this->entity->id, $category_id);
    }

    public function isUserJudge($user_id, $competition_id)
    {
        return app('App\\Repositories\\CommunityCompetitionJudgesRepository')->isUserJudge($user_id, $competition_id, $this->entity->id);
    }

    public function amIJudge($category_id, $userid = null)
    {

        if (! \Auth::check() and ! $userid) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;


        $category_id = (string) ((int) $category_id);
        $userid = (string) ((int) $userid);
        $cacheKey = 'cm:'.$this->entity->id.':am_i_judge:cat'.$category_id.':u'.$userid;

        return Cache::remember($cacheKey, 30, function () use ($category_id, $userid) {
            return app('App\\Repositories\\CommunityCompetitionJudgesRepository')->amIJudge($category_id, $userid);
        });
    }

    public function totalBusinesses()
    {
        $businesses = app('App\\Repositories\\PageRepository')->totalBusinesses($this->entity->id);

        return $businesses;
    }

    public function getVideoUrl($videoLink)
    {
        $content = $videoLink;
        if (! empty($content)) {
            $link = $content;
            $youTube = parseYouTube($link);
            if (config('enable-https', false)) {
                $youTube = str_replace('http://', 'https://', $youTube);
            }
            if (! empty($youTube)) {
                return $youTube;
            }

            $vimeoURL = parseVimeo($link);
            if (config('enable-https', false)) {
                $vimeoURL = str_replace('http://', 'https://', $vimeoURL);
            }
            if (! empty($vimeoURL)) {
                return $vimeoURL;
            }
        }

        return false;
    }

    public function getEmailCategories($category_id = 0)
    {
        $categories = app('App\\Repositories\\CommunityMembersEmailsRepository')->getEmailCategories($this->entity->id, $category_id);

        return $categories;
    }

    public function getEmailCategoriesPersonal($category_id = 0)
    {
        if (! \Auth::check() and ! $userid) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $categories = app('App\\Repositories\\CommunityMembersEmailsRepository')->getEmailCategoriesPersonal($userid);

        return $categories;
    }

    public function canAccessVideoMeeting($category_id, $community_id)
    {
        $category = app('App\\Repositories\\CommunityCategoryRepository')->get($category_id, $community_id);

        $community = app('App\\Repositories\\CommunityRepository')->getById($community_id);

        if ($category and $community) {
            if ($category->videocall_access == 1 and $community->videocall_access == 1) {
                return true;
            }
        }

        return false;
    }

    public function getAppointment($categoryid)
    {
        $appointments = app('App\\Repositories\\AppointmentRepository')->getByTopicId($categoryid, $this->entity->id);

        return $appointments;
    }

    public function isSlotAvailable($timesArray, $checkTime, $slotTime)
    {
        if ($slotTime == 15) {
            return true;
        } else {

            $endTime = date('Y-m-d H:i:s', strtotime('+'.$slotTime.'minutes', strtotime($checkTime)));

            $slots = $this->slotsList(15, $checkTime, $endTime);

            $found = 'no';
            if (! empty($slots)) {
                $found = 'yes';
                foreach ($slots as $slot) {
                    if (! in_array($slot, $timesArray)) {
                        $found = 'no';
                        break;
                    }
                }
            }
            if ($found == 'no') {
                return false;
            }

            return true;
        }
    }

    public function slotsList($duration, $startTime, $endTime)
    {
        $start = new \DateTime($startTime);
        $end = new \DateTime($endTime);
        $interval = new \DateInterval('PT'.$duration.'M');
        $period = new \DatePeriod($start, $interval, $end);
        $periods = [];
        $slots = [];
        $slot_counter = 0;

        foreach ($period as $dt) {
            $slots[] = $dt;
        }

        foreach ($slots as $key => $dt) {
            $slot_counter++;
            if ($slot_counter == count($slots)) {
                $current = $end;
            } elseif ($slot_counter <= count($slots)) {
                $current = $slots[$key + 1];
            }
            $previous = $slots[$key];
            $periods[] = $previous->format('Y-m-d H:i:s');
        }

        return $periods;
    }

    public function getDurations($timeSettings)
    {
        if ($timeSettings->min_15 == 1 and $timeSettings->min_30 == 1 and $timeSettings->hr_1 == 1) {
            return 'three-durations';
        } elseif (($timeSettings->min_15 == 1 and $timeSettings->min_30 == 1) || ($timeSettings->min_30 == 1 and $timeSettings->hr_1 == 1) || ($timeSettings->min_15 == 1 and $timeSettings->hr_1 == 1)) {
            return 'two-durations';
        } else {
            return 'one-durations';
        }
    }

    public function getActiveLanguages()
    {
        $repo = app('App\\Repositories\\CommunityLanguagesRepository');
        $languages = $repo->getByCommunityActiveAll($this->entity->id);

        // Before login, keep community pages in English only.
        if (!\Auth::check()) {
            return $languages;
        }

        $communityKey = 'lang_c_' . (int) $this->entity->id;
        $lang = \Session::get($communityKey) ?: \Session::get('lang');

        if ($lang) {
            $langNormalized = is_string($lang) ? strtolower($lang) : $lang;

            // English is always allowed even if it's not stored in community_languages.
            // Do not override an explicit 'en' selection back to the community default.
            if ($langNormalized !== 'en') {
                $language = $repo->findByVarActive($lang, $this->entity->id);
                $languageMain = app('App\\Repositories\\LanguageRepository')->findByVar($lang);

                if (! $language || ! $languageMain) {
                    \Session::put($communityKey, 'en');
                    \Session::put('lang', 'en');
                }
            }
        }

        return $languages;
    }

    public function socialLogins()
    {
        $socialLogins = app('App\\Repositories\\CommunitySocialMediaLoginsRepository')->getByCommunityId($this->entity->id);

        return $socialLogins;
    }

    public function totalUnreadPosts()
    {
        $community = $this->entity;

        $cnt = 0;
        foreach ($community->categories as $category) {
            if ($community->present()->canViewCategory($category->id)) {
                $newPosts = $community->present()->newPosts($category->id);
                $cnt = $cnt + $newPosts;
            }
        }

        return $cnt;
    }

    public function totalGroupsAvailable()
    {
        $community = $this->entity;

        $cnt = 0;
        foreach ($community->categories as $category) {
            if ($community->present()->canViewCategory($category->id)) {
                $cnt = $cnt + 1;
            }
        }

        return $cnt;
    }

    public function upcomingEvents()
    {
        $cnt = 0;

        $community_id = $this->entity->id;

        $events = app('App\\Repositories\\PostEventsRepository')->getAllUpcomingEvents();

        foreach ($events as $evt) {
            $post = app('App\\Repositories\\PostRepository')->getById($evt->post_id);
            if ($post) {
                $cnt = $cnt + 1;
            }
        }

        return $cnt;
    }

    public function countFormsSurveys()
    {
        $cnt = 0;

        $community = $this->entity;

        if ($community->isOwner()) {
            $surveys = app('App\\Repositories\\CommunitySurveysRepository')->getSurveysCount($community->id);

            return $surveys;
        } else {
            $surveys = app('App\\Repositories\\CommunitySurveysRepository')->getSurveysByUserIdCount($community->id, \Auth::user()->id);

            return $surveys;
        }
    }

    public function countTasks()
    {
        $community = $this->entity;

        $openTasks = app('App\\Repositories\\CommunityTaskManagementRepository')->getOpenTasks($community->id);

        return count($openTasks);
    }

    public function countPolls()
    {
        $community = $this->entity;

        $polls = app('App\\Repositories\\SurveyPostRepository')->getMySurveysCommunity(\Auth::user()->id, $community->id);

        return count($polls);
    }

    public function countDocuments()
    {
        $community = $this->entity;

        $documents = app('App\\Repositories\\CommunityDocumentsRepository')->countCommunityDocuments($community->id);

        return $documents;
    }

    public function countCampaigns()
    {
        $community = $this->entity;

        $campaigns = app('App\\Repositories\\CommunityCampaignRepository')->getByCommunityIdCount($community->id);

        return $campaigns;
    }

    public function countNotes()
    {
        $community = $this->entity;
        $notes = app('App\\Repositories\\NotesRepository')->get($community->id);

        return count($notes);
    }

    public function canAccessCRM()
    {
        $community = $this->entity;
        $userid = \Auth::user()->id;

        if ($community->present()->canHaveCrmAccess() == 1) {
            if ($this->entity->isOwner()) {
                return true;
            }

            $canAccessCRM = app('App\\Repositories\\CommunityMemberRepository')->canAccessCRM($userid, $community->id);
            if ($canAccessCRM) {
                return true;
            }
        }

        return false;
    }

    public function postsOwnershipRequests()
    {
        $community = $this->entity;

        return app('App\\Repositories\\PostsTransferRepository')->postRequestsCount($community->id);
    }

    public function canReviewJobs()
    {
        // if($this->entity->resume_community==1){
        // if($this->entity->job_community==1){
        if ($this->entity->isOwner()) {
            return true;
        }

        // }
        return false;
    }

    public function pendingJobsReview()
    {
        return app('App\\Repositories\\JobsRepository')->pendingJobsReview();
    }

    public function getCommunityDomainUrl($https = 'http')
    {
        $community = $this->entity;
        $urlDomain = config('community-domain.domain-url');

        $schemeName = config('community-domains-scheme', 'http');
        $scheme = $schemeName.'://';

        if (config('community-domains-own-url') == 'no'){
            return \URL::route('community-page', ['slug' => $this->entity->id]);
        }

        if ($community->domain == 1 and $community->domain_name != '') {
            $domainName = $community->domain_name;
        } else{            
            $scheme = $schemeName.'://';
            //$domainName = $community->slug.'.'.$urlDomain;
			//$domainName = \URL::route('community-page', ['slug' => $this->entity->id]);
			$domainName = config('community-domain.domain-url');
        }
        return $scheme.$domainName;
    }
	
	public function getCommunityDomainUrlInside($https = 'http')
    {
        $community = $this->entity;
        $urlDomain = config('community-domain.domain-url');

        $schemeName = config('community-domains-scheme', 'http');
        $scheme = $schemeName.'://';

        if (config('community-domains-own-url') == 'no'){
            return \URL::route('community-page', ['slug' => $this->entity->id]);
        }

        if ($community->domain == 1 and $community->domain_name != '') {
            $domainName = $community->domain_name;
        } else{            
            $scheme = $schemeName.'://';           
			//$domainName = \URL::route('community-page', ['slug' => $this->entity->id]);
			$domainName = config('community-domain.domain-url')."/c/".$this->entity->id;
        }
        return $scheme.$domainName;
    }
	
	public function getCommunityDomainUrlInsideWithUrl($https = 'http')
    {
        $community = $this->entity;
        $urlDomain = config('community-domain.domain-url');

        $schemeName = config('community-domains-scheme', 'http');
        $scheme = $schemeName.'://';

        if (config('community-domains-own-url') == 'no'){
            return \URL::route('community-page', ['slug' => $this->entity->id]);
        }

        if ($community->domain == 1 and $community->domain_name != '') {
            $domainName = $community->domain_name."/c/".$this->entity->id."/workspace";
        } else{            
            $scheme = $schemeName.'://';           
			//$domainName = \URL::route('community-page', ['slug' => $this->entity->id]);
			$domainName = config('community-domain.domain-url')."/c/".$this->entity->id."/workspace";
        }
        return $scheme.$domainName;
    }

    public function getCommunityDomain($segment = null)
    {
        $segment = (empty($segment)) ? '' : '/'.$segment;

        $community = $this->entity;
        $urlDomain = config('community-domain.domain-url');

        $schemeName = config('community-domains-scheme', 'http');
        $scheme = $schemeName.'://';

        if (config('community-domains-own-url') == 'no'){           
            return \URL::to($segment);
        }

        if ($community->domain == 1 and $community->domain_name != '') {
            $domainName = $community->domain_name;
        } else {
            $scheme = 'http://';
            //$domainName = $community->slug.'.'.$urlDomain;
			//$domainName = \URL::to($segment);
			
			return \URL::to($segment);
        }

        return $scheme.$domainName.$segment;
    }

    public function hiddenPostsCount()
    {
        return app('App\\Repositories\\PostRepository')->hiddenPostsCount($this->entity->id);
    }

    public function productsCount()
    {
        return app('App\\Repositories\\BusinessProductsRepository')->productsByCommunityId($this->entity->id);
    }

    public function countFolderFiles($folderId)
    {
        return app('App\\Repositories\\CommunityDocumentsRepository')->countFolderFiles($this->entity->id, $folderId);
    }

    /* Pricing plan features start */

    public function canCreateStore()
    {
        if ($this->entity->allow_user_create_business_override == 1 and $this->entity->allow_user_create_business == 1) {
            return 1;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'allow-users-to-create-store');

    }

    public function canShowCrowdfunding()
    {
        if ($this->entity->show_crowdfunding_override == 1 and $this->entity->show_crowdfunding == 1) {
            return 1;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'display-crowdfunding-CTA-at-website');

    }

    public function canDoSurveyNominationAction()
    {
        if ($this->entity->survey_nomination_action_override == 1 and $this->entity->survey_nomination_action == 1) {
            return 1;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'edit-delete-action-at-nominee-entry');

    }

    public function canDoCampaign()
    {
		return 1;
		
        if ($this->entity->activate_campaign_override == 1 and $this->entity->activate_campaign == 1) {
            return 1;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'activate-campaign');
    }

    public function canDoEvents()
    {
        if ($this->entity->event_access_override == 1 and $this->entity->event_access == 1) {
            return 1;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'activate-event');
    }

    public function canDoCrowdfunding()
    {
        if ($this->entity->donation_access_override == 1 and $this->entity->donation_access == 1) {
            return 1;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'activate-crowdfunding');
    }

    public function canDoVideoCall()
    {
        if ($this->entity->videocall_access_override == 1 and $this->entity->videocall_access == 1) {
            return 1;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'video-call-access');
    }

    public function canShowOrgActivationCodePage()
    {
        if ($this->entity->show_activationcode_page_override == 1 and $this->entity->show_activationcode_page == 1) {
            return 1;
        }

        if ($this->entity->show_activationcode_page_override == 1 and $this->entity->show_activationcode_page == 0) {
            return 0;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'show-organization-activation-code-page');
    }

    public function canShowCompleteProfilePage()
    {
        if ($this->entity->show_socialprofile_override == 1 and $this->entity->show_socialprofile == 1) {
            return 1;
        }

        if ($this->entity->show_socialprofile_override == 1 and $this->entity->show_socialprofile == 0) {
            return 0;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'complete-social-profile-page');
    }

    public function canShowFitness()
    {
        if ($this->entity->fitness_access_override == 1 and $this->entity->fitness_access == 1) {
            return 1;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'activate-fitness-step-tracker');
    }

    public function canJoinBusinessApplication()
    {
        if ($this->entity->join_business_access_override == 1 and $this->entity->join_business_access == 1) {
            return 1;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'join-business-application-access');
    }

    public function canHaveCrmAccess()
    {
        if ($this->entity->crm_access_override == 1 and $this->entity->crm_access == 1) {
            return 1;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'crm-access');
    }

    public function canHaveIdhubsAccess()
    {
        if ($this->entity->idhubs_access_override == 1 and $this->entity->idhubs_access == 1) {
            return 1;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'idhubs.com-access');
    }

    public function canHaveIdmartAccess()
    {
        if ($this->entity->idmart_access_override == 1 and $this->entity->idmart_access == 1) {
            return 1;
        }

        return app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'id4mart-access');
    }

    /* Pricing plan features end */

    public function getPlanDetails()
    {
        $plan = app('App\\Repositories\\CommunityPricingPlanRepository')->getByCommunityId($this->entity->id);

        return $plan;
    }

    public function getPricingPlan($plan_id)
    {
        $plan = app('App\\Repositories\\PricingPlansRepository')->getPlanByPlanId($plan_id);

        return $plan;
    }

    public function getCardDetails()
    {
        $card = app('App\\Repositories\\CommunityPricingPlanPaymentCardsRepository')->defaultCard($this->entity->id, $this->entity->user_id, 'community_plan');

        return $card;
    }

    public function canSignInToCommunity($user_id = 0)
    {
        $community = $this->entity;

        if ($community->allow_global_access == 1) {
            return true;
        }

        if ($user_id == $community->user_id) {
            return true;
        }

        $planDetails = $this->entity->present()->getPlanDetails();

        if ($planDetails) {

            if ($planDetails->paid_for_plan == 1) {
                return true;
            } else {

               // if ($planDetails->plan_id == 1) {
                   // return false;
               // } else {
                    $plan = $community->present()->getPricingPlan($planDetails->plan_id);

					if($plan->is_plan_free){
						return true;
					}else{	
						$trialDays = $plan->trial_days;
						$registrationDate = $planDetails->registration_date;
						$trialExpiryDate = date('Y-m-d', strtotime($registrationDate.' + '.$trialDays.'days'));
						$todaysDate = date('Y-m-d');
						$todayStr = strtotime($todaysDate);
						$registrationStr = strtotime($trialExpiryDate);
	
						if ($todayStr <= $registrationStr) {
							return true;
						} else {
							return false;
						}
					}	
               // }
            }
        }

        return false;
    }

    public function memberAddLimit()
    {
        $community = $this->entity;

        /*if($community->allow_global_access==1){
            return 999999999999;
        }*/

        $planDetails = $this->entity->present()->getPlanDetails();
        if ($planDetails) {

            $plan = $community->present()->getPricingPlan($planDetails->plan_id);

            if ($planDetails->paid_for_plan == 1) {
                return $plan->user_limit;
            } else {
                $trialDays = $plan->trial_days;
                $registrationDate = $planDetails->registration_date;
                $trialExpiryDate = date('Y-m-d', strtotime($registrationDate.' + '.$trialDays.'days'));
                $todaysDate = date('Y-m-d');
                $todayStr = strtotime($todaysDate);
                $registrationStr = strtotime($trialExpiryDate);
                if ($todayStr <= $registrationStr) {
                    // return $plan->user_limit;
                }

                return $plan->user_limit;
            }
        }

        return 1;
    }

    public function getAllowedMembersInPlan($selected_plan_id = 0, $newPlanDetails = null)
    {
        $community = $this->entity;

        $increasedLimit = 0;
        $increased = '';
        if ($newPlanDetails) {
            $planDetails = $newPlanDetails;
        } else {
            $planDetails = $this->entity->present()->getPlanDetails();
        }

        if (! $planDetails and $selected_plan_id) {
            $plan = $community->present()->getPricingPlan($selected_plan_id);
            if ($plan) {
                return $plan->user_limit;
            }
        }

        if ($planDetails) {
            // $column_name="increased_member_limit_plan_".$planDetails->plan_id;
            $column_name = 'increased_member_limit';
            $increasedLimit = $community->$column_name;
        }

        if ($community->set_custom_plan_members == 1) {
            return $community->allowed_users_in_plan + $increasedLimit;
        }

        if ($planDetails) {
            $plan = $community->present()->getPricingPlan($planDetails->plan_id);
			if($plan){
            	return $plan->user_limit + $increasedLimit;
			}
        }

        return 1;
    }

    public function getPlanUsersLimit()
    {
        $community = $this->entity;

        $increasedLimit = 0;
        $increased = '';

        $planDetails = $this->entity->present()->getPlanDetails();

        if ($planDetails) {
            $plan = $community->present()->getPricingPlan($planDetails->plan_id);

            return $plan->user_limit + $increasedLimit;
        }

        return 1;
    }
	
	public function getPlanCommunityUsersLimit()
    {
        $community = $this->entity;

        $planDetails = $this->entity->present()->getPlanDetails();

        if ($planDetails) {
            $plan = $community->present()->getPricingPlan($planDetails->plan_id);
			if($plan){
            	return $plan->community_user_limit;
			}	
        }

        return 1;
    }

    public function getIncreasedCorporateUsers()
    {
        $community = $this->entity;
        $increasedLimit = $community->increased_member_limit;

        return $increasedLimit;
    }

    public function allowedMembersInPlan()
    {
        $community = $this->entity;

        $increasedLimit = 0;
        $increased = '';
        $planDetails = $this->entity->present()->getPlanDetails();
        if ($planDetails) {
            // $column_name="increased_member_limit_plan_".$planDetails->plan_id;
            $column_name = 'increased_member_limit';

            $increasedLimit = $community->$column_name;
            if ($increasedLimit) {
                $increased = '& '.$increasedLimit.' increased';
            }
        }

        if ($community->set_custom_plan_members == 1) {
            return $community->allowed_users_in_plan + $increasedLimit." ( $community->allowed_users_in_plan custom $increased )";
        }

        $planDetails = $this->entity->present()->getPlanDetails();
        if ($planDetails) {
            $plan = $community->present()->getPricingPlan($planDetails->plan_id);

            return $plan->user_limit + $increasedLimit." ( $plan->user_limit plan users $increased )";
        }
    }

    public function canAddExtraMembers()
    {
        $canGenerateInvoice = config('can-generate-community-subscription-invoice');
        $generateInvoiceBeforeDays = config('community-subscription-invoice-generate-before-days');

        $community = $this->entity;
        $planDetails = $this->entity->present()->getPlanDetails();
        if ($planDetails) {
            $currentDate = date('Y-m-d');
            $expiryDate = date('Y-m-d', strtotime('-'.$generateInvoiceBeforeDays.' days', strtotime($planDetails->plan_end_date)));

            if ($currentDate < $expiryDate) {
                $plan = $community->present()->getPricingPlan($planDetails->plan_id);
				if($plan){
                	return $plan->can_add_extra_user;
				}	
            }
        }

        return false;
    }

    public function canAddExtraSpace()
    {
        $canGenerateInvoice = config('can-generate-community-subscription-invoice');
        $generateInvoiceBeforeDays = config('community-subscription-invoice-generate-before-days');

        $community = $this->entity;
        $planDetails = $this->entity->present()->getPlanDetails();

        $canIncreaseSpace = 'yes';
        if ($planDetails) {
            $currentDate = date('Y-m-d');
            $expiryDate = date('Y-m-d', strtotime('-'.$generateInvoiceBeforeDays.' days', strtotime($planDetails->plan_end_date)));

            if ($currentDate < $expiryDate) {
                $canIncreaseSpace = 'yes';
            } else {
                $canIncreaseSpace = 'no';
            }
        }

        if ($canIncreaseSpace == 'yes' and config('community-can-purchase-space')) {
            return true;
        } else {
            return false;
        }
    }

    public function extraMembersAddPrice()
    {
        $community = $this->entity;
        $planDetails = $this->entity->present()->getPlanDetails();
        if ($planDetails) {
            $plan = $community->present()->getPricingPlan($planDetails->plan_id);
            if ($plan->can_add_extra_user == 1) {
                return $plan->monthly_price_per_extra_user;
            }
        }

        return 0;
    }

    public function getPricingPlanAmount()
    {
        $community = $this->entity;
        $planDetails = $this->entity->present()->getPlanDetails();
        if ($planDetails) {
            $plan = $community->present()->getPricingPlan($planDetails->plan_id);
            if ($plan) {
                if ($planDetails->plan_type == 'yearly') {
                    return $plan->price_yearly;
                } elseif ($planDetails->plan_type == 'monthly') {
                    return $plan->price_monthly;
                }
            }
        }

        return 0;
    }

    public function canMakeMember()
    {
        $community = $this->entity;

        /*if($community->allow_global_access==1){
            return true;
        }*/

        $increasedLimit = 0;
        $planDetails = $this->entity->present()->getPlanDetails();
        if ($planDetails) {
            // $column_name="increased_member_limit_plan_".$planDetails->plan_id;
            $column_name = 'increased_member_limit';
            $increasedLimit = $community->$column_name;
        }

        // $communityMembers=$community->countMembers()+1;

        $communityMembers = $community->countMembers();
        $memberAddLimit = $community->present()->memberAddLimit();

        if ($community->set_custom_plan_members == 1 and $communityMembers < $community->allowed_users_in_plan + $increasedLimit) {
            return true;
        }

        if ($communityMembers < $memberAddLimit + $increasedLimit) {
            return true;
        }

        return false;
    }

    public function hasCardAdded()
    {
        if ($this->entity->skip_card_dtls == 1 || $this->entity->card_dtls_added == 1 || $this->entity->free_plan_signup == 1 || $this->entity->gift_app_community == 1 || $this->entity->eventmeeting == 1) {
            return true;
        }

        $planDetails = app('App\\Repositories\\PricingPlansRepository')->getPlanByPlanId($this->entity->pricing_plan);
        if ($planDetails and $planDetails->is_plan_free == 1) {
            return true;
        }

        $hasCardAdded = app('App\\Repositories\\CommunityPricingPlanPaymentCardsRepository')->hasCardAdded($this->entity->id, 'community_plan');

        if ($hasCardAdded) {
            return true;
        }

        return false;
    }

    public function getSocialNetworkingBackGroundcolor()
    {
        $community = $this->entity;

        if ($community->use_own_social_networking_background == 1) {
            $colorCode = $community->own_social_networking_background;
        } else {
            $colorCode = $community->social_networking_background;
        }

        return $colorCode;
    }

    public function canAskQuestion()
    {
        if ($this->entity->ai_chat_access_override == 1 and $this->entity->ai_chat_access == 1) {
            return 1;
        }

        $canAccess = app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'ai-chat-access');

        if ($canAccess == 1) {
            return 1;
        }

        return 0;
    }

    public function canUserAskQuestion($type)
    {
        if ($this->entity->ai_chat_access_override == 1 and $this->entity->ai_chat_access == 1) {
            return $this->entity->present()->checkUserCanAskQuestion($type);
        }

        $canAccess = app('App\\Repositories\\PricingFeaturesRepository')->checkFeature($this->entity->pricing_plan, 'ai-chat-access');

        if ($canAccess == 1) {
            return $this->entity->present()->checkUserCanAskQuestion($type);
        }

        return 0;
    }

    public function checkUserCanAskQuestion($type)
    {
        if ($this->entity->present()->isAdmin == 1) {
            return 1;
        } else {
            $member = app('App\\Repositories\\CommunityMemberRepository')->findByUserIdCommunityId(\Auth::user()->id, $this->entity->id);
            if ($member) {
                if ($type == 'internal' and $member->ai_access_internal == 1) {
                    return 1;
                } elseif ($type == 'external' and $member->ai_access_external == 1) {
                    return 1;
                }
            }
        }

        return 0;
    }

    public function getMenuViewStyle()
    {
        $community = $this->entity;
        $homecontents = $community->present()->getHomeContents();

        $menuStyle = 0;
        if ($homecontents and $homecontents->website_header_menu_view == 1) {
            $menuStyle = 1;
        }

        return $menuStyle;
    }

    public function getLogoViewStyle()
    {
        $community = $this->entity;
        $homecontents = $community->present()->getHomeContents();

        $logoStyle = 0;
        if ($homecontents and $homecontents->website_header_logo_position == 1) {
            $logoStyle = 1;
        }

        return $logoStyle;
    }

    public function getActiveAds()
    {
        if ($this->entity->activate_advertisement == 1) {
            $ads = app('App\\Repositories\\CommunityAdvertisementsRepository')->getActiveAds($this->entity->id);

            return $ads;
        }
    }

    public function getFromEmailAddress()
    {
        $mail_from_email = config('site_email');
        $community = $this->entity;
        if ($community->send_email_from and $community->send_email_from_own == 1 and $community->own_email_verified == 1) {
            $mail_from_email = $community->send_email_from;
        }

        return $mail_from_email;
    }

    public function communityGiftAppAccount()
    {
        $communityPayments = app('App\\Repositories\\GiftsAccountCommunityRepository')->getByCommunityId($this->entity->id);

        return $communityPayments;
    }

    public function isAccountSuspended()
    {
        if (\Auth::check()) {

            $account = app('App\\Repositories\\CommunityVisitorsRepository')->findByUidCid(\Auth::user()->id, $this->entity->id);
            if ($account and $account->is_suspended == 1) {
                return true;
            }

            return false;
        }

        return false;
    }

    public function getRideBalance()
    {
        if (\Auth::check()) {

            $account = app('App\\Repositories\\CommunityRideAccountRepository')->getByUserIdCmId($this->entity->id, \Auth::user()->id);
            if ($account and $account->balance) {
                return $account->balance;
            }

            return 0;
        }

        return 0;
    }

    public function unverifiedMembers()
    {
        return app('App\\Repositories\\UserRepository')->communityUnverifiedUsersCount($this->entity->id);
    }

    public function canManageCenter()
    {
        if ($this->entity->race_community == 0) {
            return false;
        }

        if ($this->entity->isOwner()) {
            return false;
        }

        return app('App\\Repositories\\CommunityRideLocationsRepository')->getUserAllLocationsCnt($this->entity->id, \Auth::user()->id);
    }

    public function rideStudentRequestsCount()
    {
        return app('App\\Repositories\\CommunityRideStudentVerificationRepository')->getRequestCountCnt($this->entity->id, \Auth::user()->id);
    }

    public function isRideStudentApplied()
    {
        return app('App\\Repositories\\CommunityRideStudentVerificationRepository')->isRideStudentApplied($this->entity->id, \Auth::user()->id);
    }

    public function checkMenuSettings()
    {
        $setting = app('App\\Repositories\\CommunityMenuSettingsRepository')->getByCommunityId($this->entity->id);

        return $setting;
    }

    public function canViewOutsideDocument($document_id)
    {
        $invite = app('App\\Repositories\\CommunityDocumentsInviteRepository')->findByDocId(\Auth::user()->id, $document_id);
        if ($invite) {
            $currentTime = date('Y-m-d H:i:s');
            $checkDate = date('Y-m-d H:i:s', strtotime($currentTime.' -48 hours'));

            if ($invite->invite_date > $checkDate) {
                return $invite->id;
            }
        }

        return '';
    }

    public function getAllPublishedSubMenus($page_id)
    {
        $subMenus = app('App\\Repositories\\CommunityPagesRepository')->getAllPublishedByMenuId($page_id);

        return $subMenus;
    }

    public function recentCommunityPosts($community_id, $limit)
    {
        $posts = app('App\\Repositories\\PostRepository')->recentCommunityPosts($community_id, $limit);

        return $posts;
    }

    public function recentCommunityEvents($community_id, $limit)
    {
        $posts = app('App\\Repositories\\PostEventsRepository')->recentCommunityEvents($community_id, $limit);

        return $posts;
    }

    public function hasPlanExpired()
    {
        $community = $this->entity;
        $todaysDate = date('Y-m-d');
        $planDetails = $community->present()->getPlanDetails();
        if ($planDetails and $todaysDate > $planDetails->plan_end_date) {
            $pendingInvoice = app('App\\Repositories\\CommunityInvoiceRepository')->pendingSubscriptionInvoice($community->id);
            if($pendingInvoice) {
                $url = \URL::route('cm-subscription-invoice', ['slug' => $community->id, 'type' => 'plans_invoice', 'id' => $pendingInvoice->id]);

                return $url;
            }
        }

        return false;
    }

    public function hasExpiredCommunity()
    {
        $community = $this->entity;

        $currentSection = \Request::segment(3);

        $hasCardAdded = app('App\\Repositories\\CommunityPricingPlanPaymentCardsRepository')->getCommunityCardDetailsById($community->id);

        $todaysDate = date('Y-m-d');

		$planDetails = $community->present()->getPlanDetails();

        $appBaseUrl = rtrim((string) config('app.url'), '/');
        if ($appBaseUrl === '') {
            $appBaseUrl = rtrim((string) \URL::to('/'), '/');
        }

        $homeUrl = $appBaseUrl . '/home';
        $userCommunitiesUrl = $appBaseUrl . '/usercommunities';
        $signupUrl = $appBaseUrl . '/usersignup';

        // If request is on a different domain than APP_URL, use /cmownpage for SSO.
        $shouldUseCmOwnPage = false;
        try {
            $appHost = parse_url($appBaseUrl, PHP_URL_HOST);
            $reqHost = \Request::getHost();
            if (! empty($appHost) && ! empty($reqHost) && strcasecmp($appHost, $reqHost) !== 0) {
                $shouldUseCmOwnPage = true;
            }
        } catch (\Throwable $e) {
            $shouldUseCmOwnPage = false;
        }

        $wrapAppRedirect = function (string $targetUrl) use ($appBaseUrl, $shouldUseCmOwnPage) {
            if (! $shouldUseCmOwnPage || ! \Auth::check()) {
                return $targetUrl;
            }

            $user = \Auth::user();
            return $appBaseUrl . '/cmownpage?reset_vc=1&lgkey=' . $user->login_key . '&lgurl=' . urlencode($targetUrl);
        };

        $planExpired = false;
        if ($planDetails && ! empty($planDetails->plan_end_date) && $planDetails->plan_end_date !== '0000-00-00') {
            $planExpired = ($todaysDate > $planDetails->plan_end_date);
        }

        // Payment plan pages should be accessible to the community owner.
        // Non-owners must never access payment screens.
		
		if(!\Auth::check()){
			return false;
		}
		
		// if (\Auth::check() && ! $community->isOwner()){
		
        if ((\Request::segment(1)=="coupon" and \Request::segment(2)=="validate") || in_array($currentSection, ['communitypaymentplans', 'communitypaymentaddmethod', 'makeplanpayment','payingforplan'], true)) {
            // Never allow non-owners to access payment screens.
            if (\Auth::check() and !$community->isOwner()) {
                //return rtrim(config('app.url'), '/') . '/home';
				
				$user = \Auth::user();
				$user->visiting_community = 0;
				$user->save();

				\Session::forget('theCommunityId');
				\Session::forget('community_url');
				\Session::forget('cm_path');
						
                return $wrapAppRedirect($homeUrl);
            }

            // Owners can view payment/plan screens at any time (before or after trial end).
            if ($community->isOwner()) {
                return false;
            }

            $trialExpiredWithoutCard = false;

            if (! $hasCardAdded && $planDetails && $planDetails->plan_end_date === '0000-00-00') {
                $pln = app('App\\Repositories\\PricingPlansRepository')->getPlanByPlanId($planDetails->plan_id);
                if ($pln && (int) $pln->is_plan_free !== 1) {
                    $trialDays = (int) ($pln->trial_days ?? 0);
                    $signupDate = $planDetails->registration_date ?? null;

                    if ($trialDays > 0 && ! empty($signupDate)) {
                        try {
                            $trialEndDate = new \DateTime($signupDate);
                            $trialEndDate->modify('+' . $trialDays . ' days');
                            $trialEndDateStr = $trialEndDate->format('Y-m-d');
                            $trialExpiredWithoutCard = ($todaysDate >= $trialEndDateStr);
                        } catch (\Throwable $e) {
                            $trialExpiredWithoutCard = false;
                        }
                    }
                }
            }
			
			$cutsomTrialDays=$community->trial_days;
			$CustomTrailStartDate=$community->trial_start_date;
		
			if($cutsomTrialDays!=0 and $CustomTrailStartDate!= '0000-00-00'){
				$customTrailEnddate=date('Y-m-d', strtotime($CustomTrailStartDate. ' + '.$cutsomTrialDays.'days'));
				if ($customTrailEnddate > $todaysDate) {
					 $trialExpiredWithoutCard=($todaysDate >= $customTrailEnddate);	
				}
			}

            if ($trialExpiredWithoutCard || $planExpired) {
                return false;
            }

            return $community->present()->url();
        }

        if ($hasCardAdded) {
		
			if ($community->skip_card_dtls == 1 and $community->skip_card_till_date != '0000-00-00'){
				$endingDate = $community->skip_card_till_date;
                if ($endingDate > $todaysDate) {
					return false;
				}
			}
			
			$cutsomTrialDays=$community->trial_days;
			$CustomTrailStartDate=$community->trial_start_date;
		
			if($cutsomTrialDays!=0 and $CustomTrailStartDate!= '0000-00-00'){
				$customTrailEnddate=date('Y-m-d', strtotime($CustomTrailStartDate. ' + '.$cutsomTrialDays.'days'));
				if ($customTrailEnddate > $todaysDate) {
					 return false;	
				}
			}
				
		
            if ($community->card_dtls_added == 0) {
                $community->card_dtls_added = 1;
                $community->save();
            }
			
			if($planDetails){

				if ($planDetails->stop_payment == 1) {
					return false;
				}
				
				$pln = app('App\\Repositories\\PricingPlansRepository')->getPlanByPlanId($planDetails->plan_id);
				if($pln){
					$trial_days=$pln->trial_days;
					$signup_date=$planDetails->registration_date;
					
					$trial_end_date = new \DateTime($signup_date);        // today
					$trial_end_date->modify('+'.$trial_days.' days');     // add 10 days
					$trial_end_date=$trial_end_date->format('Y-m-d');
					
					if($pln->is_plan_free == 1){
						return false;
					}else{
                        // Card is already added; do not force payment plan page.
                        if($planDetails->plan_end_date=='0000-00-00' and $todaysDate > $trial_end_date){
                            return false;
                        }
						
						if($planDetails->plan_end_date=='0000-00-00' and $trial_end_date > $todaysDate){
							return false;
						}
					}	
				}
	
				if($todaysDate > $planDetails->plan_end_date) {
                    // Only treat as expired subscription when a real plan_end_date exists.
                    if ($planDetails->plan_end_date == '0000-00-00') {
                        return false;
                    }

					if (\Auth::check()) {
						$user = \Auth::user();
						$user->visiting_community = 0;
						$user->save();

                        \Session::forget('theCommunityId');
                        \Session::forget('community_url');
                        \Session::forget('cm_path');
	
                            if ($community->isOwner()) {
                                return $wrapAppRedirect($userCommunitiesUrl);
                            }

                            return $wrapAppRedirect($homeUrl);
					} else {
                            return $signupUrl;
					}
				}
			}	

            return false;
        } else {
            // Plan expired with a real end date but there is no stored card.
            if ($planExpired) {
                if (\Auth::check()) {
                    if ($community->isOwner()) {
                        $invoiceUrl = $community->present()->hasPlanExpired();
                        if ($invoiceUrl) {
                            return $invoiceUrl;
                        }

                        return $community->present()->url('communitypaymentplans');
                    }

                    $user = \Auth::user();
                    $user->visiting_community = 0;
                    $user->save();

                    \Session::forget('theCommunityId');
                    \Session::forget('community_url');
                    \Session::forget('cm_path');

                    return $wrapAppRedirect($homeUrl);
                }

				return $signupUrl;
            }
			
			
			$cutsomTrialDays=$community->trial_days;
			$CustomTrailStartDate=$community->trial_start_date;
		
			if($community->skip_card_dtls == 0 and $cutsomTrialDays!=0 and $CustomTrailStartDate!= '0000-00-00'){
				$customTrailEnddate=date('Y-m-d', strtotime($CustomTrailStartDate. ' + '.$cutsomTrialDays.'days'));
				if ($todaysDate > $customTrailEnddate) {
					 if (\Auth::check()) {
						$user = \Auth::user();
						$user->visiting_community = 0;
						$user->save();

						if($community->isOwner()){
							 return $community->present()->url('communitypaymentplans');
						}

						return $wrapAppRedirect($homeUrl);
					} else {
						return $signupUrl;
					}
				}
			}else{

				if ($community->skip_card_dtls == 1 and $community->skip_card_till_date != '0000-00-00') {
					$endingDate = $community->skip_card_till_date;
	
					if ($todaysDate > $endingDate) {
						if (\Auth::check()) {
							$user = \Auth::user();
							$user->visiting_community = 0;
							$user->save();
	
							if ($community->isOwner()) {
								 return $community->present()->url('communitypaymentplans');
							   // return $wrapAppRedirect($userCommunitiesUrl);
							}
	
							return $wrapAppRedirect($homeUrl);
						} else {
							return $signupUrl;
						}
					}
				}else{
					if($planDetails){
						$pln = app('App\\Repositories\\PricingPlansRepository')->getPlanByPlanId($planDetails->plan_id);
						if($pln){
							if($pln->is_plan_free == 1){
								return false;
							}else{
								$trial_days=$pln->trial_days;
								$signup_date=$planDetails->registration_date;
							
								$trial_end_date = new \DateTime($signup_date);        // today
								$trial_end_date->modify('+'.$trial_days.' days');     // add 10 days
								$trial_end_date=$trial_end_date->format('Y-m-d');
								
								//dd($community->id);
								
								if($planDetails->plan_end_date=='0000-00-00' and $todaysDate >= $trial_end_date){
									if (\Auth::check()) {
										if ($community->isOwner()) {
											return $community->present()->url('communitypaymentplans');
										}
		
										// Members should not be sent to the community payment page.
										$user = \Auth::user();
										$user->visiting_community = 0;
										$user->save();
		
										\Session::forget('theCommunityId');
										\Session::forget('community_url');
										\Session::forget('cm_path');
		
										$currentPath = ltrim(\Request::path(), '/');
									
										return $wrapAppRedirect($homeUrl);
										
									}
										return $signupUrl;
								}
								
								if($planDetails->plan_end_date=='0000-00-00' and $trial_end_date > $todaysDate){
									return false;
								}
							}	
						}
					}	
				}	
			}
        }

        return false;
    }
	
	public function showTrialEnding()
	{
        $community = $this->entity;

        $planDetails = $community->present()->getPlanDetails();
        if (! $planDetails) {
            return false;
        }

        $pln = app('App\\Repositories\\PricingPlansRepository')->getPlanByPlanId($planDetails->plan_id);
        if (! $pln) {
            return false;
        }

        if ((int) $pln->is_plan_free === 1) {
            return false;
        }

        // Only show during trial (not paid yet)
        if (isset($planDetails->paid_for_plan) && (int) $planDetails->paid_for_plan === 1) {
            return false;
        }

        // If ANY card is saved, no need to show this message.
        // (getCommunityCardDetailsById() only returns the *default* card.)
        $hasAnyCard = app('App\\Repositories\\CommunityPricingPlanPaymentCardsRepository')->hasCardAdded($community->id, 'community_plan');
        if ($hasAnyCard) {
            return false;
        }

        $trialDays = (int) ($pln->trial_days ?? 0);
        $registrationDate = $planDetails->plan_start_datetime ?? null;
        if ($trialDays <= 0 || empty($registrationDate)) {
            return false;
        }

        try {
            $trialEndsAt = \Carbon\Carbon::parse($registrationDate)->addDays($trialDays);
        } catch (\Throwable $e) {
            return false;
        }

        $remainingSeconds = \Carbon\Carbon::now()->diffInSeconds($trialEndsAt, false);
        if ($remainingSeconds <= 0) {
            return false;
        }

        // Show only in the final 24 hours
        if ($remainingSeconds > 24 * 60 * 60) {
            return false;
        }

        $paymentUrl = $community->present()->url('communitypaymentaddmethod');
        $trialEndsAtIso = $trialEndsAt->toIso8601String();

        return '<div class="text-center trial-ending-alert" style="margin-bottom: 10px; padding:10px; color:#f00; font-size:16px;" data-trial-ends-at="'.e($trialEndsAtIso).'">'
            .'Trial ending in <span class="trial-ending-countdown"></span>. '
            .'<a href="'.e($paymentUrl).'" style="color:#f00; font-size:16px; font-weight:bold;">Click here to add your card.</a>'
            .'</div>';
	}

    public function getPaymentByDateMonth($community_id, $date_1)
    {
        return app('App\Repositories\\CommunityPricingPlanPaymentRepository')->getByTypeMonth($community_id, $date_1);
    }

    public function getSubscriptionInvoice($community_id, $id)
    {
        return app('App\Repositories\\CommunityInvoiceRepository')->getSubscriptionInvoice($community_id, $id);
    }

    public function getCmSubscriptionInvoice($community_id, $id)
    {
        return app('App\Repositories\\CommunityInvoiceRepository')->getCmSubscriptionInvoice($community_id, $id);
    }

    public function getDefaultCard($community_id)
    {
        return app('App\\Repositories\\CommunityPricingPlanPaymentCardsRepository')->getCommunityCardDetailsById($community_id);
    }

    public function getCmPlanDetails($community_id)
    {
        return app('App\\Repositories\\CommunityPricingPlanRepository')->getByCommunityId($community_id);
    }

    public function getSubscriptionTotal($community_id, $selected_year, $month)
    {
        return app('App\\Repositories\\CommunityPricingPlanPaymentRepository')->getSubscriptionTotalAll($community_id, $selected_year, $month);
    }

    public function getCashTotalByMonth($community_id, $selected_year, $month)
    {
        return app('App\\Repositories\\GiftsLoadAccountRepository')->getCashTotalByMonth($community_id, $selected_year, $month);
    }

    public function getPaymentTotalByMonth($community_id, $selected_year, $month)
    {
        return app('App\\Repositories\\PostEventsPaymentRepository')->getPaymentTotalByMonth($community_id, $selected_year, $month);
    }

    public function getEcomPaymentTotalByMonth($community_id, $selected_year, $month)
    {
        return app('App\\Repositories\\BusinessProductsOrdersRepository')->getPaymentTotalByMonth($community_id, $selected_year, $month);
    }

    public function totalAllocatedSpace()
    {
        $community = $this->entity;
        $purchased_space_in_mb = $community->purchased_space_in_mb * 1073741824;
        $allocated_space = $community->allocated_space + $purchased_space_in_mb;

		$plan_space=0;
		$plan = $this->entity->present()->getPricingPlan($this->entity->pricing_plan);
		if($plan){
		    //dd($plan->space_for_corporate);
			//return $plan->space_for_corporate;
			if($plan->space_for_corporate){
				$plan_space=$plan->space_for_corporate * 1024 * 1024 * 1024;
				//dd($plan_space);
			}	
		}
		
		$allocated_space = $community->allocated_space + $purchased_space_in_mb+$plan_space;
		
        return $allocated_space;
    }

    public function getEventsForCalendar()
    {
        $community = $this->entity;
        $event_posts = app('App\\Repositories\\PostRepository')->getAllEvents($community->id);

        $calendarEventsList = [];
        if ($event_posts) {
            foreach ($event_posts as $post) {
                if ($post->present()->canViewPagePost() and $post->present()->canShow()) {
                    $event = $post->present()->getEvent();
                    if ($event and $event->fund_nature == 0) {
                        $color = '#000';
                        $startTime = $event->starttime;
                        $endTime = $event->endtime;

                        $startTimeFormated = date('Y-m-d H:i', strtotime($startTime));
                        $endTimeFormated = date('Y-m-d H:i', strtotime($endTime));

                        $calendarEventsList[] = [
                            'title' => $event->subject,
                            'start' => $startTimeFormated,
                            'end' => $endTimeFormated,
                            'color' => $color,
                            'url' => $post->present()->communityPostUrl(),
                        ];

                    }
                }
            }
        }

        $datesEvent = json_encode($calendarEventsList, true);

        return $datesEvent;
    }

    public function canCategoryRSSAccess($category)
    {
        if ($this->entity->rss_access == 1 and $category->rss_access == 1) {
            return 1;
        }

        return 0;
    }

    public function canCommunityRSSAccess()
    {
        if ($this->entity->rss_access == 1) {
            return 1;
        }

        return 0;
    }

    public function getCommunityCategoryById($category_id)
    {
        $category = app('App\\Repositories\\CommunityCategoryRepository')->get($category_id);

        return $category;
    }

    public function getCommunityCategoryByIdCm($category_id, $community_id)
    {
        $category = app('App\\Repositories\\CommunityCategoryRepository')->get($category_id, $community_id);

        return $category;
    }

    public function getCommunityById($community_id)
    {
        $community = app('App\\Repositories\\CommunityRepository')->getById($community_id);

        return $community;
    }

    public function getMatchingEventsById($event_id)
    {
        $events = app('App\\Repositories\\PostEventsMatchingFundsRepository')->getByUserEvent(\Auth::user()->id, $event_id);

        return $events;
    }

    public function getMatchingEventsByEventId($event_id)
    {
        $events = app('App\\Repositories\\PostEventsMatchingFundsRepository')->getAllByEventId($event_id);

        return $events;
    }

    public function getEventAmountCollected($event_id)
    {
        $events = app('App\\Repositories\\PostEventsPaymentRepository')->crowdFundingAmountCollected($event_id);

        return $events;
    }

    public function getEventPaymentByPayId($payment_id)
    {
        $payment = app('App\\Repositories\\PostEventsPaymentRepository')->getByPaymentId($payment_id);

        return $payment;
    }

    public function getMyEventsRecurringByIdCount($community_id, $recurring_event_id)
    {
        return app('App\\Repositories\\PostEventsRepository')->getMyEventsRecurringByIdCount($community_id, $recurring_event_id);
    }

    public function getEventAgendaById($event_id)
    {
        $agenda = app('App\\Repositories\\PostEventsAgendaRepository')->getByEventId($event_id);

        return $agenda;
    }

    public function isRssCategoryVisible($category_id)
    {
        $categoryData = $this->entity->default_rss_categories;

        if (empty($categoryData)) {
            return true;
        }

        // Functions are now autoloaded via composer.json

        $data = perfectUnserialize($categoryData);
        if (isset($data[$category_id]) and $data[$category_id] == 0) {
            return false;
        }

        return true;
    }

    public function getRssCategoryFeeds($category_id)
    {
        $feeds = app('App\\Repositories\\RssFeedsDefaultListsRepository')->getByCategoryAll($category_id);

        return $feeds;
    }

    public function hasRssCategoryFeedAdded($category_id, $feed_id)
    {
        $feed = app('App\\Repositories\\RssFeedsRepository')->hasRssCategoryFeedAdded($this->entity->id, $category_id, $feed_id);

        return $feed;
    }

    public function getTodaysTaskUpdate($community_id, $task_id)
    {
        $update = app('App\\Repositories\\CommunityTaskManagementUpdatesRepository')->getTodaysTaskUpdate($community_id, $task_id);

        return $update;
    }

    public function isExpCategoryDeactivated($community_id, $catgory_id)
    {
        $category = app('App\\Repositories\\ExperienceCategoriesRepository')->isExpCategoryDeactivated($community_id, $catgory_id);

        return $category;
    }

    public function getMainLang($language_var)
    {
        return app('App\\Repositories\\LanguageRepository')->findByVar($language_var);
    }

    public function publicPostsAll($community)
    {
        return app('App\\Repositories\\PostRepository')->pluck('community-'.$community->id, 0, null, null, null, null, 'latestnews', null, 'dashboard');
    }

    public function findByIdUsername($user_id)
    {
        return app('App\\Repositories\\UserRepository')->findByIdUsername($user_id);
    }

    public function getBusinessPage($id)
    {
        return app('App\\Repositories\\PageRepository')->getById($id);
    }

    public function hasVotedByFormCategory($category_id)
    {
        return app('App\\Repositories\\CommunityFormsAnswersVotingRepository')->getByIpCategory($category_id);
    }

    public function getSocialFeedsDetails($community_id)
    {
        return app('App\\Repositories\\CommunitySocialFeedRepository')->getByCommunityId($community_id);
    }

    public function getPageMenu($menu_id)
    {
        return app('App\\Repositories\\CommunityPagesRepository')->getById($menu_id);
    }

    public function getPostById($post_id)
    {
        return app('App\\Repositories\\PostRepository')->getById($post_id);
    }

    public function getEventById($event_id)
    {
        return app('App\\Repositories\\PostEventsRepository')->getById($event_id);
    }

    public function postNextEventsByDateFundNature($community_id, $limit = 0)
    {
        return app('App\\Repositories\\PostEventsRepository')->postNextEventsByDateFundNature($community_id, $limit);
    }

    public function publicPostsByCategory($category_id)
    {
        return app('App\\Repositories\\PostRepository')->pluck('communitycategory-'.$category_id, 0, null, null, null, null, 'externalnews', null, 'dashboardlatest');
    }

    public function getSocialMediafeeds($community)
    {
        return app('App\\Repositories\\PostRepository')->getSocialMediafeeds($community->user_id, $community->id, 3);
    }

    public function hasLanguageSet($language_var, $community_id)
    {
        return app('App\\Repositories\\CommunityLanguagesRepository')->findByVar($language_var, $community_id);
    }

    public function getBankDetails($community_id, $tp = 0)
    {
        return app('App\\Repositories\\GiftsBankDetailsRepository')->getById($community_id, $tp);
    }

    public function crmTotalPaymentReceived($community_id)
    {
        return app('App\\Repositories\\CrmPaymentsRepository')->crmToTalPaymentReceived($community_id);
    }

    public function crmToTalPaymentDue($community_id)
    {
        return app('App\\Repositories\\CrmInvoicesRepository')->crmToTalPaymentDue(['type' => 'sum', 'status' => 'due'], $community_id);
    }

    public function crmToTalPaymentCashout($community_id)
    {
        return app('App\\Repositories\\CrmPaymentsCashoutRepository')->crmToTalPaymentCashout($community_id);
    }

    public function getPaymentSettings($community_id)
    {
        return app('App\\Repositories\\CommunityPaymentSettingRepository')->getByCmId($community_id);
    }

    public function getAssignedEventsTotal()
    {
        return app('App\\Repositories\\PostEventsMatchingFundsRepository')->getAssignedEventsTotal();
    }

    public function getEventPaymentById($payment_id)
    {
        return app('App\\Repositories\\PostEventsPaymentRepository')->getByPaymentId($payment_id);
    }

    public function hasInvitedForEvent($event_id, $user_id)
    {
        return app('App\\Repositories\\InvitedMemberRepository')->exists('eventpost', $event_id, $user_id);
    }

    public function getSubscriptionTotalByMonth($community_id, $date)
    {
        return app('App\Repositories\\CommunityPricingPlanPaymentRepository')->getSubscriptionTotalByMonth($community_id, $date);
    }

    public function getMyAllGifts($community_id, $user_id)
    {
        return app('App\\Repositories\\GiftsRepository')->getMyAllGifts($community_id, $user_id);
    }

    public function getCommunityCategoryMembers($community_id, $category_id)
    {
        return app('App\\Repositories\\CommunityCategoryMembersRepository')->listUsers($community_id, $category_id, 3);
    }

    public function getBusinessProductsOrders($product_id, $order_id)
    {
        return app('App\\Repositories\\BusinessProductsOrdersRepository')->getByProductIdSuccess($product_id, $order_id);
    }

    public function findByCommunityBusinessName($community_id, $answer)
    {
        return app('App\\Repositories\\PageRepository')->findByCommunityBusinessName($community_id, $answer);
    }

    public function getFormsReports($data_id, $userId)
    {
        return app('App\\Repositories\\CommunityFormsReportsRepository')->getByUserReportId($data_id, $userId);
    }

    public function getVisitorsPagesByUserDate($community_id, $user_id, $visitor_ip, $viewdate)
    {
        return app('App\\Repositories\\SiteVisitorsRepository')->getPagesByUserDate($community_id, $user_id, $visitor_ip, $viewdate);
    }

    public function visitorsCountPageViews($community_id, $viewdate, $page_complete_url)
    {
        return app('App\\Repositories\\SiteVisitorsRepository')->countPageViews($community_id, $viewdate, $page_complete_url);
    }

    public function visitorsGetUserId($community_id, $visitor_ip, $viewdate)
    {
        return app('App\\Repositories\\SiteVisitorsRepository')->getUserId($community_id,$visitor_ip,$viewdate);
    }
	
	public function getRecentUnreadPosts()
	{	   
		return app('App\\Repositories\\PostSeenRepository')->getRecentUnreadPosts($this->entity->id);
	}
	
	public function getTasksCount()
	{		
		$tasks = app('App\\Repositories\\CommunityTaskManagementRepository')->getTasksCount($this->entity->id);		
		return $tasks;
	}
	
	public function getTasksCountByPriority($pr)
	{		
		$tasks = app('App\\Repositories\\CommunityTaskManagementRepository')->getTasksCountByPriority($this->entity->id,$pr);		
		return $tasks;
	}
	
	public function isInfluencer($user_id,$community_id)
	{
		$influencer = app('App\\Repositories\\CommunityInfluencersRepository')->exist($user_id,$community_id);		
		return $influencer;
	}
	
	public function totalCommunityMembers()
	{
        $communityId = (int) ($this->entity->id ?? 0);
        if ($communityId <= 0) {
            return 0;
        }

        try {
            $ownerUserId = (int) ($this->entity->user_id ?? 0);

            $membersTable = (new \App\Models\CommunityMember())->getTable();
            $usersTable = (new \App\Models\User())->getTable();

            $memberIds = DB::table($membersTable)
                ->select('user_id')
                ->where('community_id', '=', $communityId);

            $signupIds = DB::table($usersTable)
                ->selectRaw('id as user_id')
                ->where('community_signup', '=', $communityId);

            $union = $memberIds->union($signupIds);
            if ($ownerUserId > 0) {
                $union = $union->union(DB::query()->selectRaw('? as user_id', [$ownerUserId]));
            }

            return (int) DB::query()->fromSub($union, 'u')->distinct()->count('user_id');
        } catch (\Throwable $e) {
            // Fallback to PHP approach if DB union/subquery fails for any reason.
            $uiIds = [(int) ($this->entity->user_id ?? 0)];
            $getCommunityMembersIds = app('App\\Repositories\\CommunityMemberRepository')->getUserIds($communityId);
            $communitySignupIds = app('App\\Repositories\\UserRepository')->getAllCommunitySignUpUsersIds($communityId);

            $allUsrs = array_values(array_unique(array_filter(array_map('intval', array_merge($uiIds, $getCommunityMembersIds, $communitySignupIds)))));
            return count($allUsrs);
        }
	}
	
	public function totalInternalMembers()
	{
        $communityId = (int) ($this->entity->id ?? 0);
        if ($communityId <= 0) {
            return 0;
        }

		$membersTable = (new \App\Models\CommunityMember())->getTable();           

		$memberCount = DB::table($membersTable)
			->where('community_id', '=', $communityId)
			->count('user_id');

            
        return (int) $memberCount + 1;
	}
	
	public function isChamberCommunity()
	{
		return true;
	
		$selectedPlanDetails=app('App\\Repositories\\PricingPlansRepository')->getPlanByPlanId($this->entity->pricing_plan);	
		
		if($this->entity->is_chamber_community==1){
			return true;
		}
		
		if($selectedPlanDetails){
			$pricing_plan_type=$selectedPlanDetails->plan_type;
			if($pricing_plan_type=='chamber'){
				return true;
			}
		}
		
		return false;
	}
}