Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 1 | Rev 16768 | 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\CompanyMicrolearningTopicMapper;
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleMapper;
use LeadersLinked\Form\PushMicrolearningNotificationForm;
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleUserMapper;
use LeadersLinked\Mapper\UserMapper;

use LeadersLinked\Model\User;

use LeadersLinked\Mapper\CompanyMicrolearningUserLogMapper;
use LeadersLinked\Mapper\CompanyMicrolearningSlideMapper;
use LeadersLinked\Form\ExtendUserMicrolearningForm;
use LeadersLinked\Form\ChangePasswordForm;
use LeadersLinked\Mapper\CompanyMicrolearningUserProgressMapper;
use LeadersLinked\Model\CompanyMicrolearningExtendUser;
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserMapper;

use LeadersLinked\Mapper\CompanyMicrolearningExtendUserCompanyMapper;
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserFunctionMapper;
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserGroupMapper;
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserInstitutionMapper;
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserProgramMapper;
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserPartnerMapper;
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserSectorMapper;
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserStudentTypeMapper;
use LeadersLinked\Mapper\CompanyUserMapper;
use LeadersLinked\Mapper\UserPasswordMapper;


class MicrolearningStudentsController 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) {
               
                $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);
                $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';
                }
                
                //$companyMicrolearningCapsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
                $companyMicrolearningCapsulUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
                $companyMicrolearningUserProgressMapper = CompanyMicrolearningUserProgressMapper::getInstance($this->adapter);
                
                $userMapper = UserMapper::getInstance($this->adapter);
                $paginator = $userMapper->fetchAllDataTableStudensByCompanyId($currentCompany->id, $search, $page, $records_x_page, $order_field, $order_direction);
                
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'microlearning/students/edit');
                $allowTimeline = $acl->isAllowed($currentUser->usertype_id, 'microlearning/students/timeline');
                $allowUnblock = $acl->isAllowed($currentUser->usertype_id, 'microlearning/students/unblock');
                $allowChangePassword = $acl->isAllowed($currentUser->usertype_id, 'microlearning/students/change-password');
                
                
                
                $items = [ ];
                $records = $paginator->getCurrentItems();
                
  

                foreach($records as $record)
                {

                    
                    $userCapsules = $companyMicrolearningCapsulUserMapper->fetchAllActiveByUserId($record['id']);

                    $total_asigned = count($userCapsules);
                    $total_without_starting = 0; 
                    $total_started = 0; 
                    $total_completed = 0;
                    
                    foreach($userCapsules as $userCapsule)
                    {
                        $userProgress = $companyMicrolearningUserProgressMapper->fetchOneByUseridAndCapsuleId($userCapsule->user_id, $userCapsule->capsule_id);
                        if($userProgress) {
                            
                            if($userProgress->completed) {
                                $total_completed++;
                            }  else {
                                $total_started++;
                            } 
                            
                        } else {
                            $total_without_starting++;
                        }
                    
                    }
                    
                    
                    $actions = [];
                    if($allowEdit) {
                        $actions['link_edit'] = $this->url()->fromRoute('microlearning/students/edit', ['id' => $record['uuid'] ]  );
                    } 
                    if($allowTimeline) {
                        $actions['link_timeline'] = $this->url()->fromRoute('microlearning/students/timeline', ['id' => $record['uuid'] ]  );
                    } 
                    
                    $totalOtherCompanies = $companyUserMapper->fetchCountOtherCompaniesByCompanyIdAndUserId($currentCompany->id, $record['id']);
                    if(!$totalOtherCompanies) {
                        
                        $actions['link_change_password'] = $allowChangePassword ? $this->url()->fromRoute('microlearning/students/change-password', ['id' => $record['uuid'] ]) : '';
                        if($record['blocked'] == User::BLOCKED_YES ) {
                            $actions['link_unblock'] = $allowUnblock ? $this->url()->fromRoute('microlearning/students/unblock', ['id' => $record['uuid'] ]) : '';
                        }
                    }
                    
                    $details = [
                        'total_asigned' => $total_asigned,
                        'total_without_starting' => $total_without_starting,
                        'total_started' => $total_started,
                        'total_completed' => $total_completed,
                    ]; 


                    $item = [
                        'uuid' => $record['uuid'],
                        'first_name' => $record['first_name'],
                        'last_name' => $record['last_name'],
                        'email' => $record['email'],
                        'details' => $details,
                        'actions' => $actions
                    ];
                    
                    
                    array_push($items, $item);
                    
                    
                }
                
                $data['items'] = $items;
                $data['total'] = $paginator->getTotalItemCount();
                
                
                return new JsonModel([
                    'success' => true,
                    'data' => $data
                ]);
            } else {
                $formPushNotification = new PushMicrolearningNotificationForm($this->adapter, $currentCompany->id);
                
                $formExtendUser = new ExtendUserMicrolearningForm($this->adapter, $currentCompany->id);
                $formChangePassword = new ChangePasswordForm();
                
                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/microlearning-students/index.phtml');
                $viewModel->setVariables([
                    'formPushNotification' => $formPushNotification,
                    'formExtendUser' => $formExtendUser,
                    'formChangePassword' => $formChangePassword,
                ]);
                
                return $viewModel ;
            }
            
        } else {
            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();
        $user_uuid  = $this->params()->fromRoute('id');

        
        $userMapper = UserMapper::getInstance($this->adapter);
        $user = $userMapper->fetchOneByUuid($user_uuid);
        
        if(!$user) {
            return new JsonModel([
                'success'   => false,
                'data'   => 'ERROR_USER_NOT_FOUND'
            ]);
        }
        
        $companyMicrolearningCapsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
        $total = $companyMicrolearningCapsuleUserMapper->fetchCountByCompanyIdAndUserId($currentCompany->id, $user->id);
        
        if(!$total) {
            return new JsonModel([
                'success'   => false,
                'data'   => 'ERROR_UNAUTHORIZED'
            ]);
        } 
        
        
        if($request->isGet()) {
            

            $data = [
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'email' => $user->email,
                'company_id' => '',
                'function_id' => '',
                'group_id' => '',
                'institution_id' => '',
                'partner_id' => '',
                'program_id' => '',
                'sector_id' => '',
                'student_type_id' => '',
                
            ];
            
            $companyMicrolearningExtendUserMapper = CompanyMicrolearningExtendUserMapper::getInstance($this->adapter);
            $companyMicrolearningExtendUser = $companyMicrolearningExtendUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
           
            if($companyMicrolearningExtendUser) {
                if($companyMicrolearningExtendUser->extend_company_id) {
                    $companyMicrolearningExtendUserCompanyMapper = CompanyMicrolearningExtendUserCompanyMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserCompany = $companyMicrolearningExtendUserCompanyMapper->fetchOne($companyMicrolearningExtendUser->extend_company_id);
                    if($companyMicrolearningExtendUserCompany) {
                        $data['company_id'] = $companyMicrolearningExtendUserCompany->uuid;
                    }
                }
                
            }
            
            if($companyMicrolearningExtendUser) {
                if($companyMicrolearningExtendUser->extend_function_id) {
                    $companyMicrolearningExtendUserFunctionMapper = CompanyMicrolearningExtendUserFunctionMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserFunction = $companyMicrolearningExtendUserFunctionMapper->fetchOne($companyMicrolearningExtendUser->extend_function_id);
                    if($companyMicrolearningExtendUserFunction) {
                        $data['function_id'] = $companyMicrolearningExtendUserFunction->uuid;
                    }
                }
            }
            
            if($companyMicrolearningExtendUser) {
                if($companyMicrolearningExtendUser->extend_group_id) {
                    $companyMicrolearningExtendUserGroupMapper = CompanyMicrolearningExtendUserGroupMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserGroup = $companyMicrolearningExtendUserGroupMapper->fetchOne($companyMicrolearningExtendUser->extend_group_id);
                    if($companyMicrolearningExtendUserGroup) {
                        $data['group_id'] = $companyMicrolearningExtendUserGroup->uuid;
                    }
                }
            }
            
            if($companyMicrolearningExtendUser) {
                if($companyMicrolearningExtendUser->extend_institution_id) {
                    $companyMicrolearningExtendUserInstitutionMapper = CompanyMicrolearningExtendUserInstitutionMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserInstitution = $companyMicrolearningExtendUserInstitutionMapper->fetchOne($companyMicrolearningExtendUser->extend_institution_id);
                    if($companyMicrolearningExtendUserInstitution) {
                        $data['institution_id'] = $companyMicrolearningExtendUserInstitution->uuid;
                    }
                }
            }
            
            if($companyMicrolearningExtendUser) {
                if($companyMicrolearningExtendUser->extend_partner_id) {
                    $companyMicrolearningExtendUserPartnerMapper = CompanyMicrolearningExtendUserPartnerMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserPartner = $companyMicrolearningExtendUserPartnerMapper->fetchOne($companyMicrolearningExtendUser->extend_partner_id);
                    if($companyMicrolearningExtendUserPartner) {
                        $data['partner_id'] = $companyMicrolearningExtendUserPartner->uuid;
                    }
                }
            }
            
            if($companyMicrolearningExtendUser) {
                if($companyMicrolearningExtendUser->extend_program_id) {
                    $companyMicrolearningExtendUserProgramMapper = CompanyMicrolearningExtendUserProgramMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserProgram = $companyMicrolearningExtendUserProgramMapper->fetchOne($companyMicrolearningExtendUser->extend_program_id);
                    if($companyMicrolearningExtendUserProgram) {
                        $data['program_id'] = $companyMicrolearningExtendUserProgram->uuid;
                    }
                }
            }
            
            if($companyMicrolearningExtendUser) {
                if($companyMicrolearningExtendUser->extend_sector_id) {
                    $companyMicrolearningExtendUserSectorMapper = CompanyMicrolearningExtendUserSectorMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserSector = $companyMicrolearningExtendUserSectorMapper->fetchOne($companyMicrolearningExtendUser->extend_sector_id);
                    if($companyMicrolearningExtendUserSector) {
                        $data['sector_id'] = $companyMicrolearningExtendUserSector->uuid;
                    }
                }
            }
            
            if($companyMicrolearningExtendUser) {
                if($companyMicrolearningExtendUser->extend_student_type_id) {
                    $companyMicrolearningExtendUserStudentTypeMapper = CompanyMicrolearningExtendUserStudentTypeMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserStudentType = $companyMicrolearningExtendUserStudentTypeMapper->fetchOne($companyMicrolearningExtendUser->extend_student_type_id);
                    if($companyMicrolearningExtendUserStudentType) {
                        $data['student_type_id'] = $companyMicrolearningExtendUserStudentType->uuid;
                    }
                }
            }
            
            
            return new JsonModel([
                'success'   => true,
                'data'   => $data,
            ]);
            
        }
        
        
        if($request->isPost()) {
            $form = new  ExtendUserMicrolearningForm($this->adapter, $currentCompany->id);
            $dataPost = $request->getPost()->toArray();
            
            $form->setData($dataPost);
            
            if($form->isValid()) {
                $dataPost = (array) $form->getData();
                
                $companyMicrolearningExtendUserMapper = CompanyMicrolearningExtendUserMapper::getInstance($this->adapter);
                $companyMicrolearningExtendUser = $companyMicrolearningExtendUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
                if(!$companyMicrolearningExtendUser) {
                    $companyMicrolearningExtendUser = new CompanyMicrolearningExtendUser();
                    $companyMicrolearningExtendUser->company_id = $currentCompany->id; 
                    $companyMicrolearningExtendUser->user_id = $user->id;
                } 
                
                
                $extend_company_uuid        = filter_var( $this->params()->fromPost('company_id'), FILTER_SANITIZE_STRING);
                $extend_function_uuid       = filter_var( $this->params()->fromPost('function_id'), FILTER_SANITIZE_STRING);
                $extend_group_uuid          = filter_var( $this->params()->fromPost('group_id'), FILTER_SANITIZE_STRING);
                $extend_institution_uuid    = filter_var( $this->params()->fromPost('institution_id'), FILTER_SANITIZE_STRING);
                $extend_program_uuid        = filter_var( $this->params()->fromPost('program_id'), FILTER_SANITIZE_STRING);
                $extend_partner_uuid        = filter_var( $this->params()->fromPost('partner_id'), FILTER_SANITIZE_STRING);
                $extend_sector_uuid         = filter_var( $this->params()->fromPost('sector_id'), FILTER_SANITIZE_STRING);
                $extend_student_type_uuid   = filter_var( $this->params()->fromPost('student_type_id'), FILTER_SANITIZE_STRING);
                
            
                if($extend_company_uuid) {
                    $companyMicrolearningExtendUserCompanyMapper = CompanyMicrolearningExtendUserCompanyMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserCompany = $companyMicrolearningExtendUserCompanyMapper->fetchOneByUuid($extend_company_uuid);
                    if($companyMicrolearningExtendUserCompany && $companyMicrolearningExtendUserCompany->company_id = $currentCompany->id) {
                        $companyMicrolearningExtendUser->extend_company_id = $companyMicrolearningExtendUserCompany->id;
                    } else {
                        $companyMicrolearningExtendUser->extend_company_id = null;
                    } 
                    
                } else {
                    $companyMicrolearningExtendUser->extend_company_id = null;
                } 
                
                
                if($extend_function_uuid) {
                    $companyMicrolearningExtendUserFunctionMapper = CompanyMicrolearningExtendUserFunctionMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserFunction = $companyMicrolearningExtendUserFunctionMapper->fetchOneByUuid($extend_function_uuid);
                    if($companyMicrolearningExtendUserFunction && $companyMicrolearningExtendUserFunction->company_id = $currentCompany->id) {
                        $companyMicrolearningExtendUser->extend_function_id = $companyMicrolearningExtendUserFunction->id;
                    } else {
                        $companyMicrolearningExtendUser->extend_function_id = null;
                    }
                    
                } else {
                    $companyMicrolearningExtendUser->extend_function_id = null;
                } 
                
                if($extend_group_uuid) {
                    $companyMicrolearningExtendUserGroupMapper = CompanyMicrolearningExtendUserGroupMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserGroup = $companyMicrolearningExtendUserGroupMapper->fetchOneByUuid($extend_group_uuid);
                    if($companyMicrolearningExtendUserGroup && $companyMicrolearningExtendUserGroup->company_id = $currentCompany->id) {
                        $companyMicrolearningExtendUser->extend_group_id = $companyMicrolearningExtendUserGroup->id;
                    } else {
                        $companyMicrolearningExtendUser->extend_group_id = null;
                    }
                    
                } else {
                    $companyMicrolearningExtendUser->extend_group_id = null;
                } 
                
                if($extend_institution_uuid) {
                    $companyMicrolearningExtendUserInstitutionMapper = CompanyMicrolearningExtendUserInstitutionMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserInstitution = $companyMicrolearningExtendUserInstitutionMapper->fetchOneByUuid($extend_institution_uuid);
                    if($companyMicrolearningExtendUserInstitution && $companyMicrolearningExtendUserInstitution->company_id = $currentCompany->id) {
                        $companyMicrolearningExtendUser->extend_institution_id = $companyMicrolearningExtendUserInstitution->id;
                    } else {
                        $companyMicrolearningExtendUser->extend_institution_id = null;
                    }
                    
                } else {
                    $companyMicrolearningExtendUser->extend_institution_id = null;
                } 
                
                if($extend_program_uuid) {
                    $companyMicrolearningExtendUserProgramMapper = CompanyMicrolearningExtendUserProgramMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserProgram = $companyMicrolearningExtendUserProgramMapper->fetchOneByUuid($extend_program_uuid);
                    if($companyMicrolearningExtendUserProgram && $companyMicrolearningExtendUserProgram->company_id = $currentCompany->id) {
                        $companyMicrolearningExtendUser->extend_program_id = $companyMicrolearningExtendUserProgram->id;
                    } else {
                        $companyMicrolearningExtendUser->extend_program_id = null;
                    }
                    
                } else {
                    $companyMicrolearningExtendUser->extend_program_id = null;
                } 
                
                if($extend_partner_uuid) {
                    $companyMicrolearningExtendUserPartnerMapper = CompanyMicrolearningExtendUserPartnerMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserPartner = $companyMicrolearningExtendUserPartnerMapper->fetchOneByUuid($extend_partner_uuid);
                    if($companyMicrolearningExtendUserPartner && $companyMicrolearningExtendUserPartner->company_id = $currentCompany->id) {
                        $companyMicrolearningExtendUser->extend_partner_id = $companyMicrolearningExtendUserPartner->id;
                    } else {
                        $companyMicrolearningExtendUser->extend_partner_id = null;
                    }
                    
                } else {
                    $companyMicrolearningExtendUser->extend_partner_id = null;
                } 
                
                if($extend_sector_uuid) {
                    $companyMicrolearningExtendUserSectorMapper = CompanyMicrolearningExtendUserSectorMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserSector = $companyMicrolearningExtendUserSectorMapper->fetchOneByUuid($extend_sector_uuid);
                    if($companyMicrolearningExtendUserSector && $companyMicrolearningExtendUserSector->company_id = $currentCompany->id) {
                        $companyMicrolearningExtendUser->extend_sector_id = $companyMicrolearningExtendUserSector->id;
                    } else {
                        $companyMicrolearningExtendUser->extend_sector_id = null;
                    }
                    
                } else {
                    $companyMicrolearningExtendUser->extend_sector_id = null;
                } 
                
                if($extend_student_type_uuid) {
                    $companyMicrolearningExtendUserStudentTypeMapper = CompanyMicrolearningExtendUserStudentTypeMapper::getInstance($this->adapter);
                    $companyMicrolearningExtendUserStudentType = $companyMicrolearningExtendUserStudentTypeMapper->fetchOneByUuid($extend_student_type_uuid);
                    if($companyMicrolearningExtendUserStudentType && $companyMicrolearningExtendUserStudentType->company_id = $currentCompany->id) {
                        $companyMicrolearningExtendUser->extend_student_type_id = $companyMicrolearningExtendUserStudentType->id;
                    } else {
                        $companyMicrolearningExtendUser->extend_student_type_id = null;
                    }
                    
                } else {
                    $companyMicrolearningExtendUser->extend_student_type_id = null;
                } 
                
 
                
                if($companyMicrolearningExtendUser->id) {
                    $result = $companyMicrolearningExtendUserMapper->update($companyMicrolearningExtendUser);
                    if($result) {
                        $this->logger->info('Se actualizo la información extendida de micro aprendizaje  del usuario ' . $user->email, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                        
                        $data = [
                            'success'   => true,
                            'data'   => 'LABEL_RECORD_ADDED'
                        ];
                    } else {
                        $data = [
                            'success'   => false,
                            'data'      => $companyMicrolearningExtendUserMapper->getError()
                        ];
                        
                    }
                } else {
                    $result = $companyMicrolearningExtendUserMapper->insert($companyMicrolearningExtendUser);
                    if($result) {
                        $this->logger->info('Se agrego la información extendida de micro aprendizaje  del usuario ' . $user->email, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                        
                        $data = [
                            'success'   => true,
                            'data'   => 'LABEL_RECORD_ADDED'
                        ];
                    } else {
                        $data = [
                            'success'   => false,
                            'data'      => $companyMicrolearningExtendUserMapper->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([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function timelineAction()
    {
        
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser    = $currentUserPlugin->getUser();
        $currentCompany = $currentUserPlugin->getCompany();
        
        $request    = $this->getRequest();
        $user_uuid  = $this->params()->fromRoute('id');
        
        
        $userMapper = UserMapper::getInstance($this->adapter);
        $user = $userMapper->fetchOneByUuid($user_uuid);
        
        if(!$user) {
            return new JsonModel([
                'success'   => false,
                'data'   => 'ERROR_USER_NOT_FOUND'
            ]);
        }
        
        if($request->isGet()) {
            $page = intval(filter_var($this->params()->fromQuery('page'), FILTER_SANITIZE_NUMBER_INT) , 10);
            if(!$page) {
                $page = 1;
            } 
            $records_x_page = 10;
            
            $companyMicrolearningTopicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
            $companyMicrolearningCapsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
            $companyMicrolearningSlideMapper = CompanyMicrolearningSlideMapper::getInstance($this->adapter);
            
            $topics = [];
            $capsules = []; 
            $slides = [] ; 
            
            
            $companyMicrolearningUserLogMapper = CompanyMicrolearningUserLogMapper::getInstance($this->adapter); 
        
            $paginator = $companyMicrolearningUserLogMapper->getAllMessagesPaginatorByUserIdAndCompanyId($user->id, $currentCompany->id, $page, $records_x_page); 
            
            $items = [] ; 
            foreach($paginator->getCurrentItems() as $record)
            {
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on); 
                
                $item = [
                    'activity' => $record->activity,
                    'added_on' => $dt->format('d/m/Y h:i a')
                ]; 
                
                if($record->topic_id) {
                    
                    if(isset($topics[$record->topic_id])) {
                        $topic = $topics[ $record->topic_id ]; 
                    }  else {
                        $topic = $companyMicrolearningTopicMapper->fetchOne( $record->topic_id ); 
                    } 
                    
                    if($topic) {
                        $item['topic'] = $topic->name;
                    } 
                    
                    if(isset($capsules[$record->capsule_id])) {
                        $capsule = $capsules[ $record->capsule_id ];
                    }  else {
                        $capsule = $companyMicrolearningCapsuleMapper->fetchOne( $record->capsule_id );
                    }
                    
                    if($capsule) {
                        $item['capsule'] = $capsule->name;
                    } 
                    
                    if(isset($slides[$record->slide_id])) {
                        $slide = $slides[ $record->slide_id ];
                    }  else {
                        $slide = $companyMicrolearningSlideMapper->fetchOne( $record->slide_id );
                    }
                    
                    if($slide) {
                        $item['slide'] = $slide->name;
                    } 
                } 
                
                
                array_push($items, $item); 
            }
            
            $response = [
                'success' => true,
                'data' => [
                    'total' => [
                        'count' => $paginator->getTotalItemCount(),
                        'pages' => $paginator->getPages()->pageCount,
                    ],
                    'current' => [
                        'items'    => $items,
                        'page'     => $paginator->getCurrentPageNumber(),
                        'count'    => $paginator->getCurrentItemCount(),
                    ]
                ]
            ];
            
            return new JsonModel($response);
        
        }
        
        

        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    
    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 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'
        ]);
    }
    
   
    
}