Proyectos de Subversion LeadersLinked - Services

Rev

Rev 707 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php

declare(strict_types=1);

namespace LeadersLinked\Controller;

use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\JsonModel;
use LeadersLinked\Mapper\CalendarEventMapper;
use LeadersLinked\Mapper\CompanyFollowerMapper;
use LeadersLinked\Mapper\JobDescriptionMapper;
use LeadersLinked\Mapper\PerformanceEvaluationFormMapper;
use LeadersLinked\Mapper\PerformanceEvaluationTestMapper;
use LeadersLinked\Mapper\QueryMapper;
use LeadersLinked\Mapper\RecruitmentSelectionCandidateMapper;
use LeadersLinked\Mapper\RecruitmentSelectionInterviewMapper;
use LeadersLinked\Mapper\RecruitmentSelectionVacancyMapper;
use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Mapper\ZoomMeetingMapper;
use LeadersLinked\Library\Functions;
use LeadersLinked\Mapper\UserNotificationSettingMapper;

use LeadersLinked\Model\CalendarEvent;
use LeadersLinked\Model\User;
use LeadersLinked\Mapper\ConnectionMapper;
use LeadersLinked\Mapper\ProfileVisitMapper;
use LeadersLinked\Mapper\GroupMemberMapper;
use LeadersLinked\Model\GroupMember;
use LeadersLinked\Mapper\GroupMapper;
use LeadersLinked\Model\Group;
use Laminas\Db\Sql\Expression;
use LeadersLinked\Mapper\CompanyUserMapper;
use LeadersLinked\Model\CompanyUser;
use LeadersLinked\Model\UserType;
use LeadersLinked\Model\Notification;
use LeadersLinked\Mapper\NotificationMapper;
use LeadersLinked\Mapper\EmailTemplateMapper;
use LeadersLinked\Model\EmailTemplate;
use LeadersLinked\Library\QueueEmail;
use LeadersLinked\Mapper\PostMapper;
use LeadersLinked\Mapper\CompanyMapper;
use LeadersLinked\Model\Company;
use LeadersLinked\Model\Connection;
use LeadersLinked\Mapper\UserProfileMapper;
use LeadersLinked\Model\Network;
use LeadersLinked\Mapper\LocationMapper;
use LeadersLinked\Mapper\CompanySizeMapper;
use LeadersLinked\Mapper\DegreeMapper;
use LeadersLinked\Mapper\LanguageMapper;
use LeadersLinked\Mapper\SkillMapper;
use LeadersLinked\Mapper\AptitudeMapper;
use LeadersLinked\Mapper\HobbyAndInterestMapper;
use LeadersLinked\Mapper\IndustryMapper;
use LeadersLinked\Mapper\SurveyTestMapper;
use LeadersLinked\Mapper\SurveyCampaignMapper;
use LeadersLinked\Mapper\GroupTypeMapper;
use LeadersLinked\Mapper\FeedMapper;
use LeadersLinked\Model\Feed;
use LeadersLinked\Model\AbuseReport;
use LeadersLinked\Form\AbuseReport\CreateForm;
use LeadersLinked\Model\Post;
use LeadersLinked\Mapper\CommentMapper;
use LeadersLinked\Model\Comment;
use LeadersLinked\Mapper\AbuseReportMapper;
use LeadersLinked\Mapper\UserBlockedMapper;
use LeadersLinked\Model\UserBlocked;
use LeadersLinked\Library\Storage;
use LeadersLinked\Mapper\MicrolearningTopicUserMapper;

class HelperController extends AbstractActionController
{

    /**
     *
     * @var \Laminas\Db\Adapter\AdapterInterface
     */
    private $adapter;
    
    /**
     *
     * @var \LeadersLinked\Cache\CacheInterface
     */
    private $cache;
    
    
    /**
     *
     * @var \Laminas\Log\LoggerInterface
     */
    private $logger;
    
    /**
     *
     * @var array
     */
    private $config;
    
    
    /**
     *
     * @var \Laminas\Mvc\I18n\Translator
     */
    private $translator;


    /**
     *
     * @var array
     */
    private $navigation;

    /**
     *
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
     * @param \LeadersLinked\Cache\CacheInterface $cache
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
     * @param array $config
     * @param \Laminas\Mvc\I18n\Translator $translator
     * @param array $navigation
     */
    public function __construct($adapter, $cache, $logger, $config, $translator, $navigation)
    {
        $this->adapter      = $adapter;
        $this->cache        = $cache;
        $this->logger       = $logger;
        $this->config       = $config;
        $this->translator   = $translator;
        $this->navigation   = $navigation;
    }


    /**
     * Recuperamos las personas que pueda conocer
     * tiene que enviarse un petición GET a la siguiente url: /helpers/people-you-may-know
     * retorna un json en caso de ser  positivo
     * [
     *  'success' : true,
     *  'data' : [
     *      [
     *        'id'      => 'id del usuario encriptado',
     *        'name'    => 'nombre del usuario',
     *        'image'   => 'imagen del usuario',
     *        'profile' => 'url del profile',
     *     ]
     * ]
     * En caso de ser negativo
     * [
     *  'success' : false,
     *  'data' : mensaje de error
     * ]
     * @return \Laminas\View\Model\JsonModel
     */
    public function peopleYouMayKnowAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
            $first_degree_connections_ids = $connectionMapper->fetchAllConnectionsByUserReturnIds($currentUser->id);
            $first_degree_connections_ids = $first_degree_connections_ids ? $first_degree_connections_ids : [0];

            $second_degree_connections_ids = $connectionMapper->fetchAllSecondDegreeConnectionsForUserIdReturnIds($currentUser->id);
            $second_degree_connections_ids = $second_degree_connections_ids ? $second_degree_connections_ids : [0];

