<?php

namespace App\Repositories;

use App\Models\CommunityMember;
use App\Notification;
use Illuminate\Cache\Repository;
use Illuminate\Mail\Mailer;

class CommunityMemberRepository
{
    public function __construct(
        CommunityMember $communityMember,
        Repository $cache,
        NotificationRepository $notificationRepository,
        MustAvoidUserRepository $mustAvoidUserRepository,
        UserRepository $userRepository,
        Mailer $mailer
    ) {
        $this->model = $communityMember;
        $this->cache = $cache;
        $this->notification = $notificationRepository;
        $this->mustAvoidUserRepository = $mustAvoidUserRepository;
        $this->userRepository = $userRepository;
        $this->mailer = $mailer;
    }

    public function isMember($id, $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->exists($id, $userid);
    }

    public function getUserIds($id)
    {
        if ($this->cache->has('community-members-'.$id)) {
            $cached = $this->cache->get('community-members-'.$id);
            // Ensure cached result is an array
            return is_array($cached) ? $cached : (is_object($cached) && method_exists($cached, 'toArray') ? $cached->toArray() : []);
        } else {
            $members = $this->model->where('community_id', '=', $id)->pluck('user_id');

            // Convert Collection to array for consistent return type
            $membersArray = is_object($members) && method_exists($members, 'toArray') ? $members->toArray() : $members;

            $this->cache->forever('community-members-'.$id, $membersArray);

            return $membersArray;
        }
    }

    public function getIds($userid)
    {
        if ($this->cache->has('user-communities'.$userid)) {
            $cached = $this->cache->get('user-communities'.$userid);
            // Ensure cached result is an array
            return is_array($cached) ? $cached : (is_object($cached) && method_exists($cached, 'toArray') ? $cached->toArray() : []);
        } else {
            $members = $this->model->where('user_id', '=', $userid)->pluck('community_id');
            
            // Convert Collection to array for consistent return type
            $membersArray = is_object($members) && method_exists($members, 'toArray') ? $members->toArray() : $members;
            $membersArray[] = 0;

            $this->cache->forever('user-communities'.$userid, $membersArray);

            return $membersArray;
        }
    }

    public function getCommunities($userid, $limit)
    {
        return $this->model->with('community')->where('user_id', '=', $userid)->paginate($limit);
    }

    public function getMyAllJoinedCommunities($userid, $limit)
    {
        // if (\Session::has('theCommunityId')){
        //
        //			$cmId = \Session::get('theCommunityId');
        //		    return $this->model->with('community')->where('user_id', '=', $userid)->where('community_id', '!=', $cmId)->get();
        //		}else{
        return $this->model->with('community')->where('user_id', '=', $userid)->get();
        // }
    }

    public function getMyJoinedCommunities($userid, $limit)
    {
        return $this->model->with('community')->where('user_id', '=', $userid)->get();
    }

    public function listUsers($id, $limit = 10, $term = null)
    {
        $data = $this->model->with('user');

        if ($term) {
            $membersIds = $this->getMembersIds($id);
            $usersIds = $this->userRepository->searchByIdTerm($term, $membersIds);
            $data->whereIn('user_id', $usersIds);
        }

        return $data
            ->whereNotIn('user_id', $this->mustAvoidUserRepository->get())
            ->where('community_id', '=', $id)->paginate($limit);
    }

    /**
     * MEthod to add member to a community
     *
     * @param  int  $id
     * @param  int  $userid
     * @return bool
     */
    public function add($id, $userid = null)
    {
        if (! \Auth::check() and empty($userid)) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        if (! $this->exists($id, $userid)) {
            $member = $this->model->newInstance();
            $member->community_id = sanitizeText($id);
            $member->user_id = sanitizeText($userid);
            $member->save();

            $this->cache->forget('community-members-'.$id);
            $this->cache->forget('user-communities'.$userid);
            $this->cache->forget('community-suggestions-'.$userid);

            // lets send a notification to the owner of this community
            // $community = app('App\\Repositories\\CommunityRepository')->get($id);

            $community = app('App\\Repositories\\CommunityRepository')->getById($id);
            $this->notification->send($community->user_id, [
                'path' => 'notification.community.join',
                'community' => $community,
            ], $userid, false, null, null, $community->id);

            $this->userRepository->setFavoutriteCmByUserId($id, $userid);

            return true;
        }

        return true;
    }

