Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 129 | Rev 15351 | 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\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 LeadersLinked\Library\Functions;
use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Mapper\UserPasswordMapper;

use LeadersLinked\Model\User;
use LeadersLinked\Form\ChangePasswordForm;
use LeadersLinked\Model\CompanyUser;
use LeadersLinked\Mapper\CompanyUserMapper;
use LeadersLinked\Mapper\CompanyUserRoleMapper;
use LeadersLinked\Mapper\RoleMapper;
use LeadersLinked\Model\UserType;
use LeadersLinked\Model\UserPassword;
use PhpOffice\PhpSpreadsheet\IOFactory;
use LeadersLinked\Form\UserUploadForm;
use LeadersLinked\Mapper\CompanyServiceMapper;
use LeadersLinked\Model\CompanyService;
use LeadersLinked\Model\Role;
use LeadersLinked\Mapper\CompanyRoleMapper;
use LeadersLinked\Model\CompanyUserRole;
use LeadersLinked\Model\Notification;
use LeadersLinked\Model\EmailTemplate;
use LeadersLinked\Mapper\NotificationMapper;
use LeadersLinked\Mapper\UserNotificationSettingMapper;
use LeadersLinked\Mapper\EmailTemplateMapper;
use LeadersLinked\Library\QueueEmail;

