Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 15371 | Autoría | 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\QueryMapper;
use LeadersLinked\Mapper\UserMapper;
use Laminas\Hydrator\ArraySerializableHydrator;
use Laminas\Db\ResultSet\HydratingResultSet;
use Laminas\Paginator\Adapter\DbSelect;
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
use Laminas\Paginator\Paginator;
use LeadersLinked\Mapper\CompanyPerformanceEvaluationFormMapper;
use LeadersLinked\Mapper\CompanyUserMapper;
use LeadersLinked\Mapper\JobDescriptionMapper;
use LeadersLinked\Mapper\CompetencyTypeMapper;
use LeadersLinked\Mapper\CompetencyMapper;
use LeadersLinked\Mapper\JobDescriptionCompetencyMapper;
use LeadersLinked\Mapper\JobDescriptionBehaviorCompetencyMapper;
use LeadersLinked\Mapper\BehaviorMapper;
use LeadersLinked\Library\InterviewPDF;
use LeadersLinked\Form\PerformanceEvaluationEvaluationForm;
use LeadersLinked\Form\PerformanceEvaluationEvaluationSelfForm;
use LeadersLinked\Mapper\CompanyPerformanceEvaluationTestMapper;
use LeadersLinked\Mapper\CompanyPerformanceEvaluationTestSelfMapper;
use LeadersLinked\Mapper\CompanyPerformanceEvaluationTestBothMapper;
use LeadersLinked\Mapper\CompanyPerformanceEvaluationTestSupervisorMapper;
use LeadersLinked\Model\Company;
use LeadersLinked\Model\CompanyPerformanceEvaluationTest;
use LeadersLinked\Model\CompanyPerformanceEvaluationTestSelf;
use LeadersLinked\Model\CompanyPerformanceEvaluationTestBoth;
use LeadersLinked\Model\CompanyPerformanceEvaluationTestSupervisor;
use LeadersLinked\Mapper\CompetencyBehaviorMapper;