    public function exists($id, $userid)
    {
        $members = $this->getUserIds($id);

        // Convert Collection to array if needed for in_array compatibility
        if (is_object($members) && method_exists($members, 'toArray')) {
            $members = $members->toArray();
        }

        return in_array($userid, $members);
    }

    public function delete($id, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        $this->cache->forget('community-members-'.$id);
        $this->cache->forget('user-communities'.$userid);

        return $this->model->where('community_id', '=', $id)->where('user_id', '=', $userid)->delete();
    }

    public function deleteAllByCommunity($id)
    {
        $this->cache->forget('community-members-'.$id);

        return $this->model->where('community_id', '=', $id)->delete();
    }

    public function deleteAllByUser($userid)
    {
        return $this->model->where('user_id', '=', $userid)->delete();
    }

    public function getJoinedCommunities($userid, $offset)
    {
        return $this->model->with('community')->where('user_id', '=', $userid)->skip($offset)->take(10)->get();
    }

    public function listAllUsers($id, $offset)
    {
        return $this->model->with('user')
            ->whereNotIn('user_id', $this->mustAvoidUserRepository->get())
            ->where('community_id', '=', $id)->skip($offset)->take(10)->get();
    }

    public function getMembersIds($community_id)
    {
        $members = $this->model->where('community_id', '=', $community_id)->pluck('user_id');
        
        // Convert Collection to array for consistent return type
        return is_object($members) && method_exists($members, 'toArray') ? $members->toArray() : $members;
    }

    public function assignAdmin($id, $value)
    {
        return $data = $this->model->where('id', '=', $id)->update(['is_admin' => $value]);

        /*if($value==1){
            $community = app('App\\Repositories\\CommunityRepository')->getById($data->community_id);
            $this->notification->send($data->user_id, [
                'path' => 'notification.community.admin',
                'community' => $community
            ], $userid,false,null,null,$community->id);
        }*/
    }

    public function listAllMembers($id)
    {
        return $this->model->with('user')
            ->whereNotIn('user_id', $this->mustAvoidUserRepository->get())
            ->where('community_id', '=', $id)->get();
    }

    public function acceptGroupMemberRequest($id, $userid = null)
    {
        if (! \Auth::check() and empty($userid)) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        if (! $this->exists($id, $userid)) {
            $member = $this->model->newInstance();
            $member->community_id = sanitizeText($id);
            $member->user_id = sanitizeText($userid);
            $member->save();

            $this->cache->forget('community-members-'.$id);
            $this->cache->forget('user-communities'.$userid);
            $this->cache->forget('community-suggestions-'.$userid);

            $this->userRepository->setFavoutriteCmByUserId($id, $userid);

            return true;
        }

        return true;
    }

    public function addEventCommunityMember($id, $userid = null)
    {
        $userid = (empty($userid)) ? \Auth::user()->id : $userid;

        if (! $this->exists($id, $userid)) {
            $member = $this->model->newInstance();
            $member->community_id = sanitizeText($id);
            $member->user_id = sanitizeText($userid);
            $member->save();

            $this->cache->forget('community-members-'.$id);
            $this->cache->forget('user-communities'.$userid);
            $this->cache->forget('community-suggestions-'.$userid);
        }

        return true;
    }

