<?php

namespace App\Repositories;
use Illuminate\Support\Str;

use App\Models\Community;
use Illuminate\Events\Dispatcher;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Mail\Mailer;
use Illuminate\Support\Facades\Cache;

class CommunityRepository
{
    public function __construct(
        Community $community,
        CommunityMemberRepository $communityMemberRepository,
        NotificationReceiverRepository $notificationReceiverRepository,
        MustAvoidUserRepository $mustAvoidUserRepository,
        NotificationRepository $notificationRepository,
        CommunityMembersEmailsRepository $communityMembersEmailsRepository,
        UserRepository $userRepository,
        InvitedMemberRepository $invitedMemberRepository,
        CommunityCategoryMembersRepository $communityCategoryMembersRepository,
        CommunityHomeContentsRepository $communityHomeContentsRepository,
        CommunityCategoryRepository $communityCategoryRepository,
        CommunitySpaceUsedRepository $communitySpaceUsedRepository,
        CommunityPricingPlanRepository $communityPricingPlanRepository,
        // PricingPlansRepository $pricingPlansRepository,
        Filesystem $filesystem,
        Dispatcher $event,
        Mailer $mailer
    ) {
        $this->model = $community;
        $this->memberRepository = $communityMemberRepository;
        $this->notificationReceiver = $notificationReceiverRepository;
        $this->mustAvoidUserRepository = $mustAvoidUserRepository;
        $this->notification = $notificationRepository;
        $this->communityMembersEmailsRepository = $communityMembersEmailsRepository;
        $this->userRepository = $userRepository;
        $this->invitedMemberRepository = $invitedMemberRepository;
        $this->communityCategoryMembersRepository = $communityCategoryMembersRepository;
        $this->communityHomeContentsRepository = $communityHomeContentsRepository;
        $this->communityCategoryRepository = $communityCategoryRepository;
        $this->communitySpaceUsedRepository = $communitySpaceUsedRepository;
        $this->communityPricingPlanRepository = $communityPricingPlanRepository;
        // $this->pricingPlansRepository=$pricingPlansRepository;
        $this->file = $filesystem;
        $this->event = $event;
        $this->mailer = $mailer;
    }

    /**
     * Method to create a community
     *
     * @param  array  $val
     * @return bool
     */
    public function create($val, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $expected = [
            'public_name' => '',
            'private_name' => '',
            'can_post' => '',
            'searchable' => '',
            'privacy' => 1,
            'public_url',
            'private_url',
            'public_moderator_action' => 1,
            'private_moderator_action' => 1,
        ];

        /**
         * @var $public_name
         * @var $private_name
         * @var $can_post
         * @var $searchable
         * @var $privacy
         * @var $public_url
         * @var $private_url
         */
        extract(array_merge($expected, $val));

        $name = ($privacy == 1) ? $public_name : $private_name;

        if (empty($name)) {
            return false;
        }

        $community = $this->model->newInstance();
        $community->title = sanitizeText($name, 100);
        $community->user_id = $userid;
        $community->privacy = sanitizeText($privacy);

        if ($privacy == 1) {
            $community->can_post = sanitizeText($can_post);
            $community->can_join = 1;
            $community->can_invite = 1;
            $community->searchable = 1;
            $community->slug = $public_url;
            $community->moderator_action_required = $public_moderator_action;
        } else {
            $community->can_post = 1;
            $community->can_invite = 1;
            $community->can_join = 0;
            $community->searchable = sanitizeText($searchable);
            $community->slug = $private_url;
            $community->moderator_action_required = $private_moderator_action;
        }
        $community->save();

        /**
         * Add this user to the notification receivers for this community

        /**
         * Add this user to the notification receivers for this community
         */
        $this->notificationReceiver->add($userid, 'community', $community->id);

        $this->event->dispatch('community.add', [$community]);

        return $community;
    }

    /**
     * Method to save community
     *
     * @param  array  $val
     * @param  \App\Models\Community  $community
     * @return bool
     */
    public function save($val, $community)
    {
        $expected = [
            'privacy' => '',
            'description' => '',
            'title' => '',
            'can_post' => '',
            'can_invite' => '',
            'searchable' => '',
            'info' => [],
            'moderator_action' => '',
        ];

        /**
         * @var $description
         * @var $title
         * @var $can_post
         * @var $can_invite
         * @var $searchable
         * @var $info
         */
        extract(array_merge($expected, $val));

        $community->privacy = sanitizeText($privacy);

        $community->description = \Hook::fire('filter-text', sanitizeText($description));
        $community->can_post = sanitizeText($can_post);
        $community->can_invite = sanitizeText($can_invite);
        $community->searchable = sanitizeText($searchable);
        $community->info = perfectSerialize($info);
        $community->title = sanitizeText($title);
        $community->moderator_action_required = sanitizeText($moderator_action);
        $community->save();

        return true;
    }

