Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

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

<?php
/**
 * 
 * Controlador: Mis Perfiles 
 * 
 */
declare(strict_types=1);

namespace LeadersLinked\Controller;

use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Log\LoggerInterface;
use Laminas\View\Model\ViewModel;
use Laminas\View\Model\JsonModel;
use Laminas\Db\Sql\Expression;
use LeadersLinked\Model\User;
use LeadersLinked\Mapper\ConnectionMapper;
use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Model\Connection;
use Laminas\Paginator\Adapter\DbSelect;
use Laminas\Paginator\Paginator;
use LeadersLinked\Mapper\UserBlockedMapper;
use LeadersLinked\Model\UserBlocked;
use LeadersLinked\Mapper\QueryMapper;
use LeadersLinked\Model\UserType;
use LeadersLinked\Model\CompanyUser;
use LeadersLinked\Mapper\GroupMemberMapper;
use LeadersLinked\Model\GroupMember;
use LeadersLinked\Mapper\CompanyUserMapper;
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleUserMapper;
use LeadersLinked\Model\Notification;
use LeadersLinked\Mapper\NotificationMapper;
use LeadersLinked\Mapper\UserNotificationSettingMapper;
use LeadersLinked\Mapper\EmailTemplateMapper;
use LeadersLinked\Model\EmailTemplate;
use LeadersLinked\Library\QueueEmail;

class ConnectionController extends AbstractActionController
{
    /**
     *
     * @var AdapterInterface
     */
    private $adapter;
    
    
    /**
     *
     * @var AbstractAdapter
     */
    private $cache;
    
    /**
     *
     * @var  LoggerInterface
     */
    private $logger;

    
    /**
     *
     * @var array
     */
    private $config;
    
    /**
     *
     * @param AdapterInterface $adapter
     * @param AbstractAdapter $cache
     * @param LoggerInterface $logger
     * @param array $config
     */
    public function __construct($adapter, $cache , $logger,  $config)
    {
        $this->adapter      = $adapter;
        $this->cache        = $cache;
        $this->logger       = $logger;
        $this->config       = $config;

    }
    
    /**
     * 
     * Generación del listado de perfiles
     * {@inheritDoc}
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
     */
    public function indexAction()
    {
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }

    public function myConnectionsAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        if($request->isGet()) {
            
            
            $headers  = $request->getHeaders();
            $isJson = false;
            if($headers->has('Accept')) {
                $accept = $headers->get('Accept');
                
                $prioritized = $accept->getPrioritized();
                
                foreach($prioritized as $key => $value) {
                    $raw = trim($value->getRaw());
                    
                    if(!$isJson) {
                        $isJson = strpos($raw, 'json');
                    }
                    
                }
            }
            
            if($isJson) {
                $search = trim(filter_var($this->params()->fromQuery('search', ''), FILTER_SANITIZE_STRING));
                
                
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                $user_ids = $connectionMapper->fetchAllConnectionsByUserReturnIds($currentUser->id);
                
                $userBlockedMapper = UserBlockedMapper::getInstance($this->adapter);
                $user_blocked_ids = $userBlockedMapper->fetchAllBlockedReturnIds($currentUser->id);
                $user_ids = array_diff($user_ids, $user_blocked_ids);

                $queryMapper = QueryMapper::getInstance($this->adapter);
                
                $select = $queryMapper->getSql()->select(UserMapper::_TABLE);
                $select->where->in('id', $user_ids); 
                $select->where->equalTo('status', User::STATUS_ACTIVE);
                $select->where->equalTo('network_id', $currentUser->network_id);
                
                if($search) {
                    $select->where->NEST->like('first_name', '%' . $search . '%')->or->like('last_name', '%' . $search . '%')->UNNEST;
                }
                $select->order('first_name ASC, last_name ASC');
                
                $records = $queryMapper->fetchAll($select);
                $items = [];
                foreach($records as $record)
                {

                    
                    $item = [
                        'name' => trim($record['first_name'] . ' ' . $record['last_name']),
                        'image' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $record['uuid'], 'filename' => $record['image'] ]),
                        'link_view' => $this->url()->fromRoute('profile/view', ['id' => $record['uuid']  ]),
                        'link_inmail'   => $this->url()->fromRoute('inmail', ['id' => $record['uuid']  ]),
                        'link_cancel' => $this->url()->fromRoute('connection/cancel', ['id' => $record['uuid']  ]),
                        'link_block'=> $this->url()->fromRoute('connection/block', ['id' => $record['uuid']  ]),

                    ];
                    

                    
                    array_push($items, $item);
                }
                

                
                