    public function deactivateCRM($id, $community)
    {
        $this->model->where('id', '=', $id)->update(['crm_access' => 0]);

        $data = $this->findById($id);

        $community_id = $community->id;

        $communityOwner = $this->crmUserExist($community->user_id, $community_id);
        $communityOwnerId = '';
        if ($communityOwner) {
            $communityOwnerId = $communityOwner[0]->id;
        }

        if ($data and $communityOwnerId) {
            $user_id = $data->user_id;

            $user = $this->userRepository->findByIdUsername($user_id);

            if ($user) {
                if (! $this->crmUserExist($user_id, $community_id)) {
                    \DB::table('id_crm_users')->insert([
                        'email' => $user->email_address,
                        'password' => $user->password,
                        'first_name' => $user->fullname,
                        'type' => 'team',
                        'idhubs_id' => $user_id,
                        'creatorid' => $communityOwnerId,
                        'community_id' => $community_id,
                        'role_id' => 12,
                        'crm_access' => 0
                    ]);
                } else {
                    \DB::table('id_crm_users')->where('idhubs_id', $user_id)->where('community_id', $community_id)->update(['crm_access' => 0]);
                }
            }
        }
    }

    public function activateCRM($id, $community)
    {
        $this->model->where('id', '=', $id)->update(['crm_access' => 1]);

        $data = $this->findById($id);

        $community_id = $community->id;

        $communityOwner = $this->crmUserExist($community->user_id, $community_id);
        $communityOwnerId = '';
        if ($communityOwner) {
            $communityOwnerId = $communityOwner[0]->id;
        }

        if ($data and $communityOwnerId) {
            $user_id = $data->user_id;

            $user = $this->userRepository->findByIdUsername($user_id);

            if ($user) {
                if (! $this->crmUserExist($user_id, $community_id)) {
                    \DB::table('id_crm_users')->insert([
                        'email' => $user->email_address,
                        'password' => $user->password,
                        'first_name' => $user->fullname,
                        'type' => 'team',
                        'idhubs_id' => $user_id,
                        'creatorid' => $communityOwnerId,
                        'community_id' => $community_id,
                        'role_id' => 12,
                        'crm_access' => 1
                    ]);
                } else {
                    \DB::table('id_crm_users')->where('idhubs_id', $user_id)->where('community_id', $community_id)->update(['crm_access' => 1]);
                }
            }
        }
    }

    public function crmUserExist($user_id, $community_id)
    {
        $crmUser = \DB::table('id_crm_users')
            ->where('idhubs_id', $user_id)
            ->where('community_id', $community_id)
            ->get();

        return $crmUser->toArray();
    }

    public function findById($id)
    {
        return $this->model->where('id', '=', $id)->first();
    }

    public function canAccessCRM($user_id, $community_id)
    {
        return $this->model
            ->where('user_id', '=', $user_id)
            ->where('community_id', '=', $community_id)
            ->where('crm_access', '=', 1)
            ->first();
    }

    public function findByIdCommunityId($id, $community_id)
    {
        return $this->model->where('id', '=', $id)->where('community_id', '=', $community_id)->first();
    }

    public function getNominatedUserIds($community_id)
    {
        $userIds = $this->model
            ->where('show_posts', '=', 1)
            ->where('community_id', '=', $community_id)
            ->pluck('user_id');
            
        // Convert Collection to array for consistent return type
        return is_object($userIds) && method_exists($userIds, 'toArray') ? $userIds->toArray() : $userIds;
    }

    public function findByUserIdCommunityId($id, $community_id)
    {
        return $this->model->where('user_id', '=', $id)->where('community_id', '=', $community_id)->first();
    }
	
	public function getSubAdmins($community_id)
    {
        return $this->model->where('is_sub_admin', '=', 1)->where('community_id', '=', $community_id)->count();
    }
	
	public function removeSubAdminsFromPlan($community_id,$limit)
    {
        $suadmins=$this->model->where('is_sub_admin', '=', 1)->where('community_id', '=', $community_id)->paginate($limit);
		foreach( $suadmins as $admin){
			$admin->is_sub_admin=0;
			$admin->save();
		}
    }
}