    public function adminSave($val, $community)
    {
        // if (\Auth::user()->id != 1) return false;
        $expected = [
            'description' => '',
            'title' => '',
            'type' => '',
            'searchable' => '',
            'moderator_action' => '',
            'domain' => '',
            'moderator_action_event' => '',
            'domain_activated' => '',
            'allocated_space' => '',
            'pricing_plan' => 1,
            'contest_access' => 0,
            'gift_app_community' => 0,
            'skip_card_dtls' => 0,
            'show_main_footer' => 1,
            'idhubs_commission' => '',
            'take_payment_in_own_account' => 0,
            'idhubs_commission_croud' => 0,
            'activate_advertisement' => 0,
            'stripe_charge' => 0,
            'stripe_connect_acc_id' => '',
            'stripe_fees' => 0,
            'special_plan_access' => 0,
            'gift_collection_sequence' => 0,
            'race_community' => 0,
            'stripe_charges_add' => 0,
            'job_community' => 0,
            'take_community_payment_in_own_account' => 0,
            'app_version' => '',
            'show_main_footer_inside' => 1,
            'set_custom_plan_members' => 0,
            'allowed_users_in_plan' => 0,
            'ai_chatbox' => '',
            'pricing_plan' => '',
            'skip_card_till_date' => '',
			'trial_start_date' => '',
			'trial_days' => 0,
            'show_ai_chatbox' => '',
            'rss_access' => '',
            'enable_share_experience' => '',
            'theme_template_allowed' => 0,
            'subscription_discount_percent' => '',
        ];

        /**
         * @var $description
         * @var $title
         * @var $can_post
         * @var $searchable
         * @var $info
         */
        extract(array_merge($expected, $val));

        /* $community->description = \Hook::dispatch('filter-text', sanitizeText($description)); */
        $community->searchable = $searchable;
        $community->title = $title;
        $community->privacy = $type;
        $community->moderator_action_required = $moderator_action;
        $community->moderator_action_required_event = sanitizeText($moderator_action_event);
        $community->domain_name = $domain;
        $community->domain = $domain_activated;
        $community->pricing_plan=$pricing_plan;

        $community->contest_access = $contest_access;

        if ($allocated_space > 0) {
            $community->allocated_space = $allocated_space * 1048576;
        } else {
            $community->allocated_space = 0;
        }

        if (! $stripe_charge) {
            $stripe_charge = 0;
        }

        if (! $stripe_fees) {
            $stripe_fees = 0;
        }
		
		if($pricing_plan){			
			$community->free_plan_signup = 1;
		}

        $planDetails = $community->present()->getPlanDetails();
        if ($planDetails) {
            $planDetails->plan_id = $pricing_plan;
            $planDetails->save();
        } else {
            $this->communityPricingPlanRepository->savePlan($community->id, $community->user_id, $pricing_plan, 'yearly');

            $planDetails = $community->present()->getPlanDetails();
            if ($planDetails) {
                $planDetails->registration_date = date('Y-m-d', strtotime($community->created_at));
                $planDetails->save();
            }
        }

        $community->gift_app_community = $gift_app_community;
        $community->skip_card_dtls = $skip_card_dtls;

        // Trial settings apply only when skip-card is disabled.
        if ((int) $skip_card_dtls === 0) {
            if (! empty($trial_start_date)) {
                $community->trial_start_date = $trial_start_date;
            }
            $community->trial_days = (int) ($trial_days ?? 0);
        } else {
            $community->trial_start_date = '0000-00-00';
            $community->trial_days = 0;
        }

        $community->show_main_footer = $show_main_footer;
        $community->show_main_footer_inside = $show_main_footer_inside;
        $community->idhubs_commission = $idhubs_commission;
        $community->take_payment_in_own_account = $take_payment_in_own_account;
        $community->idhubs_commission_croud = $idhubs_commission_croud;
        $community->activate_advertisement = $activate_advertisement;
        $community->stripe_charge = $stripe_charge;
        $community->stripe_connect_acc_id = $stripe_connect_acc_id;
        $community->stripe_fees = $stripe_fees;
        $community->special_plan_access = $special_plan_access;
        $community->gift_collection_sequence = $gift_collection_sequence;
        $community->race_community = $race_community;
        $community->stripe_charges_add = $stripe_charges_add;
        $community->job_community = $job_community;
        $community->take_community_payment_in_own_account = $take_community_payment_in_own_account;
        $community->app_version = $app_version;
        $community->set_custom_plan_members = $set_custom_plan_members;
        $community->allowed_users_in_plan = $allowed_users_in_plan;
        $community->ai_chatbox = $ai_chatbox;
        $community->show_ai_chatbox = $show_ai_chatbox;
        $community->rss_access = $rss_access;
        $community->enable_share_experience = $enable_share_experience;
       // $community->pricing_plan = $pricing_plan;
        $community->skip_card_till_date = $skip_card_till_date;
        $community->subscription_discount_percent = $subscription_discount_percent;
        $community->theme_template_allowed = $theme_template_allowed;
        $community->save();

        return true;
    }

    /**
     * Make to check if a community exists through the slug
     *
     * @param  string  $slug
     * @return bool
     */
    public function exists($title)
    {
        return $this->model->where('title', '=', $title)->first();
    }

    public function seperateExists($title, $id)
    {
        return $this->model->where('title', '=', $title)->where('id', '!=', $id)->first();
    }

    public function get($slug)
    {
        return $this->model->with(['categories', 'members'])
            ->whereNotIn('user_id', $this->mustAvoidUserRepository->get())
            ->where('slug', '=', $slug)->orWhere('id', '=', $slug)->first();
    }

    public function join($id, $userid = null)
    {
        return $this->memberRepository->add($id, $userid);
    }