class UserController 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;
        
    }
    
    public function indexAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $currentCompany = $currentUserPlugin->getCompany();
        
        $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) {
            {
                $sandbox = $this->config['leaderslinked.runmode.sandbox'];
                if($sandbox) {
                    $user_profile_url = $this->config['leaderslinked.frontend.sandbox_user_profile'];
                } else {
                    $user_profile_url = $this->config['leaderslinked.frontend.production_user_profile'];
                }
                
                
                
                $search = $this->params()->fromQuery('search', []);
                $search = empty($search['value']) ? '' : filter_var($search['value'], FILTER_SANITIZE_STRING);
                
                //$page               = intval($this->params()->fromQuery('start', 1), 10);
                //$records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
                
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
                $page               = (intval($this->params()->fromQuery('start', 1), 10)/$records_x_page)+1;
                
                $order =  $this->params()->fromQuery('order', []);
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : strtoupper(filter_var( $order[0]['dir'], FILTER_SANITIZE_STRING));
    
                $fields =  ['first_name', 'last_name', 'email'];
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'first_name';
                
                if(!in_array($order_direction, ['ASC', 'DESC'])) {
                    $order_direction = 'ASC';
                }
                

                if($currentCompany) {
                    $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
                    
                    $roles = []; 
                    $roleMapper = RoleMapper::getInstance($this->adapter);
                    $records = $roleMapper->fetchAll(); 
                    foreach ($records as $record)
                    {
                        $roles[ $record->id ] = $record->name;
                    }
            
                    
                    //Usuarios cuando el nivel es empresa
                    
                    $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                    $allowUnblock = $acl->isAllowed($currentUser->usertype_id, 'users/unblock');
                    $allowChangePassword = $acl->isAllowed($currentUser->usertype_id, 'users/change-password');
                    
                    $allowAccept    = $acl->isAllowed($currentUser->usertype_id, 'users/accept') ? 1 : 0;
                    $allowCancel    = $acl->isAllowed($currentUser->usertype_id, 'users/cancel') ? 1 : 0;
                    $allowReject    = $acl->isAllowed($currentUser->usertype_id, 'users/reject') ? 1 : 0;
                    $allowEdit     = $acl->isAllowed($currentUser->usertype_id, 'users/edit') ? 1 : 0;
                    
                    
                    $status = filter_var($this->params()->fromQuery('status'), FILTER_SANITIZE_STRING);
                    if(!in_array($status, [
                        CompanyUser::STATUS_ACCEPTED,
                        CompanyUser::STATUS_ADMIN_WILL_ADD,
                        CompanyUser::STATUS_CANCELLED,
                        CompanyUser::STATUS_PENDING,
                        CompanyUser::STATUS_REJECTED,
                        CompanyUser::STATUS_SENT,
                    ])) { 
                        $status = '';
                    }
                    
                    
                    
                    $userMapper = UserMapper::getInstance($this->adapter);
                    $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
                    
                    $paginator = $userMapper->fetchAllDataTableByCompanyId($currentCompany->id, $status,  $search, $page, $records_x_page, $order_field, $order_direction);
                    
                    $items = [];
                    $records = $paginator->getCurrentItems();
                    
                    foreach($records as $record)
                    {
                        
                        $actions = []; 
                        $actions['link_profile'] = str_replace('[uuid]', $record['uuid'], $user_profile_url);
                        
                        
                        
                        
                        $details = []; 
                        switch ($record['status'])
                        {
                            
                            case CompanyUser::STATUS_PENDING :
                                $details['status']  = 'LABEL_PENDING';
                                $actions['link_accept'] = $allowAccept ? $this->url()->fromRoute('users/accept', ['id' => $record['uuid']]) : '';
                                $actions['link_reject'] = $allowReject ? $this->url()->fromRoute('users/reject', ['id' => $record['uuid']]) : '';
                                break;
                                
                            case CompanyUser::STATUS_ACCEPTED : 
                                $details['status']  = 'LABEL_ACCEPTED';
                                if($record['creator'] == CompanyUser::CREATOR_NO) { 
                                    $actions['link_edit'] = $allowEdit ? $this->url()->fromRoute('users/edit', ['id' => $record['uuid']]) : '';
                                    
                                    
                                    
                                    $actions['link_cancel'] = $allowCancel ? $this->url()->fromRoute('users/cancel', ['id' => $record['uuid']]) : '';
                                } 
                                
                                break;
                                
                            case CompanyUser::STATUS_ADMIN_WILL_ADD : 
                                $details['status']  = 'LABEL_ADMIN_WILL_ADD';
                                $actions['link_cancel'] = $allowCancel ? $this->url()->fromRoute('users/cancel', ['id' => $record['uuid']]) : '';
                                $actions['link_edit'] = $allowEdit ? $this->url()->fromRoute('users/edit', ['id' => $record['uuid']]) : '';
                                
                                break;
                                
                            case CompanyUser::STATUS_SENT :
                                $details['status']  = 'LABEL_INVITED';
                                $actions['link_accept'] = $allowAccept ? $this->url()->fromRoute('users/accept', ['id' => $record['uuid']]) : '';
                                $actions['link_reject'] = $allowReject ? $this->url()->fromRoute('users/reject', ['id' => $record['uuid']]) : '';
                                break;
                                
                            case CompanyUser::STATUS_REJECTED :
                                $actions['link_accept'] = $allowAccept ? $this->url()->fromRoute('users/accept', ['id' => $record['uuid']]) : '';
                                $details['status']  = 'LABEL_REJECTED';
                                break;
                                
                            case CompanyUser::STATUS_CANCELLED :
                                $actions['link_accept'] = $allowAccept ? $this->url()->fromRoute('users/accept', ['id' => $record['uuid']]) : '';
                                $details['status']  = 'LABEL_CANCELLED';
                                break;
                                
                            default : 
                                $details['status']  = '';
                                break;
                                
                        }
                        
                        $totalOtherCompanies = $companyUserMapper->fetchCountOtherCompaniesByCompanyIdAndUserId($currentCompany->id, $record['id']);
                        if(!$totalOtherCompanies) {
                        
                            $actions['link_change_password'] = $allowChangePassword ? $this->url()->fromRoute('users/change-password', ['id' => $record['uuid'] ]) : '';
                            if($record['blocked'] == User::BLOCKED_YES ) {
                                $actions['link_unblock'] = $allowUnblock ? $this->url()->fromRoute('users/unblock', ['id' => $record['uuid'] ]) : '';
                            } 
                        }
                        
                        if($record['blocked'] == User::BLOCKED_YES ) {
                            $details['blocked'] = 'LABEL_YES';
                        } else if($record['blocked'] == User::BLOCKED_NO ) {
                            $details['blocked'] = 'LABEL_NO';
                        }
                        if($record['email_verified'] == User::EMAIL_VERIFIED_YES ) {
                            $details['email_verified'] = 'LABEL_YES';
                            
                        } else if($record['email_verified'] == User::EMAIL_VERIFIED_NO ) {
                            $details['email_verified'] = 'LABEL_NO';
                        }
                        $details['login_attempt'] = $record['login_attempt'];
                        
                        
                        $company_user_roles = $companyUserRoleMapper->fetchAllByCompanyIdAndUserId($currentCompany->id, $record['id']);
                        
                        $details['roles'] = [];
                        
                        if($record['creator'] == CompanyUser::CREATOR_YES) {
                            $details['roles'][] = 'LABEL_ALL_PERMITS';
                            $details['creator'] = 'LABEL_YES' ;
                        }  else { 
                            $details['creator'] = 'LABEL_NO'; 
                            foreach($company_user_roles as $company_user_role)
                            {
                                $role = $roles[ $company_user_role->role_id ];
                                $details['roles'][] = $role;
                                
                            }
                        } 
                        
                       
                        $details['backend'] = $record['backend'] == CompanyUser::BACKEND_YES ? 'LABEL_YES' : 'LABEL_NO';
                        

                        
                        
                        
                        
                        $item = [
                            'first_name' => $record['first_name'] ,
                            'last_name' => $record['last_name'],
                            'email' => $record['email'],
                            'details' => $details,
                            'actions' =>  $actions ,
                       ];
                        
                        array_push($items, $item);
                    }
                } else {
                    //Usuario cuando el nivel es administrador
                    
          
                    
                    $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                    $allowUnblock = $acl->isAllowed($currentUser->usertype_id, 'users/unblock');
                    $allowChangePassword = $acl->isAllowed($currentUser->usertype_id, 'users/change-password');
                    
                    $userMapper = UserMapper::getInstance($this->adapter);
                    $paginator = $userMapper->fetchAllDataTable($search, $page, $records_x_page, $order_field, $order_direction);
                    
                    $items = [];
                    $records = $paginator->getCurrentItems();
                    
                    foreach($records as $record)
                    {
                        $actions = [];
                        $actions['link_profile'] = str_replace('[uuid]', $record->uuid, $user_profile_url);
                        
                        
                        $details = [] ;
                        if($record->status == User::STATUS_ACTIVE ) {
                            $details['status'] = 'LABEL_ACTIVE';
                        } else if($record->status == User::STATUS_INACTIVE ) {
                            $details['status'] = 'LABEL_INACTIVE';  
                        }
                        if($record->blocked == User::BLOCKED_YES ) {
                            $details['blocked'] = 'LABEL_YES';
                        } else if($record->blocked == User::BLOCKED_NO ) {
                            $details['blocked'] = 'LABEL_NO';
                        }
                        if($record->email_verified == User::EMAIL_VERIFIED_YES ) {
                            $details['email_verified'] = 'LABEL_YES';
                            
                        } else if($record->email_verified == User::EMAIL_VERIFIED_NO ) {
                            $details['email_verified'] = 'LABEL_NO';
                        }
                        $details['login_attempt'] = $record->login_attempt;
                        
                        
                        $actions['link_change_password'] = $allowChangePassword ? $this->url()->fromRoute('users/change-password', ['id' => $record->uuid ]) : '';
                        $actions['link_unblock'] = $allowUnblock && $record->blocked == User::BLOCKED_YES ? $this->url()->fromRoute('users/unblock', ['id' => $record->uuid ]) : '';

                        $item = [
                            
                            
                            'first_name' => $record->first_name,
                            'last_name' => $record->last_name,
                            'email' => $record->email,
                            'details' => $details,
                            'actions' => $actions
                         ];
                        
                        array_push($items, $item);
                    }
                }
            }
            
            return new JsonModel([
                'success' => true,
                'data' => [
                    'items' => $items,
                    'total' => $paginator->getTotalItemCount(),
                ]
            ]);
                

            
        }
        else if($request->isGet()) {
            $this->layout()->setTemplate('layout/layout-backend');
            $viewModel = new ViewModel();
            
            $formChangePassword = new ChangePasswordForm();
            $company = $currentUserPlugin->getCompany();
            if($company) {
                
                $formUploadUsers = new UserUploadForm();

                $viewModel->setTemplate('leaders-linked/users/company.phtml');
                $viewModel->setVariables([
                    'formUploadUsers' => $formUploadUsers,
                    'formChangePassword' => $formChangePassword,
                ] ); 
            } else { 
                $viewModel->setTemplate('leaders-linked/users/index.phtml');
                $viewModel->setVariables([
                    'formChangePassword' => $formChangePassword,
                ]);
            }
            return $viewModel ;
      
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);;
        }
    }
    /*
    public function addAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        
        
        if($request->isPost()) {
            $form = new  AddForm($this->adapter);
            $dataPost = $request->getPost()->toArray();
            
            $form->setData($dataPost);
            
            if($form->isValid()) {
                $dataPost = (array) $form->getData();

                $hydrator = new ObjectPropertyHydrator();
                $user = new User();
                $hydrator->hydrate($dataPost, $user);  

                
                $userMapper = UserMapper::getInstance($this->adapter);
                $result = $userMapper->insert($user);
                
                if($result) {
                    $this->logger->info('Se agrego el usuario ' . $user->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    $data = [
                        'success'   => true,
                        'data'   => 'LABEL_RECORD_ADDED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $userMapper->getError()
                    ];
                    
                }
                
                return new JsonModel($data);
                
            } else {
                $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
                ]);
            }

        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }
    
    public function editAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        $id = $this->params()->fromRoute('id');

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

        $userMapper = UserMapper::getInstance($this->adapter);
        $user = $userMapper->fetchOne($id);
        if(!$user) {
            $data = [
                'success'   => false,
                'data'   => 'ERROR_RECORD_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        if($request->isPost()) {
            $form = new  EditForm($this->adapter);
            $dataPost = $request->getPost()->toArray();
            
            $form->setData($dataPost);
            
            if($form->isValid()) {
                $dataPost = (array) $form->getData();
                
                $hydrator = new ObjectPropertyHydrator();
                $hydrator->hydrate($dataPost, $user);
                $result = $userMapper->update($user);
                
                if($result) {
                    $this->logger->info('Se actualizo el usuario ' . $user->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    $data = [
                        'success' => true,
                        'data' => 'LABEL_RECORD_UPDATED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $userMapper->getError()
                    ];
                }
                
                return new JsonModel($data);
                
            } else {
                $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
                ]);
            }
        } else if ($request->isGet()) {
            $hydrator = new ObjectPropertyHydrator();
            
            $data = [
                'success' => true,
                'data' => $hydrator->extract($user)
            ];
            
            return new JsonModel($data);
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }
    
    public function deleteAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        $id = $this->params()->fromRoute('id');
        
        if(!$id) {
            $data = [
                'success'   => false,
                'data'   => 'ERROR_INVALID_PARAMETER'
            ];
            
            return new JsonModel($data);
        }
        
                
        $userMapper = UserMapper::getInstance($this->adapter);
        $user = $userMapper->fetchOne($id);
        if(!$user) {
            $data = [
                'success'   => false,
                'data'   => 'ERROR_RECORD_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        if($request->isPost()) {
            $result = $userMapper->delete($user);
            if($result) {
                $this->logger->info('Se borro el usuario ' . $user->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                $data = [
                    'success' => true,
                    'data' => 'LABEL_RECORD_DELETED'
                ];
            } else {

                $data = [
                    'success'   => false,
                    'data'      => $userMapper->getError()
                ];

                return new JsonModel($data);
            }

        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }*/
    
    public function unblockAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $request = $this->getRequest();

        
        if($request->isPost()) {
            
            $uuid = $this->params()->fromRoute('id');
            if(!$uuid) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_INVALID_PARAMETER'
                ]);
            }
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuid($uuid);
            
            if(!$user) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_NOT_FOUND'
                ]);
            }
     
            if($user->blocked == User::BLOCKED_NO) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_IS_NOT_BLOCKED'
                ]);
            }


                
            $result = $userMapper->unblock($user);
            if($result) {
                $this->logger->info('El usuario : ' . $user->email . ' ha sido desbloqueado ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                return new JsonModel([
                    'success'   => true,
                    'data'      => 'LABEL_USER_HAS_BEEN_UNBLOCKED',
                ]);
            }  else {
                
                return new JsonModel([
                    'success'   => false,
                    'data'      => $userMapper->getError()
                ]);
            }
            
            
        }
        
        
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function emailVerifyAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $request = $this->getRequest();
        
        
        if($request->isPost()) {
            
            $uuid = $this->params()->fromRoute('id');
            if(!$uuid) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_INVALID_PARAMETER'
                ]);
            }
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuid($uuid);
            
            if(!$user) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_NOT_FOUND'
                ]);
            }
            
            if($user->blocked == User::BLOCKED_NO) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_IS_NOT_PENDING_FOR_EMAIL_VERIFY'
                ]);
            }
            
            
            
            $result = $userMapper->emailVerifyAndActive($user);
            if($result) {
                $this->logger->info('El usuario : ' . $user->email . ' ha sido desbloqueado ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                return new JsonModel([
                    'success'   => true,
                    'data'      => 'LABEL_USER_HAS_BEEN_UNBLOCKED',
                ]);
            }  else {
                
                return new JsonModel([
                    'success'   => false,
                    'data'      => $userMapper->getError()
                ]);
            }
            
            
        }
        
        
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function changePasswordAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();

        if($request->isGet()) {
            $uuid = $this->params()->fromRoute('id');
            if(!$uuid) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_INVALID_PARAMETER'
                ]);
            }
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuid($uuid);
            
            
            
            if($user) {
                return new JsonModel([
                    'success'   => true,
                    'data'      => [
                        'first_name' => $user->first_name,
                        'last_name' => $user->last_name,
                        'email' => $user->email,
                    ]
                ]);
            } else {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_NOT_FOUND'
                ]);
            }
            
        }
        
        if($request->isPost()) {
            
            $uuid = $this->params()->fromRoute('id');
            if(!$uuid) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_INVALID_PARAMETER'
                ]);
            }
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuid($uuid);
            
            if(!$user) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_NOT_FOUND'
                ]);
            }
            
            
            $dataPost = $request->getPost()->toArray();
            $form = new ChangePasswordForm();
            $form->setData($dataPost);
            
            if($form->isValid()) {
                
                
                
                $data = (array) $form->getData();
                $password = $data['password'];
                

                
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
                $userPasswords = $userPasswordMapper->fetchAllByUserId($user->id);
                
                $oldPassword = false;
                foreach($userPasswords as $userPassword)
                {
                    if(password_verify($password, $userPassword->password) || (md5($password) == $userPassword->password))
                    {
                        $oldPassword = true;
                        break;
                    }
                }
                
                if($oldPassword) {
                    $this->logger->err('Cambio de contraseña del usuario - error contraseña ya utilizada anteriormente', ['user_id' =>  $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    return new JsonModel([
                        'success'   => false,
                        'data'      => 'ERROR_PASSWORD_HAS_ALREADY_BEEN_USED'
                        
                    ]);
                } else {
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
                    
                    
                    $result = $userMapper->updatePassword($user, $password_hash);
                    if($result) {
                        $this->logger->info('Cambio de contraseña del usuario realizado', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                        
                        
                        return new JsonModel([
                            'success'   => true,
                            'data'      => 'LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED'
                            
                        ]);
                    } else {
                        $this->logger->err('Cambio de contraseña del usuario - error desconocido', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                        
                        return new JsonModel([
                            'success'   => true,
                            'data'      => 'ERROR_THERE_WAS_AN_ERROR'
                            
                        ]);
                    }
                }
                
            } else {
                $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
                ]);
            }
            
        }
        
        
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function cancelAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $currentCompany = $currentUserPlugin->getCompany(); 
        
        $request = $this->getRequest();
        
        
        if($request->isPost()) {
            
            $uuid = $this->params()->fromRoute('id');
            if(!$uuid) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_INVALID_PARAMETER'
                ]);
            }
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuid($uuid);
            
            if(!$user) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_COMPANY_NOT_FOUND'
                ]);
            }
            
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id); 
            
            if(!$companyUser) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_NOT_FOUND'
                ]);
            }
            
            
            if(!in_array($companyUser->status, [  CompanyUser::STATUS_ADMIN_WILL_ADD, CompanyUser::STATUS_ACCEPTED])) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_COMPANY_WRONG_STATUS'
                ]);
            }
            
            $companyUser->status = CompanyUser::STATUS_CANCELLED;
            $result = $companyUserMapper->update($companyUser);
            if($result) {
                $this->logger->info('La relación del usuario : ' . $user->email . ' con la empresa : ' . $currentCompany->name  . ' ha sido cancelada ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                return new JsonModel([
                    'success'   => true,
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_CANCELLED',
                ]);
            }  else {
                
                return new JsonModel([
                    'success'   => false,
                    'data'      => $userMapper->getError()
                ]);
            }
            
            
        }
        
        
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function acceptAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $currentCompany = $currentUserPlugin->getCompany();
        
        $request = $this->getRequest();
        
        
        if($request->isPost()) {
            
            $uuid = $this->params()->fromRoute('id');
            if(!$uuid) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_INVALID_PARAMETER'
                ]);
            }
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuid($uuid);
            
            if(!$user) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_NOT_FOUND'
                ]);
            }
            
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
            
            if(!$companyUser) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_NOT_FOUND'
                ]);
            }
            
            if($companyUser->status != CompanyUser::STATUS_PENDING
                && $companyUser->status != CompanyUser::STATUS_SENT
                && $companyUser->status != CompanyUser::STATUS_CANCELLED
                && $companyUser->status != CompanyUser::STATUS_REJECTED) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_COMPANY_WRONG_STATUS'
                ]);
            }
            
            $companyUser->status = CompanyUser::STATUS_ACCEPTED;
            $result = $companyUserMapper->update($companyUser);
            if($result) {
                $this->logger->info('La relación del usuario : ' . $user->email . ' con la empresa : ' . $currentCompany->name  . ' ha sido aceptada ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                return new JsonModel([
                    'success'   => true,
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_ACCEPTED'
                ]);
            }  else {
                
                return new JsonModel([
                    'success'   => false,
                    'data'      => $userMapper->getError()
                ]);
            }
            
            
        }
        
        
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function rejectAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $currentCompany = $currentUserPlugin->getCompany();
        
        $request = $this->getRequest();
        
        
        if($request->isPost()) {
            
            $uuid = $this->params()->fromRoute('id');
            if(!$uuid) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_INVALID_PARAMETER'
                ]);
            }
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuid($uuid);
            
            if(!$user) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_NOT_FOUND'
                ]);
            }
            
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
            
            if(!$companyUser) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_COMPANY_NOT_FOUND'
                ]);
            }
            
            if($companyUser->status != CompanyUser::STATUS_PENDING 
                && $companyUser->status != CompanyUser::STATUS_SENT) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_COMPANY_WRONG_STATUS'
                ]);
            }
            
            $companyUser->status = CompanyUser::STATUS_REJECTED;
            $result = $companyUserMapper->update($companyUser);
            if($result) {
                $this->logger->info('La relación del usuario : ' . $user->email . ' con la empresa : ' . $currentCompany->name  . ' ha sido rechazada ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                return new JsonModel([
                    'success'   => true,
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_REJECTED',
                ]);
            }  else {
                
                return new JsonModel([
                    'success'   => false,
                    'data'      => $userMapper->getError()
                ]);
            }
            
            
        }
        
        
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function inviteAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $currentCompany = $currentUserPlugin->getCompany();
        
        $request = $this->getRequest();
        
        if($request->isGet()) {
            
            $search = trim(filter_var( $this->params()->fromQuery('search'), FILTER_SANITIZE_STRING)) ;
            if(strlen($search) >= 3) {
                
                $userMapper = UserMapper::getInstance($this->adapter);
                $records  = $userMapper->fetchAllSuggestForInvitationByCompanyId($currentCompany->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->fetchOneByUuid($uuid);
            
            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'
                ]);
            }
            
            
            
            
            
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
            
            if($companyUser && $companyUser->status == CompanyUser::STATUS_ACCEPTED) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_COMPANY_FOUND'
                ]);
            }
            

            
            if($companyUser) {
                
                $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
                $result = $companyUserMapper->update($companyUser);
                
            } else {
                $companyUser = new CompanyUser();
                $companyUser->company_id = $currentCompany->id;
                $companyUser->backend = CompanyUser::BACKEND_NO;
                $companyUser->creator = CompanyUser::CREATOR_NO;
                $companyUser->owner = CompanyUser::OWNER_NO;
                $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
                $companyUser->user_id = $user->id;
                
                
                
                $result = $companyUserMapper->insert($companyUser);
            }
           
  
            
            if($result) {

                
                $notification = new Notification();
                $notification->type     = Notification::TYPE_RECEIVE_INVITATION_COMPANY;
                $notification->read     = Notification::NO;
                $notification->user_id  = $user->id;
                $notification->company_id = $currentCompany->id;
                $notification->message  = 'LABEL_NOTIFICATION_RECEIVE_INVITATION_COMPANY';
                $notification->url      = 'company/view/' . $currentCompany->uuid;
                
                $notificationMapper = NotificationMapper::getInstance($this->adapter);
                $notificationMapper->insert($notification);
                
                $userNotificationMapper = UserNotificationSettingMapper::getInstance($this->adapter);
                $userNotification = $userNotificationMapper->fetchOne($user->id);
                
                if($userNotification && $userNotification->receive_invitation_company)
                {
                    $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
                    $emailTemplate = $emailTemplateMapper->fetchOne(EmailTemplate::ID_RECEIVE_INVITATION_COMPANY);
                    
                    if($emailTemplate) {
                        
                        $sandbox = $this->config['leaderslinked.runmode.sandbox'];
                        if($sandbox) {
                            $company_profile_url = $this->config['leaderslinked.frontend.sandbox_company_profile'];
                        } else {
                            $company_profile_url = $this->config['leaderslinked.frontend.production_company_profile'];
                        }
                        
                        $company_profile_url = str_replace('[uuid]', $currentCompany->uuid, $company_profile_url);
                        
                        $arrayCont = [
                            'firstname'             => $currentUser->first_name,
                            'lastname'              => $currentUser->last_name,
                            'other_user_firstname'  => $user->first_name,
                            'other_user_lastname'   => $user->last_name,
                            'company_name'          => $currentCompany->name,
                            'group_name'            => '',
                            'content'               => '',
                            'code'                  => '',
                            'link'                  => $company_profile_url,
                        ];
                        
                        $email = new QueueEmail($this->adapter);
                        $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
                    }
                }
                
                
                $this->logger->info('La empresa : ' . $currentCompany->name . ' envio al usuario : ' . $user->email . ' una invitación ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                return new JsonModel([
                    'success'   => true,
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_SENT',
                ]);
            }  else {
                
                return new JsonModel([
                    'success'   => false,
                    'data'      => $userMapper->getError()
                ]);
            }
            
            
        }
        
        
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    
    public function deleteAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $currentCompany = $currentUserPlugin->getCompany();
        
        $request = $this->getRequest();
        
        
        if($request->isPost()) {
            
            $uuid = $this->params()->fromRoute('id');
            if(!$uuid) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_INVALID_PARAMETER'
                ]);
            }
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuid($uuid);
            
            if(!$user) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_NOT_FOUND'
                    
                ]);
            }
            
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
            
            if($companyUser) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_COMPANY_NOT_FOUND'
                ]);
            }
            
            
            if(!$currentCompany->internal) {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_INTERNAL_COMPANY_ONLY'
                ]);
            }

            

            $result = $companyUserMapper->delete($companyUser->id);
            if($result) {
                $this->logger->info('La relación del usuario : ' . $user->email . ' con la empresa : ' . $currentCompany->name  . ' ha sido eliminada ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                return new JsonModel([
                    'success'   => true,
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_DELETED',
                ]);
            }  else {
                
                return new JsonModel([
                    'success'   => false,
                    'data'      => $userMapper->getError()
                ]);
            }
            
            
        }
        
        
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    
    public function uploadAction()
    {
        $request = $this->getRequest();
        
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser    = $currentUserPlugin->getUser();
        $currentCompany = $currentUserPlugin->getCompany();
        
        $request    = $this->getRequest();

        if($request->isPost()) {
            
            $step = filter_var( $this->params()->fromPost('step'), FILTER_SANITIZE_STRING);
            if($step == 'validation') {
                $userMapper = UserMapper::getInstance($this->adapter);
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
                
                $form = new  UserUploadForm();
                $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
                
                $form->setData($dataPost);
                
                if($form->isValid()) {
                    
                    $file = $_FILES['file'];
                    $tmp_filename = $file['tmp_name'];
                    $final_filename =  'data/' . $file['name'];
                    
                    if(!move_uploaded_file($tmp_filename, $final_filename)) {
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_UPLOAD_FILE'
                        ]);
                    }
                    
                    
                    $users = [];
                    
                    
                    $spreadsheet = IOFactory::load($final_filename);
                    $records = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
                    
                    $emails = [];
                    
                    foreach($records as $record)
                    {
                        //A = Nombre    B = Apellidos   C = Email       D = contraseña
                        
                        
                        $email = trim(filter_var($record['C'], FILTER_SANITIZE_EMAIL));
                        $first_name = trim(filter_var($record['A'], FILTER_SANITIZE_STRING));
                        $last_name = trim(filter_var($record['B'], FILTER_SANITIZE_STRING));
                        $password = trim(filter_var($record['D'], FILTER_SANITIZE_STRING));
                        
                        if(empty($first_name) || empty($last_name) || !filter_var($email, FILTER_VALIDATE_EMAIL) ||  empty($password)) {
                            continue;
                        }
                        
                        if(!in_array($email, $emails)) {
                            
                            $user = $userMapper->fetchOneByEmail($email);
                            
                            array_push($emails, $email);
                            array_push($users, [
                                'first_name' => $first_name,
                                'last_name' => $last_name,
                                'password'  => $password,
                                'email' => $email,
                            ]);
                        }
                        
                        
                        
                        
                        
                    }
                    
                    $key = md5($currentUser->id . '-' . microtime(true));
                    $this->cache->setItem($key, serialize($users));
                    
                    return new JsonModel([
                        'success' => true,
                        'data' => [
                            'key' => $key,
                            'items' => $users,
                        ]
                    ]);
                    
                    
                    
                } else {
                    $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
                    ]);
                }
            } else if($step == 'process') {
                
                $key = filter_var( $this->params()->fromPost('key'), FILTER_SANITIZE_STRING);
                if(!$key) {
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_CACHE_KEY_EMPTY'
                    ]);
                }
                
                $value = $this->cache->getItem($key);
                if(!$value) {
                    
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_CACHE_NOT_FOUND'
                    ]);
                }
                
                $records = unserialize($value);
                if(!$records) {
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_CACHE_INVALID'
                    ]);
                }
                
                $userMapper = UserMapper::getInstance($this->adapter);
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);

                $users_created = 0;
                $user_ids = [];
                foreach($records as $record)
                {
                    $first_name = $record['first_name'];
                    $last_name = $record['last_name'];
                    $password = $record['password'];
                    $email = $record['email'];
                    
                    
                    $user = $userMapper->fetchOneByEmail($email);
                    if(!$user) {
                        $password_hash = password_hash($password, PASSWORD_DEFAULT);
                        
                        $user = new User();
                        
                        $user->blocked = User::BLOCKED_NO;
                        $user->email_verified = User::EMAIL_VERIFIED_YES;
                        $user->email = $email;
                        $user->first_name = $first_name;
                        $user->last_name = $last_name;
                        $user->password = $password_hash;
                        $user->login_attempt = 0;
                        $user->usertype_id = UserType::USER;
                        $user->status = User::STATUS_ACTIVE;
                        
                        $result = $userMapper->insert($user);
                        if($result) {
                            $userPassword = new UserPassword();
                            $userPassword->user_id = $user->id;
                            $userPassword->password = $password_hash;
                            $userPasswordMapper->insert($userPassword);
                        } else {
                            continue;
                        }
                    } else {
                        if($user->email_verified == User::EMAIL_VERIFIED_NO || $user->status != User::STATUS_ACTIVE) {
                            $user->email_verified = User::EMAIL_VERIFIED_YES;
                            $user->status != User::STATUS_ACTIVE;
                            
                            if(!$userMapper->update($user)) {
                                continue;
                            }
                        }
                    }
                    
                    if(!in_array($user->id, $user_ids)) {
                        array_push($user_ids, $user->id);
                    }
                }
                
                foreach($user_ids as $user_id)
                {
                    $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user_id);
                    if(!$companyUser) {
                        
                        $companyUser = new CompanyUser(); 
                        $companyUser->company_id = $currentCompany->id; 
                        $companyUser->user_id = $user_id; 
                        $companyUser->backend = CompanyUser::BACKEND_NO;
                        $companyUser->creator = CompanyUser::CREATOR_NO;
                        $companyUser->owner = CompanyUser::OWNER_NO; 
                        $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
                        
                        if($companyUserMapper->insert($companyUser)) {
                            $users_created++;
                        }
                        
                    }
                    
                }
                
                $this->logger->info('Se agregaron ' . $users_created . ' usuarios  la empresa ' . $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                return new JsonModel([
                    'success' => true,
                    'data' => [
                        'users_created' => $users_created
                    ]
                ]);
                
                
                
                
            } else {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
                ]);
            }
            
            
            
            
        }
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    
    public function editAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $currentCompany = $currentUserPlugin->getCompany();
        
        $request = $this->getRequest();
        $uuid = $this->params()->fromRoute('id');
        
        
        if(!$uuid) {
            $data = [
                'success'   => false,
                'data'   => 'ERROR_INVALID_PARAMETER'
            ];
            
            return new JsonModel($data);
        }
        
        $userMapper = UserMapper::getInstance($this->adapter);
        $user = $userMapper->fetchOneByUuid($uuid);
        if(!$user) {
            $data = [
                'success'   => false,
                'data'   => 'ERROR_COMPANY_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
        if(!$companyUser) {
            return new JsonModel([
                'success'   => false,
                'data'   => 'ERROR_COMPANY_USER_NOT_FOUND'
            ]);
   
        }
        
        if($companyUser->status != CompanyUser::STATUS_ACCEPTED && $companyUser->status != CompanyUser::STATUS_ADMIN_WILL_ADD) {
            return new JsonModel([
                'success'   => false,
                'data'   => 'ERROR_COMPANY_USER_IS_NOT_ACTIVE'
            ]);
        }
        
        
        
        
        if($request->isPost()) {
            
            $companyRoleMapper = CompanyRoleMapper::getInstance($this->adapter);
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
            $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
            
            $backend = filter_var( $this->params()->fromPost('backend'), FILTER_SANITIZE_STRING );
            $companyUser->backend = $backend == CompanyUser::BACKEND_YES ? CompanyUser::BACKEND_YES : CompanyUser::BACKEND_NO; 
            $companyUserMapper->update($companyUser);
            
            
            $roleMapper = RoleMapper::getInstance($this->adapter);
            $roles = $roleMapper->fetchAll();
            
            
            foreach($roles as $role)
            {
                $companyRole = $companyRoleMapper->fetchOneByCompanyIdAndRoleId($currentCompany->id, $role->id);
                if(!$companyRole) {
                    $companyUserRoleMapper->deleteByCompanyIdAndRoleId($currentCompany->id, $role->id); 
                    continue;
                } 
                
                $checked     = filter_var( $this->params()->fromPost('checked' . $role->id), FILTER_SANITIZE_NUMBER_INT);
                
                if($checked) {
                    
                    $companyUserRole = $companyUserRoleMapper->fetchOneByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $role->id);
                    if(!$companyUserRole) {
                        
                        $companyUserRole = new CompanyUserRole(); 
                        $companyUserRole->company_id = $currentCompany->id;
                        $companyUserRole->role_id = $role->id;
                        $companyUserRole->user_id = $user->id;
                        
                        $companyUserRoleMapper->insert($companyUserRole);
                        
                    }
                    
                    
                    
                    
                } else {
      
                    $companyUserRoleMapper->deleteByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $role->id);
                } 
            }
            
            $this->logger->info('Se actualizo los roles del usuario : ' . $user->email . ' en la empresa ' . $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
            
            return new JsonModel([
                'success' => true,
                'data' => 'LABEL_RECORD_UPDATED'
            ]);
            
            
        } else if ($request->isGet()) {
            $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
            
            $roleMapper = RoleMapper::getInstance($this->adapter);
            $records = $roleMapper->fetchAll();
            

             
            $companyRoleMapper = CompanyRoleMapper::getInstance($this->adapter);
            $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
            
            $roles = [];
            foreach($records as $record)
            {
                if($record->creator == Role::CREATOR_YES) {
                    continue;
                }
                
                if($record->service_id) {
                    $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($currentCompany->id, $record->service_id);
                    if(!$companyService || $companyService->status == CompanyService::INACTIVE) {
                        continue;
                    }
                    
                }
                
               
                
                $companyRole = $companyRoleMapper->fetchOneByCompanyIdAndRoleId($currentCompany->id, $record->id);
                if(!$companyRole) {
                    continue;
                }
                
                $companyUserRole  = $companyUserRoleMapper->fetchOneByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $record->id);
                
                
                $roles[ $record->id ] = [
                    'id' => $record->id,
                    'name' => $record->name,
                    'fixed' => $record->creator == Role::CREATOR_YES ? true : false,
                    'checked' => $companyUserRole ? true : false,
                ];
                
                
            }
            

            
            $data = [
                'success' => true,
                'data' => [
                   'backend' => $companyUser->backend == CompanyUser::BACKEND_YES ? 1 : 0,
                   'roles' => $roles,
                ] ,
            ];
            
            
            
            return new JsonModel($data);
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }
    
    
}