class PerformanceEvaluationEvaluationController 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();

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

            //$isJson = true;
            if ($isJson) {


                $data = [
                    'items' => [],
                    'total' => 0,
                ];


                $search = $this->params()->fromQuery('search');
                $search = empty($search) ? '' : filter_var($search, FILTER_SANITIZE_STRING);

                $start = intval($this->params()->fromQuery('start', 0), 10);
                $records_x_page = intval($this->params()->fromQuery('length', 10), 10);
                $page =  intval($start / $records_x_page);
                $page++;
                
                $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 = ['max_date'];
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'first_name';

                if (!in_array($order_direction, ['ASC', 'DESC'])) {
                    $order_direction = 'ASC';
                }


                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'performance-evaluation/evaluations/delete');
               
                
                
                $queryMapper = QueryMapper::getInstance($this->adapter);
                $sql = $queryMapper->getSql();
                $select = $sql->select();
                $select->columns(['uuid', 'last_date', 'form_id']);
                $select->from(['tb1' => CompanyPerformanceEvaluationTestMapper::_TABLE]);
                $select->join(['tb2' => CompanyPerformanceEvaluationFormMapper::_TABLE], 'tb1.form_id = tb2.id ', ['form' =>'name']);
                $select->join(['tb3' => UserMapper::_TABLE], 'tb1.supervisor_id = tb3.id ', ['first_name', 'last_name', 'email']);
                $select->where->equalTo('tb1.company_id', $currentCompany->id);
                $select->where->notEqualTo('tb1.status', CompanyPerformanceEvaluationTest::STATUS_DELETED);

                if ($search) {
                    $select->where->nest()
                            ->like('tb1.last_date', '%' . $search . '%')
                            ->like('tb2.name', '%' . $search . '%')
                            ->like('tb3.first_name', '%' . $search . '%')
                            ->or->like('tb3.last_name', '%' . $search . '%')
                            ->or->like('tb3.email', '%' . $search . '%')
                            ->unnest();
                }


                $select->order($order_field . ' ' . $order_direction);

                $hydrator = new ArraySerializableHydrator();
                $resultset = new HydratingResultSet($hydrator);

                $adapter = new DbSelect($select, $sql, $resultset);
                $paginator = new Paginator($adapter);
                $paginator->setItemCountPerPage($records_x_page);
                $paginator->setCurrentPageNumber($page);

                $items = [];
                $records = $paginator->getCurrentItems();
                $testSelfMapper = CompanyPerformanceEvaluationTestSelfMapper::getInstance($this->adapter);
                $testBothMapper = CompanyPerformanceEvaluationTestBothMapper::getInstance($this->adapter);
                $testSupervisorMapper = CompanyPerformanceEvaluationTestSupervisorMapper::getInstance($this->adapter);
                foreach ($records as $record) 
                {
                    $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
                    $test =  $testMapper->fetchOneByUuid($record['uuid']);
                   
                    $dt = \DateTime::createFromFormat('Y-m-d', $record['last_date']);
                    $last_date = $dt->format('d/m/Y');

                    $testSelf = $testSelfMapper->fetchOneByTestId($test->id);
                    $testBoth = $testBothMapper->fetchOneByTestId($test->id);
                    $testSupervisor = $testSupervisorMapper->fetchOneByTestId($test->id);
                    $link_delete = $this->url()->fromRoute('performance-evaluation/evaluations/delete', ['id' => $record['uuid'] ]);
                  
                    $item = [
                        'last_date' => $last_date,
                        'form' => $record['form'],
                        'first_name' => $test->first_name,
                        'last_name' => $test->last_name,
                        'supervisor' => trim(trim($record['first_name']) . ' ' . trim($record['last_name'])) . ' (' . trim($record['email']) . ')',
                        'actions' => [
                            'link_delete' => $allowDelete ? $link_delete : '',
                        ]
                    ];
                    if($testSelf) {
                        $item['actions']['link_report_self'] = $this->url()->fromRoute('performance-evaluation/evaluations/report-self', ['id' => $record['uuid'] ]);
                    } else{
                        $item['actions']['link_self'] = $this->url()->fromRoute('performance-evaluation/evaluations/self', ['id' => $record['uuid'] ]);
                    }
                    if($testBoth) {
                        $item['actions']['link_report_both'] = $this->url()->fromRoute('performance-evaluation/evaluations/report-both', ['id' => $record['uuid'] ]);
                    } else{
                        $item['actions']['link_both'] = $this->url()->fromRoute('performance-evaluation/evaluations/both', ['id' => $record['uuid'] ]);
                    }
                    if($testSupervisor) {
                        $item['actions']['link_report_superviser'] = $this->url()->fromRoute('performance-evaluation/evaluations/report-superviser', ['id' => $record['uuid'] ]);
                    } else{
                        $item['actions']['link_superviser'] = $this->url()->fromRoute('performance-evaluation/evaluations/superviser', ['id' => $record['uuid'] ]);
                    }

                    array_push($items, $item);
                }

                $data['items'] = $items;
                $data['total'] = $paginator->getTotalItemCount();


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


                $form = new PerformanceEvaluationEvaluationForm($this->adapter, $currentCompany->id);
                $formSelf = new PerformanceEvaluationEvaluationSelfForm($this->adapter, $currentCompany->id);


                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/performance-evaluation-evaluations/index.phtml');
                $viewModel->setVariables([
                    'form' => $form,
                    'formSelf' => $formSelf,
                ]);

                return $viewModel;
            }
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
            
        }
        } catch (\Throwable $e) {
            $e->getMessage();
            return new JsonModel([
                'success' => false,
                'data' => $e
            ]);
        }
    }


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

        $email = $request->getQuery('email');

        if(!$email){
            $data = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($data);
        }

        $userMapper = UserMapper::getInstance($this->adapter);
        $user = $userMapper->fetchOneByEmail($email);

        if (!$user) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_USER_NOT_FOUND',
            ]);   
        } else if($request->isGet()){
            $data = [
                'success' => true,
                'data' => [
                    'user_id' => $user->id,
                    'first_name' => $user->first_name,
                    'last_name' => $user->last_name,
                   
                ]
            ];
            return new JsonModel($data);
           
        }else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }
    }

    public function addAction() {
        $request = $this->getRequest();

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

        $request = $this->getRequest();
        

        if ($request->isPost()) {
            $dataPost = $request->getPost()->toArray();
            $form = new  PerformanceEvaluationEvaluationForm($this->adapter, $currentCompany->id);
            $actual_date = time();
            $actual_dt = date('Y-m-d', $actual_date);
            $last_dt = strtotime($dataPost['last_date']);
                // return new JsonModel([
                //     'success' => false,
                //     'data' => $last_dt
                // ]);
                if($actual_dt > $last_dt){
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_UNAUTHORIZED'
                    ]);   
                }
            
            $form->setData($dataPost);

            if($form->isValid()) {
                $dataPost = (array) $form->getData();
                
                $form_id = $dataPost['form_id'];
                $supervisor_id = $dataPost['supervisor_id'];
                $first_name= $dataPost['first_name'];
                $last_name= $dataPost['last_name'];
                $email= $dataPost['email'];
                $user_id= $dataPost['user_id'];
                $dt = $dataPost['last_date'];
                
                $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
                $form = $formMapper->fetchOneByUuid($form_id);
                if (!$form) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_FORM_NOT_FOUND'
                    ]);
                }
                
                if ($form->company_id != $currentCompany->id) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_UNAUTHORIZED'
                    ]);
                }
                
                
                $userMapper = UserMapper::getInstance($this->adapter);
                $supervisor = $userMapper->fetchOneByUuid($supervisor_id);
                
                if (!$supervisor) {
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_USER_NOT_FOUND'
                    ]);
                }
                
                
                
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
                $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($form->company_id, $supervisor->id);
                if (!$companyUser) {
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_UNAUTHORIZED'
                    ]);
                }
                
                
                $test = new CompanyPerformanceEvaluationTest();
                $test->company_id = $form->company_id;
                $test->form_id = $form->id;
                $test->supervisor_id = $supervisor->id;
                $test->last_date = $dt;
                $test->first_name = $first_name;
                $test->last_name = $last_name;
                $test->email = $email;
                //$tst->user_id = $user_id;

                
                $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
                $result = $testMapper->insert($test);
                
                if($result) {
                    $this->logger->info('Se agrego el Test de Performance ' . $form->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    $data = [
                        'success'   => true,
                        'data'   => 'LABEL_RECORD_ADDED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $testMapper->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
                ]);
            }
            
            

        }

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

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

        $request = $this->getRequest();

        $uuid = $this->params()->fromRoute('id');

        if ($request->isGet()) {
            $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
            $test = $testMapper->fetchOneByUuid($uuid);
          
            $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
            $form = $formMapper->fetchOne($test->form_id);
           
            $jobDescriptionMapper = JobDescriptionMapper::getInstance($this->adapter);
            $jobDescription = $jobDescriptionMapper->fetchOne($form->job_description_id);
          
            $jobDescriptionCompetencyMapper = JobDescriptionCompetencyMapper::getInstance($this->adapter);
            $jobDescriptionCompetencies = $jobDescriptionCompetencyMapper->fetchByJobDescriptionId($jobDescription->id);
            // return new JsonModel([
            //     'success' => false,
            //     'data' => $jobDescriptionCompetencies
            // ]);
            $competencyTypeMapper = CompetencyTypeMapper::getInstance($this->adapter);
            $competencyMapper = CompetencyMapper::getInstance($this->adapter);
            $competencyBehaviorMapper = CompetencyBehaviorMapper::getInstance($this->adapter);
            $behaviorMapper = BehaviorMapper::getInstance($this->adapter);
    
            $data = [
                'job_description' => [
                    'uuid' => $jobDescription->uuid,
                    'name' => $jobDescription->name,
                    'functions' => $jobDescription->functions,
                    'objectives' => $jobDescription->objectives,
                    'competencies' => []
                ],
                'self' => [
                    'points' => 0,
                    'comment' => '',
                ],
                'test' => $test,
            ];

            foreach ($jobDescriptionCompetencies as $jobDescriptionCompetency) {
                $competency = $competencyMapper->fetchOne($jobDescriptionCompetency->competency_id);
                $competencyType = $competencyTypeMapper->fetchOne($competency->competency_type_id);
                $behaviorCompetencies = $competencyBehaviorMapper->fetchAllByCompetencyId($competency->id);

                $behaviors = [];

                foreach ($behaviorCompetencies as $behaviorCompetency) {
                    $behavior = $behaviorMapper->fetchOne($behaviorCompetency->behavior_id);

                    $behaviors []= [
                        'uuid' => $behavior->uuid,
                        'description' => $behavior->description,
                        'points' => 0,
                        'comment' => '',
                        'competency_uuid' => $competency->uuid,
                    ];
                }

                array_push($data['job_description']['competencies'], [
                    'competency_uuid' => $competency->uuid,
                    'competency_name' => $competency->name,
                    'competency_type_uuid' => $competencyType->uuid,
                    'competency_type_name' => $competencyType->name,
                    'behaviors' => $behaviors,
                ]);
            }

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

        } else if($request->isPost()){
            try{
            $dataPost = $request->getPost()->toArray();

            $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
            $test = $testMapper->fetchOneByUuid($uuid);
            
            $formSelf = new PerformanceEvaluationEvaluationSelfForm($this->adapter, $currentCompany->id);
            $dataPost['first_name'] = $test->first_name;
            $dataPost['last_name'] = $test->last_name;
            $dataPost['email'] = $test->email;
            $formSelf->setData($dataPost);

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

                $hydrator = new ObjectPropertyHydrator();
                $performanceEvaluationTestSelf = new CompanyPerformanceEvaluationTestSelf();
                $hydrator->hydrate($dataPost, $performanceEvaluationTestSelf);

                $performanceEvaluationTestSelf->company_id = $currentCompany->id;
                $performanceEvaluationTestSelf->test_id = $test->id;
                $performanceEvaluationTestSelf->form_id = $test->form_id;
                $performanceEvaluationTestSelf->supervisor_id = $test->supervisor_id;

                $performanceEvaluationTestSelfMapper = CompanyPerformanceEvaluationTestSelfMapper::getInstance($this->adapter);
                
                $result = $performanceEvaluationTestSelfMapper->insert($performanceEvaluationTestSelf);
            

                if ($result) {
                    $this->logger->info('Se agrego la entrevista ' . $performanceEvaluationTestSelf->id, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                    // Get record by id
                    $performanceEvaluationTestSelfMapper = CompanyPerformanceEvaluationTestSelfMapper::getInstance($this->adapter);
                    $record = $performanceEvaluationTestSelfMapper->fetchOne($performanceEvaluationTestSelf->id);


                    if ($record) {

                        $data = [
                            'success' => true,
                            'id' => $record->id,
                            'data' => 'LABEL_RECORD_ADDED'
                        ];
                    } else {

                        $data = [
                            'success' => false,
                            'data' => 'ERROR_RECORD_NOT_FOUND'
                        ];
                    }
                } else {
                    $data = [
                        'success' => false,
                        'data' => $performanceEvaluationTestSelfMapper->getError()
                    ];
                }

                return new JsonModel($data);
            } else {
                $messages = [];
                $form_messages = (array) $formSelf->getMessages();
                foreach ($form_messages as $fieldname => $field_messages) {

                    $messages[$fieldname] = array_values($field_messages);
                }

                return new JsonModel([
                    'success' => false,
                    'data' => $messages
                ]);
            }}catch (\Throwable $e) {
                $e->getMessage();
                return new JsonModel([
                    'success' => false,
                    'data' => $e
                ]);
            }
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }

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

        $request = $this->getRequest();

        $uuid = $this->params()->fromRoute('id');

        if ($request->isGet()) {
            $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
            $test = $testMapper->fetchOneByUuid($uuid);
          
            $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
            $form = $formMapper->fetchOne($test->form_id);
           
            $jobDescriptionMapper = JobDescriptionMapper::getInstance($this->adapter);
            $jobDescription = $jobDescriptionMapper->fetchOne($form->job_description_id);
          
            $jobDescriptionCompetencyMapper = JobDescriptionCompetencyMapper::getInstance($this->adapter);
            $jobDescriptionCompetencies = $jobDescriptionCompetencyMapper->fetchByJobDescriptionId($jobDescription->id);
            // return new JsonModel([
            //     'success' => false,
            //     'data' => $jobDescriptionCompetencies
            // ]);
            $competencyTypeMapper = CompetencyTypeMapper::getInstance($this->adapter);
            $competencyMapper = CompetencyMapper::getInstance($this->adapter);
            $competencyBehaviorMapper = CompetencyBehaviorMapper::getInstance($this->adapter);
            $behaviorMapper = BehaviorMapper::getInstance($this->adapter);
    
            $data = [
                'job_description' => [
                    'uuid' => $jobDescription->uuid,
                    'name' => $jobDescription->name,
                    'functions' => $jobDescription->functions,
                    'objectives' => $jobDescription->objectives,
                    'competencies' => []
                ],
                'both' => [
                    'points' => 0,
                    'comment' => '',
                ],
                'test' => $test,
            ];

            foreach ($jobDescriptionCompetencies as $jobDescriptionCompetency) {
                $competency = $competencyMapper->fetchOne($jobDescriptionCompetency->competency_id);
                $competencyType = $competencyTypeMapper->fetchOne($competency->competency_type_id);
                $behaviorCompetencies = $competencyBehaviorMapper->fetchAllByCompetencyId($competency->id);

                $behaviors = [];

                foreach ($behaviorCompetencies as $behaviorCompetency) {
                    $behavior = $behaviorMapper->fetchOne($behaviorCompetency->behavior_id);

                    $behaviors []= [
                        'uuid' => $behavior->uuid,
                        'description' => $behavior->description,
                        'points' => 0,
                        'comment' => '',
                        'competency_uuid' => $competency->uuid,
                    ];
                }

                array_push($data['job_description']['competencies'], [
                    'competency_uuid' => $competency->uuid,
                    'competency_name' => $competency->name,
                    'competency_type_uuid' => $competencyType->uuid,
                    'competency_type_name' => $competencyType->name,
                    'behaviors' => $behaviors,
                ]);
            }

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

        } else if($request->isPost()){
            try{
            $dataPost = $request->getPost()->toArray();

            $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
            $test = $testMapper->fetchOneByUuid($uuid);
            
            $formSelf = new PerformanceEvaluationEvaluationSelfForm($this->adapter, $currentCompany->id);
            $dataPost['first_name'] = $test->first_name;
            $dataPost['last_name'] = $test->last_name;
            $dataPost['email'] = $test->email;
            $formSelf->setData($dataPost);

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

                $hydrator = new ObjectPropertyHydrator();
                $performanceEvaluationTestBoth = new CompanyPerformanceEvaluationTestBoth();
                $hydrator->hydrate($dataPost, $performanceEvaluationTestBoth);

                $performanceEvaluationTestBoth->company_id = $currentCompany->id;
                $performanceEvaluationTestBoth->test_id = $test->id;
                $performanceEvaluationTestBoth->form_id = $test->form_id;
                $performanceEvaluationTestBoth->supervisor_id = $test->supervisor_id;

                $performanceEvaluationTestBothMapper = CompanyPerformanceEvaluationTestBothMapper::getInstance($this->adapter);
                
                $result = $performanceEvaluationTestBothMapper->insert($performanceEvaluationTestBoth);
            

                if ($result) {
                    $this->logger->info('Se agrego la entrevista ' . $performanceEvaluationTestBoth->id, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                    // Get record by id
                    $performanceEvaluationTestBothMapper = CompanyPerformanceEvaluationTestBothMapper::getInstance($this->adapter);
                    $record = $performanceEvaluationTestBothMapper->fetchOne($performanceEvaluationTestBoth->id);


                    if ($record) {

                        $data = [
                            'success' => true,
                            'id' => $record->id,
                            'data' => 'LABEL_RECORD_ADDED'
                        ];
                    } else {

                        $data = [
                            'success' => false,
                            'data' => 'ERROR_RECORD_NOT_FOUND'
                        ];
                    }
                } else {
                    $data = [
                        'success' => false,
                        'data' => $performanceEvaluationTestBothMapper->getError()
                    ];
                }

                return new JsonModel($data);
            } else {
                $messages = [];
                $form_messages = (array) $formSelf->getMessages();
                foreach ($form_messages as $fieldname => $field_messages) {

                    $messages[$fieldname] = array_values($field_messages);
                }

                return new JsonModel([
                    'success' => false,
                    'data' => $messages
                ]);
            }}catch (\Throwable $e) {
                $e->getMessage();
                return new JsonModel([
                    'success' => false,
                    'data' => $e
                ]);
            }
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }

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

        $request = $this->getRequest();

        $uuid = $this->params()->fromRoute('id');

        if ($request->isGet()) {
            $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
            $test = $testMapper->fetchOneByUuid($uuid);
          
            $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
            $form = $formMapper->fetchOne($test->form_id);
           
            $jobDescriptionMapper = JobDescriptionMapper::getInstance($this->adapter);
            $jobDescription = $jobDescriptionMapper->fetchOne($form->job_description_id);
          
            $jobDescriptionCompetencyMapper = JobDescriptionCompetencyMapper::getInstance($this->adapter);
            $jobDescriptionCompetencies = $jobDescriptionCompetencyMapper->fetchByJobDescriptionId($jobDescription->id);
            // return new JsonModel([
            //     'success' => false,
            //     'data' => $jobDescriptionCompetencies
            // ]);
            $competencyTypeMapper = CompetencyTypeMapper::getInstance($this->adapter);
            $competencyMapper = CompetencyMapper::getInstance($this->adapter);
            $competencyBehaviorMapper = CompetencyBehaviorMapper::getInstance($this->adapter);
            $behaviorMapper = BehaviorMapper::getInstance($this->adapter);
    
            $data = [
                'job_description' => [
                    'uuid' => $jobDescription->uuid,
                    'name' => $jobDescription->name,
                    'functions' => $jobDescription->functions,
                    'objectives' => $jobDescription->objectives,
                    'competencies' => []
                ],
                'supervisor' => [
                    'points' => 0,
                    'comment' => '',
                ],
                'test' => $test,
            ];

            foreach ($jobDescriptionCompetencies as $jobDescriptionCompetency) {
                $competency = $competencyMapper->fetchOne($jobDescriptionCompetency->competency_id);
                $competencyType = $competencyTypeMapper->fetchOne($competency->competency_type_id);
                $behaviorCompetencies = $competencyBehaviorMapper->fetchAllByCompetencyId($competency->id);

                $behaviors = [];

                foreach ($behaviorCompetencies as $behaviorCompetency) {
                    $behavior = $behaviorMapper->fetchOne($behaviorCompetency->behavior_id);

                    $behaviors []= [
                        'uuid' => $behavior->uuid,
                        'description' => $behavior->description,
                        'points' => 0,
                        'comment' => '',
                        'competency_uuid' => $competency->uuid,
                    ];
                }

                array_push($data['job_description']['competencies'], [
                    'competency_uuid' => $competency->uuid,
                    'competency_name' => $competency->name,
                    'competency_type_uuid' => $competencyType->uuid,
                    'competency_type_name' => $competencyType->name,
                    'behaviors' => $behaviors,
                ]);
            }

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

        } else if($request->isPost()){
            try{
            $dataPost = $request->getPost()->toArray();

            $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
            $test = $testMapper->fetchOneByUuid($uuid);
            
            $formSelf = new PerformanceEvaluationEvaluationSelfForm($this->adapter, $currentCompany->id);
            $dataPost['first_name'] = $test->first_name;
            $dataPost['last_name'] = $test->last_name;
            $dataPost['email'] = $test->email;
            $formSelf->setData($dataPost);

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

                $hydrator = new ObjectPropertyHydrator();
                $performanceEvaluationTestSupervisor = new CompanyPerformanceEvaluationTestSupervisor();
                $hydrator->hydrate($dataPost, $performanceEvaluationTestSupervisor);

                $performanceEvaluationTestSupervisor->company_id = $currentCompany->id;
                $performanceEvaluationTestSupervisor->test_id = $test->id;
                $performanceEvaluationTestSupervisor->form_id = $test->form_id;
                $performanceEvaluationTestSupervisor->supervisor_id = $test->supervisor_id;

                $performanceEvaluationTestSupervisorMapper = CompanyPerformanceEvaluationTestSupervisorMapper::getInstance($this->adapter);
                
                $result = $performanceEvaluationTestSupervisorMapper->insert($performanceEvaluationTestSupervisor);
            

                if ($result) {
                    $this->logger->info('Se agrego la entrevista ' . $performanceEvaluationTestSupervisor->id, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                    // Get record by id
                    $performanceEvaluationTestSupervisorMapper = CompanyPerformanceEvaluationTestSupervisorMapper::getInstance($this->adapter);
                    $record = $performanceEvaluationTestSupervisorMapper->fetchOne($performanceEvaluationTestSupervisor->id);


                    if ($record) {

                        $data = [
                            'success' => true,
                            'id' => $record->id,
                            'data' => 'LABEL_RECORD_ADDED'
                        ];
                    } else {

                        $data = [
                            'success' => false,
                            'data' => 'ERROR_RECORD_NOT_FOUND'
                        ];
                    }
                } else {
                    $data = [
                        'success' => false,
                        'data' => $performanceEvaluationTestSupervisorMapper->getError()
                    ];
                }

                return new JsonModel($data);
            } else {
                $messages = [];
                $form_messages = (array) $formSelf->getMessages();
                foreach ($form_messages as $fieldname => $field_messages) {

                    $messages[$fieldname] = array_values($field_messages);
                }

                return new JsonModel([
                    'success' => false,
                    'data' => $messages
                ]);
            }}catch (\Throwable $e) {
                $e->getMessage();
                return new JsonModel([
                    'success' => false,
                    'data' => $e
                ]);
            }
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }
    
    public function editAction() {
        $request = $this->getRequest();
        
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $currentCompany = $currentUserPlugin->getCompany();
        
        $request = $this->getRequest();
        $id = $this->params()->fromRoute('id');
        
        $formTestMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
        $formTest =  $formTestMapper->fetchOneByUuid($id);
       
        if (!$formTest) {
            return new JsonModel([
                'success' => true,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ]);
        }
        
        if ($formTest->company_id != $currentCompany->id) {
            return new JsonModel([
                'success' => true,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }
        
        
        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($formTest->company_id, $currentUser->id);
        if (!$companyUser) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }
        
        if ($request->isGet()) {
            
            $dt = \DateTime::createFromFormat('Y-m-d', $formTest->last_date);
            
            $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
            $form = $formMapper->fetchOne($formTest->form_id);
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOne($formTest->supervisor_id);
            
            $data = [
                'success'   => true,
                'data'   => [
                    'last_date' => $dt->format('d/m/Y'),
                    'form' => $form->uuid,
                    'supervisor' => $user->uuid,
                ]
            ];
        
            return new JsonModel($data);
            
            
        
        } else if ($request->isPost()) {
            
            
            $dataPost = $request->getPost()->toArray();
            $form = new  PerformanceEvaluationEvaluationForm($this->adapter, $currentCompany->id);
            $form->setData($dataPost);
            
            if($form->isValid()) {
                $dataPost = (array) $form->getData();
                
                $form_id = $dataPost['form_id'];
                $user_id = $dataPost['supervisor_id'];
                $dt = \DateTime::createFromFormat('d/m/Y', $dataPost['last_date']);
                $last_date = $dt->format('Y-m-d');
                
                $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
                $form = $formMapper->fetchOneByUuid($form_id);
                if (!$form) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_FORM_NOT_FOUND'
                    ]);
                }
                
                if ($form->company_id != $currentCompany->id) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_UNAUTHORIZED'
                    ]);
                }
                
                
                $userMapper = UserMapper::getInstance($this->adapter);
                $user = $userMapper->fetchOneByUuid($user_id);
                
                if (!$user) {
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_USER_NOT_FOUND'
                    ]);
                }
                
                
                
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
                $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($form->company_id, $user->id);
                if (!$companyUser) {
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_UNAUTHORIZED'
                    ]);
                }
                
                $formTest->supervisor_id = $user->id;
                $formTest->last_date = $last_date;
                
                $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
                $result = $testMapper->update($formTest);
                
                if($result) {
                    $this->logger->info('Se actualizo el Test de Performance ' . $form->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    $data = [
                        'success'   => true,
                        'data'   => 'LABEL_RECORD_UPDATED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $testMapper->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
                ]);
            }
        }
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }

    public function deleteAction() {
        $request = $this->getRequest();

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

        $request = $this->getRequest();
        $id = $this->params()->fromRoute('id');
        
        $formTestMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
        $formTest =  $formTestMapper->fetchOneByUuid($id);
        if (!$formTest) {
            return new JsonModel([
                'success' => true,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ]);
        }
        
        if ($formTest->company_id != $currentCompany->id) {
            return new JsonModel([
                'success' => true,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }
        

        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($formTest->company_id, $currentUser->id);
        if (!$companyUser) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }

        if ($request->isPost()) {

            $formTestMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
            $formTest->status = CompanyPerformanceEvaluationTest::STATUS_DELETED;
            if($formTestMapper->update($formTest)) {
                return new JsonModel([
                    'success' => true,
                    'data' => 'LABEL_PERFORMANCE_TEST_DELETED'
                ]);
                
            } else {
                return new JsonModel([
                    'success' => false,
                    'data' => $feedMapper->getError()
                ]);
            }
            
        }

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

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

        $uuid = $this->params()->fromRoute('id');

        $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
        $test = $testMapper->fetchOneByUuid($uuid);
       
        $testSelfMapper = CompanyPerformanceEvaluationTestSelfMapper::getInstance($this->adapter);
        $testSelf = $testSelfMapper->fetchOneByTestId($test->id);
       
        $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
        $form = $formMapper->fetchOne($test->form_id);
    
        if (!$form) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_FORM_EVALUATION_NOT_FOUND'
            ]);
        }

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

            $jobDescriptionCompetencyMapper = JobDescriptionCompetencyMapper::getInstance($this->adapter);
            $competencyMapper = CompetencyMapper::getInstance($this->adapter);
            $competenceTypeMapper = CompetencyTypeMapper::getInstance($this->adapter);
            $competencyBehaviorMapper = CompetencyBehaviorMapper::getInstance($this->adapter);
            $jobDescriptionBehaviorCompetencyMapper = JobDescriptionBehaviorCompetencyMapper::getInstance($this->adapter);
            $behaviorMapper = BehaviorMapper::getInstance($this->adapter);

            $competencies = [];

            $jobDescriptionCompetency = $jobDescriptionCompetencyMapper->fetchByJobDescriptionId($form->job_description_id);

            $content = json_decode($testSelf->content, true);

            foreach ($jobDescriptionCompetency as $record) {

                $competency = $competencyMapper->fetchOne($record->competency_id);
                $competenceType = $competenceTypeMapper->fetchOne($competency->competency_type_id);

                if ($competency && $competenceType) {

                    $behaviorCompetencies = $competencyBehaviorMapper->fetchAllByCompetencyId($competency->id);
                    $behaviors = [];

                    foreach ($behaviorCompetencies as $rows) {

                        $behavior = $behaviorMapper->fetchOne($rows->behavior_id);
                        $jobDescriptionBehaviorCompetency = $jobDescriptionBehaviorCompetencyMapper->fetchOneByBehavior($form->job_description_id, $record->competency_id, $rows->behavior_id);

                        if ($behavior && $jobDescriptionBehaviorCompetency) {
                            $rowData = [
                                'description' => $behavior->description,
                                'level' => $jobDescriptionBehaviorCompetency->level,
                                'comment' => '',
                                'evaluation' => '',
                               
                            ];

                            foreach($content as $eval) {
                                if ($eval['competencyUuid'] == $competency->uuid &&
                                    $eval['behaviorUuid'] == $behavior->uuid) {

                                    $rowData['comment'] = $eval['comment'];
                                    $rowData['evaluation'] = $eval['evaluation'];
                                    

                                    break;
                                }
                            }

                            $behaviors []= $rowData;
                        }
                    }

                    array_push($competencies, [
                        'name' => $competency->name,
                        'description' => $competency->description,
                        'type' => $competenceType->name,
                        'behaviors' => $behaviors
                    ]);
                }
            }

            return $this->renderSelfPDF($currentCompany, $testSelf, $competencies);
        }

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

      /**
     * Render PDF
     * @param Company $company
     * @param CompanyPerformanceEvaluationTestSelf $interviewEvaluation
     * @param array $competencies
     * @return mixed
     */
    public function renderSelfPDF($company, $testSelf, $competencies) 
    {



        //Generate New PDF
        $pdf = new InterviewPDF();


        $target_path = $this->config['leaderslinked.fullpath.company'] . DIRECTORY_SEPARATOR . $company->uuid;
        
        $header = $company->header ? $target_path . DIRECTORY_SEPARATOR . $company->header : '';
        if(empty($header) || !file_exists($header)) {
            $header = $this->config['leaderslinked.images_default.company_pdf_header'];
        }
        
        $footer = $company->footer ? $target_path . DIRECTORY_SEPARATOR . $company->footer : '';
        if(empty($footer) || !file_exists($footer)) {
            $footer = $this->config['leaderslinked.images_default.company_pdf_footer'];
        }
        
        $pdf->header = $header;
        $pdf->footer = $footer;

        $pdf->SetMargins(10, 0, 10);

        $pdf->AliasNbPages();
        $pdf->AddPage();
        
        $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
        $test = $testMapper->fetchOne($testSelf->test_id);

        $userMapper = UserMapper::getInstance($this->adapter);
        $supervisor = $userMapper->fetchOne($testSelf->supervisor_id);

        switch ($testSelf->points) {
            case "0":
                $points = "Sugerir otro cargo";
                break;
            case "1":
                $points = "25%";
                break;
            case "2":
                $points = "50%";
                break;
            case "3":
                $points = "75%";
                break;
            case "4":
                $points = "100%";
                break;
            default :
                $points = "ERROR";
                break;
        }

        $rows = [
            array(
                'title' => 'Nombre Evaluado: ',
                'content' => $testSelf ? ' ' . $testSelf->first_name . ' ' . $testSelf->last_name : 'No Aplica'
            ),
            array(
                'title' => 'Supervisado por: ',
                'content' => $supervisor ? ' ' . $supervisor->first_name . ' ' . $supervisor->last_name : ' No Aplica '
            ),
            array(
                'title' => 'Comentarios del supervisor: ',
                'content' => $testSelf ? ' ' . $testSelf->comment : 'No Aplica'
            ),
            array(
                'title' => 'Porcentage',
                'content' => $points
            )
        ];

        $pdf->borderTable('DATOS DE LA ENTREVISTA', $rows);
          
        $sections = json_decode($testSelf->content, true);
        /*
                for ($s = 0; $s < count($sections); $s++) {
        
                    $pdf->singleTable($sections[$s]['title'], [
                        array(
                            'content' => $sections[$s]['type'] != 'multiple' ? $sections[$s]['text'] : ''
                    )]);
        
                    if ($sections[$s]['type'] == 'multiple') {
                        
                        $pdf->titleOptionTable($sections[$s]['text']);
        
                        for ($o = 0; $o < count($sections[$s]['options']); $o++) {
        
                            $pdf->optionTable($sections[$s]['options'][$o]['title']);
                        }
                        $pdf->Ln();
                    }
                    if ($s % 2 == 0 && $s > 1) {
                        $pdf->AddPage();
                    }
                }*/
        
        // Competencies
        if (count($competencies) != 0) {

            // add new page

            $pdf->AddPage();

            $competencies_header[] = array('content' => 'Indique el nivel de desempeño del evaluado en relación a sus conductas y actitudes frente a cada valor, según la clasificación siguiente:');

            $pdf->singleTable('Anexo de valores:', $competencies_header);


            // Add scale section
            $pdf->sectionScale();

            $i = 0;

            foreach ($competencies as $record) {

                $i = $i + 1;

                $pdf->competencyTable($i, $record);

                if ($i % 3 == 0 && $i < count($competencies)) {
                    $pdf->AddPage();
                }
            }
            
        }
 
        return $pdf->Output();
           
    }

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

        $uuid = $this->params()->fromRoute('id');

        $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
        $test = $testMapper->fetchOneByUuid($uuid);
       
        $testBothMapper = CompanyPerformanceEvaluationTestBothMapper::getInstance($this->adapter);
        $testBoth = $testBothMapper->fetchOneByTestId($test->id);
       
        $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
        $form = $formMapper->fetchOne($test->form_id);
    
        if (!$form) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_FORM_EVALUATION_NOT_FOUND'
            ]);
        }

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

            $jobDescriptionCompetencyMapper = JobDescriptionCompetencyMapper::getInstance($this->adapter);
            $competencyMapper = CompetencyMapper::getInstance($this->adapter);
            $competenceTypeMapper = CompetencyTypeMapper::getInstance($this->adapter);
            $competencyBehaviorMapper = CompetencyBehaviorMapper::getInstance($this->adapter);
            $jobDescriptionBehaviorCompetencyMapper = JobDescriptionBehaviorCompetencyMapper::getInstance($this->adapter);
            $behaviorMapper = BehaviorMapper::getInstance($this->adapter);

            $competencies = [];

            $jobDescriptionCompetency = $jobDescriptionCompetencyMapper->fetchByJobDescriptionId($form->job_description_id);

            $content = json_decode($testBoth->content, true);

            foreach ($jobDescriptionCompetency as $record) {

                $competency = $competencyMapper->fetchOne($record->competency_id);
                $competenceType = $competenceTypeMapper->fetchOne($competency->competency_type_id);

                if ($competency && $competenceType) {

                    $behaviorCompetencies = $competencyBehaviorMapper->fetchAllByCompetencyId($competency->id);
                    $behaviors = [];

                    foreach ($behaviorCompetencies as $rows) {

                        $behavior = $behaviorMapper->fetchOne($rows->behavior_id);
                        $jobDescriptionBehaviorCompetency = $jobDescriptionBehaviorCompetencyMapper->fetchOneByBehavior($form->job_description_id, $record->competency_id, $rows->behavior_id);

                        if ($behavior && $jobDescriptionBehaviorCompetency) {
                            $rowData = [
                                'description' => $behavior->description,
                                'level' => $jobDescriptionBehaviorCompetency->level,
                                'comment' => '',
                                'evaluation' => '',
                               
                            ];

                            foreach($content as $eval) {
                                if ($eval['competencyUuid'] == $competency->uuid &&
                                    $eval['behaviorUuid'] == $behavior->uuid) {

                                    $rowData['comment'] = $eval['comment'];
                                    $rowData['evaluation'] = $eval['evaluation'];
                                    

                                    break;
                                }
                            }

                            $behaviors []= $rowData;
                        }
                    }

                    array_push($competencies, [
                        'name' => $competency->name,
                        'description' => $competency->description,
                        'type' => $competenceType->name,
                        'behaviors' => $behaviors
                    ]);
                }
            }

            return $this->renderBothPDF($currentCompany, $testBoth, $competencies);
        }

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

    public function renderBothPDF($company, $testBoth, $competencies) {


        
        //Generate New PDF
        $pdf = new InterviewPDF();




        $target_path = $this->config['leaderslinked.fullpath.company'] . DIRECTORY_SEPARATOR . $company->uuid;

        $header = $company->header ? $target_path . DIRECTORY_SEPARATOR . $company->header : '';
        if(empty($header) || !file_exists($header)) {
            $header = $this->config['leaderslinked.images_default.company_pdf_header'];
        }
            
        $footer = $company->footer ? $target_path . DIRECTORY_SEPARATOR . $company->footer : '';
        if(empty($footer) || !file_exists($footer)) {
            $footer = $this->config['leaderslinked.images_default.company_pdf_footer'];
        }

        $pdf->header = $header;
        $pdf->footer = $footer;
        
        
        $pdf->SetMargins(10, 0, 10);

        $pdf->AliasNbPages();
        $pdf->AddPage();
        
        $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
        $test = $testMapper->fetchOne($testBoth->test_id);

        $userMapper = UserMapper::getInstance($this->adapter);
        $supervisor = $userMapper->fetchOne($testBoth->supervisor_id);

        switch ($testBoth->points) {
            case "0":
                $points = "N/A";
                break;
            case "1":
                $points = "25%";
                break;
            case "2":
                $points = "50%";
                break;
            case "3":
                $points = "75%";
                break;
            case "4":
                $points = "100%";
                break;
            default :
                $points = "ERROR";
                break;
        }

        $rows = [
            array(
                'title' => 'Nombre Evaluado: ',
                'content' => $testBoth ? ' ' . $testBoth->first_name . ' ' . $testBoth->last_name : 'No Aplica'
            ),
            array(
                'title' => 'Supervisado por: ',
                'content' => $supervisor ? ' ' . $supervisor->first_name . ' ' . $supervisor->last_name : ' No Aplica '
            ),
            array(
                'title' => 'Comentarios del supervisor: ',
                'content' => $testBoth ? ' ' . $testBoth->comment : 'No Aplica'
            ),
            array(
                'title' => 'Porcentage de adaptibilidad ',
                'content' => $points
            )
        ];

        $pdf->borderTable('DATOS DE LA ENTREVISTA', $rows);
          
        $sections = json_decode($testBoth->content, true);
        /*
                for ($s = 0; $s < count($sections); $s++) {
        
                    $pdf->singleTable($sections[$s]['title'], [
                        array(
                            'content' => $sections[$s]['type'] != 'multiple' ? $sections[$s]['text'] : ''
                    )]);
        
                    if ($sections[$s]['type'] == 'multiple') {
                        
                        $pdf->titleOptionTable($sections[$s]['text']);
        
                        for ($o = 0; $o < count($sections[$s]['options']); $o++) {
        
                            $pdf->optionTable($sections[$s]['options'][$o]['title']);
                        }
                        $pdf->Ln();
                    }
                    if ($s % 2 == 0 && $s > 1) {
                        $pdf->AddPage();
                    }
                }*/
        
        // Competencies
        if (count($competencies) != 0) {

            // add new page

            $pdf->AddPage();

            $competencies_header[] = array('content' => 'Indique el nivel de desempeño del evaluado en relación a sus conductas y actitudes frente a cada valor, según la clasificación siguiente:');

            $pdf->singleTable('Anexo de valores:', $competencies_header);


            // Add scale section
            $pdf->sectionScale();

            $i = 0;

            foreach ($competencies as $record) {

                $i = $i + 1;

                $pdf->competencyTable($i, $record);

                if ($i % 3 == 0 && $i < count($competencies)) {
                    $pdf->AddPage();
                }
            }
            
        }
 
        return $pdf->Output();
           
    }

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

        $uuid = $this->params()->fromRoute('id');

        $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
        $test = $testMapper->fetchOneByUuid($uuid);
       
        $testSupervisorMapper = CompanyPerformanceEvaluationTestSupervisorMapper::getInstance($this->adapter);
        $testSupervisor = $testSupervisorMapper->fetchOneByTestId($test->id);
       
        $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
        $form = $formMapper->fetchOne($test->form_id);
    
        if (!$form) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_FORM_EVALUATION_NOT_FOUND'
            ]);
        }

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

            $jobDescriptionCompetencyMapper = JobDescriptionCompetencyMapper::getInstance($this->adapter);
            $competencyMapper = CompetencyMapper::getInstance($this->adapter);
            $competenceTypeMapper = CompetencyTypeMapper::getInstance($this->adapter);
            $competencyBehaviorMapper = CompetencyBehaviorMapper::getInstance($this->adapter);
            $jobDescriptionBehaviorCompetencyMapper = JobDescriptionBehaviorCompetencyMapper::getInstance($this->adapter);
            $behaviorMapper = BehaviorMapper::getInstance($this->adapter);

            $competencies = [];

            $jobDescriptionCompetency = $jobDescriptionCompetencyMapper->fetchByJobDescriptionId($form->job_description_id);

            $content = json_decode($testSupervisor->content, true);

            foreach ($jobDescriptionCompetency as $record) {

                $competency = $competencyMapper->fetchOne($record->competency_id);
                $competenceType = $competenceTypeMapper->fetchOne($competency->competency_type_id);

                if ($competency && $competenceType) {

                    $behaviorCompetencies = $competencyBehaviorMapper->fetchAllByCompetencyId($competency->id);
                    $behaviors = [];

                    foreach ($behaviorCompetencies as $rows) {

                        $behavior = $behaviorMapper->fetchOne($rows->behavior_id);
                        $jobDescriptionBehaviorCompetency = $jobDescriptionBehaviorCompetencyMapper->fetchOneByBehavior($form->job_description_id, $record->competency_id, $rows->behavior_id);

                        if ($behavior && $jobDescriptionBehaviorCompetency) {
                            $rowData = [
                                'description' => $behavior->description,
                                'level' => $jobDescriptionBehaviorCompetency->level,
                                'comment' => '',
                                'evaluation' => '',
                               
                            ];

                            foreach($content as $eval) {
                                if ($eval['competencyUuid'] == $competency->uuid &&
                                    $eval['behaviorUuid'] == $behavior->uuid) {

                                    $rowData['comment'] = $eval['comment'];
                                    $rowData['evaluation'] = $eval['evaluation'];
                                    

                                    break;
                                }
                            }

                            $behaviors []= $rowData;
                        }
                    }

                    array_push($competencies, [
                        'name' => $competency->name,
                        'description' => $competency->description,
                        'type' => $competenceType->name,
                        'behaviors' => $behaviors
                    ]);
                }
            }

            return $this->renderSupervisorPDF($currentCompany, $testSupervisor, $competencies);
        }

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

      /**
     * Render PDF
     * @param Company $company
     * @param CompanyPerformanceEvaluationTestSelf $interviewEvaluation
     * @param array $competencies
     * @return mixed
     */
    public function renderSupervisorPDF($company, $testSupervisor, $competencies) 
    {

        //Generate New PDF
        $pdf = new InterviewPDF();

        $pdf->header = '';
        $pdf->footer = '';

        $target_path = $this->config['leaderslinked.fullpath.company'] . DIRECTORY_SEPARATOR . $company->uuid;
        
        $header = $company->header ? $target_path . DIRECTORY_SEPARATOR . $company->header : '';
        if(empty($header) || !file_exists($header)) {
            $header = $this->config['leaderslinked.images_default.company_pdf_header'];
        }
        
        $footer = $company->footer ? $target_path . DIRECTORY_SEPARATOR . $company->footer : '';
        if(empty($footer) || !file_exists($footer)) {
            $footer = $this->config['leaderslinked.images_default.company_pdf_footer'];
        }
        
        $pdf->header = $header;
        $pdf->footer = $footer;

        $pdf->SetMargins(10, 0, 10);

        $pdf->AliasNbPages();
        $pdf->AddPage();
        
        $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
        $test = $testMapper->fetchOne($testSupervisor->test_id);

        $userMapper = UserMapper::getInstance($this->adapter);
        $supervisor = $userMapper->fetchOne($testSupervisor->supervisor_id);

        switch ($testSupervisor->points) {
            case "0":
                $points = "Sugerir otro cargo";
                break;
            case "1":
                $points = "25%";
                break;
            case "2":
                $points = "50%";
                break;
            case "3":
                $points = "75%";
                break;
            case "4":
                $points = "100%";
                break;
            default :
                $points = "ERROR";
                break;
        }

        $rows = [
            array(
                'title' => 'Nombre Evaluado: ',
                'content' => $testSupervisor ? ' ' . $testSupervisor->first_name . ' ' . $testSupervisor->last_name : 'No Aplica'
            ),
            array(
                'title' => 'Supervisado por: ',
                'content' => $supervisor ? ' ' . $supervisor->first_name . ' ' . $supervisor->last_name : ' No Aplica '
            ),
            array(
                'title' => 'Comentarios del supervisor: ',
                'content' => $testSupervisor ? ' ' . $testSupervisor->comment : 'No Aplica'
            ),
            array(
                'title' => 'Porcentage de adaptibilidad ',
                'content' => $points
            )
        ];

        $pdf->borderTable('DATOS DE LA ENTREVISTA', $rows);
          
        $sections = json_decode($testSupervisor->content, true);
        /*
                for ($s = 0; $s < count($sections); $s++) {
        
                    $pdf->singleTable($sections[$s]['title'], [
                        array(
                            'content' => $sections[$s]['type'] != 'multiple' ? $sections[$s]['text'] : ''
                    )]);
        
                    if ($sections[$s]['type'] == 'multiple') {
                        
                        $pdf->titleOptionTable($sections[$s]['text']);
        
                        for ($o = 0; $o < count($sections[$s]['options']); $o++) {
        
                            $pdf->optionTable($sections[$s]['options'][$o]['title']);
                        }
                        $pdf->Ln();
                    }
                    if ($s % 2 == 0 && $s > 1) {
                        $pdf->AddPage();
                    }
                }*/
        
        // Competencies
        if (count($competencies) != 0) {

            // add new page

            $pdf->AddPage();

            $competencies_header[] = array('content' => 'Indique el nivel de desempeño del evaluado en relación a sus conductas y actitudes frente a cada valor, según la clasificación siguiente:');

            $pdf->singleTable('Anexo de valores:', $competencies_header);


            // Add scale section
            $pdf->sectionScale();

            $i = 0;

            foreach ($competencies as $record) {

                $i = $i + 1;

                $pdf->competencyTable($i, $record);

                if ($i % 3 == 0 && $i < count($competencies)) {
                    $pdf->AddPage();
                }
            }
            
        }
 
        return $pdf->Output();
           
    }
}