Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17179 | 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\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\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\User\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;
use LeadersLinked\Mapper\NetworkMapper;
use LeadersLinked\Model\Network;
use LeadersLinked\Mapper\CompanyMapper;
use LeadersLinked\Mapper\ConnectionMapper;
use LeadersLinked\Model\Connection;
use LeadersLinked\Mapper\CompanyFollowerMapper;
use LeadersLinked\Model\CompanyFollower;
use LeadersLinked\Mapper\CountryMapper;
use LeadersLinked\Mapper\LocationMapper;
use LeadersLinked\Model\Location;
use LeadersLinked\Form\User\ChangeTypeForm;
use LeadersLinked\Form\User\ChangePasswordForm;
use LeadersLinked\Form\User\NetworkDataForm;
use LeadersLinked\Cache\CacheInterface;
use LeadersLinked\Cache\CacheImpl;

class UserController extends AbstractActionController
{
    /**
     *
     * @var \Laminas\Db\Adapter\AdapterInterface
     */
    private $adapter;

    /**
     *
     * @var \LeadersLinked\Cache\CacheInterface
     */
    private $cache;


    /**
     *
     * @var \Laminas\Log\LoggerInterface
     */
    private $logger;

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


    /**
     *
     * @var \Laminas\Mvc\I18n\Translator
     */
    private $translator;


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

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

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