                $response = [
                    'success' => true,
                    'data' => $items
                ];
                
                return new JsonModel($response);
                
                
            } else {
                
                $notificationMapper = NotificationMapper::getInstance($this->adapter);
                $notificationMapper->markAllNotificationsAsReadByTypeAndUserId(Notification::TYPE_ACCEPT_MY_REQUEST_CONNECTION, $currentUser->id);
                
                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/connection/my-connections.phtml');
                return $viewModel ;
            }
            
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    public function invitationsSentAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        if($request->isGet()) {
            
            
            $headers  = $request->getHeaders();
            $isJson = false;
            if($headers->has('Accept')) {
                $accept = $headers->get('Accept');
                
                $prioritized = $accept->getPrioritized();
                
                foreach($prioritized as $key => $value) {
                    $raw = trim($value->getRaw());
                    
                    if(!$isJson) {
                        $isJson = strpos($raw, 'json');
                    }
                    
                }
            }
            
            if($isJson) {
                $search = trim(filter_var($this->params()->fromQuery('search', ''), FILTER_SANITIZE_STRING));
                
                
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                $user_ids = $connectionMapper->fetchAllSentInvitationsReturnIds($currentUser->id);
                
                $userBlockedMapper = UserBlockedMapper::getInstance($this->adapter);
                $user_blocked_ids = $userBlockedMapper->fetchAllBlockedReturnIds($currentUser->id);
                $user_ids = array_diff($user_ids, $user_blocked_ids);
                
                
                $queryMapper = QueryMapper::getInstance($this->adapter);
                
                $select = $queryMapper->getSql()->select(UserMapper::_TABLE);
                $select->where->in('id', $user_ids);
                $select->where->equalTo('status', User::STATUS_ACTIVE);
                $select->where->equalTo('network_id', $currentUser->network_id);
                
                if($search) {
                    $select->where->NEST->like('first_name', '%' . $search . '%')->or->like('last_name', '%' . $search . '%')->UNNEST;
                }
                $select->order('first_name ASC, last_name ASC');
                
                $records = $queryMapper->fetchAll($select);
                $items = [];
                foreach($records as $record)
                {
                    $item = [
                        'name' => trim($record['first_name'] . ' ' . $record['last_name']),
                        'image' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $record['uuid'], 'filename' => $record['image'] ]),
                        'link_view' => $this->url()->fromRoute('profile/view', ['id' => $record['uuid']  ]),
                        'link_delete' => $this->url()->fromRoute('connection/delete', ['id' => $record['uuid']  ]),
                    ];
                    
                    array_push($items, $item);
                }
                
                $response = [
                    'success' => true,
                    'data' => $items
                ];
                
                return new JsonModel($response);
            } else {
                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/connection/invitations-sent.phtml');
                return $viewModel ;
            }
            
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    public function invitationsReceivedAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        if($request->isGet()) {
            
            
            $headers  = $request->getHeaders();
            $isJson = false;
            if($headers->has('Accept')) {
                $accept = $headers->get('Accept');
                
                $prioritized = $accept->getPrioritized();
                
                foreach($prioritized as $key => $value) {
                    $raw = trim($value->getRaw());
                    
                    if(!$isJson) {
                        $isJson = strpos($raw, 'json');
                    }
                    
                }
            }
            
            if($isJson) {
                $search = trim(filter_var($this->params()->fromQuery('search', ''), FILTER_SANITIZE_STRING));
                
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                $user_ids = $connectionMapper->fetchAllReceiveInvitationsReturnIds($currentUser->id);
                
                
                $userBlockedMapper = UserBlockedMapper::getInstance($this->adapter);
                $user_blocked_ids = $userBlockedMapper->fetchAllBlockedReturnIds($currentUser->id);
                $user_ids = array_diff($user_ids, $user_blocked_ids);
                
                $queryMapper = QueryMapper::getInstance($this->adapter);
                $select = $queryMapper->getSql()->select(UserMapper::_TABLE);
                $select->where->in('id', $user_ids);
                $select->where->equalTo('status', User::STATUS_ACTIVE);
                $select->where->equalTo('network_id', $currentUser->network_id);
                
                if($search) {
                    $select->where->NEST->like('first_name', '%' . $search . '%')->or->like('last_name', '%' . $search . '%')->UNNEST;
                }
                $select->order('first_name ASC, last_name ASC');
                
                $records = $queryMapper->fetchAll($select);
                $items = [];
                foreach($records as $record)
                {
                    $item = [
                        'name' => trim($record['first_name'] . ' ' . $record['last_name']),
                        'image' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $record['uuid'], 'filename' => $record['image'] ]),
                        'link_view' => $this->url()->fromRoute('profile/view', ['id' => $record['uuid']  ]),
                        'link_approve' => $this->url()->fromRoute('connection/approve', ['id' => $record['uuid']  ]),
                        'link_reject' => $this->url()->fromRoute('connection/reject', ['id' => $record['uuid']  ]),
                        
                    ];
                    
                    array_push($items, $item);
                }

                $response = [
                    'success' => true,
                    'data' => $items
                ];
                
                return new JsonModel($response);
            } else {
                $notificationMapper = NotificationMapper::getInstance($this->adapter);
                $notificationMapper->markAllNotificationsAsReadByTypeAndUserId(Notification::TYPE_RECEIVE_CONNECTION_REQUEST, $currentUser->id);
                
                
                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/connection/invitations-received.phtml');
                return $viewModel ;
            }
            
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    public function cancelAction()
    {
        $request = $this->getRequest();
        if($request->isPost()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
            
            $id = $this->params()->fromRoute('id');
            
            $id = $this->params()->fromRoute('id');
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
            
            if(!$user) {
                return new JsonModel([
                    'success' => true,
                    'data' => 'ERROR_USER_NOT_FOUND'
                ]);
            }
            

            
            if($user->id == $currentUser->id || in_array($user->status, [User::STATUS_DELETED, User::STATUS_INACTIVE]) || $user->email_verified == User::EMAIL_VERIFIED_NO || $user->blocked == User::BLOCKED_YES) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_USER_UNAVAILABLE'
                ]);
            }
            
            
                
            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
            if($connection) {
                if($connection->status == Connection::STATUS_ACCEPTED) {
                    if($connectionMapper->cancel($connection)) {
                        return new JsonModel([
                            'success' => true,
                            'data' => 'LABEL_CONNECTION_CANCELED'
                        ]);
                    } else {
                        return new JsonModel([
                            'success' => true,
                            'data' => $connectionMapper->getError()
                        ]);
                    }
                } else {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'LABEL_CONNECTION_CANCELED'
                    ]);
                }
            } else {
                return new JsonModel([
                    'success' => true,
                    'data' => 'LABEL_CONNECTION_NOT_FOUND'
                ]);
                    
            }
          
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    public function approveAction()
    {
        $request = $this->getRequest();
        if($request->isPost()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
            
            $id = $this->params()->fromRoute('id');
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
            
            if($user) {
            
                if($user->id == $currentUser->id || in_array($user->status, [User::STATUS_DELETED, User::STATUS_INACTIVE]) || $user->email_verified == User::EMAIL_VERIFIED_NO || $user->blocked == User::BLOCKED_YES) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_USER_UNAVAILABLE'
                    ]);
                }
                
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
                if($connection) {
                    if($connection->status == Connection::STATUS_SENT) {
                        if($connectionMapper->approve($connection)) {
                            
                            if($currentUser->id == $connection->request_to) {
                                $other_user_id = $connection->request_from;
                            } else {
                                $other_user_id = $connection->request_to;
                            } 
                            
                            $otherUser = $userMapper->fetchOne($other_user_id);
                            
                            $notification = new Notification();
                            $notification->type     = Notification::TYPE_ACCEPT_MY_REQUEST_CONNECTION;
                            $notification->read     = Notification::NO;
                            $notification->user_id  = $otherUser->id;
                            $notification->message  = 'LABEL_NOTIFICATION_ACCEPT_MY_REQUEST_CONNECTION';
                            $notification->url      = $this->url()->fromRoute('connection/my-connections');
                            
                            $notificationMapper = NotificationMapper::getInstance($this->adapter);
                            $notificationMapper->insert($notification);
                            
                            $userNotificationMapper = UserNotificationSettingMapper::getInstance($this->adapter);
                            $userNotification = $userNotificationMapper->fetchOne($otherUser->id);
                            
                            if($userNotification && $userNotification->receive_connection_request)
                            {
                                $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
                                $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_ACCEPT_MY_REQUEST_CONNECTION, $currentUser->network_id);
                                
                                if($emailTemplate) {
                                    $arrayCont = [
                                        'firstname'             => $currentUser->first_name,
                                        'lastname'              => $currentUser->last_name,
                                        'other_user_firstname'  => $otherUser->first_name,
                                        'other_user_lastname'   => $otherUser->last_name,
                                        'company_name'          => '',
                                        'group_name'            => '',
                                        'content'               => '',
                                        'code'                  => '',
                                        'link'                  => $this->url()->fromRoute('connection/my-connections', [], ['force_canonical' => true])
                                    ];
                                    
                                    $email = new QueueEmail($this->adapter);
                                    $email->processEmailTemplate($emailTemplate, $arrayCont, $otherUser->email, trim($otherUser->first_name . ' ' . $otherUser->last_name));
                                }
                            }
                            
                            return new JsonModel([
                                'success' => true,
                                'data' => 'LABEL_CONNECTION_APPROVED'
                            ]);
                        } else {
                            return new JsonModel([
                                'success' => true,
                                'data' => $connectionMapper->getError()
                            ]);
                        }
                    } else {
                        return new JsonModel([
                            'success' => true,
                            'data' => 'LABEL_CONNECTION_NOT_PENDING'
                        ]);
                    }
                } else {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'LABEL_CONNECTION_NOT_FOUND'
                    ]);
                    
                }
            } else {
                return new JsonModel([
                    'success' => true,
                    'data' => 'ERROR_USER_NOT_FOUND'
                ]);
            }
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    public function rejectAction()
    {
        $request = $this->getRequest();
        if($request->isPost()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
            
            $id = $this->params()->fromRoute('id');
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
            
            if($user) {
                
                if($user->id == $currentUser->id || in_array($user->status, [User::STATUS_DELETED, User::STATUS_INACTIVE]) || $user->email_verified == User::EMAIL_VERIFIED_NO || $user->blocked == User::BLOCKED_YES) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_USER_UNAVAILABLE'
                    ]);
                }
                
            
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
                if($connection) {
                    if($connection->status == Connection::STATUS_SENT) {
                        if($connectionMapper->reject($connection)) {
                            return new JsonModel([
                                'success' => true,
                                'data' => 'LABEL_CONNECTION_REJECTED'
                            ]);
                        } else {
                            return new JsonModel([
                                'success' => true,
                                'data' => $connectionMapper->getError()
                            ]);
                        }
                    } else {
                        return new JsonModel([
                            'success' => true,
                            'data' => 'LABEL_CONNECTION_NOT_PENDING'
                        ]);
                    }
                } else {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'LABEL_CONNECTION_NOT_FOUND'
                    ]);
                    
                }
            } else {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_USER_NOT_FOUND'
                ]);
            }
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    public function requestAction()
    {
        $request = $this->getRequest();
        if($request->isPost()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
            
            $id = $this->params()->fromRoute('id');
            
          
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
            
            if($user) {
                
                if($user->id == $currentUser->id || in_array($user->status, [User::STATUS_DELETED, User::STATUS_INACTIVE]) || $user->email_verified == User::EMAIL_VERIFIED_NO || $user->blocked == User::BLOCKED_YES) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_USER_UNAVAILABLE'
                    ]);
                }
                
            
                $send_notification = false;
                
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
                if(!$connection) {
                    $userBlockedMapper = UserBlockedMapper::getInstance($this->adapter);
                    $userBlocked = $userBlockedMapper->fetchOneByUserIdAndBlockedId($currentUser->id, $user->id);
                    
                    if(!$userBlocked ) {
                        $connection = new Connection();
                        $connection->request_from = $currentUser->id;
                        $connection->request_to = $user->id;
                        $connection->status = Connection::STATUS_SENT;
                        
                        
                        if($connectionMapper->insert($connection)) {
                            
                            $send_notification = true;
                            
                            $response = [
                                'success' => true,
                                'data' => 'LABEL_CONNECTION_REQUESTED'
                            ];
                        } else {
                            $response = [
                                'success' => true,
                                'data' => $connectionMapper->getError()
                            ];
                        }
                    } else {
                        $response = [
                            'success' => true,
                            'data' => 'ERROR_USER_NOT_FOUND'
                        ];
                    }
                } else {
                    
                    
                    $connection->request_from = $currentUser->id;
                    $connection->request_to = $user->id;
                    $connection->status = Connection::STATUS_SENT;
                    if( $connectionMapper->update($connection)) {
                        $send_notification = true;
                        $response = [
                            'success' => true,
                            'data' => 'LABEL_CONNECTION_REQUESTED'
                        ];
                    } else {
                        $response = [
                            'success' => true,
                            'data' => $connectionMapper->getError()
                        ];
                    }
                    

                    
                }
                
                if($send_notification) {
                    $notification = new Notification();
                    $notification->type     = Notification::TYPE_RECEIVE_CONNECTION_REQUEST;
                    $notification->read     = Notification::NO;
                    $notification->user_id  = $user->id;
                    $notification->message  = 'LABEL_NOTIFICATION_RECEIVE_CONNECTION_REQUEST';
                    $notification->url      = $this->url()->fromRoute('connection/invitations-received');
                    
                    $notificationMapper = NotificationMapper::getInstance($this->adapter);
                    $notificationMapper->insert($notification);
                    
                    $userNotificationMapper = UserNotificationSettingMapper::getInstance($this->adapter);
                    $userNotification = $userNotificationMapper->fetchOne($user->id);
                    
                    if($userNotification && $userNotification->receive_connection_request)
                    {
                        $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
                        $emailTemplate = $emailTemplateMapper->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_RECEIVE_CONNECTION_REQUEST, $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'            => '',
                                'content'               => '',
                                'code'                  => '',
                                'link'                  => $this->url()->fromRoute('connection/invitations-received', [], ['force_canonical' => true])
                            ];
                            
                            $email = new QueueEmail($this->adapter);
                            $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
                        }
                    }
                }
                
                return new JsonModel($response);
                
            } else {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_METHOD_NOT_ALLOWED'
                ]);
            }
            
            
            
        }
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    
    public function deleteAction()
    {
        $request = $this->getRequest();
        if($request->isPost()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
            
            $id = $this->params()->fromRoute('id');
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
            
            if(!$user) {
                return new JsonModel([
                    'success' => true,
                    'data' => 'ERROR_USER_NOT_FOUND'
                ]);
            }
            
            if($user->id == $currentUser->id || in_array($user->status, [User::STATUS_DELETED, User::STATUS_INACTIVE]) || $user->email_verified == User::EMAIL_VERIFIED_NO || $user->blocked == User::BLOCKED_YES) {
                
                return new JsonModel([
                    'success' => true,
                    'data' => 'ERROR_USER_UNAVAILABLE'
                ]);
            }
            
           
            
            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $user->id);
            if($connection) {
                if($connection->status == Connection::STATUS_SENT) {
                    if($connectionMapper->delete($connection)) {
                        return new JsonModel([
                            'success' => true,
                            'data' => 'LABEL_CONNECTION_DELETED'
                        ]);
                    } else {
                        return new JsonModel([
                            'success' => true,
                            'data' => $connectionMapper->getError()
                        ]);
                    }
                } else {
                    $connection->status = Connection::STATUS_CANCELLED;
                    if($connectionMapper->update($connection)) {
                        return new JsonModel([
                            'success' => true,
                            'data' => 'LABEL_CONNECTION_CANCELLED'
                        ]);
                    } else {
                        return new JsonModel([
                            'success' => true,
                            'data' => $connectionMapper->getError()
                        ]);
                    }
                    
                    
                    return new JsonModel([
                        'success' => true,
                        'data' => 'LABEL_CONNECTION_NOT_PENDING'
                    ]);
                }
            } else {
                return new JsonModel([
                    'success' => true,
                    'data' => 'LABEL_CONNECTION_NOT_FOUND'
                ]);
                
            }
        } else {
        
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    public function blockAction()
    {
        $request = $this->getRequest();
        if($request->isPost()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
            
            $id = $this->params()->fromRoute('id');
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
            if($user) {
                if($user->id == $currentUser->id || in_array($user->status, [User::STATUS_DELETED, User::STATUS_INACTIVE]) || $user->email_verified == User::EMAIL_VERIFIED_NO || $user->blocked == User::BLOCKED_YES) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_USER_UNAVAILABLE'
                    ]);
                }
                    
                $userBlockedMapper = UserBlockedMapper::getInstance($this->adapter);
                $userBlocked = $userBlockedMapper->fetchOneByUserIdAndBlockedId($currentUser->id, $user->id);
                if($userBlocked) {
                    return new JsonModel([
                        'success' => false,
                        'data' =>  'ERROR_THIS_USER_WAS_ALREADY_BLOCKED'
                    ]);
                } else {
                    $userBlocked = new UserBlocked();
                    $userBlocked->user_id = $currentUser->id;
                    $userBlocked->blocked_id = $user->id;
                        
                    if($userBlockedMapper->insert($userBlocked)) {
                        return new JsonModel([
                            'success' => true,
                            'data' => 'LABEL_USER_HAS_BEEN_BLOCKED'
                        ]);
                    } else {
                        return new JsonModel([
                            'success' => false,
                            'data' => $userBlockedMapper->getError()
                        ]);
                    }
                }
            } else {
                return new JsonModel([
                    'success' => false,
                    'data' =>  'ERROR_USER_NOT_FOUND'
                ]);
            }
        } else {
            
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    public function unblockAction()
    {
        $request = $this->getRequest();
        if($request->isPost()) {
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
            
            $id = $this->params()->fromRoute('id');
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuidAndNetworkId($id, $currentUser->network_id);
                
            if($user) {
                if($user->id == $currentUser->id || in_array($user->status, [User::STATUS_DELETED, User::STATUS_INACTIVE]) || $user->email_verified == User::EMAIL_VERIFIED_NO || $user->blocked == User::BLOCKED_YES) {
                    return new JsonModel([
                        'success' => true,
                       'data' => 'ERROR_USER_UNAVAILABLE'
                    ]);
                }
                    
                $userBlockedMapper = UserBlockedMapper::getInstance($this->adapter);
                $userBlocked = $userBlockedMapper->fetchOneByUserIdAndBlockedId($currentUser->id, $user->id);
                if($userBlocked) {
                   if($userBlockedMapper->deleteByUserIdAndBlockedId($currentUser->id, $user->id)) {
                       return new JsonModel([
                           'success' => true,
                           'data' => 'LABEL_USER_HAS_BEEN_UNBLOCKED'
                        ]);
                    } else {
                        return new JsonModel([
                            'success' => false,
                            'data' => $userBlockedMapper->getError()
                        ]);
                    }
                } else {
                    return new JsonModel([
                        'success' => false,
                        'data' =>  'ERROR_USER_IS_NOT_BLOCKED'
                    ]);
                }
            } else {
                return new JsonModel([
                    'success' => false,
                    'data' =>  'ERROR_USER_NOT_FOUND'
                ]);
            }
            
            
        } else {
            
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    
    public function peopleBlockedAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        if($request->isGet()) {
            
            
            $headers  = $request->getHeaders();
            $isJson = false;
            if($headers->has('Accept')) {
                $accept = $headers->get('Accept');
                
                $prioritized = $accept->getPrioritized();
                
                foreach($prioritized as $key => $value) {
                    $raw = trim($value->getRaw());
                    
                    if(!$isJson) {
                        $isJson = strpos($raw, 'json');
                    }
                    
                }
            }
            
            if($isJson) {
                $search = trim(filter_var($this->params()->fromQuery('search', ''), FILTER_SANITIZE_STRING));
                
                $userBlockedMapper = UserBlockedMapper::getInstance($this->adapter);
                $user_ids = $userBlockedMapper->fetchAllBlockedReturnIds($currentUser->id);
                
                
                $queryMapper = QueryMapper::getInstance($this->adapter);
                
                $select = $queryMapper->getSql()->select(UserMapper::_TABLE);
                $select->where->in('id', $user_ids);
                $select->where->equalTo('status', User::STATUS_ACTIVE);
                $select->where->equalTo('network_id', $currentUser->network_id);
                
                if($search) {
                    $select->where->NEST->like('first_name', '%' . $search . '%')->or->like('last_name', '%' . $search . '%')->UNNEST;
                }
                $select->order('first_name ASC, last_name ASC');
                
                //echo $select->getSqlString($this->adapter->platform); exit;
 
                
                $records = $queryMapper->fetchAll($select);
                $items = [];
                foreach($records as $record)
                {
                    
                    $userBlocked = $userBlockedMapper->fetchOneByUserIdAndBlockedId($record['id'], $currentUser->id);
                    $link_view = $userBlocked ? '' : $this->url()->fromRoute('profile/view', ['id' => $record['uuid']  ]);
                    
                    $item = [
                        'name' => trim($record['first_name'] . ' ' . $record['last_name']),
                        'image' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $record['uuid'], 'filename' => $record['image'] ]),
                        'link_view' => $link_view,
                        'link_unblock' => $this->url()->fromRoute('connection/unblock', ['id' => $record['uuid']  ]),
                    ];
                    
                    array_push($items, $item);
                }
                
                
                
                $response = [
                    'success' => true,
                    'data' => $items
                ];
                
                return new JsonModel($response);
            } else {
                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/connection/people-blocked.phtml');
                return $viewModel ;
            }
            
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    
    public function peopleYouMayKnowAction()
    {

        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        if($request->isGet()) {
            
            
            $headers  = $request->getHeaders();
            $isJson = false;
            if($headers->has('Accept')) {
                $accept = $headers->get('Accept');
                
                $prioritized = $accept->getPrioritized();
                
                foreach($prioritized as $key => $value) {
                    $raw = trim($value->getRaw());
                    
                    if(!$isJson) {
                        $isJson = strpos($raw, 'json');
                    }
                    
                }
            }
            
            if($isJson) {
                $page = (int) $this->params()->fromQuery('page');
                $search = trim(filter_var($this->params()->fromQuery('search', ''), FILTER_SANITIZE_STRING));
                
                
                $queryMapper = QueryMapper::getInstance($this->adapter);
                /*
                $select = $queryMapper->getSql()->select(UserExperienceMapper::_TABLE);
                $select->columns(['industry_id' => new Expression('DISTINCT(industry_id)')]);
                $select->where->equalTo('user_id', $currentUser->id);
                
                
                $industry_ids = [];
                $records = $queryMapper->fetchAll($select);
                foreach($records as $record)
                {
                    array_push($industry_ids, $record['industry_id']);
                }*/
                
                $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 capsulas */
                $capsule_user_ids = [];
                $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);

                $company_ids = [];
                $records = $capsuleUserMapper->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 = $capsuleUserMapper->fetchAllUserIdsForCapsulesActiveByCompanyId($company_id);
                    foreach($otherUsers as $user_id)
                    {
                        if($currentUser->id != $user_id ) {
                            
                            if(!in_array($user_id, $capsule_user_ids)) {
                                array_push($capsule_user_ids, $user_id);
                            }
                        }
                    }
                }
                
                $capsule_user_ids = $capsule_user_ids ? $capsule_user_ids : [0];
                
                
                $other_users = array_unique(array_merge(
                    $second_degree_connections_ids,
                    $company_user_ids,
                    $group_member_ids,
                    $capsule_user_ids
                ));
                
                $queryMapper = QueryMapper::getInstance($this->adapter);
                $select = $queryMapper->getSql()->select();
                $select->columns(['id', 'uuid',  'first_name','last_name', 'image']);
                $select->from(['u' => UserMapper::_TABLE]);
                $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->where->equalTo('u.network_id', $currentUser->network_id);
                
                

                if($search) {
                    $select->where->NEST->like('first_name', '%' . $search . '%')->or->like('last_name', '%' . $search . '%')->UNNEST;
                }

                $select->order(['first_name','last_name']);
                

                //$select->order(new Expression("rand()"));
                      
                    
                //echo $select->getSqlString($this->adapter->platform); exit;
                
   
                
                $dbSelect = new DbSelect($select, $this->adapter);
                $paginator = new Paginator($dbSelect);
                $paginator->setCurrentPageNumber($page ? $page : 1);
                $paginator->setItemCountPerPage(12);
                   
                    
                $items = [];
                $records = $paginator->getCurrentItems();
                    
                foreach($records as $record)
                {
                    $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $record['id']);
                    
                    
                    
                    $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'], $capsule_user_ids)) {
                        array_push($relation, 'LABEL_RELATION_TYPE_CAPSULE_USER');
                    }
                    
                    $item = [
                        'name' => trim($record['first_name'] . ' ' . $record['last_name']),
                        'image' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $record['uuid'], 'filename' => $record['image'] ]),
                        'link_view' => $this->url()->fromRoute('profile/view', ['id' => $record['uuid']  ]),
                        'link_inmail'   => $this->url()->fromRoute('inmail', ['id' => $record['uuid']  ]),
                        'relation' => $relation,
                        'link_cancel'   => '',
                        'link_request'  => '',
                        
                    ];
                    
                    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);
                }
                    
                $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 {
                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/connection/people-you-may-know.phtml');
                return $viewModel ;
            }
            
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
}