            /*Usuarios de la empresas donde trabajo o soy dueño */
            $company_user_ids = [];
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);

            $records = $companyUserMapper->fetchAllByUserId($currentUser->id);
            foreach ($records as $record) {

                if ($record->status != CompanyUser::STATUS_ACCEPTED) {
                    continue;
                }

                $otherUsers = $companyUserMapper->fetchAllByCompanyId($record->company_id);
                foreach ($otherUsers as $otherUser) {
                    if ($currentUser->id != $otherUser->user_id && $otherUser->creator == CompanyUser::CREATOR_NO && $otherUser->status == CompanyUser::STATUS_ACCEPTED) {

                        if (!in_array($otherUser->user_id, $company_user_ids)) {
                            array_push($company_user_ids, $otherUser->user_id);
                        }
                    }
                }
            }
            $company_user_ids =  $company_user_ids ? $company_user_ids : [0];

            /* Usuario de los grupos donde soy dueño o participo */

            $groupMemberMapper = GroupMemberMapper::getInstance($this->adapter);

            $group_member_ids = [];

            $records = $groupMemberMapper->fetchAllByUserId($currentUser->id);
            foreach ($records as $record) {
                if ($record->status != GroupMember::STATUS_ACCEPTED) {
                    continue;
                }

                $otherUsers = $groupMemberMapper->fetchAllByGroupId($record->group_id);
                foreach ($otherUsers as $otherUser) {
                    if ($currentUser->id != $otherUser->user_id && $otherUser->status == GroupMember::STATUS_ACCEPTED) {

                        if (!in_array($otherUser->user_id, $group_member_ids)) {
                            array_push($group_member_ids, $otherUser->user_id);
                        }
                    }
                }
            }

            $group_member_ids = $group_member_ids ? $group_member_ids : [0];



            /* Usuarios con que comparto topicos */
            $topic_user_ids = [];
            $topicUserMapper = MicrolearningTopicUserMapper::getInstance($this->adapter);

            $company_ids = [];
            $records = $topicUserMapper->fetchAllActiveByUserId($currentUser->id);
            foreach ($records as $record) {
                if (!in_array($record->company_id, $company_ids)) {
                    array_push($company_ids, $record->company_id);
                }
            }



            foreach ($company_ids as $company_id) {
                $otherUsers = $topicUserMapper->fetchAllUserIdsForTopicsActiveByCompanyId($company_id);
                foreach ($otherUsers as $user_id) {
                    if ($currentUser->id != $user_id) {

                        if (!in_array($user_id, $topic_user_ids)) {
                            array_push($topic_user_ids, $user_id);
                        }
                    }
                }
            }

            $topic_user_ids = $topic_user_ids ? $topic_user_ids : [0];


            $other_users = array_unique(array_merge(
                $second_degree_connections_ids,
                $company_user_ids,
                $group_member_ids,
                $topic_user_ids
            ));








            $items = [];
            $queryMapper = QueryMapper::getInstance($this->adapter);
            $select = $queryMapper->getSql()->select();
            $select->columns(['id', 'uuid',  'first_name', 'last_name', 'image']);
            $select->from(['u' => UserMapper::_TABLE]);
            $select->join(['up' => UserProfileMapper::_TABLE], 'up.user_id = u.id ', ['description']);
            $select->where->equalTo('network_id', $currentUser->network_id);
            $select->where->in('u.id', $other_users);
            $select->where->notIn('u.id', $first_degree_connections_ids);
            $select->where->notEqualTo('u.id', $currentUser->id);
            $select->where->equalTo('u.status', User::STATUS_ACTIVE);
            $select->where->in('u.usertype_id', [UserType::ADMIN, UserType::USER]);
            $select->order(['first_name', 'last_name']);

            //echo $select->getSqlString($this->adapter->platform); exit;

            $storage = Storage::getInstance($this->config, $this->adapter);

            
            $records = $queryMapper->fetchAll($select);
            foreach ($records as $record) {

                $relation = [];
                if (in_array($record['id'], $second_degree_connections_ids)) {
                    array_push($relation, 'LABEL_RELATION_TYPE_SECOND_GRADE');
                }
                if (in_array($record['id'], $company_user_ids)) {
                    array_push($relation, 'LABEL_RELATION_TYPE_COMPANY_USER');
                }
                if (in_array($record['id'], $group_member_ids)) {
                    array_push($relation, 'LABEL_RELATION_TYPE_GROUP_MEMBER');
                }
                if (in_array($record['id'], $topic_user_ids)) {
                    array_push($relation, 'LABEL_RELATION_TYPE_TOPIC_USER');
                }


                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $record['id']);

                $item = [
                    'id'    => $record['uuid'],
                    'name'  => trim($record['first_name'] . ' ' . $record['last_name']),
                    'image' =>   $storage->getUserImageForCodeAndFilename($record['uuid'], $record['image']),
                    'profile'   => $this->url()->fromRoute('profile/view', ['id' => $record['uuid']]),
                    'relation' => $relation,
                    'link_cancel'   => '',
                    'link_request'  => '',
                    'user_profile' => $record['description'],
                ];

                if ($connection) {
                    switch ($connection->status) {
                        case Connection::STATUS_SENT:
                            $item['link_cancel'] = $this->url()->fromRoute('connection/delete', ['id' => $record['uuid']]);
                            break;

                        case Connection::STATUS_ACCEPTED:
                            $item['link_cancel'] = $this->url()->fromRoute('connection/cancel', ['id' => $record['uuid']]);
                            break;

                        default:
                            $item['link_request'] = $this->url()->fromRoute('connection/request', ['id' => $record['uuid']]);
                            break;
                    }
                } else {
                    $item['link_request'] = $this->url()->fromRoute('connection/request', ['id' => $record['uuid']]);
                }


                array_push($items, $item);
            }

            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    /**
     * Recuperamos las personas que pueda conocer
     * tiene que enviarse un petición GET a la siguiente url: /helpers/people-viewed-profile/:user_profile_id
     * retorna un json en caso de ser  positivo
     * [
     *  'success' : true,
     *  'data' : [
     *      [
     *        'id'      => 'id del usuario encriptado',
     *        'name'    => 'nombre del usuario',
     *        'image'   => 'imagen del usuario',
     *        'profile' => 'url del profile',
     *     ]
     * ]
     * En caso de ser negativo
     * [
     *  'success' : false,
     *  'data' : mensaje de error
     * ]
     * @return \Laminas\View\Model\JsonModel
     */
    public function peopleViewedProfileAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

            $items = [];
            $user_profile_id = $this->params()->fromRoute('user_profile_id');

            $items = [];

            $mapper = QueryMapper::getInstance($this->adapter);
            $select = $mapper->getSql()->select(ProfileVisitMapper::_TABLE);
            $select->columns(['user_id' => new Expression('DISTINCT(visitor_id)')]);
            $select->where->equalTo('user_profile_id', $user_profile_id);
            $records = $mapper->fetchAll($select);

            if ($records) {

                $user_ids = [];
                foreach ($records as $record) {
                    array_push($user_ids, $record['user_id']);
                }

                $mapper = QueryMapper::getInstance($this->adapter);
                $select = $mapper->getSql()->select(UserMapper::_TABLE);
                $select->columns(['id', 'uuid', 'first_name', 'last_name', 'image']);
                $select->where->in('id', $user_ids);
                $select->where->equalTo('network_id', $currentUser->network_id);
                $select->where->equalTo('status', User::STATUS_ACTIVE);
                $select->order(['last_name ASC', 'first_name ASC']);

                $storage = Storage::getInstance($this->config, $this->adapter);

                
                $records = $mapper->fetchAll($select);
                foreach ($records as $record) {
                    array_push($items, [
                        'id'        => $record['uuid'],
                        'name'      => trim($record['first_name'] . ' ' . $record['last_name']),
                        'image' => $storage->getUserImageForCodeAndFilename($record['uuid'], $record['image']),
                        'profile'   => $this->url()->fromRoute('profile/view', ['id' => $record['uuid']]),
                        'profile'   => $this->url()->fromRoute('profile/view', ['id' => $record['uuid']]),
                    ]);
                }
            }


            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }


    /**
     * Recuperamos los seguidores de la empresa
     * tiene que enviarse un petición GET a la siguiente url: /helpers/company-follower/:company_id
     * retorna un json en caso de ser  positivo
     * [
     *  'success' : true,
     *  'data' : [
     *      [
     *        'id'      => 'id del usuario encriptado',
     *        'name'    => 'nombre del usuario',
     *        'image'   => 'imagen del usuario',
     *        'profile' => 'url del profile',
     *     ]
     * ]
     * En caso de ser negativo
     * [
     *  'success' : false,
     *  'data' : mensaje de error
     * ]
     * @return \Laminas\View\Model\JsonModel
     */
    public function companyFollowerAction()
    {


        $request = $this->getRequest();
        if ($request->isGet()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

            $company_uuid  = $this->params()->fromRoute('company_id');

            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOneByUuidAndNetworkId($company_uuid, $currentUser->network_id);

            $items = [];
            if ($company && $company->status == Company::STATUS_ACTIVE) {

                $companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);
                $records = $companyFollowerMapper->fetchAllByCompanyId($company->id);

                $ids = [];
                foreach ($records as $record) {
                    if (!in_array($record->follower_id, $ids)) {
                        array_push($ids, $record->follower_id);
                    }
                }

                if ($ids) {

                    $mapper = QueryMapper::getInstance($this->adapter);
                    $select = $mapper->getSql()->select(UserMapper::_TABLE);
                    $select->columns(['id', 'uuid', 'first_name', 'last_name', 'image']);
                    $select->where->equalTo('network_id', $currentUser->network_id);
                    $select->where->in('id', $ids);
                    $select->where->equalTo('status', User::STATUS_ACTIVE);
                    $select->order(['last_name', 'first_name']);

                    //echo $select->getSqlString($this->adapter->platform); exit;


                    $storage = Storage::getInstance($this->config, $this->adapter);

                    $records = $mapper->fetchAll($select);
                    foreach ($records as $record) {


                        array_push($items, [
                            'id'        => $record['uuid'],
                            'name'      => trim($record['first_name'] . ' ' . $record['last_name']),
                            'image'     =>  $storage->getUserImageForCodeAndFilename($record['uuid'], $record['image']),
                            'profile'   => $this->url()->fromRoute('profile/view', ['id' => $record['uuid']]),
                        ]);
                    }
                }
            }

            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function companySuggestionAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

            $company_uuid = $this->params()->fromRoute('company_id');

            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOneByUuidAndNetworkId($company_uuid, $currentUser->network_id);

            $items = [];
            if ($company && $company->status == Company::STATUS_ACTIVE) {


                $mapper = QueryMapper::getInstance($this->adapter);
                $select = $mapper->getSql()->select(CompanyMapper::_TABLE);
                $select->columns(['id', 'uuid', 'name', 'image']);
                $select->where->equalTo('network_id', $currentUser->network_id);
                $select->where->notEqualTo('id', $company->id);
                $select->where->equalTo('status', Company::STATUS_ACTIVE);
                $select->where->equalTo('industry_id', $company->industry_id);
                //  $select->where->equalTo('company_size_id', $company->company_size_id);
                $select->order(['name']);


                //echo $select->getSqlString($this->adapter->platform); exit;

                $storage = Storage::getInstance($this->config, $this->adapter);

                
                $records = $mapper->fetchAll($select);
                foreach ($records as $record) {
                    array_push($items, [
                        'id'        => $record['uuid'],
                        'name'      => trim($record['name']),
                        'image'     => $storage->getCompanyImageForCodeAndFilename($record['uuid'], $record['image']) ,
                        'profile'   => $this->url()->fromRoute('company/view', ['id' => $record['uuid']]),
                    ]);
                }
            }

            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    /**
     * Recuperamos los miembros del grupo
     * tiene que enviarse un petición GET a la siguiente url: /helpers/group-members/:group_id
     * retorna un json en caso de ser  positivo
     * [
     *  'success' : true,
     *  'data' : [
     *      [
     *        'id'      => 'id del usuario encriptado',
     *        'name'    => 'nombre del usuario',
     *        'image'   => 'imagen del usuario',
     *        'profile' => 'url del profile',
     *     ]
     * ]
     * En caso de ser negativo
     * [
     *  'success' : false,
     *  'data' : mensaje de error
     * ]
     * @return \Laminas\View\Model\JsonModel
     */
    public function groupMembersAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $request = $this->getRequest();
        if ($request->isGet()) {

            $group_uuid = $this->params()->fromRoute('group_id');

            $groupMapper = GroupMapper::getInstance($this->adapter);
            $group = $groupMapper->fetchOneByUuidAndNetworkId($group_uuid, $currentUser->network_id);

            $items = [];
            if ($group && $group->status == Group::STATUS_ACTIVE) {

                $mapper = QueryMapper::getInstance($this->adapter);
                $select = $mapper->getSql()->select();
                $select->columns(['id', 'uuid', 'first_name', 'last_name', 'image']);
                $select->from(['u' => UserMapper::_TABLE]);
                $select->join(['gm' => GroupMemberMapper::_TABLE], 'gm.user_id = u.id ', ['user_id', 'status']);
                $select->join(['g' => GroupMapper::_TABLE], 'gm.group_id = g.id', ['group_uuid' => 'uuid']);
                $select->where->equalTo('u.network_id',  $currentUser->network_id);
                $select->where->equalTo('g.network_id', $currentUser->network_id);
                $select->where->equalTo('g.uuid', $group_uuid);

                if ($group->user_id == $currentUser->id) {
                    $select->where->in('gm.status', [
                        GroupMember::STATUS_ACCEPTED,
                        GroupMember::STATUS_ADDED_BY_ADMIN,
                        GroupMember::STATUS_AUTO_JOIN,
                        GroupMember::STATUS_JOINING_REQUESTED,
                    ]);
                } else {
                    $select->where->in('gm.status', [GroupMember::STATUS_ACCEPTED, GroupMember::STATUS_AUTO_JOIN]);
                }


                $select->where->equalTo('u.status', User::STATUS_ACTIVE);
                $select->order(['last_name', 'first_name']);

                //echo $select->getSqlString($this->adapter->platform);


                $storage = Storage::getInstance($this->config, $this->adapter);


                $records = $mapper->fetchAll($select);
                foreach ($records as $record) {

                    $actions = [];
                    if ($group->user_id == $currentUser->id) {
                        if ($record['id'] != $currentUser->id) {



                            switch ($record['status']) {
                                case GroupMember::STATUS_JOINING_REQUESTED:
                                    $actions['link_approve'] = $this->url()->fromRoute('helpers/group-members/approve', ['group_id' => $group->uuid, 'user_id' => $record['uuid']]);
                                    $actions['link_reject'] = $this->url()->fromRoute('helpers/group-members/reject', ['group_id' => $group->uuid, 'user_id' => $record['uuid']]);
                                    break;

                                case GroupMember::STATUS_ACCEPTED:
                                case GroupMember::STATUS_AUTO_JOIN:
                                case GroupMember::STATUS_ADDED_BY_ADMIN:
                                    $actions['link_cancel'] = $this->url()->fromRoute('helpers/group-members/cancel', ['group_id' => $group->uuid, 'user_id' => $record['uuid']]);
                                    break;
                            }
                        }
                    }

                    array_push($items, [
                        'id'        => $record['uuid'],
                        'name'      => trim($record['first_name'] . ' ' . $record['last_name']),
                        'image'     =>  $storage->getGroupImageForCodeAndFilename($record['uuid'], $record['image']),
                        'profile'   => $this->url()->fromRoute('profile/view', ['id' => $record['uuid']]),
                        'actions'   => $actions,

                    ]);
                }
            }

            return new JsonModel([
                'success' => true,
                'data' => [
                    'items' => $items,
                    'link_invite' => $group->user_id == $currentUser->id ? $this->url()->fromRoute('helpers/group-members/invite', ['group_id' => $group->uuid])  : '',
                ]
            ]);
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function groupMemberInviteAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $group_uuid = $this->params()->fromRoute('group_id');

        $groupMapper = GroupMapper::getInstance($this->adapter);
        $group = $groupMapper->fetchOneByUuidAndNetworkId($group_uuid, $currentUser->network_id);

        if (!$group) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_GROUP_NOT_FOUND'
            ]);
        }

        if ($group->status != Group::STATUS_ACTIVE) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_GROUP_IS_NOT_ACTIVE'
            ]);
        }

        if ($currentUser->id != $group->user_id) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_GROUP_IS_NOT_YOU_ARE_THE_OWNER_OF_THIS_GROUP'
            ]);
        }


        $request = $this->getRequest();
        if ($request->isGet()) {
            $search = filter_var($this->params()->fromQuery('search', ''));
            if (strlen($search) >= 3) {

                $userMapper = UserMapper::getInstance($this->adapter);
                $records  = $userMapper->fetchAllSuggestForInvitationByGroupIdAndNetworkIdAndSearch($group->id, $currentUser->network_id, $search);

                $users = [];
                foreach ($records as $record) {
                    array_push($users, [
                        'value' => $record->uuid,
                        'text' => trim($record->first_name . ' ' . $record->last_name) . ' (' . $record->email . ')'

                    ]);
                }

                return new JsonModel([
                    'success' => true,
                    'data' => $users
                ]);
            } else {
                return new JsonModel([
                    'success' => true,
                    'data' => []
                ]);
            }
        } else if ($request->isPost()) {
            $uuid = $this->params()->fromPost('id');
            if (!$uuid) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_INVALID_PARAMETER'
                ]);
            }

            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuidAndNetworkId($uuid, $currentUser->network_id);

            if (!$user) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_NOT_FOUND'
                ]);
            }

            if ($user->status != User::STATUS_ACTIVE) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_IS_INACTIVE'
                ]);
            }

            if ($group->user_id == $user->id) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_GROUP_YOU_ARE_THE_OWNER_OF_THIS_GROUP'
                ]);
            }

            $groupMemberMapper = GroupMemberMapper::getInstance($this->adapter);
            $groupMember = $groupMemberMapper->fetchOneByGroupIdAndUserId($group->id, $user->id);



            if ($groupMember) {
                $result = false;

                switch ($groupMember->status) {
                    case GroupMember::STATUS_ACCEPTED:
                    case GroupMember::STATUS_AUTO_JOIN:

                        return new JsonModel([
                            'success'   => false,
                            'data'      => 'ERROR_GROUP_YOU_ARE_MEMBER',
                        ]);
                        break;


                    case $groupMember->status == GroupMember::STATUS_REJECTED:
                    case $groupMember->status == GroupMember::STATUS_CANCELLED:

                        $groupMember->status = GroupMember::STATUS_ADDED_BY_ADMIN;
                        $groupMember->joining_request_on = date('H-m-d H:i:s');

                        $result = $groupMemberMapper->update($groupMember);
                        break;

                    case GroupMember::STATUS_ADDED_BY_ADMIN:
                    case  GroupMember::STATUS_JOINING_REQUESTED:
                        return new JsonModel([
                            'success'   => false,
                            'data'      => 'ERROR_GROUP_THERE_IS_A_PENDING_REQUEST'
                        ]);
                        break;

                    default:
                        return new JsonModel([
                            'success'   => false,
                            'data'      => 'ERROR_UNKNOWN_OPERATION'
                        ]);
                        break;
                }
            } else {



                $groupMember = new GroupMember();
                $groupMember->user_id = $user->id;
                $groupMember->group_id = $group->id;
                $groupMember->status = GroupMember::STATUS_ADDED_BY_ADMIN;
                $groupMember->joining_request_on = date('H-m-d H:i:s');

                $result = $groupMemberMapper->insert($groupMember);
            }

            if ($result) {

                $notification = new Notification();
                $notification->type     = Notification::TYPE_RECEIVE_INVITATION_GROUP;
                $notification->read     = Notification::NO;
                $notification->user_id  = $user->id;
                $notification->group_id = $group->id;
                $notification->message  = 'LABEL_NOTIFICATION_RECEIVE_INVITATION_GROUP';
                $notification->url      = $this->url()->fromRoute('group/view', ['id' => $group->uuid]);

                $notificationMapper = NotificationMapper::getInstance($this->adapter);
                $notificationMapper->insert($notification);

                $userNotificationMapper = UserNotificationSettingMapper::getInstance($this->adapter);
                $userNotification = $userNotificationMapper->fetchOne($user->id);

                if ($userNotification && $userNotification->receive_invitation_group) {
                    $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
                    $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_RECEIVE_INVITATION_GROUP, $currentUser->network_id);

                    if ($emailTemplate) {
                        $arrayCont = [
                            'firstname'             => $currentUser->first_name,
                            'lastname'              => $currentUser->last_name,
                            'other_user_firstname'  => $user->first_name,
                            'other_user_lastname'   => $user->last_name,
                            'company_name'          => '',
                            'group_name'            => $group->name,
                            'content'               => '',
                            'code'                  => '',
                            'link'                  => $this->url()->fromRoute('group/view', ['id' => $group->uuid], ['force_canonical' => true])
                        ];

                        $email = new QueueEmail($this->adapter);
                        $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
                    }
                }

                return new JsonModel([
                    'success'   => true,
                    'data'      => 'LABEL_GROUP_REQUEST_SUCCESS'
                ]);
            } else {

                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_GROUP_REQUEST_COULD_NOT_BE_SENT'
                ]);
            }
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function  groupMemberCancelAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $group_uuid = $this->params()->fromRoute('group_id');
            $user_uuid  = $this->params()->fromRoute('user_id');

            $groupMapper = GroupMapper::getInstance($this->adapter);
            $group = $groupMapper->fetchOneByUuidAndNetworkId($group_uuid, $currentUser->network_id);

            if (!$group) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_GROUP_NOT_FOUND'
                ]);
            }

            if ($group->status != Group::STATUS_ACTIVE) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_GROUP_IS_NOT_ACTIVE'
                ]);
            }

            if ($currentUser->id != $group->user_id) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_GROUP_IS_NOT_YOU_ARE_THE_OWNER_OF_THIS_GROUP'
                ]);
            }

            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuidAndNetworkId($user_uuid, $currentUser->network_id);

            if (!$user) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_USER_NOT_FOUND'
                ]);
            }

            if ($user->id == $currentUser->id) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_GROUP_YOU_ARE_THE_OWNER_OF_THIS_GROUP'
                ]);
            }



            $groupMemberMapper = GroupMemberMapper::getInstance($this->adapter);
            $groupMember = $groupMemberMapper->fetchOneByGroupIdAndUserId($group->id, $user->id);
            if ($groupMember) {

                if (
                    $groupMember->status == GroupMember::STATUS_ACCEPTED ||
                    $groupMember->status == GroupMember::STATUS_ADDED_BY_ADMIN ||
                    $groupMember->status == GroupMember::STATUS_AUTO_JOIN
                ) {

                    $groupMember->status = GroupMember::STATUS_CANCELLED;
                    if ($groupMemberMapper->update($groupMember)) {

                        return new JsonModel([
                            'success' => true,
                            'data' =>  'LABEL_GROUP_MEMBER_CANCELLED_SUCCESS'
                        ]);
                    } else {
                        return new JsonModel([
                            'success' => true,
                            'data' =>    'LABEL_GROUP_MEMBER_CANCELLED_FAILED'
                        ]);
                    }
                }
            }


            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_GROUP_REQUEST_OR_MEMBER_NOT_FOUND_TO_CANCEL'
            ]);
        } else {

            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function  groupMemberRejectAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $group_uuid = $this->params()->fromRoute('group_id');
            $user_uuid  = $this->params()->fromRoute('user_id');

            $groupMapper = GroupMapper::getInstance($this->adapter);
            $group = $groupMapper->fetchOneByUuidAndNetworkId($group_uuid, $currentUser->network_id);

            if (!$group) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_GROUP_NOT_FOUND'
                ]);
            }

            if ($group->status != Group::STATUS_ACTIVE) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_GROUP_IS_NOT_ACTIVE'
                ]);
            }

            if ($currentUser->id != $group->user_id) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_GROUP_IS_NOT_YOU_ARE_THE_OWNER_OF_THIS_GROUP'
                ]);
            }

            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuidAndNetworkId($user_uuid, $currentUser->network_id);

            if (!$user) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_USER_NOT_FOUND'
                ]);
            }

            if ($user->id == $currentUser->id) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_GROUP_YOU_ARE_THE_OWNER_OF_THIS_GROUP'
                ]);
            }



            $groupMemberMapper = GroupMemberMapper::getInstance($this->adapter);
            $groupMember = $groupMemberMapper->fetchOneByGroupIdAndUserId($group->id, $user->id);
            if ($groupMember) {

                if ($groupMember->status == GroupMember::STATUS_JOINING_REQUESTED) {

                    $groupMember->status = GroupMember::STATUS_REJECTED;
                    if ($groupMemberMapper->update($groupMember)) {

                        return new JsonModel([
                            'success' => true,
                            'data' =>  'LABEL_GROUP_MEMBER_REJECTED_SUCCESS'
                        ]);
                    } else {
                        return new JsonModel([
                            'success' => true,
                            'data' =>    'LABEL_GROUP_MEMBER_REJECTED_FAILED'
                        ]);
                    }
                }
            }


            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_GROUP_THERE_IS_NO_PENDING_REQUEST_TO_REJECT'
            ]);
        } else {

            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function  groupMemberApproveAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $group_uuid = $this->params()->fromRoute('group_id');
            $user_uuid  = $this->params()->fromRoute('user_id');

            $groupMapper = GroupMapper::getInstance($this->adapter);
            $group = $groupMapper->fetchOneByUuidAndNetworkId($group_uuid, $currentUser->network_id);

            if (!$group) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_GROUP_NOT_FOUND'
                ]);
            }

            if ($group->status != Group::STATUS_ACTIVE) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_GROUP_IS_NOT_ACTIVE'
                ]);
            }

            if ($currentUser->id != $group->user_id) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_GROUP_IS_NOT_YOU_ARE_THE_OWNER_OF_THIS_GROUP'
                ]);
            }

            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuidAndNetworkId($user_uuid, $currentUser->network_id);

            if (!$user) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_USER_NOT_FOUND'
                ]);
            }

            if ($user->id == $currentUser->id) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_GROUP_YOU_ARE_THE_OWNER_OF_THIS_GROUP'
                ]);
            }



            $groupMemberMapper = GroupMemberMapper::getInstance($this->adapter);
            $groupMember = $groupMemberMapper->fetchOneByGroupIdAndUserId($group->id, $user->id);
            if ($groupMember) {

                if ($groupMember->status == GroupMember::STATUS_JOINING_REQUESTED) {

                    $groupMember->status = GroupMember::STATUS_ACCEPTED;
                    if ($groupMemberMapper->update($groupMember)) {


                        $notification = new Notification();
                        $notification->type     = Notification::TYPE_ACCEPT_MY_REQUEST_JOIN_GROUP;
                        $notification->read     = Notification::NO;
                        $notification->user_id  = $user->id;
                        $notification->group_id = $group->id;
                        $notification->message  = 'LABEL_NOTIFICATION_ACCEPT_MY_REQUEST_JOIN_GROUP';
                        $notification->url      = $this->url()->fromRoute('group/view', ['id' => $group->uuid]);

                        $notificationMapper = NotificationMapper::getInstance($this->adapter);
                        $notificationMapper->insert($notification);

                        $userNotificationMapper = UserNotificationSettingMapper::getInstance($this->adapter);
                        $userNotification = $userNotificationMapper->fetchOne($user->id);

                        if ($userNotification && $userNotification->receive_invitation_group) {
                            $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
                            $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_ACCEPT_MY_REQUEST_JOIN_GROUP, $currentUser->network_id);

                            if ($emailTemplate) {
                                $arrayCont = [
                                    'firstname'             => $currentUser->first_name,
                                    'lastname'              => $currentUser->last_name,
                                    'other_user_firstname'  => $user->first_name,
                                    'other_user_lastname'   => $user->last_name,
                                    'company_name'          => '',
                                    'group_name'            => $group->name,
                                    'content'               => '',
                                    'code'                  => '',
                                    'link'                  => $this->url()->fromRoute('group/view', ['id' => $group->uuid], ['force_canonical' => true])
                                ];

                                $email = new QueueEmail($this->adapter);
                                $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
                            }
                        }

                        return new JsonModel([
                            'success' => true,
                            'data' =>  'LABEL_GROUP_MEMBER_APPROVED_SUCCESS'
                        ]);
                    } else {
                        return new JsonModel([
                            'success' => true,
                            'data' =>    'LABEL_GROUP_MEMBER_APPROVED_FAILED'
                        ]);
                    }
                }
            }


            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_GROUP_THERE_IS_NO_PENDING_REQUEST_TO_APPROVED'
            ]);
        } else {

            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }


    /**
     * Recuperamos los grupos sugeridos
     * tiene que enviarse un petición GET a la siguiente url: /helpers/groups-suggestion/:group_id
     * retorna un json en caso de ser  positivo
     * [
     *  'success' : true,
     *  'data' : [
     *      [
     *        'id'      => 'id del grupo encriptado',
     *        'name'    => 'nombre del grupo',
     *        'image'   => 'imagen del grupo',
     *        'profile' => 'url del profile',
     *     ]
     * ]
     * En caso de ser negativo
     * [
     *  'success' : false,
     *  'data' : mensaje de error
     * ]
     * @return \Laminas\View\Model\JsonModel
     */
    public function groupsSuggestionAction()
    {

        $request = $this->getRequest();
        if ($request->isGet()) {

            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
            $first_degree_connections_ids = $connectionMapper->fetchAllConnectionsByUserReturnIds($currentUser->id);
            $first_degree_connections_ids = $first_degree_connections_ids ? $first_degree_connections_ids : [0];

            $second_degree_connections_ids = $connectionMapper->fetchAllSecondDegreeConnectionsForUserIdReturnIds($currentUser->id);
            $second_degree_connections_ids = $second_degree_connections_ids ? $second_degree_connections_ids : [0];

            /*Usuarios de la empresas donde trabajo o soy dueño */
            $company_user_ids = [];
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);

            $records = $companyUserMapper->fetchAllByUserId($currentUser->id);
            foreach ($records as $record) {

                if ($record->status != CompanyUser::STATUS_ACCEPTED) {
                    continue;
                }

                $otherUsers = $companyUserMapper->fetchAllByCompanyId($record->company_id);
                foreach ($otherUsers as $otherUser) {
                    if ($currentUser->id != $otherUser->user_id && $otherUser->creator == CompanyUser::CREATOR_NO && $otherUser->status == CompanyUser::STATUS_ACCEPTED) {

                        if (!in_array($otherUser->user_id, $company_user_ids)) {
                            array_push($company_user_ids, $otherUser->user_id);
                        }
                    }
                }
            }
            $company_user_ids =  $company_user_ids ? $company_user_ids : [0];

            /* Usuario de los grupos donde soy dueño o participo */

            $groupMemberMapper = GroupMemberMapper::getInstance($this->adapter);

            $group_member_ids = [];

            $records = $groupMemberMapper->fetchAllByUserId($currentUser->id);
            foreach ($records as $record) {
                if ($record->status != GroupMember::STATUS_ACCEPTED) {
                    continue;
                }

                $otherUsers = $groupMemberMapper->fetchAllByGroupId($record->group_id);
                foreach ($otherUsers as $otherUser) {
                    if ($currentUser->id != $otherUser->user_id && $otherUser->status == GroupMember::STATUS_ACCEPTED) {

                        if (!in_array($otherUser->user_id, $group_member_ids)) {
                            array_push($group_member_ids, $otherUser->user_id);
                        }
                    }
                }
            }

            $group_member_ids = $group_member_ids ? $group_member_ids : [0];

            /* Usuarios con que comparto topicos */
            $topic_user_ids = [];
            $topicUserMapper = MicrolearningTopicUserMapper::getInstance($this->adapter);

            $company_ids = [];
            $records = $topicUserMapper->fetchAllActiveByUserId($currentUser->id);
            foreach ($records as $record) {
                if (!in_array($record->company_id, $company_ids)) {
                    array_push($company_ids, $record->company_id);
                }
            }

            foreach ($company_ids as $company_id) {
                $otherUsers = $topicUserMapper->fetchAllUserIdsForTopicsActiveByCompanyId($company_id);
                foreach ($otherUsers as $user_id) {
                    if ($currentUser->id != $user_id) {

                        if (!in_array($user_id, $topic_user_ids)) {
                            array_push($topic_user_ids, $user_id);
                        }
                    }
                }
            }

            $topic_user_ids = $topic_user_ids ? $topic_user_ids : [0];


            $other_users = array_unique(array_merge(

                $second_degree_connections_ids,
                $company_user_ids,
                $group_member_ids,
                $topic_user_ids
            ));

            $queryMapper = QueryMapper::getInstance($this->adapter);


            $groupMemberMapper = GroupMemberMapper::getInstance($this->adapter);
            $group_ids = $groupMemberMapper->fetchAllGroupIdsByUserIds($other_users);
            $group_ids = $group_ids ? $group_ids : [0];




            $select = $queryMapper->getSql()->select();
            $select->columns(['id', 'uuid', 'name', 'image', 'status', 'privacy', 'priority' => new Expression('0')]);
            $select->from(['g' => GroupMapper::_TABLE]);
            $select->where->equalTo('network_id', $currentUser->network_id);
            $select->where->equalTo('privacy', Group::PRIVACY_IS_PUBLIC);
            $select->where->equalTo('status', Group::STATUS_ACTIVE);
            $select->where->in('g.id', $group_ids);
            $select->where->notEqualTo('g.user_id', $currentUser->id);
            $select->order('name ASC');



            //echo $select->getSqlString($this->adapter->platform); exit;

            $records = $queryMapper->fetchAll($select);
            usort($records, function ($a, $b) {
                if ($a['priority'] == $b['priority']) {
                    return 0;
                } else {
                    return $a['priority'] < $b['priority'] ? 1 : -1;
                }
            });


            $items = [];
            
            $storage = Storage::getInstance($this->config, $this->adapter);


            foreach ($records as $record) {

                array_push($items, [
                    'id'        => $record['uuid'],
                    'name'      => trim($record['name']),
                    'image'     => $storage->getGroupImageForCodeAndFilename($record['uuid'], $record['image']),
                    'profile'   => $this->url()->fromRoute('group/view', ['id' => $record['uuid']]),
                    'priority'  => $record['priority'],

                ]);
            }

            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function postsAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

            $items = [];
            $postMapper = PostMapper::getInstance($this->adapter);
            $posts = $postMapper->fetchAllActiveByNetworkId($currentUser->network_id);


            $storage = Storage::getInstance($this->config, $this->adapter);
            $path = $storage->getPathPost();

            foreach ($posts as $post) {
                $dt = \DateTime::createFromFormat('Y-m-d', $post->date);
                array_push($items, [
                    'image' => $storage->getGenericImage($path, $post->uuid, $post->image),
                    'date' => $dt->format('d/m/Y'),
                    'title' => $post->title,
                    'link' => $this->url()->fromRoute('post', ['id' => $post->uuid]),
                ]);
            }

            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
        }

        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }



    public function searchPeopleAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {

            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

            $storage = Storage::getInstance($this->config, $this->adapter);

            $search = Functions::sanitizeFilterString($this->params()->fromQuery('search'));
            if (strlen($search) >= 3) {

                $userBlockedIds = [$currentUser->id];
                
                
                $userBlockedMapper = \LeadersLinked\Mapper\UserBlockedMapper::getInstance($this->adapter);
                $ids = $userBlockedMapper->fetchAllBlockedReturnIds($currentUser->id);
                foreach($ids as $id)
                {
                    if(!in_array($id, $userBlockedIds)) {
                        array_push($userBlockedIds, $id);
                    }
                }
                
                $ids = $userBlockedMapper->fetchAllUserBlockMeReturnIds($currentUser->id);
                foreach($ids as $id)
                {
                    if(!in_array($id, $userBlockedIds)) {
                        array_push($userBlockedIds, $id);
                    }
                }
                
                
                
                
                $records_x_page = 10;
                $page = intval($this->params()->fromQuery('page', 0), 10);
                $page = $page > 0 ? $page : 1;
                
                $userMapper = UserMapper::getInstance($this->adapter);
                $paginator  = $userMapper->fetchAllSuggestPaginateByNetworkIdAndSearchAndNotBlocked(
                    $currentUser->network_id, $search, $records_x_page, $page, $userBlockedIds );

                $items = [];
                foreach ( $paginator as $record) {
                    if ($currentUser->id == $record->id) {
                        continue;
                    }
 

                    array_push($items, [
                        'uuid' => $record->uuid,
                        'name' => trim($record->first_name . ' ' . $record->last_name),
                        'image' => $storage->getUserImage($record),
                        'profile' => $this->url()->fromRoute('profile/view', ['id' => $record->uuid]),
                        'last_message' => '',
                        'count_unread' => 0,
                        'selected' => 0,
                        'last_message' => '',
                        'messages_url' => $this->url()->fromRoute('inmail/messages',['uuid' => $record->uuid]),
                        'save_url' => $this->url()->fromRoute('inmail/messages/send',['uuid' => $record->uuid]),
                        'delete_url' => $this->url()->fromRoute('inmail/messages/delete',['uuid' => $record->uuid])
                    ]);
                }
                
                
                $response = [
                    'success' => true,
                    'data' => [
                        'total' => [
                            'count' => $paginator->getTotalItemCount(),
                            'pages' => $paginator->getPages()->pageCount,
                        ],
                        'current' => [
                            'items'    => $items,
                            'page'     => $paginator->getCurrentPageNumber(),
                            'count'    => $paginator->getCurrentItemCount(),
                        ]
                    ]
                ];

                return new JsonModel($response);
            } else {
                return new JsonModel([
                    'success' => true,
                    'data' => []
                ]);
            }
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function footerAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {


            $links = isset($this->navigation['footer']) ?  $this->navigation['footer'] : [];


            $data = [];
            foreach ($links as $link) {
                $data[$link['route']] = $link['label'];
            }


            return new JsonModel([
                'success' => true,
                'data' => $data,
            ]);
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }


    /**
     * Recuperamos los grupos sugeridos
     * tiene que enviarse un petición GET a la siguiente url: /helpers/groups-suggestion/:group_id
     * retorna un json en caso de ser  positivo
     * [
     *  'success' : true,
     *  'data' : [
     *      [
     *        'id'      => 'id del grupo encriptado',
     *        'name'    => 'nombre del grupo',
     *        'image'   => 'imagen del grupo',
     *        'profile' => 'url del profile',
     *     ]
     * ]
     * En caso de ser negativo
     * [
     *  'success' : false,
     *  'data' : mensaje de error
     * ]
     * @return \Laminas\View\Model\JsonModel
     */
    public function myGroupsAction()
    {

        $request = $this->getRequest();
        if ($request->isGet()) {

            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();


            $queryMapper = QueryMapper::getInstance($this->adapter);
            $select = $queryMapper->getSql()->select();
            $select->columns(['id', 'uuid', 'name', 'image', 'status', 'privacy', 'priority' => new Expression('0')]);
            $select->from(['g' => GroupMapper::_TABLE]);
            $select->where->equalTo('status', Group::STATUS_ACTIVE);
            $select->where->equalTo('g.user_id', $currentUser->id);
            $select->order('name ASC');


            $items = [];
            $storage = Storage::getInstance($this->config, $this->adapter);


            $records = $queryMapper->fetchAll($select);
            foreach ($records as $record) {

                array_push($items, [
                    'id'        => $record['uuid'],
                    'name'      => trim($record['name']),
                    'image'     =>  $storage->getGroupImageForCodeAndFilename($record['uuid'], $record['image']),
                    'profile'   => $this->url()->fromRoute('group/view', ['id' => $record['uuid']]),
                    'priority'  => $record['priority'],

                ]);
            }

            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function nextEventsAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {

            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();

            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
            $currentNetwork = $currentNetworkPlugin->getNetwork();



            $dt = new \DateTime();
            $dt->setTime(0, 0, 0);
            $start = $dt->format('Y-m-d H:i:s');

            $dt->add(new \DateInterval('P30D'));
            $dt->setTime(23, 59, 59);
            $end = $dt->format('Y-m-d H:i:s');




            $events = [];



            //3 días
            $expirePeriod = 86400 * 3;
            $t1 = time();

            $companies = [];
            $companyMapper = CompanyMapper::getInstance($this->adapter);

            $companyUsers = [];
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
            $records = $companyUserMapper->fetchAllByUserId($currentUser->id);

            foreach ($records as $record) {
                $companyUsers[$record->company_id] = $record->backend == CompanyUser::BACKEND_YES;
            }



            $zoomMeetingMapper = ZoomMeetingMapper::getInstance($this->adapter);
            $recruitmentSelectionCandidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
            $recruitmentSelectionVacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
            $recruitmentSelectionInterviewMapper = RecruitmentSelectionInterviewMapper::getInstance($this->adapter);
            $performanceEvaluationTestMapper = PerformanceEvaluationTestMapper::getInstance($this->adapter);
            $performanceEvaluationFormMapper = PerformanceEvaluationFormMapper::getInstance($this->adapter);
            $jobDescriptionMapper = JobDescriptionMapper::getInstance($this->adapter);
            $userMapper = UserMapper::getInstance($this->adapter);

            $calendarEventMapper = CalendarEventMapper::getInstance($this->adapter);
            $records = $calendarEventMapper->fetchAllByUserIdAndStartTimeAndEndTime($currentUser->id, $start, $end);
            foreach ($records as $record) {
                switch ($record->type) {
                    
                    case CalendarEvent::TYPE_SURVEY_NORMAL:
                        $backgroundColor = $currentNetwork->css_calendar_survey_bg_color;
                        $textColor = $currentNetwork->css_calendar_survey_text_color;
                    
                        $surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
                        $surveyTest = $surveyTestMapper->fetchOne($record->relational_id);
                        
                        if($surveyTest && $surveyTest->user_id == $currentUser->id) {
                            
                            $surveyCampaingMapper = SurveyCampaignMapper::getInstance($this->adapter);
                            $surveyCampaing = $surveyCampaingMapper->fetchOne($surveyTest->campaign_id);
                            
                            $url = '';
                            $hasLink = !empty($companyUsers[$surveyTest->company_id]);
                            
                            if ($hasLink) {
                                
                                if (!isset($companies[$surveyTest->company_id])) {
                                    $company  = $companyMapper->fetchOne($surveyTest->company_id);
                                    
                                    $companies[$company->id]  = $company;
                                } else {
                                    $company = $companies[$surveyTest->company_id];
                                }
                                
                                
                                $url = $this->url()->fromRoute('backend/signin-company', [
                                    'id' => $company->uuid,
                                    'relational' => $surveyTest->uuid,
                                    'type' => CalendarEvent::TYPE_SURVEY_ORGANIZATIONAL_CLIMATE,
                                ], ['force_canonical' => true]);
                            }
                            
                            $dtStart = \DateTime::createFromFormat('Y-m-d', $surveyCampaing->end_date);
                            
                            
                            array_push($events, [
                                'id'                => $surveyTest->uuid,
                                'title'             => $surveyCampaing->name,
                                'start'             => $dtStart->format('Y-m-d'),
                                'url'               => $url,
                                'backgroundColor'   => $backgroundColor,
                                'textColor'         => $textColor,
                                'allDay'            => true,
                                'type'              => 'task',
                                'source'            => 'internal',
                            ]);
                        }
                        
                        break;
                    
                    case CalendarEvent::TYPE_SURVEY_ORGANIZATIONAL_CLIMATE:
                        $backgroundColor = $currentNetwork->css_calendar_organizational_climate_bg_color;
                        $textColor = $currentNetwork->css_calendar_organizational_climate_text_color;
                        
                        $surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
                        $surveyTest = $surveyTestMapper->fetchOne($record->relational_id);
                        
                        if($surveyTest && $surveyTest->user_id == $currentUser->id) {
                            
                            $surveyCampaingMapper = SurveyCampaignMapper::getInstance($this->adapter);
                            $surveyCampaing = $surveyCampaingMapper->fetchOne($surveyTest->campaign_id);
                            
                            $url = '';
                            $hasLink = !empty($companyUsers[$surveyTest->company_id]);
                            
                            if ($hasLink) {
                                
                                if (!isset($companies[$surveyTest->company_id])) {
                                    $company  = $companyMapper->fetchOne($surveyTest->company_id);
                                    
                                    $companies[$company->id]  = $company;
                                } else {
                                    $company = $companies[$surveyTest->company_id];
                                }
                                
                                
                                $url = $this->url()->fromRoute('backend/signin-company', [
                                    'id' => $company->uuid,
                                    'relational' => $surveyTest->uuid,
                                    'type' => CalendarEvent::TYPE_SURVEY_ORGANIZATIONAL_CLIMATE,
                                ], ['force_canonical' => true]);
                            }
                            
                            $dtStart = \DateTime::createFromFormat('Y-m-d', $surveyCampaing->end_date);
                            
                            
                            array_push($events, [
                                'id'                => $surveyTest->uuid,
                                'title'             => $surveyCampaing->name,
                                'start'             => $dtStart->format('Y-m-d'),
                                'url'               => $url,
                                'backgroundColor'   => $backgroundColor,
                                'textColor'         => $textColor,
                                'allDay'            => true,
                                'type'              => 'task',
                                'source'            => 'internal',
                            ]);
                        }
                        
                        break;
                       
                        
                        
                        
                        
                        
                        
                        
                        
                    
                    case CalendarEvent::TYPE_RECRUITMENT_SELECTION_INTERVIEW:
                        $backgroundColor = $currentNetwork->css_calendar_recruitment_and_selection_bg_color;
                        $textColor = $currentNetwork->css_calendar_recruitment_and_selection_text_color;


                        $recruitmentSelectionInterview = $recruitmentSelectionInterviewMapper->fetchOne($record->relational_id);
                        if ($recruitmentSelectionInterview) {
                            $recruitmentSelectionVacancy = $recruitmentSelectionVacancyMapper->fetchOne($recruitmentSelectionInterview->vacancy_id);

                            $recruitmentSelectionCandidate = $recruitmentSelectionCandidateMapper->fetchOne($recruitmentSelectionInterview->candidate_id);
                            if ($recruitmentSelectionVacancy && $recruitmentSelectionCandidate) {
                                $jobDescription = $jobDescriptionMapper->fetchOne($recruitmentSelectionVacancy->job_description_id);
                                if ($jobDescription) {
                                    $url = '';
                                    $hasLink = !empty($companyUsers[$recruitmentSelectionInterview->company_id]);

                                    if ($hasLink) {

                                        if (!isset($companies[$recruitmentSelectionInterview->company_id])) {
                                            $company  = $companyMapper->fetchOne($recruitmentSelectionInterview->company_id);

                                            $companies[$company->id]  = $company;
                                        } else {
                                            $company = $companies[$recruitmentSelectionInterview->company_id];
                                        }


                                        $url = $this->url()->fromRoute('backend/signin-company', [
                                            'id' => $company->uuid,
                                            'relational' => $recruitmentSelectionInterview->uuid,
                                            'type' => CalendarEvent::TYPE_RECRUITMENT_SELECTION_INTERVIEW
                                        ], ['force_canonical' => true]);
                                    }
                                    
                                    $dtStart = \DateTime::createFromFormat('Y-m-d', $recruitmentSelectionInterview->last_date);




                                    array_push($events, [
                                        'id'                => $recruitmentSelectionInterview->uuid,
                                        'title'             => $recruitmentSelectionVacancy->name,
                                        'start'             => $dtStart->format('Y-m-d'),
                                        'url'               => $url,
                                        'backgroundColor'   => $backgroundColor,
                                        'textColor'         => $textColor,
                                        'allDay'            => true,
                                        'type'              => 'task',
                                        'source'            => 'internal',
                                    ]);
                                }
                            }
                        }


                        break;

                    case CalendarEvent::TYPE_PERFORMANCE_EVALUATION:


                        $backgroundColor = $currentNetwork->css_calendar_performance_evaluation_bg_color;
                        $textColor = $currentNetwork->css_calendar_performance_evaluation_text_color;


                        $performanceEvaluationTest = $performanceEvaluationTestMapper->fetchOne($record->relational_id);
                        if ($performanceEvaluationTest) {

                            $performanceEvaluationForm = $performanceEvaluationFormMapper->fetchOne($performanceEvaluationTest->form_id);
                            if ($performanceEvaluationForm) {
                                $jobDescription = $jobDescriptionMapper->fetchOne($performanceEvaluationForm->job_description_id);
                                if ($jobDescription) {
                                    $url = '';
                                    $hasLink = !empty($companyUsers[$performanceEvaluationTest->company_id]);

                                    if ($performanceEvaluationTest->supervisor_id) {
                                        $supervisor = $userMapper->fetchOne($performanceEvaluationTest->supervisor_id);
                                    } else {
                                        $supervisor = '';
                                    }

                                    if ($performanceEvaluationTest->employee_id) {
                                        $employee = $userMapper->fetchOne($performanceEvaluationTest->employee_id);
                                    } else {
                                        $employee = '';
                                    }

                                   

                                    if ($hasLink) {

                                        if (!isset($companies[$performanceEvaluationTest->company_id])) {
                                            $company  = $companyMapper->fetchOne($performanceEvaluationTest->company_id);

                                            $companies[$company->id]  = $company;
                                        } else {
                                            $company = $companies[$performanceEvaluationTest->company_id];
                                        }


                                        $url = $this->url()->fromRoute('backend/signin-company', [
                                            'id' => $company->uuid,
                                            'relational' => $performanceEvaluationTest->uuid,
                                            'type' => CalendarEvent::TYPE_PERFORMANCE_EVALUATION
                                        ], ['force_canonical' => true]);
                                    }

                                    $dtStart = \DateTime::createFromFormat('Y-m-d', $performanceEvaluationTest->last_date);

                                    array_push($events, [
                                        'id'                => $performanceEvaluationTest->uuid,
                                        'title'             =>  $performanceEvaluationForm->name,
                                        'start'             => $dtStart->format('Y-m-d'),
                                        'url'               => $url,
                                        'backgroundColor'   => $backgroundColor,
                                        'textColor'         => $textColor,
                                        'allDay'            => true,
                                        'type'              => 'task',
                                        'source'            => 'internal',
                                    ]);
                                }
                            }
                        }





                        break;


                    case CalendarEvent::TYPE_ZOOM:
                        $zoomMeeting = $zoomMeetingMapper->fetchOne($record->relational_id);
                        if ($zoomMeeting) {

                            $backgroundColor = $currentNetwork->css_calendar_zoom_bg_color;
                            $textColor = $currentNetwork->css_calendar_zoom_text_color;

                            $dtStart = \DateTime::createFromFormat('Y-m-d H:i:s', $zoomMeeting->start_time);
                            $t2 = $dtStart->getTimestamp();

                            if ($t2 > $t1) {

                                $t3 = $t1 + $expirePeriod;
                                if ($t3 > $t2) {
                                    $backgroundColor = $currentNetwork->css_calendar_expire_bg_color;
                                    $textColor = $currentNetwork->css_calendar_expire_text_color;
                                }
                            }



                            if ($currentUser->timezone && $currentUser->timezone != $zoomMeeting->timezone) {

                                $start =  str_replace(' ', 'T', Functions::convertDateTimeBetweenTimeZones($zoomMeeting->start_time, $zoomMeeting->timezone, $currentUser->timezone));
                                $end =  str_replace(' ', 'T', Functions::convertDateTimeBetweenTimeZones($zoomMeeting->end_time, $zoomMeeting->timezone, $currentUser->timezone));
                            } else {
                                $start = str_replace(' ', 'T', $zoomMeeting->start_time);
                                $end = str_replace(' ', 'T', $zoomMeeting->end_time);
                            }


                            
                            $url = $zoomMeeting->join_url;




                            $agenda = $zoomMeeting->agenda . "<br>" .
                                " LABEL_ZOOM_MEETING_START_DATE : " . $dtStart->format('Y-m-d') . "<br>" .
                                " LABEL_ZOOM_MEETING_START_TIME : " . $dtStart->format('H:i a') . "<br>" .
                                " LABEL_ZOOM_MEETING_TIMEZONE : " . $zoomMeeting->timezone . "<br>" .
                                " LABEL_ZOOM_MEETING_TITLE :  " . $zoomMeeting->topic  . "<br>" .
                                " LABEL_ZOOM_MEETING_URL : " . $zoomMeeting->join_url . "<br>" .
                                " LABEL_ZOOM_MEETING_PASSWORD : " . $zoomMeeting->password . "<br>";

                            array_push($events, [
                                'id'                => $zoomMeeting->id,
                                'title'             => $zoomMeeting->topic,
                                'agenda'            => $agenda,
                                'start'             => $start,
                                'end'               => $end,
                                'url'               => $zoomMeeting->join_url,
                                'backgroundColor'   => $backgroundColor,
                                'textColor'         => $textColor,
                                'type'              => 'event',
                                'source'            => 'external',
                            ]);
                        }
                        break;
                }
            }



            return new JsonModel([
                'success' => true,
                'data' => $events
            ]);
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    public function menuAction()
    {
        
        
        $request = $this->getRequest();
        
        

        if ($request->isGet()) {
            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
            $network =  $currentNetworkPlugin->getNetwork();
            
            
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            if($currentUserPlugin->hasIdentity()) {
                $currentUser = $currentUserPlugin->getUser();
                

                
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                
                $link_admin         = $currentUser->usertype_id == UserType::ADMIN ? 1 : 0;
                $link_impersonate   = $currentUser->is_super_user == User::IS_SUPER_USER_YES ? 1 : 0;
                if($link_impersonate) {
                    $url_impersonate = $this->url()->fromRoute('signin/impersonate'); 
                } else {
                    $url_impersonate = '';
                }

                $fullname = trim($currentUser->first_name . ' ' . $currentUser->last_name);
                
                $profileVisitMapper = ProfileVisitMapper::getInstance($this->adapter);
                $visits = $profileVisitMapper->getTotalByVisitedId($currentUser->id);
                
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                $connections = $connectionMapper->fetchTotalConnectionByUser($currentUser->id);
                
                
                if($currentUser->location_id) {
                    $locationMapper = LocationMapper::getInstance($this->adapter);
                    $location = $locationMapper->fetchOne($currentUser->location_id);
                    
                    $country = $location->country;
                } else {
                    $country = '';
                }
                

                

                if($currentUser->usertype_id == UserType::ADMIN) {
                    $url_admin = $this->url()->fromRoute( 'backend/signin-admin');
                } else {
                    $url_admin = '';
                }
                
     
                
                $link_company = '';
                if($network->default != Network::DEFAULT_YES) {
                    $companyMapper = CompanyMapper::getInstance($this->adapter);
                    $company = $companyMapper->fetchDefaultForNetworkByNetworkId($network->id);
                    if($company) {
                        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
                        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($company->id, $currentUser->id);
                        if($companyUser) {
                            if($companyUser && $companyUser->status == CompanyUser::STATUS_ACCEPTED && $companyUser->backend == CompanyUser::BACKEND_YES ) {
                                $link_company = ['route' => 'backend/signin-company', 'id' => $company->uuid ];
                            }
                        }
                    }
                } else {
                   
                }
                
                
   
                
                
                if ($acl->isAllowed($currentUser->usertype_id,  'knowledge-area')) {
                    $route_knowledge_area = $this->url()->fromRoute('knowledge-area', [], ['force_canonical' => true]);
                    $link_knowledge_area = 1;
                } else {
                    
                    $route_knowledge_area = '';
                    $link_knowledge_area = 0;
                }
                
                if ($acl->isAllowed($currentUser->usertype_id,  'my-coach')) {
                    $route_my_coach = $this->url()->fromRoute('my-coach', [], ['force_canonical' => true]);
                    $link_my_coach = 1;
                } else {
                    
                    $route_my_coach = '';
                    $link_my_coach = 0;
                }
                
                if($network->default == Network::DEFAULT_YES) {
                    if($network->relationship_user_mode == Network::RELATIONSHIP_USER_MODE_USER_2_USER)  {
                        $pages = getAclMenuDefaultNetworkConnectionUser2User();
                    } else {
                        $pages = getAclMenuDefaultNetworkConnectionAll2All();
                    }
                } else {
                    if($network->relationship_user_mode == Network::RELATIONSHIP_USER_MODE_USER_2_USER)  {
                        
                        $pages = getAclMenuNonDefaulNetworkConnectionUser2User();
                        
                    } else {
                        $pages = getAclMenuNonDefaultNetworkConnectionAll2All();
                    }
                }
                
                
                $menu = [];
                foreach ($pages as $page) {
                    
                    if (!$page || empty($page['route']) || !$acl->isAllowed($currentUser->usertype_id, $page['route'])) {
                        continue;
                    }
                    
                    $childs = [];
                    
                    $ajax = false;
                    if ($page['route'] == 'company' && $network->default == Network::DEFAULT_NO) {
                        
                        
                        
                        if ($link_company) {
                            $ajax = true;
                            $page['route'] = $this->url()->fromRoute($link_company['route'], ['id' => $link_company['id']]);
                            
                            $childs = [
                                'label' => 'Acceder',
                                'href' => $page['route'],
                                'ajax' => $ajax,
                                'childs' => []
                            ];
                            
                            
                            
                            
                        } else {
                            continue;
                        }
                    }
                    
                    $option = [
                        'label' => $page['label'],
                        'href' => $page['route'],
                        'img' => empty($page['class']) ? '' : $page['class'],
                        'ajax' => $ajax ? 1 : 0,
                        'childs' => $childs,
                    ];
                    
                    if ($page['route'] == 'company' && $network->default == Network::DEFAULT_NO) {
                        if ($link_company) {
                            array_push($option['childs'], );
                            
                
                        } 
                    }
                    
                    $childs = empty($page['pages']) ? [] : $page['pages'];
                    if ($childs) {
                        foreach ($childs as $child) {
                            if (!$acl->isAllowed($currentUser->usertype_id,  $child['route'])) {
                                continue;
                            }
                            
                            $childs_level2 = [];
                            
                            $childsLevel2 = empty($child['pages']) ? [] : $child['pages'];
                            
                            if ($childsLevel2) {
                                foreach ($childsLevel2 as $childLevel2) {
                                    if (!$acl->isAllowed($currentUser->usertype_id,  $childLevel2['route'])) {
                                        continue;
                                    }
                                    
                                    array_push($childs_level2, [
                                        'label' => $childLevel2['label'],
                                        'href' => $childLevel2['route'],
                                        
                                    ]);
                                }
                            }
                            
                            array_push($option['childs'], [
                                'label' => $child['label'],
                                'href' => $child['route'],
                                'childs' => $childs_level2,
                            ]);
                        }
                    }
                    
                    array_push($menu, $option);
                }
                
           
                $storage = Storage::getInstance($this->config, $this->adapter);

                
                $image = $storage->getUserImage($currentUser);
                $isChatPage = $this->getEvent()->getViewModel()->getVariable('is_chat');
                $routeCheckSession = $this->url()->fromRoute('check-session');
                $routeAbuseReport = $this->url()->fromRoute('abuse-report');

                
                if($network->navbar) {
                    
                    
                    
                    $storage = Storage::getInstance($this->config, $this->adapter);
                    $path = $storage->getPathNetwork();
                        
                    $navbar = $storage->getGenericImage($path, $network->uuid, $network->navbar);
                        
                    
  
                } else {
                    $navbar = '';
                }
                
                return new JsonModel([
                    'menu'                  => $menu,
                    'isChatPage'            => $isChatPage == 1,
                    'routeCheckSession'     => $routeCheckSession,
                    'routeAbuseReport'      => $routeAbuseReport,
                    'linkAdmin'             => $link_admin == 1,
                    'urlAdmin'              => $url_admin,
                    'linkImpersonate'       => $link_impersonate ==1 ,
                    'urlImpersonate'        => $url_impersonate,
                    'image'                 => $image,
                    'fullName'              => $fullname,
                    'country'               => $country,
                    'visits'                => $visits,
                    'connections'           => $connections,
                    'logoForNavbar'         => $navbar,
                    'defaultNetwork'        => $network->default,
               ]);     

                
                
            }
            
            
            return new JsonModel([
                'menu'                  => [],
                'isChatPage'            => false,
                'routeCheckSession'     => '',
                'linkAdmin'             => false,
                'urlAdmin'              => '',
                'linkImpersonate'       => false,
                'urlImpersonate'        => '',
                'image'                 => '',
                'fullName'              => '',
                'country'               => 0,
                'visits'                => 0,
                'connections'           => 0,
                'logoForNavbar'         => 'https://' . $network->main_hostname . '/storage-network/type/navbar',
                'defaultNetwork'        => $network->default,
                'linkKnowledgeArea'     => false,
                'routeKnowledgeArea'    => '',
                'linkMyCoach'           => false,
                'routeMyCoach'          => '',
            ]);   
           
        } else {
            
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }

        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function companySizesAction()
    {
        $request = $this->getRequest();
        
        
        
        if ($request->isGet()) {
            $items = [];     
            
            $mapper = CompanySizeMapper::getInstance($this->adapter);
            $records = $mapper->fetchAllActive();
            foreach($records as $record)
            {
                 $items[ $record->uuid ] = $record->name;
            }
            
            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
            
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function degreesAction()
    {
        $request = $this->getRequest();
        
        
        
        if ($request->isGet()) {
            $items = [];
            
            $mapper = DegreeMapper::getInstance($this->adapter);
            $records = $mapper->fetchAllActive();
            foreach($records as $record)
            {
                $items[ $record->uuid ] = $record->name;
            }
            
            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
            
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function languagesAction()
    {
        $request = $this->getRequest();
        
        
        
        if ($request->isGet()) {
            $items = [];
            
            $mapper = LanguageMapper::getInstance($this->adapter);
            $records = $mapper->fetchAllActive();
            foreach($records as $record)
            {
                $items[ $record->id ] = $record->name;
            }
            
            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
            
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function skillsAction()
    {
        $request = $this->getRequest();
        
        
        
        if ($request->isGet()) {
            $items = [];
            
            $mapper = SkillMapper::getInstance($this->adapter);
            $records = $mapper->fetchAllActive();
            foreach($records as $record)
            {
                $items[ $record->uuid ] = $record->name;
            }
            
            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
            
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    
    public function aptitudesAction()
    {
        $request = $this->getRequest();
        
        
        
        if ($request->isGet()) {
            $items = [];
            
            $mapper = AptitudeMapper::getInstance($this->adapter);
            $records = $mapper->fetchAllActive();
            foreach($records as $record)
            {
                $items[ $record->uuid ] = $record->name;
            }
            
            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
            
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function hobbiesAction()
    {
        $request = $this->getRequest();
        
        
        
        if ($request->isGet()) {
            $items = [];
            
            $mapper = HobbyAndInterestMapper::getInstance($this->adapter);
            $records = $mapper->fetchAllActive();
            foreach($records as $record)
            {
                $items[ $record->uuid ] = $record->name;
            }
            
            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
            
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function industriesAction()
    {
        $request = $this->getRequest();
        
        
        
        if ($request->isGet()) {
            $items = [];
            
            $mapper = IndustryMapper::getInstance($this->adapter);
            $records = $mapper->fetchAllActive();
            foreach($records as $record)
            {
                $items[ $record->uuid ] = $record->name;
            }
            
            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
            
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function timeZonesAction() {
        
        $request = $this->getRequest();
        
        
        
        if ($request->isGet()) {
            $items = [];
            
            
            $records = Functions::getAllTimeZones();
            foreach($records as $record)
            {
                $items[ $record ] = $record;
            }
            
            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
            
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
        
        

        

        
    }
    
    
    public function groupTypesAction()
    {
        $request = $this->getRequest();
        
        
        
        if ($request->isGet()) {
            $items = [];
            
            $mapper = GroupTypeMapper::getInstance($this->adapter);
            $records = $mapper->fetchAllActive();
            foreach($records as $record)
            {
                $items[ $record->uuid ] = $record->name;
            }
            
            return new JsonModel([
                'success' => true,
                'data' => $items
            ]);
            
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    
    public function abuseReportAction() 
    {
        


        $request = $this->getRequest();
        
        if ($request->isPost()) {
            
            $dataPost = $request->getPost()->toArray();
            
            $form = new CreateForm();
            $form->setData($dataPost);
            

            
            if(!$form->isValid()) {
                $messages = [];
     
                
                
                $form_messages = (array) $form->getMessages();
                foreach($form_messages  as $fieldname => $field_messages)
                {
                    
                    $messages[$fieldname] = array_values($field_messages);
                }
                
          
                
                return new JsonModel([
                    'success'   => false,
                    'data'   => $messages
                ]);
                
            }

            
            $dataPost = (array) $form->getData();

            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
            $network =  $currentNetworkPlugin->getNetwork();
            
            
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
            
            $id     = $this->params()->fromRoute('id');
            $type   = $this->params()->fromRoute('type');

            $blockUser = $dataPost['block_user'] == 'y';
            
            $abuseReport = new AbuseReport();
            $abuseReport->network_id = $network->id;
            $abuseReport->user_reporting_id = $currentUser->id;
            $abuseReport->status = AbuseReport::STATUS_PENDING;
            $abuseReport->comment = $dataPost['comment'];
            $abuseReport->reason = $dataPost['reason'];
            

            
            switch($type)
            {
                case 'feed' : 
                    $feedMapper = FeedMapper::getInstance($this->adapter);
                    $feed = $feedMapper->fetchOneByUuid($id);
                    if(!$feed || $feed->status != Feed::STATUS_PUBLISHED || $feed->network_id != $network->id) {
                        
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_NOT_AVAILABLE'
                        ]);
                    }
                    
                    if($feed->user_id == 1) {
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_OWNER_SYSADMIN'
                        ]);
                    }
                    
                    if($feed->user_id == $currentUser->id) {
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_OWNER_IS_YOURSELF'
                        ]);
                    }

                    $abuseReport->related_id        =  $feed->id;
                    $abuseReport->user_reported_id  = $feed->user_id;
                    $abuseReport->type              = AbuseReport::TYPE_FEED;
                   
                    
                    
                    break; 
                    
                case 'post' :
                    $postMapper = PostMapper::getInstance($this->adapter);
                    $post = $postMapper->fetchOneByUuid($id);
                    if(!$post || $post->status != Post::STATUS_ACTIVE || $post->network_id != $network->id) {
                        
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_NOT_AVAILABLE'
                        ]);
                    }
                    
                    if($post->user_id == 1) {
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_OWNER_SYSADMIN'
                        ]);
                    }
                    
                    
                    if($post->user_id == $currentUser->id) {
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_OWNER_IS_YOURSELF'
                        ]);
                    }
                    
                    
                    $abuseReport->related_id        = $post->id;
                    $abuseReport->user_reported_id  = $post->user_id;
                    $abuseReport->type              = AbuseReport::TYPE_POST;
                    
                    break; 
                    
                    
                case 'comment' :
                    $commentMapper = CommentMapper::getInstance($this->adapter);
                    $comment = $commentMapper->fetchOneByUuid($id);
                    if(!$comment || $comment->network_id != $network->id || $comment->status != Comment::STATUS_PUBLISHED) {
                        
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_NOT_AVAILABLE'
                        ]);
                    }
                    
                    if($comment->user_id == 1) {
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_OWNER_SYSADMIN'
                        ]);
                    }
                    
                    if($comment->user_id == $currentUser->id) {
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_OWNER_IS_YOURSELF'
                        ]);
                    }
                    
                    $abuseReport->related_id        = $comment->id;
                    $abuseReport->user_reported_id  = $comment->user_id;
                    $abuseReport->type              = AbuseReport::TYPE_COMMENT;
                    
                    break; 
                    
                
                case 'message' :
                    $messageMapper = MessageMapper::getInstance($this->adapter);
                    $message = $messageMapper->fetchOneByUuid($id);
                    if(!$message || $message->receiver_id != $currentUser->id || $message->receiver_status != Message::STATUS_NORMAL) {
                        
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_NOT_AVAILABLE'
                        ]);
                    }
                    
                    if($message->sender_id == 1) {
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_OWNER_SYSADMIN'
                        ]);
                    }
                    
                    $abuseReport->related_id        = $message->id;
                    $abuseReport->user_reported_id  = $message->sender_id;
                    $abuseReport->type              = AbuseReport::TYPE_INMAIL_MESSAGE;
                    
                    break; 
                
                case 'chat-message' :
                    $messageMapper = ChatMessageMapper::getInstance($this->adapter);
                    $message = $messageMapper->fetchOneByUuid($id);
                    if(!$message || $message->to_id != $currentUser->id || $message->status != ChatMessage::STATUS_PUBLISHED) {
                        
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_NOT_AVAILABLE'
                        ]);
                    }
                    
                    if($message->from_id == 1) {
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_OWNER_SYSADMIN'
                        ]);
                    }
                    
                    $abuseReport->related_id        = $message->id;
                    $abuseReport->user_reported_id  = $message->from_id;
                    $abuseReport->type              = AbuseReport::TYPE_CHAT_USER_MESSAGE;
                    
                    break; 
               
                case 'chat-group-message' :
                    $messageMapper = ChatGroupMessageMapper::getInstance($this->adapter);
                    $message = $messageMapper->fetchOne($id);
                    if(!$message || $message->status != ChatMessage::STATUS_PUBLISHED) {
                        
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_NOT_AVAILABLE'
                        ]);
                    }
                    
                    $userMessageMapper = ChatGroupUserMessageMapper::getInstance($this->adapter);
                    $userMessage = $userMessageMapper->fetchOneByIdMessageIdAndReceiverId($message->id, $currentUser->id);
                    if(!$userMessage) {
                        
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_NOT_AVAILABLE'
                        ]);
                    }
                    
                    
                    if($message->sender_id == 1) {
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_ABUSE_REPORT_CONTENT_OWNER_SYSADMIN'
                        ]);
                    }
                    
                    $abuseReport->related_id        = $message->id;
                    $abuseReport->user_reported_id  = $message->sender_id;
                    $abuseReport->type              = AbuseReport::TYPE_CHAT_USER_MESSAGE;
                    
                    break; 
            }
            
           

            $abuseReportMapper = AbuseReportMapper::getInstance($this->adapter);
            if($abuseReportMapper->insert($abuseReport)) {
                
                if($blockUser) {
                    
                    $userBlockedMapper = UserBlockedMapper::getInstance($this->adapter);
                    $userBlocked = $userBlockedMapper->fetchOneByUserIdAndBlockedId($abuseReport->user_reporting_id, $abuseReport->user_reporting_id);
                    if($userBlocked) {
                        
                        
                        return new JsonModel([
                            'success' => true,
                            'data' => [
                                'message' => 'LABEL_ABUSE_REPORT_SENT_WITH_BLOCK_USER',
                                'block' => true
                            ]
                        ]);
                        
                    } else {
                        
                        $userBlocked = new UserBlocked();
                        $userBlocked->user_id = $abuseReport->user_reporting_id;
                        $userBlocked->blocked_id = $abuseReport->user_reported_id;
                        
                        if($userBlockedMapper->insert($userBlocked)) {
                            return new JsonModel([
                                'success' => true,
                                'data' => [
                                    'message' => 'LABEL_ABUSE_REPORT_SENT_WITH_BLOCK_USER',
                                    'block' => true
                                ]
                            ]);
                            
                        } else {
                            return new JsonModel([
                                'success' => true,
                                'data' => [
                                    'message' => 'LABEL_ABUSE_REPORT_SENT_WITHOUT_BLOCK_USER',
                                    'block' => false
                                ]
                            ]);
                            
                            
                        }
                    }
                    
                    
                } else {
                    return new JsonModel([
                        'success' => true,
                        'data' => [
                            'message' => 'LABEL_ABUSE_REPORT_SENT_WITHOUT_BLOCK_USER',
                            'block' => false
                        ]
                    ]);
                }
                
                
            } else {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_ABUSE_REPORT_NOT_SENT' 
                ]);
            }
            
            
            
            
            
       
            
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
        
        
      
        
        
    }
    
    public function habitsAndSkillsAction()
    {
        $request = $this->getRequest();
        $request = $this->getRequest();
        if ($request->isGet()) {
            
            $items = [];

                $currentUserPlugin = $this->plugin('currentUserPlugin');
                $currentUser = $currentUserPlugin->getUser();
                
                
                
                $company_ids = [];
                $habitUserMapper = \LeadersLinked\Mapper\HabitUserMapper::getInstance($this->adapter);
                $records = $habitUserMapper->fetchAllActiveByUserId($currentUser->id);
                foreach($records as $record)
                {
                    if($record->company_id) {
                    
                        if(!in_array($record->company_id, $company_ids)) {
                            array_push($company_ids, $record->company_id);
                        }
                    }
                }
                
                
                if($company_ids) {
                
                    $habitSkillMapper = \LeadersLinked\Mapper\HabitSkillMapper::getInstance($this->adapter);
                    $records = $habitSkillMapper->fetchAllTemplateByCompayIds($company_ids);
                    foreach($records as $record)
                    {
                        array_push($items, [
                            'uuid'  => $record->uuid, 
                            'name'  => $record->name, 
                            'link'  =>  $this->url()->fromRoute('helpers/habits-and-skills/get', ['id' => $record->uuid], ['force_canonical' => true]),
    
    
                            
                        ]);
                    }
                }

            
            
            return new JsonModel([
                'success' => true,
                'data' => $items,
            ]);
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function habitsAndSkillsGetAction()
    {
        $request = $this->getRequest();
        $request = $this->getRequest();
        if ($request->isGet()) {
            
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
            
           
            $id = Functions::sanitizeFilterString($this->params()->fromRoute('id'));

            $habitSkillMapper = \LeadersLinked\Mapper\HabitSkillMapper::getInstance($this->adapter);
            $habitSkill = $habitSkillMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
            

            if(!$habitSkill) {
                return new JsonModel([
                    'success' => true,
                    'data' => 'ERROR_HABIT_NOT_FOUND'
                ]);
            }
           
      
            $allow = false;
            $habitUserMapper = \LeadersLinked\Mapper\HabitUserMapper::getInstance($this->adapter);
            $records = $habitUserMapper->fetchAllActiveByUserId($currentUser->id);
            foreach($records as $record)
            {
                if($habitSkill->company_id ==  $record->company_id) {
                        
                    $allow = true;
                    break;
                }
            }
            
            if(!$allow) {
                return new JsonModel([
                    'success' => true,
                    'data' => 'ERROR_HABIT_YOU_DO_NOT_HAVE_ACCESS_TO_THIS'
                ]);
            }
                
            return new JsonModel([
                'success' => true,
                'data' =>[
                    'uuid'              => $habitSkill->uuid,
                    'name'              => $habitSkill->name,
                    'description'       => $habitSkill->description,
                    'intelligence'      => $habitSkill->intelligence,
                    'monday_active'     => $habitSkill->monday_active,
                    'monday_time'       => $habitSkill->monday_time,
                    'tuesday_active'    => $habitSkill->tuesday_active,
                    'tuesday_time'      => $habitSkill->tuesday_time,
                    'wednesday_active'  => $habitSkill->wednesday_active,
                    'wednesday_time'    => $habitSkill->wednesday_time,
                    'thursday_active'   => $habitSkill->thursday_active,
                    'thursday_time'     => $habitSkill->thursday_time,
                    'friday_active'     => $habitSkill->friday_active,
                    'friday_time'       => $habitSkill->friday_time,
                    'saturday_active'   => $habitSkill->saturday_active,
                    'saturday_time'     => $habitSkill->saturday_time,
                    'sunday_active'     => $habitSkill->sunday_active,
                    'sunday_time'       => $habitSkill->sunday_time,
                    
                    'quantitative_value' => $habitSkill->quantitative_value,
                    'qualitative_description' => $habitSkill->qualitative_description,
                    'notification_10min_before' => $habitSkill->notification_10min_before,
                    'notification_30min_before' => $habitSkill->notification_30min_before,
                    
                    
                ],
            ]);
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    
    public function myHabitsAndSkillsGetAction()
    {
        $request = $this->getRequest();
        $request = $this->getRequest();
        if ($request->isGet()) {
            
            $items = [];
            
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
            
            
            $habitSkillMapper = \LeadersLinked\Mapper\HabitSkillMapper::getInstance($this->adapter);
            $records = $habitSkillMapper->fetchAllByUserId($currentUser->id);
            foreach($records as $record)
            {
                array_push($items, [
                    'uuid'  => $record->uuid,
                    'name'  => $record->name,
                    'link'  =>  $this->url()->fromRoute('habits/skills/registers', ['id' => $record->uuid], ['force_canonical' => true]),
                ]);
            }

            
            return new JsonModel([
                'success' => true,
                'data' => $items,
            ]);
            
        }
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    

}