        $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) { {
                $network_id = $this->params()->fromQuery('network_id');
                if ($currentUser->is_super_user == User::IS_SUPER_USER_YES) {

                    $networkMapper = NetworkMapper::getInstance($this->adapter);
                    $network = $networkMapper->fetchOneByUuid($network_id);
                    if (!$network) {
                        $network = $currentNetwork;
                    }
                } else {
                    $network = $currentNetwork;
                }



                $search = $this->params()->fromQuery('search', []);
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);

                //$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(Functions::sanitizeFilterString($order[0]['dir']));

                $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 = Functions::sanitizeFilterString($this->params()->fromQuery('status'));
                    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, $search, $status,   $page, $records_x_page, $order_field, $order_direction);

                    $items = [];
                    $records = $paginator->getCurrentItems();

                    foreach ($records as $record) {

                        $actions = [];
                        $actions['link_profile'] = 'https://' . $network->main_hostname . '/profile/view/' . $record['uuid'];




                        $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');
                    $allowChangeType   = $acl->isAllowed($currentUser->usertype_id, 'users/change-type') ? 1 : 0;



                    $userMapper = UserMapper::getInstance($this->adapter);
                    $paginator = $userMapper->fetchAllDataTableByNetworkId($network->id, $search, $page, $records_x_page, $order_field, $order_direction);

                    $items = [];
                    $records = $paginator->getCurrentItems();

                    foreach ($records as $record) {
                        $actions = [];

                        if ($currentNetwork->id == $record->network_id) {

                            $actions['link_profile'] = 'https://' . $network->main_hostname . '/profile/view/' . $record->uuid;
                        } else {
                            $actions['link_profile'] = '';
                        }

                        $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';
                        }

                        if ($record->usertype_id == UserType::ADMIN) {
                            $details['user_type'] = 'LABEL_ADMINISTRATOR';
                        } else   if ($record->usertype_id == UserType::USER) {
                            $details['user_type'] = 'LABEL_USER';
                        }

                        $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]) : '';
                        $actions['link_change_type'] =  $record->is_super_user == User::IS_SUPER_USER_NO && $allowChangeType ? $this->url()->fromRoute('users/change-type', ['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();


            $networks = [];
            $networkMapper = NetworkMapper::getInstance($this->adapter);

            if ($currentUser->is_super_user == User::IS_SUPER_USER_YES) {
                $records = $networkMapper->fetchAll();
                foreach ($records as $record) {
                    $networks[$record->uuid] = $record->name;
                }
            } else {
                $networks[$currentNetwork->uuid] = $currentNetwork->name;
            }


            $formFilter = new NetworkDataForm($networks);
            $formUploadUsers = new UserUploadForm();
            $formChangePassword = new ChangePasswordForm();
            $formChangeType = new ChangeTypeForm();

            $company = $currentUserPlugin->getCompany();
            if ($company) {
                $viewModel->setTemplate('leaders-linked/users/company.phtml');
            } else {
                $viewModel->setTemplate('leaders-linked/users/index.phtml');
            }
            $viewModel->setVariables([
                'formUploadUsers' => $formUploadUsers,
                'formChangePassword' => $formChangePassword,
                'formChangeType' => $formChangeType,
                'formFilter' => $formFilter
            ]);
            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 = Functions::sanitizeFilterString($this->params()->fromQuery('search'));
            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'
                ]);
            }
            $networkMapper = NetworkMapper::getInstance($this->adapter);
            $network = $networkMapper->fetchOne($currentUser->network_id);


            if ($companyUser) {


                if ($network->default == Network::DEFAULT_YES) {
                    $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
                } else {
                    $companyUser->status = CompanyUser::STATUS_ACCEPTED;
                }
                $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;

                if ($network->default == Network::DEFAULT_YES) {
                    $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
                } else {
                    $companyUser->status = CompanyUser::STATUS_ACCEPTED;
                }


                $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->fetchOneByCodeAndNetworkId(EmailTemplate::CODE_RECEIVE_INVITATION_COMPANY, $currentUser->network_id);

                    if ($emailTemplate) {
                        $company_profile_url = 'https://' . $network->main_hostname . '/company/view/' . $currentCompany->uuid;


                        $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()]);

                if ($network->default == Network::DEFAULT_YES) {
                    return new JsonModel([
                        'success'   => true,
                        'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_CREATED',
                    ]);
                } else {
                    return new JsonModel([
                        'success'   => true,
                        'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_INVITED_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();

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

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

        $request    = $this->getRequest();

        if ($request->isPost()) {

            $step = Functions::sanitizeFilterString($this->params()->fromPost('step'));
            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


                        $first_name = Functions::sanitizeFilterString($record['A']);
                        $last_name = Functions::sanitizeFilterString($record['B']);
                        $email = trim(filter_var($record['C'], FILTER_SANITIZE_EMAIL));

                        $password = Functions::sanitizeFilterString($record['D']);
                        $isAdult = strtolower(Functions::sanitizeFilterString($record['E']));
                        $country = strtolower(Functions::sanitizeFilterString($record['F']));


                        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,
                                'is_adult' => $isAdult,
                                'country' => $country,

                            ]);
                        }
                    }

                    $key = md5($currentUser->id . '-' . microtime(true));
                    $this->cache->setItem($key, serialize($users));

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

                    @unlink($final_filename);
                } 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 = Functions::sanitizeFilterString($this->params()->fromPost('key'));
                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'
                    ]);
                }

                $locationMapper = LocationMapper::getInstance($this->adapter);
                $countryMapper = CountryMapper::getInstance($this->adapter);


                $networkMapper = NetworkMapper::getInstance($this->adapter);
                $networkDefault = $networkMapper->fetchOneByDefault();

                $userMapper = UserMapper::getInstance($this->adapter);
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);


                $user_ids_in_default_network = [];


                $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->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
                    if (!$user) {
                        $password_hash = password_hash($password, PASSWORD_DEFAULT);

                        $user = new User();
                        $user->network_id = $currentNetwork->id;
                        $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;
                        $user->is_adult = $record['is_adult'] == 'y' ? User::IS_ADULT_YES : User::IS_ADULT_NO;

                        $result = $userMapper->insert($user);
                        if ($result) {
                            $users_created++;

                            $country_code = trim($record['country']);

                            if ($country_code) {
                                $country = $countryMapper->fetchOneByCodeOrCountry($record['country']);
                                if ($country) {

                                    $location = new Location();
                                    $location->formatted_address = $country->country;
                                    $location->country = $country->country;
                                    if ($locationMapper->insert($location)) {

                                        $user->location_id = $location->id;
                                        $userMapper->updateLocation($user);
                                    }
                                }
                            } else {
                                $country_code = '';
                            }

                            $userPassword = new UserPassword();
                            $userPassword->user_id = $user->id;
                            $userPassword->password = $password_hash;
                            $userPasswordMapper->insert($userPassword);


                            if ($currentNetwork->default == Network::DEFAULT_YES) {
                                array_push($user_ids_in_default_network, $user->id);
                            } else {



                                if ($user->is_adult == User::IS_ADULT_YES) {

                                    $userInDefaultNetwork = $userMapper->fetchOneByEmailAndNetworkId($user->email, $networkDefault->id);
                                    if ($userInDefaultNetwork) {

                                        array_push($user_ids_in_default_network, $userInDefaultNetwork->id);

                                        if ($userInDefaultNetwork->email_verified == User::EMAIL_VERIFIED_NO || $userInDefaultNetwork->status != User::STATUS_ACTIVE) {
                                            $userInDefaultNetwork->email_verified = User::EMAIL_VERIFIED_YES;
                                            $userInDefaultNetwork->status != User::STATUS_ACTIVE;

                                            if (!$userMapper->update($userInDefaultNetwork)) {
                                                continue;
                                            }
                                        }
                                    } else {
                                        $userInDefaultNetwork = new User();
                                        $userInDefaultNetwork->network_id = $networkDefault->id;
                                        $userInDefaultNetwork->blocked = User::BLOCKED_NO;
                                        $userInDefaultNetwork->email_verified = User::EMAIL_VERIFIED_YES;
                                        $userInDefaultNetwork->email = $email;
                                        $userInDefaultNetwork->first_name = $first_name;
                                        $userInDefaultNetwork->last_name = $last_name;
                                        $userInDefaultNetwork->password = $password_hash;
                                        $userInDefaultNetwork->login_attempt = 0;
                                        $userInDefaultNetwork->usertype_id = UserType::USER;
                                        $userInDefaultNetwork->status = User::STATUS_ACTIVE;
                                        $userInDefaultNetwork->is_adult = User::IS_ADULT_YES;
                                        $result = $userMapper->insert($userInDefaultNetwork);
                                        if ($result) {
                                            array_push($user_ids_in_default_network, $userInDefaultNetwork->id);

                                            if ($country) {

                                                $location = new Location();
                                                $location->formatted_address = $country->country;
                                                $location->country = $country->country;
                                                if ($locationMapper->insert($location)) {

                                                    $userInDefaultNetwork->location_id = $location->id;
                                                    $userMapper->updateLocation($userInDefaultNetwork);
                                                }
                                            }


                                            $userPassword = new UserPassword();
                                            $userPassword->user_id = $userInDefaultNetwork->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;
                            }
                        }
                    }

                    array_push($user_ids, $user->id);
                }

                if ($currentCompany) {

                    $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);

                    $company_users_created = 0;

                    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;

                            if ($currentNetwork->default == Network::DEFAULT_YES) {
                                $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
                            } else {
                                $companyUser->status = CompanyUser::STATUS_ACCEPTED;
                            }

                            if ($companyUserMapper->insert($companyUser)) {
                                $company_users_created++;
                            }
                        }
                    }

                    $this->logger->info('Se agregaron ' . $users_created . '  usuarios  la empresa ' . $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                } else {

                    $this->logger->info('Se agregaron ' . $users_created . ' usuarios a la red', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                }

                if ($user_ids_in_default_network) {
                    $companyMapper = CompanyMapper::getInstance($this->adapter);
                    $companyToFollower = $companyMapper->fetchOneDefaultForFollowers();

                    $companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);

                    $userToConnection = $userMapper->fetchOneDefaultForConnection();


                    $connectionMapper = ConnectionMapper::getInstance($this->adapter);

                    foreach ($user_ids_in_default_network as $user_id) {
                        if ($userToConnection) {
                            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user_id, $userToConnection->id);
                            if (!$connection) {
                                $connection = new Connection();
                                $connection->request_from = $user_id;
                                $connection->request_to = $userToConnection->id;
                                $connection->status = Connection::STATUS_ACCEPTED;

                                $connectionMapper->insert($connection);
                            } else {
                                if ($connection->status == Connection::STATUS_SENT) {
                                    $connectionMapper->approve($connection);
                                }
                            }
                        }

                        if ($companyToFollower) {
                            $companyFollower = $companyFollowerMapper->fetchOneByCompanyIdAndUserId($companyToFollower->id, $user_id);
                            if (!$companyFollower) {
                                $companyFollower = new CompanyFollower();
                                $companyFollower->company_id = $companyToFollower->id;
                                $companyFollower->follower_id = $user_id;

                                $companyFollowerMapper->insert($companyFollower);
                            }
                        }
                    }
                }



                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 = Functions::sanitizeFilterString($this->params()->fromPost('backend'));
            $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);
    }


    /**
     * Handles the change of user type.
     *
     * This action supports both GET and POST requests:
     * - GET: Retrieves the current user type for a given user UUID.
     * - POST: Updates the user type based on the provided data.
     *
     * @return JsonModel
     */
    public function changeTypeAction()
    {
        // Retrieve the current user and request objects
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $request = $this->getRequest();

        // Handle GET request to fetch current user type and additional fields
        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'      => [
                        'usertype_id' => $user->usertype_id,
                        'email_verified' => $user->email_verified,
                        'blocked' => $user->blocked,
                        'status' => $user->status,
                    ]
                ]);
            } else {
                return new JsonModel([
                    'success'   => false,
                    'data'      => 'ERROR_USER_NOT_FOUND'
                ]);
            }
        }

        // Handle POST request to update user type and additional fields
        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'
                ]);
            }

            // Validate and process form data
            $dataPost = $request->getPost()->toArray();
            $form = new ChangeTypeForm();
            $form->setData($dataPost);

            if ($form->isValid()) {
                $dataPost = (array) $form->getData();

                // Update the user type and additional fields in the database
                $result = $userMapper->updateUserFieldsAdmin($user, $dataPost['email_verified'], $dataPost['blocked'], $dataPost['status'], $dataPost['usertype_id']);

                if ($result) {
                    $this->logger->info('Cambio del tipo de usuario y otros campos realizado', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                    return new JsonModel([
                        'success'   => true,
                        'data'      => 'LABEL_USER_CHANGE_TYPE_HAS_BEEN_UPDATED'
                    ]);
                } else {
                    $this->logger->err('Cambio del tipo de usuario - error desconocido', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                    return new JsonModel([
                        'success'   => true,
                        'data'      => 'ERROR_THERE_WAS_AN_ERROR'
                    ]);
                }
            } else {
                // Handle form validation errors
                $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 error for unsupported request methods
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
}