    public function getMyCommunities($userid = null, $limit = 9)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        return $this->model->with(['members', 'posts'])->where('user_id', '=', $userid)->orderBy('created_at', 'desc')->paginate($limit);
    }

    public function getJoinedCommunities($userid = null, $limit = 9)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        return $this->memberRepository->getCommunities($userid, $limit);
    }

    public function getMyAllJoinedCommunities($userid = null, $limit = 9)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        return $this->memberRepository->getMyAllJoinedCommunities($userid, $limit);
    }

    public function getMyJoinedCommunities($userid = null, $limit = 9)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        return $this->memberRepository->getMyJoinedCommunities($userid, $limit);
    }

    public function search($term, $limit = 10)
    {
        return $this->model->with(['members', 'posts'])
            ->where('searchable', '!=', 0)
            ->whereNotIn('user_id', $this->mustAvoidUserRepository->get())
            ->where(function ($query) use ($term) {
                $query->where('title', 'LIKE', '%'.$term.'%')
                    ->orWhere('description', 'LIKE', '%'.$term.'%');
            })->orderBy('created_at', 'desc')
            ->paginate($limit);
    }

    public function discover($limit = 9)
    {
        // return $this->model->with(['members', 'posts'])->where('searchable', '!=', 0)->orderBy('created_at', 'desc')->paginate($limit);
        return $this->model->with(['members', 'posts'])->where('privacy', '=', 1)->orderBy('created_at', 'desc')->paginate($limit);
    }

    public function suggest($limit = 5)
    {
        $ids = $this->memberRepository->getIds(\Auth::user()->id);

        $ids = array_merge([0], $ids);

        $communityUsers = app('App\Repositories\\UserRepository')->getSimilarCommunityUsers(\Auth::user()->id);
        if (! empty($communityUsers)) {
            $query = $this->model->with(['members', 'posts'])
                ->whereNotIn('id', $ids)
                ->whereNotIn('user_id', $this->mustAvoidUserRepository->get())
                ->where('searchable', '!=', '0')
                ->where('user_id', '!=', \Auth::user()->id)
                ->where('external_community', '=', 1)
                ->whereIn('user_id', $communityUsers)
                ->orderBy(\DB::raw('rand()'));

            if (config('enable-query-cache')) {
                return $query = $query->remember(config('query-cache-time-out', 5), 'community-suggestions-'.\Auth::user()->id)->take($limit)->get();
            } else {
                return $query = $query->paginate($limit);
            }
        } else {
            return null;
        }
    }

    /**
     * Method to update logo
     *
     * @param  int  $id
     * @param  string  $logo
     * @return bool
     */
    public function updateLogo($id, $logo)
    {
        return $this->model->where('id', '=', $id)->update(['logo' => sanitizeText($logo)]);
    }

    /**
     * Method to leave community
     *
     * @param  int  $id
     * @param  int  $userid
     * @return bool
     */
    public function leave($id, $userid = null)
    {
        $this->communityCategoryMembersRepository->deleteByCommunity($id, $userid);

        return $this->memberRepository->delete($id, $userid);
    }

    public function assignModerator($id, $userid, $user_id = null)
    {
        $user_id = (empty($user_id)) ? \Auth::user()->id : $user_id;

        $community = $this->get($id);

        if ($community and $community->isOwner($user_id)) {
            $moderators = $community->getModerators();

            if (! in_array($userid, $moderators)) {
                $moderators[] = $userid;
                $community->moderators = perfectSerialize($moderators);
                $community->save();

                $this->notification->send($userid, [
                    'path' => 'notification.community.moderator',
                    'type' => 'community-moderator',
                    'typeId' => $community->id,
                ], $user_id, false, null, null, $community->id);
            }

            return true;
        }

        return false;
    }

    public function removeModerator($id, $userid, $user_id = null)
    {
        $user_id = (empty($user_id)) ? \Auth::user()->id : $user_id;

        $community = $this->get($id);

        if ($community and $community->isOwner($user_id)) {
            $moderators = $community->getModerators();
            $newModerators = [];
            foreach ($moderators as $m) {
                if ($m != $userid) {
                    $newModerators[] = $m;
                }
            }

            $community->moderators = perfectSerialize($newModerators);
            $community->save();

            return true;
        }

        return false;
    }

    public function getAll($term = null, $limit = 10)
    {
        $communities = $this->model;

        if ($term) {
            $communities = $communities->where('title', 'LIKE', '%'.$term.'%');
        }

        return $communities = $communities->paginate($limit);
    }

    public function getAllCommunitiesList($term = null, $withdomain = 'all', $limit = 5)
    {
        $communities = $this->model;

        if ($withdomain == 'yes') {
            $communities = $communities->where('domain_name', '!=', '')->where('domain', '=', 1);
        } elseif ($withdomain == 'no') {
            $communities = $communities->where('domain_name', '=', '')->orWhere('domain', '=', 0);
        }

        if ($term) {
            $communities = $communities->where('title', 'LIKE', '%'.$term.'%');
        }

        return $communities = $communities->orderBy('id', 'desc')->paginate($limit);
    }

    public function delete($id, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $community = $this->get($id);

        if ($community) {
            if ($community->user_id != $userid) {
                if (! \Auth::user()->isAdmin()) {
                    return false;
                }
            }
            foreach ([
                'App\\Repositories\\PostRepository',
                'App\\Repositories\\CommunityMemberRepository',
                'App\\Repositories\\CommunityCategoryRepository',
                'App\\Repositories\\InvitedMemberRepository',
            ] as $repository) {
                app($repository)->deleteAllByCommunity($id, $userid);
            }

            $community->delete();
        }

        return false;
    }

    public function deleteAllByUser($userid)
    {
        return $this->model->where('user_id', '=', $userid)->delete();
    }

    public function total()
    {
        return $this->model->count();
    }

    public function getById($id)
    {
        return Cache::remember('community_by_id_' . $id, now()->addMonth(), function() use ($id) {
            $community = $this->model
                ->where('id', '=', $id)
                ->where('status', '=', 1)
                ->where(function ($community) {
                    $community->where('card_dtls_added', '=', 1)->orWhere('skip_card_dtls', '=', 1)->orWhere('free_plan_signup', '=', 1);
                })
                ->first();

            return $community;
        });
    }

    public function getByIdAll($id)
    {
        $community = $this->model
            ->where('id', '=', $id)
            ->where('status', '=', 1)
            ->first();

        return $community;
    }

    public function finfByCmId($id)
    {
        $community = $this->model
            ->where('id', '=', $id)
            ->first();

        return $community;
    }

    public function findBySlug($slug)
    {
        return $this->model->where('slug', '=', $slug)->first();
    }

    public function getBySlug($slug)
    {
        $cacheKey = 'community_by_slug_' . md5($slug);
        
        return Cache::remember($cacheKey, now()->addMonth(), function () use ($slug) {
            return $this->model
                ->whereNotIn('user_id', $this->mustAvoidUserRepository->get())
                ->where(function ($community) use ($slug) {
                    $community->where('slug', '=', $slug)->orWhere('id', '=', $slug);
                })
                ->where(function ($community) {
                    $community->where('card_dtls_added', '=', 1)->orWhere('skip_card_dtls', '=', 1)->orWhere('free_plan_signup', '=', 1);
                })
                ->where('status', '=', 1)->first();
        });
    }

    /* Get my all communities */
    public function getMyAllCommunities($userid, $offset)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        return $this->model->with(['members', 'posts'])->where('user_id', '=', $userid)->orderBy('created_at', 'desc')->skip($offset)->take(10)->get();
    }

    public function getAllCommunities($offset)
    {
        return $this->model->with(['members', 'posts'])->where('searchable', '!=', 0)->orderBy('created_at', 'desc')->skip($offset)->take(10)->get();
    }

    public function getAllJoinedCommunities($userid, $offset)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        return $this->memberRepository->getJoinedCommunities($userid, $offset);
    }

    public function getPendingEventsCount($community_id)
    {
        $data = \DB::table('events')->where('TYPE', 'community')->where('TYPE_ID', $community_id)->where('STATUS', '!=', 1)->get();

        return $data;
    }

    public function addExternalCommunity($userid, $community_name, $description = '', $searchable = '', $moderator_action = '', $domain = '', $domain_name = '', $community_slug = '', $status = 0, $inside_created = 0, $community_full_address = '', $city = '', $state = '', $country = '', $zip = '', $email_address = '', $pricing_plan = 1)
    {
        if ($community_slug == '') {
            $community_slug = $this->generateSlug($community_name);
        }

        $community = $this->model->newInstance();
        $community->title = sanitizeText($community_name);
        $community->description = \Hook::fire('filter-text', sanitizeText($description));
        $community->user_id = $userid;
        $community->privacy = 0;
        $community->can_post = 1;
        $community->can_invite = 1;
        $community->can_join = 0;
        $community->searchable = sanitizeText($searchable);
        $community->slug = $community_slug;
        $community->moderator_action_required = $moderator_action;
        $community->external_community = 1;
        $community->status = $status;
        $community->domain = $domain;
        $community->domain_name = $domain_name;
        $community->inside_created = $inside_created;
        $community->full_address = $community_full_address;
        $community->address = $community_full_address;
        $community->city = $city;
        $community->state = $state;
        $community->country = $country;
        $community->zip = $zip;
        $community->site_title = sanitizeText($community_name);
        $community->email = $email_address;
		$community->all_features_activated = 0;
		
        $community->pricing_plan = $pricing_plan;
		$community->free_plan_signup = 1;

        // $planDetails=$this->pricingPlansRepository->getPlanByPlanId($pricing_plan);

		if($pricing_plan){
			$planDetails = app('App\\Repositories\\PricingPlansRepository')->getPlanByPlanId($pricing_plan);
	
			//if ($planDetails) {
				//$community->free_plan_signup = $planDetails->is_plan_free;
			//}
			$community->free_plan_signup = 1;
		}
		
        $community->save();

        // $arrVal=['hometheme'=>3];
        $arrVal = [
            'hometheme' => 3,
            'website_title' => $community_name,
            'homepage_texts' => '<h2>Welcome to '.$community_name.'</h2>',
        ];

        $homecontents = $this->communityHomeContentsRepository->addContents($arrVal, $community->id, $userid);
        if ($homecontents) {
            $homecontents->theme = 3;
            $homecontents->save();
        }

        $blog_category = $this->communityCategoryRepository->add($community->id, 'Blogs');
        if ($blog_category) {
            $blog_category->group_type = 1;
            $blog_category->save();
        }

        $marketing_category = $this->communityCategoryRepository->add($community->id, 'Marketing');
        if ($marketing_category) {
            $marketing_category->group_type = 1;
            $marketing_category->save();
        }

        $events_category = $this->communityCategoryRepository->add($community->id, 'Events');
        if ($events_category) {
            $events_category->group_type = 1;
            $events_category->save();
        }

        $management_category = $this->communityCategoryRepository->add($community->id, 'Management');

	    if($pricing_plan){
        	$savePlan = $this->communityPricingPlanRepository->savePlan($community->id, $userid, $pricing_plan);
		}
		
        $this->registerCrmUser($community->id);

        return $community;
    }

    public function generateSlug($name)
    {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '', $name)));

        $data = $this->findBySlug($slug);

        $_newslug = $slug;

        if (! is_null($data) > 0) {
            $n = 1;
            $max_index = 30;
            while ($n < $max_index) { // just to be safe
                $_newslug = $slug.$n;
                $findnewslug = $this->findBySlug($_newslug);
                if (! is_null($findnewslug) == 0) {
                    break;
                }
                $n++;
            }
        }

        return $_newslug;
    }

    public function externalCommunities($access_type = 0)
    {
        if ($access_type == 1) {
            $communities = $this->model->where('external_community', 1)->where('allow_global_access', 1)->orderBy('id', 'desc')->get();
        } elseif ($access_type == 2) {
            $communities = $this->model->where('external_community', 1)->where('allow_global_access', 0)->orderBy('id', 'desc')->get();
        } else {
            $communities = $this->model->where('external_community', 1)->orderBy('id', 'desc')->get();
        }

        return $communities;
    }

    public function externalCommunitiesByName()
    {
        $communities = $this->model->select('id', 'slug', 'domain', 'title','domain_name')->where('external_community', 1)->orderBy('title', 'asc')->get();

        return $communities;
    }

    public function externalCommunityAction($value, $communityId, $userId)
    {
        $community = $this->model->where('user_id', '=', $userId)->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->status = $value;
            $community->save();
        }
    }
	
	public function saveExternalDomain($val, $community)
    {
		$expected = [
            'domain_name' => '',
        ];
		
		extract(array_merge($expected, $val));
		
		$getByDomain=$this->getByDomain($domain_name);
		if($getByDomain and $getByDomain->id!=$community->id){
			return false;
		}
		
		$community->domain = 1;
		$community->domain_name = $domain_name;
		$community->save();
		
		return $community;
	}

    /**
     * Method to save External community
     *
     * @param  array  $val
     * @param  \App\Models\Community  $community
     * @return bool
     */
    public function saveExternal($val, $community)
    {
        $expected = [
            'privacy' => '',
            'description' => '',
            'title' => '',
            'can_post' => '',
            'can_invite' => '',
            'searchable' => '',
            'info' => [],
            'moderator_action' => '',
            'address' => '',
            'city' => '',
            'state' => '',
            'country' => '',
            'contact' => '',
            'email' => '',            
            'domain_name' => '',
            'slug' => '',
            'zip' => '',
            'auto_signon' => 0,
            'timezone' => '',
            'send_postadd_email' => 0,
            'domain_name' => '',
            'moderator_action_event' => '',
            'full_address' => '',
            'transaction_commisions' => 0,
            'user_money_transfer_option' => 0,
        ];

        /**
         * @var $description
         * @var $title
         * @var $can_post
         * @var $can_invite
         * @var $searchable
         * @var $info
         */
        extract(array_merge($expected, $val));

        if ($slug) {
            $checkCommunityData = $this->checkCommunitySlug($slug, $community->id);

            if ($checkCommunityData == 0) {
                return false;
            }
        }

        if (! $transaction_commisions) {
            $transaction_commisions = 0;
        }

        $community->description = $description;
        $community->info = perfectSerialize($info);
        $community->title = sanitizeText($title);
        $community->address = sanitizeText($address);
        $community->city = sanitizeText($city);
        $community->state = sanitizeText($state);
        $community->country = sanitizeText($country);
        $community->contact = sanitizeText($contact);
        $community->email = sanitizeText($email);
       
        //$community->domain_name = sanitizeText($domain_name);
        $community->zip = sanitizeText($zip);
       // $community->domain_name = $domain_name;
        $community->full_address = $full_address;

        $community->transaction_commisions = $transaction_commisions;
        // $community->user_money_transfer_option=$user_money_transfer_option;
        $existingSlug = $community->slug;

        if ($slug and $community->slug_changed == 0 and $existingSlug != $slug) {
            $community->slug = $slug;
            $community->slug_changed = 1;
        }

        $community->save();

        return true;
    }
	
	
	 public function saveExternalLogos($val, $community)
    {
        $expected = [
            'theme_color' => '',
            'social_networking_background' => '',
            'use_own_theme_color' => 0,
            'own_theme_color' => '',
            'use_own_social_networking_background' => 0,
            'own_social_networking_background' => '',
			'site_title' => '',
        ];
        extract(array_merge($expected, $val));

        $community->site_title = sanitizeText($site_title);
        $community->theme_color = sanitizeText($theme_color);
        $community->social_networking_background = $social_networking_background;
        $community->use_own_theme_color = $use_own_theme_color;
        $community->own_theme_color = $own_theme_color;
        $community->use_own_social_networking_background = $use_own_social_networking_background;
        $community->own_social_networking_background = $own_social_networking_background;

        $community->save();

        if (request()->hasFile('logoimage')) {
            $CDNRepository = app('App\\Repositories\\CDNRepository');
            $logoimage = request()->file('logoimage');
            $filePath = 'uploads/cover/';

            $fileExt = $logoimage->getClientOriginalExtension();
            $file_original_ext = $fileExt;
            $file_original_name = $logoimage->getClientOriginalName();
            $file_original_size = $logoimage->getSize();

            if (checkAvailableSpace($community->id, $file_original_size) != 0) {
                $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);

                $fileName = md5($logoimage->getClientOriginalName().time()).'.'.strtolower($fileExt);
                $logoimage_path = $filePath.$fileName;

                $logoimage->move(public_path().'/'.$filePath, $fileName);

                $uploadPath = 'uploads/cover/'.$fileName;
                $newFileName = $CDNRepository->upload(public_path().'/'.$uploadPath, $uploadPath);

                $CDNRepository->deleteThisFile(public_path().'/'.$logoimage_path);
                $logoimage_path = $newFileName;
                $this->updateLogo($community->id, $logoimage_path);

                $fileArray = [
                    'community_id' => $community->id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $logoimage_path,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => 'community-logo',
                    'type_id' => 0,
                    'upload_key' => Str::random(20),
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }
        }

        if (request()->hasFile('logofooterimage')) {
            $CDNRepository = app('App\\Repositories\\CDNRepository');
            $logofooterimage = request()->file('logofooterimage');
            $filePath = 'uploads/cover/';

            $fileExt = $logofooterimage->getClientOriginalExtension();
            $file_original_ext = $fileExt;
            $file_original_name = $logofooterimage->getClientOriginalName();
            $file_original_size = $logofooterimage->getSize();

            if (checkAvailableSpace($community->id, $file_original_size) != 0) {
                $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);

                $fileName = md5($logofooterimage->getClientOriginalName().time()).'.'.strtolower($fileExt);
                $logoimage_path = $filePath.$fileName;

                $logofooterimage->move(public_path().'/'.$filePath, $fileName);

                $uploadPath = 'uploads/cover/'.$fileName;
                $newFileName = $CDNRepository->upload(public_path().'/'.$uploadPath, $uploadPath);

                $CDNRepository->deleteThisFile(public_path().'/'.$logoimage_path);
                $logoimage_path = $newFileName;
                $community->footer_logo = $logoimage_path;
                $community->save();

                $fileArray = [
                    'community_id' => $community->id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $logoimage_path,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => 'community-logo',
                    'type_id' => 0,
                    'upload_key' => Str::random(20),
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }
        }

        if (request()->hasFile('logoeventappimage')) {
            $CDNRepository = app('App\\Repositories\\CDNRepository');
            $logoeventappimage = request()->file('logoeventappimage');
            $filePath = 'uploads/cover/';

            $fileExt = $logoeventappimage->getClientOriginalExtension();
            $file_original_ext = $fileExt;
            $file_original_name = $logoeventappimage->getClientOriginalName();
            $file_original_size = $logoeventappimage->getSize();

            if (checkAvailableSpace($community->id, $file_original_size) != 0) {
                $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);

                $fileName = md5($logoeventappimage->getClientOriginalName().time()).'.'.strtolower($fileExt);
                $logoimage_path = $filePath.$fileName;

                $logoeventappimage->move(public_path().'/'.$filePath, $fileName);

                $uploadPath = 'uploads/cover/'.$fileName;
                $newFileName = $CDNRepository->upload(public_path().'/'.$uploadPath, $uploadPath);

                $CDNRepository->deleteThisFile(public_path().'/'.$logoimage_path);
                $logoimage_path = $newFileName;
                $community->event_app_logo = $logoimage_path;
                $community->save();

                $fileArray = [
                    'community_id' => $community->id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $logoimage_path,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => 'community-logo',
                    'type_id' => 0,
                    'upload_key' => Str::random(20),
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }
        }

        return true;
    }

    public function saveExternalPrivilage($val, $community)
    {
        $expected = [
            'can_post' => '',
            'can_invite' => '',
            'searchable' => '',
            'moderator_action' => '',
            'auto_signon' => 0,
            'moderator_action_event' => '',
            'send_postadd_email' => 0,
            'timezone' => '',
            'privacy' => '',
            'owner_business_access' => 0,
            'owner_community_access' => 0,
            'owner_event_access' => 0,
            'owner_donation_access' => 0,
            'user_campaign_activate' => 0,
            'currency' => '',
            'can_share_recipe' => 0,
            'new_message_email_alert' => 0,
			'can_sale_on_socialmedia'=>0,
			'transaction_fees_percent'=>0,
        ];

        /**
         * @var $description
         * @var $title
         * @var $can_post
         * @var $can_invite
         * @var $searchable
         * @var $info
         */
        extract(array_merge($expected, $val));

        $community->privacy = sanitizeText($privacy);
        $community->can_post = sanitizeText($can_post);
        $community->can_invite = sanitizeText($can_invite);
        $community->searchable = sanitizeText($searchable);
        $community->moderator_action_required = sanitizeText($moderator_action);
        $community->moderator_action_required_event = sanitizeText($moderator_action_event);
        $community->auto_signon = sanitizeText($auto_signon);
        $community->timezone = $timezone;
        $community->send_postadd_email = $send_postadd_email;
        $community->owner_business_access = $owner_business_access;
        $community->owner_community_access = $owner_community_access;
        $community->owner_event_access = $owner_event_access;
        $community->owner_donation_access = $owner_donation_access;
        $community->user_campaign_activate = $user_campaign_activate;
        $community->currency = $currency;
        $community->can_share_recipe = $can_share_recipe;
        $community->new_message_email_alert = $new_message_email_alert;
		$community->can_sale_on_socialmedia = $can_sale_on_socialmedia;
		$community->transaction_fees_percent=$transaction_fees_percent;
        $community->save();

        app('App\\Repositories\\PageRepository')->updateCurrencyByCommunity($community->id, $currency);

        return $community;
    }

    public function checkCommunitySlug($val, $communityId)
    {
        $checkCommunityData = $this->findBySlug($val);

        if (! preg_match('/^([-a-z0-9])+$/i', $val)) {
            return 0;
        } else {
            if (! empty($checkCommunityData) and $checkCommunityData->id != $communityId) {
                return 0;
            } elseif ($val == 'frontend' || $val == 'admincp' || $val == 'home' || $val == 'community' || $val == 'sports' || $val == 'video' || $val == 'id4pro' || $val == 'id4org' || $val == 'id4mart') {
                return 0;
            } else {
                return 1;
            }
        }
    }

    public function checkFieldsComplete($communityId)
    {
        $community = $this->getById($communityId);

        $status = 1;

        if ($community) {
            $title = $community->title;
            $slug = $community->slug;
            $description = $community->description;
            $address = $community->address;
            $city = $community->city;
            $state = $community->state;
            $country = $community->country;
            $contact = $community->contact;
            $email = $community->email;
            $site_title = $community->site_title;
            $zip = $community->zip;

            /*if($title=='' || $slug=='' || $description=='' || $address=='' || $city=='' || $state=='' || $country=='' || $contact=='' || $email=='' || $site_title==''){
                $status = 0;
            }*/

            /*if($title=='' || $slug=='' || $description=='' || $address=='' || $city=='' || $state=='' || $country=='' || $email=='' || $site_title==''){
                $status = 0;
            }*/

            if ($title == '' || $slug == '' || $address == '' || $city == '' || $state == '' || $country == '' || $email == '' || $site_title == '') {
                $status = 0;
            }
        }

        return $status;
    }

    public function getExternalByUserId($user_id)
    {
        $cacheKey = 'community_external_by_user_' . $user_id;
        
        return Cache::remember($cacheKey, now()->addMonth(), function () use ($user_id) {
            return $this->model
                ->where('user_id', '=', $user_id)
                ->where('external_community', '=', 1)
                ->where('status', '=', 1)
                ->where(function ($community) {
                    $community->where('card_dtls_added', '=', 1)
                        ->orWhere('skip_card_dtls', '=', 1)
                        ->orWhere('free_plan_signup', '=', 1);
                })
                ->first();
        });
    }

    public function getMyCommunity($user_id)
    {
        $cacheKey = 'community_my_by_user_' . $user_id;
        
        return Cache::remember($cacheKey, now()->addMonth(), function () use ($user_id) {
            return $this->model
                ->where('user_id', '=', $user_id)
                ->where('external_community', '=', 1)
                ->where('status', '=', 1)
                ->first();
        });
    }
	
	public function isMyCommunityCreated($user_id)
    {
        $cacheKey = 'community_created_by_user_' . $user_id;
        
        return Cache::remember($cacheKey, now()->addMonth(), function () use ($user_id) {
            return $this->model
                ->where('user_id', '=', $user_id)
                ->where('external_community', '=', 1)
                ->first();
        });
    }

    public function communitySignonAction($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->auto_signon = $value;
            $community->save();
        }
    }

    public function communityBusinessAction($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->business_access = $value;
            $community->save();
        }
    }

    public function communityLocalAction($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->community_access = $value;
            $community->save();
        }
    }

    public function addMapContactShow($val, $communityId)
    {
        $expected = [
            'map_show' => '',
            'contactform_show' => '',
        ];

        extract(array_merge($expected, $val));

        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->map_show = $map_show;
            $community->contactform_show = $contactform_show;
            $community->save();
        }
    }

    public function isUserAssociatedWithCommunity($user_id)
    {
        return $this->model->join('community_members', 'communities.id', '=', 'community_members.community_id')->where('communities.status', 1)->where('communities.external_community', 1)->where('community_members.user_id', $user_id)->select('communities.id')->get();
    }

    public function updateLogoAvatar($id, $logo)
    {
        $result = $this->model->where('id', '=', $id)->update(['logo_avatar' => sanitizeText($logo)]);
        
        return $result;
    }

    public function uploadFevicon($id, $logo)
    {
        $result = $this->model->where('id', '=', $id)->update(['fevicon_image' => sanitizeText($logo)]);
        
        return $result;
    }

    public function saveUniqueIdentity($communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        $uniqueIdentity = substr(hash('sha256', mt_rand().microtime()), 0, 5);
        $community->unique_identity = $uniqueIdentity;
        $community->save();
    }

    public function getByIdentityCode($identityCode)
    {
        return $community = $this->model->where('unique_identity', '=', $identityCode)->first();
    }

    public function validateOrganizationCode($identityCode)
    {
        $community = $this->getByIdentityCode($identityCode);
        $url = 'invalidUrl';
        if ($community) {
            $validate = $this->communityMembersEmailsRepository->getByCommunityEmail(\Auth::user()->email_address, $community->id);
            if ($validate) {
                if (\Auth::user()->favourite_community == 0) {
                    $this->userRepository->setFavouriteCm($community->id);
                }

                $this->memberRepository->add($community->id);
                $url = $community->present()->url();
            }
        }

        return $url;
    }

    public function communityAllowBusiness($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->allow_user_create_business = $value;
            $community->save();
        }
    }

    public function publicBusinessCommunity()
    {
        return $community = $this->model->where('public_business_community', '=', 1)->where('allow_user_create_business', '=', 1)->first();
    }

    public function showCrowdfunding($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->show_crowdfunding = $value;
            $community->save();
        }
    }

    public function getByDomain($domain)
    {
        $setDomain = explode('www.', $domain);

        if (isset($setDomain[1])) {
            $newSetDomain = $domain;
            $domain = $setDomain[1];
        } else {
            $newSetDomain = 'www.'.$domain;
            $domain = $domain;
        }

        $cacheKey = 'community_by_domain_' . md5($domain . '|' . $newSetDomain);
        
        return Cache::remember($cacheKey, now()->addMonth(), function () use ($domain, $newSetDomain) {
            return $this->model->where('domain_name', '=', $domain)->orWhere('domain_name', '=', $newSetDomain)->first();
        });
    }

    public function saveCommunityDomain($domain, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->domain_name = $domain;
            $community->save();
        }
    }

    public function surveyNominationAction($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->survey_nomination_action = $value;
            $community->save();
        }
    }

    public function activateCampaign($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->activate_campaign = $value;
            $community->save();
        }
    }

    public function makeCommunityMember($community, $user = null)
    {
        $user = (empty($user)) ? \Auth::user() : $user;

        $communityId = $community->id;

        $isUserInvited = $this->invitedMemberRepository->isInvitedByEmailType('community', $communityId, $user->email_address);
        $isMember = $this->memberRepository->isMember($community->id, $user->id);

        $isUserInvitedMember = $this->invitedMemberRepository->isInvitedByEmailTypeGroupMember('community', $communityId, $user->email_address);

        if ($isUserInvited and $isUserInvitedMember and ! $isMember) {
            $this->userRepository->setFavouriteCm($community->id, $user);
            $this->memberRepository->add($community->id, $user->id);
        }

        if ($isUserInvited) {
            $invitedGroups = $this->invitedMemberRepository->isInvitedByEmailTypeGroupId('community', $communityId, $user->email_address);

            if (! empty($invitedGroups)) {
                foreach ($invitedGroups as $group) {
                    if ($group->group_member == 1) {

                        $topic = $this->communityCategoryRepository->getById($group->group_id);
                        if ($topic and $topic->membership_type == 0) {

                            $isGroupMember = $this->communityCategoryMembersRepository->isGroupMember($user->id, $group->group_id, $communityId);
                            if (empty($isGroupMember)) {
                                $this->communityCategoryMembersRepository->add($group->group_id, $communityId, $user->id, $user);
                            }

                            $this->invitedMemberRepository->deleteMembersEmailAddressByGroup('community', $communityId, $topic->id, $user->email_address);
                        }
                    }
                }
            }

            $this->invitedMemberRepository->deleteMembersEmailAddress('community', $communityId, $user->email_address);
        }

        // app('App\Repositories\\AppointmentRepository')->updateUserId($user);
    }

    public function activateEvent($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->event_access = $value;
            $community->save();
        }
    }

    public function activateDonation($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->donation_access = $value;
            $community->save();
        }
    }

    public function activateZoom($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->zoom_access = $value;
            $community->save();
        }
    }

    public function activateVideoCall($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->videocall_access = $value;
            $community->save();
        }
    }

    public function activateActivationCode($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->show_activationcode_page = $value;
            $community->save();

            return $community;
        }
    }

    public function getMeetingCommunity()
    {
        return $this->model->where('eventmeeting', '=', 1)->first();
    }

    public function draftEmails($val, $community)
    {
        $expected = [
            'welcome_email' => '',
            'activation_email' => '',
            'activation_successfull_email' => '',
            'welcome_email_subject' => '',
            'activation_email_subject' => '',
            'activation_successfull_email_subject' => '',
        ];

        extract(array_merge($expected, $val));

        $community->welcome_email = $welcome_email;
        $community->activation_email = $activation_email;
        $community->activation_successfull_email = $activation_successfull_email;

        $community->welcome_email_subject = $welcome_email_subject;
        $community->activation_email_subject = $activation_email_subject;
        $community->activation_successfull_email_subject = $activation_successfull_email_subject;

        $community->save();

        return $community;
    }

    public function emailSignature($val, $community)
    {
        $expected = [
            'email_signature' => '',
        ];

        extract(array_merge($expected, $val));

        $community->email_signature = $email_signature;
        $community->save();

        return $community;
    }

    public function activateSocialProfile($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->show_socialprofile = $value;
            $community->save();

            return $community;
        }
    }

    public function getByIdsAll($communityIds)
    {
        if ($communityIds) {
            return $this->model->whereIn('id', $communityIds)->orderBy('title', 'asc')->get();
        }

        return false;
    }

    public function activateFitness($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->fitness_access = $value;
            $community->save();

            return $community;
        }
    }

    public function searchByName($term)
    {
        $community = $this->model
            ->where('title', 'LIKE', '%'.$term.'%')
            ->where(function ($community) {
                $community->where('card_dtls_added', '=', 1)->orWhere('skip_card_dtls', '=', 1)->orWhere('free_plan_signup', '=', 1);
            })
            ->orderBy('title', 'asc')->get();

        return $community;
    }

    public function activateBusinessApplication($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->join_business_access = $value;
            $community->save();

            return $community;
        }
    }

    public function registerCrmUser($communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if ($community) {
            if (! $this->crmUserExist($community->user_id, $community->id)) {
                $user = $community->user;

                \DB::insert("insert into id_crm_users(email,password,first_name,type,idhubs_id,creatorid,community_id,role_id,crm_access,organization_owner)values('".$user->email_address."','".$user->password."','".$user->fullname."','team','".$user->id."',1,'".$community->id."',11,1,1)");
            }

            $crmUser = $this->crmUserExist($community->user_id, $community->id);

            if ($crmUser) {

                if (! $this->crmClientUserExist($community->id)) {
                    $currentDate = date('Y-m-d H:i:s');

                    \DB::insert("insert into id_crm_clients(client_creatorid,client_company_name,client_phone,community_id,client_created,client_updated,community_client_own)values('".$crmUser[0]->id."','".$community->title."','".$community->contact."','".$community->id."','".$currentDate."','".$currentDate."',1)");

                    $clientUser = $this->crmClient($community->id);
                    if ($clientUser) {
                        \DB::insert("insert into id_crm_users(email,password,first_name,type,idhubs_id,creatorid,community_id,role_id,crm_access,organization_owner,clientid,community_client_own,account_owner)values('".$community->email."','".$crmUser[0]->password."','".$community->title."','client',0,'".$crmUser[0]->id."','".$community->id."',2,1,0,'".$clientUser[0]->client_id."',1,'yes')");
                    }

                } else {
                    \DB::table('crm_users')->where('type', 'client')->where('community_client_own', 1)->where('community_id', $community->id)->update(['crm_access' => 1]);
                }
            }
        }
    }

    public function activateCrmApplication($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->crm_access = $value;
            $community->save();

            if ($value == 1) {
                if (! $this->crmUserExist($community->user_id, $community->id)) {
                    $user = $community->user;

                    \DB::insert("insert into id_crm_users(email,password,first_name,type,idhubs_id,creatorid,community_id,role_id,crm_access,organization_owner)values('".$user->email_address."','".$user->password."','".$user->fullname."','team','".$user->id."',1,'".$community->id."',11,1,1)");
                } else {
                    \DB::table('crm_users')->where('idhubs_id', $community->user_id)->where('community_id', $community->id)->update(['crm_access' => 1]);
                }

                $crmUser = $this->crmUserExist($community->user_id, $community->id);

                if ($crmUser) {

                    if (! $this->crmClientUserExist($community->id)) {
                        $currentDate = date('Y-m-d H:i:s');

                        \DB::insert("insert into id_crm_clients(client_creatorid,client_company_name,client_phone,community_id,client_created,client_updated,community_client_own)values('".$crmUser[0]->id."','".$community->title."','".$community->contact."','".$community->id."','".$currentDate."','".$currentDate."',1)");

                        $clientUser = $this->crmClient($community->id);
                        if ($clientUser) {
                            \DB::insert("insert into id_crm_users(email,password,first_name,type,idhubs_id,creatorid,community_id,role_id,crm_access,organization_owner,clientid,community_client_own,account_owner)values('".$community->email."','".$crmUser[0]->password."','".$community->title."','client',0,'".$crmUser[0]->id."','".$community->id."',2,1,0,'".$clientUser[0]->client_id."',1,'yes')");
                        }

                    } else {
                        \DB::table('crm_users')->where('type', 'client')->where('community_client_own', 1)->where('community_id', $community->id)->update(['crm_access' => 1]);
                    }
                }

            } else {
                \DB::table('crm_users')->where('idhubs_id', $community->user_id)->where('community_id', $community->id)->update(['crm_access' => 0]);
            }

            return $community;
        }

        return $community;
    }

    public function crmUserExist($user_id, $community_id)
    {
        $crmUser = \DB::table('crm_users')
            ->where('idhubs_id', $user_id)
            ->where('community_id', $community_id)
            ->get();

        return $crmUser->toArray();
    }

    public function crmClientUserExist($community_id)
    {
        $crmUser = \DB::table('crm_users')
            ->where('type', 'client')
            ->where('community_id', $community_id)
            ->where('community_client_own', 1)
            ->get();

        return $crmUser->toArray();
    }

    public function crmClient($community_id)
    {
        $crmUser = \DB::table('crm_clients')
            ->where('community_id', $community_id)
            ->where('community_client_own', 1)
            ->get();

        return $crmUser->toArray();
    }

    public function getResumeCommunity()
    {
        $community = $this->model->where('resume_community', '=', 1)->first();

        return $community;
    }

    public function activateWebsiteBookmark($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->website_bookmark = $value;
            $community->save();

            return $community;
        }
    }

    public function saveSpaceUsed($community_id, $file_size)
    {
        $community = $this->model->where('id', '=', $community_id)->first();
        if (! empty($community)) {
            $community->space_used = $community->space_used + $file_size;
            $community->save();

            return $community;
        }
    }

    public function reduceSpaceUsed($community_id, $file_size)
    {
        $community = $this->model->where('id', '=', $community_id)->first();
        if (! empty($community)) {
            $newSpaceUsed = (int) $community->space_used - (int) $file_size;
            if ($newSpaceUsed < 0) {
                $newSpaceUsed = 0;
            }
            $community->space_used = $newSpaceUsed;
            $community->save();

            return $community;
        }
    }

    public function activateIdhubsApplication($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->idhubs_access = $value;
            $community->save();

            return $community;
        }
    }

    public function activateIdmartApplication($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->idmart_access = $value;
            $community->save();

            return $community;
        }
    }

    public function activateAIchat($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->ai_chat_access = $value;
            $community->save();

            return $community;
        }
    }

    public function updateSeoContents($val, $community)
    {
        $expected = [
            'seo_title' => '',
            'seo_description' => '',
            'seo_keywords' => '',
        ];

        extract(array_merge($expected, $val));

        $community->seo_title = $seo_title;
        $community->seo_description = $seo_description;
        $community->seo_keywords = $seo_keywords;

        $community->save();

        if (request()->hasFile('logoimage')) {
            $CDNRepository = app('App\\Repositories\\CDNRepository');
            $logoimage = request()->file('logoimage');
            $filePath = 'uploads/community/'.$community->id.'/';

            $fileExt = $logoimage->getClientOriginalExtension();
            $file_original_ext = $fileExt;
            $file_original_name = $logoimage->getClientOriginalName();
            $file_original_size = $logoimage->getSize();

            if (checkAvailableSpace($community->id, $file_original_size) != 0) {
                $this->file->makeDirectory(public_path().'/'.$filePath, 0777, true, true);

                $fileName = md5($logoimage->getClientOriginalName().time()).'.'.strtolower($fileExt);
                $logoimage_path = $filePath.$fileName;

                $logoimage->move(public_path().'/'.$filePath, $fileName);

                $uploadPath = 'uploads/community/'.$community->id.'/'.$fileName;
                $newFileName = $CDNRepository->upload(public_path().'/'.$uploadPath, $uploadPath);

                $CDNRepository->deleteThisFile(public_path().'/'.$logoimage_path);
                $logoimage_path = $newFileName;

                $community->seo_website_image = $logoimage_path;
                $community->save();

                $fileArray = [
                    'community_id' => $community->id,
                    'user_id' => \Auth::user()->id,
                    'file_path' => $logoimage_path,
                    'file_name' => $file_original_name,
                    'file_type' => $file_original_ext,
                    'file_size' => $file_original_size,
                    'uploaded_date' => date('Y-m-d'),
                    'type' => 'community-website-image',
                    'type_id' => 0,
                    'upload_key' => Str::random(20),
                ];
                $this->communitySpaceUsedRepository->save($fileArray);
            }
        }

        return $community;
    }

    public function crmPaymentCommunities($ids)
    {
        return $this->model->whereIn('id', $ids)->paginate(10);
    }

    public function communityWithUser($id)
    {
        $community = $this->model->with('user')->where('id', '=', $id)->first();

        return $community;
    }

    public function allowGlobalAccess($value, $communityId)
    {
        $community = $this->model->where('id', '=', $communityId)->first();

        if (! empty($community)) {
            $community->allow_global_access = $value;
            $community->save();

            return $community;
        }
    }

    public function getExternalByUserIdIncomplete($user_id)
    {
        $community = $this->model
            ->where('user_id', '=', $user_id)
            ->where('external_community', '=', 1)
            ->where('status', '=', 1)
            ->where('card_dtls_added', '=', 0)
            ->where('skip_card_dtls', '=', 0)
            ->where('free_plan_signup', '=', 0)
            ->first();

        return $community;
    }

    public function getGiftCommunitites()
    {
        $communities = $this->model
            ->where('external_community', '=', 1)
            ->where('status', '=', 1)
            ->where('gift_app_community', '=', 1)
            ->paginate(10);

        return $communities;
    }

    public function getAllActiveCommunitites($term = '', $card_loaded = 'no')
    {
        if ($card_loaded == 'yes') {
            $community_ids = app('App\Repositories\\CommunityPricingPlanPaymentCardsRepository')->getCommunityCardDetailsIds();

            if ($term) {
                $communities = $this->model
                    ->where('external_community', '=', 1)
                    ->where('status', '=', 1)
                    ->where('title', 'LIKE', '%'.$term.'%')
                    ->whereIn('id', $community_ids)
                    ->orderBy('id', 'desc')
                    ->paginate(5);

            } else {
                $communities = $this->model
                    ->where('external_community', '=', 1)
                    ->where('status', '=', 1)
                    ->whereIn('id', $community_ids)
                    ->orderBy('id', 'desc')
                    ->paginate(5);
            }

        } else {
            if ($term) {
                $communities = $this->model
                    ->where('external_community', '=', 1)
                    ->where('status', '=', 1)
                    ->where('title', 'LIKE', '%'.$term.'%')
                    ->orderBy('id', 'desc')
                    ->paginate(5);

            } else {
                $communities = $this->model
                    ->where('external_community', '=', 1)
                    ->where('status', '=', 1)
                    ->orderBy('id', 'desc')
                    ->paginate(5);
            }
        }

        return $communities;
    }

    public function getAllByIds($community_ids)
    {
        return $communities = $this->model
            ->where('external_community', '=', 1)
            ->whereIn('id', $community_ids)
            ->orderBy('id', 'desc')
            ->get();
    }

    public function sendCardExpiryAlert($community)
    {
        $user = $community->user;

        $community_subscription_url = '';
        try {
            $community_subscription_url = $community->present()->url('communitypaymenturl').'/'.base64_encode($user->id);

            $this->mailer->send('emails.community.send-card-alert', [
                'username' => $user->username,
                'fullname' => $user->fullname,
                'email_address' => $user->email_address,
                'user_id' => $user->id,
                'community_id' => $community->id,
                'community_subscription_url' => $community_subscription_url,
            ], function ($mail) use ($user) {
                $mail->to($user->email_address, $user->fullname)
                    ->subject('Important: Subscription Expiration Notice');
            });

            // return 'Email send successfully';
        } catch (\Exception $e) {
            //	return $e;
        }
    }

    public function sendCardCustomAlert($community, $subject, $body)
    {
        $user = $community->user;
        $community_subscription_url = '';
        try {

            $this->mailer->send('emails.community.custom-email-body', [
                'email_body' => $body,
            ], function ($mail) use ($user, $subject) {
                $mail->to($user->email_address, $user->fullname)
                    ->subject($subject);
            });

            // return 'Email send successfully';
        } catch (\Exception $e) {
            //	return $e;
        }
    }

    public function checkCardStatus()
    {
        $canSendAlert = config('community-subscription-expiry-alert');
        if ($canSendAlert) {
            $beforeDays = config('community-subscription-expiry-alert-before-days');
            $communitiesPlans = $this->communityPricingPlanRepository->getCommunitySubscriptionsEnding($beforeDays);
            foreach ($communitiesPlans as $plan) {
                $getCard = app('App\\Repositories\\CommunityPricingPlanPaymentCardsRepository')->getCommunityCardDetailsById($plan->community_id);
                // if($getCard){
                // $expiry=$getCard->expiry_year."-".$getCard->expiry_month."-00";
                // if($expiry < $plan->plan_end_date){
                $community = $this->getByIdAll($plan->community_id);
                if ($community) {
                    $this->sendCardExpiryAlert($community);
                }
                // }
                //	}
            }
        }
    }

    public function sendCardExpiryAlertGlobal($community)
    {
        $user = $community->user;

        $community_subscription_url = '';
        try {
            $community_subscription_url = $community->present()->url('communitypaymenturl').'/'.base64_encode($user->id);

            $this->mailer->send('emails.community.send-card-alert-global', [
                'username' => $user->username,
                'fullname' => $user->fullname,
                'email_address' => $user->email_address,
                'user_id' => $user->id,
                'community_id' => $community->id,
                'community_subscription_url' => $community_subscription_url,
            ], function ($mail) use ($user) {
                $mail->to($user->email_address, $user->fullname)
                    ->subject('Important: Complementary Subscription Expiration Notice');
            });

            // return 'Email send successfully';
        } catch (\Exception $e) {
            //	return $e;
        }
    }

    public function checkTaxAmount($amount, $address, $city, $state, $postal_code, $country, $currency)
    {
        require_once base_path('functions/stripe-php-master/init.php');

        /*$stripe = array(
              "secret_key"      => config('stripe_secret_key'),
              "publishable_key" => config('stripe_publishable_key')
        );

        \Stripe\Stripe::setApiKey($stripe['secret_key']);*/

        $stripe = new \Stripe\StripeClient(config('stripe_secret_key'));

        $error_message = '';

        try {
            $stripe->tax->calculations->create([
                'currency' => 'usd',
                'line_items' => [
                    [
                        'amount' => $amount,
                        'reference' => 'L1',
                    ],
                ],
                'customer_details' => [
                    'address' => [
                        'line1' => $address,
                        'city' => $city,
                        'state' => $state,
                        'postal_code' => $postal_code,
                        'country' => $country,
                    ],
                ],
            ]);

            return $stripe;

        } catch (\Stripe\Error\Base $e) {
            return $error_message = $e->getMessage();
        } catch (\Stripe\Error\Card $e) {
            return $error_message = $e->getMessage(); // I think this is the missing one
        } catch (\Stripe\Error\Authentication $e) {
            return $error_message = $e->getMessage();
        } catch (\Stripe\Error\InvalidRequest $e) {
            return $error_message = $e->getMessage();
        } catch (Exception $e) {
            return $error_message = $e->getMessage();
        }
    }
}


