Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 15087 | Autoría | Ultima modificación | Ver Log |

<?php

declare(strict_types=1);

namespace LeadersLinked\Controller;

use Laminas\Db\Adapter\AdapterInterface;
use LeadersLinked\Library\InterviewPDF;
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Log\LoggerInterface;
use Laminas\View\Model\JsonModel;
use LeadersLinked\Form\RecruitmentSelectionInterviewFormForm;
use LeadersLinked\Form\InterviewFileForm;
use LeadersLinked\Form\JobDescriptionForm;
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
use LeadersLinked\Library\Functions;
use LeadersLinked\Mapper\CompanyMapper;
use LeadersLinked\Mapper\CompetencyTypeMapper;
use LeadersLinked\Model\JobDescription;
use LeadersLinked\Mapper\CompetencyMapper;
use LeadersLinked\Mapper\BehaviorCompetencyMapper;
use LeadersLinked\Model\BehaviorCompetency;
use LeadersLinked\Library\JobPdf;
use LeadersLinked\Mapper\JobDescriptionCompetencyMapper;
use LeadersLinked\Mapper\JobDescriptionSubordinateMapper;
use LeadersLinked\Model\JobDescriptionCompetency;
use LeadersLinked\Model\JobDescriptionBehaviorCompetency;
use LeadersLinked\Mapper\JobDescriptionBehaviorCompetencyMapper;
use LeadersLinked\Model\JobDescriptionSubordinate;
use LeadersLinked\Mapper\BehaviorMapper;
use LeadersLinked\Model\Behavior;
use LeadersLinked\Model\Company;
use LeadersLinked\Mapper\RecruitmentSelectionInterviewMapper;
use LeadersLinked\Mapper\RecruitmentSelectionInterviewFileMapper;
use LeadersLinked\Model\RecruitmentSelectionInterview;
use LeadersLinked\Model\RecruitmentSelectionInterviewFile;
use LeadersLinked\Mapper\RecruitmentSelectionVacancyMapper;
use LeadersLinked\Model\RecruitmentSelectionVacancy;
use LeadersLinked\Mapper\RecruitmentSelectionCandidateMapper;
use LeadersLinked\Model\RecruitmentSelectionCandidate;
use LeadersLinked\Mapper\JobDescriptionMapper;
use Laminas\View\Model\ViewModel;
use LeadersLinked\Form\RecruitmentSelectionCandidateFormForm;
use Laminas\Hydrator\ArraySerializableHydrator;
use Laminas\Db\ResultSet\HydratingResultSet;
use LeadersLinked\Mapper\QueryMapper;
use Laminas\Paginator\Adapter\DbSelect;
use Laminas\Paginator\Paginator;
use LeadersLinked\Mapper\CompetencyBehaviorMapper;

class RecruitmentSelectionInterviewFormController 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) {
                $vacancy_uuid = $this->params()->fromRoute('vacancy_uuid');

                $search = $this->params()->fromQuery('search', []);
                $search = empty($search['value']) ? '' : filter_var($search['value'], 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 = ['uuid', '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';
                }

                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/interview/form/edit');
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/interview/form/delete');
                $allowReport = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/interview/report');
                $allowFile = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/interview/file');

                $queryMapper = QueryMapper::getInstance($this->adapter);
                $sql = $queryMapper->getSql();
                $select = $sql->select();
                $select->columns(['uuid', 'company_id', 'status', 'type', 'vacancy_id', 'points']);
                $select->from(['i' => RecruitmentSelectionInterviewMapper::_TABLE]);
                $select->join(['c' => RecruitmentSelectionCandidateMapper::_TABLE], "i.candidate_id = c.id", ['first_name', 'last_name', 'email']);
                $select->join(['v' => RecruitmentSelectionVacancyMapper::_TABLE],"c.vacancy_id = v.id", ['name', 'last_date']);
                $select->where->equalTo('i.company_id', $currentCompany->id);
                $select->where->equalTo('v.uuid', $vacancy_uuid);
               
               // echo $select->getSqlString($this->adapter->platform); exit;

                if($search) {
                    $select->where->nest()
                    ->like('first_name', '%' . $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();

                foreach ($records as $record) {
                    $params = [
                        'vacancy_uuid' => $vacancy_uuid,
                        'interview_uuid' => $record['uuid'],
                    ];

                    $link_delete = $this->url()->fromRoute('recruitment-and-selection/interview/form/delete', $params);
                
                    $link_edit = $this->url()->fromRoute('recruitment-and-selection/interview/form/edit', $params);

                    $link_report = $this->url()->fromRoute('recruitment-and-selection/interview/report', $params);
                  
                    $link_file = $this->url()->fromRoute('recruitment-and-selection/interview/file', $params);
                    
                    $item = [
                        'uuid' => $record['uuid'],
                        'first_name' => $record['first_name'],
                        'last_name' => $record['last_name'],
                        'email' => $record['email'],
                        'vacancy' =>$record['name'],
                        'points' =>$record['points'],
                        'last_date' =>$record['last_date'],
                        'status' => $record['status'],
                        'type' => $record['type'],
                        // 'file' => $this->url()->fromRoute('storage', ['type' => 'recruitment_selection', 'code' => $record['uuid'], 'filename' => $record['file']]),
                        'actions' => [
                            'link_edit' => $allowEdit ? $link_edit : '',
                            'link_delete' => $allowDelete ? $link_delete : '',
                            'link_report' => $allowReport ? $link_report : '',
                            'link_file' => $allowFile ? $link_file : '',
                        ]
                    ];

                    if($record['type'] == 'r'){
                        $item['actions']['link_file'] = $allowFile ? $link_file : '';
                    } else{
                        $item['actions']['link_file'] = null;
                    }

                    array_push($items, $item);
                }

                return new JsonModel([
                    'success' => true,
                    'data' => [
                        'items' => $items,
                        'total' => $paginator->getTotalItemCount()
                    ],
                ]);
            } else {
                $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
                $vacancies = $vacancyMapper->fetchAllByCompanyId($currentCompany->id);

                $form = new RecruitmentSelectionInterviewFormForm($this->adapter, $currentCompany ? $currentCompany->id : null);
                $formFile = new InterviewFileForm($this->adapter, $currentCompany ? $currentCompany->id : null);

                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/recruitment-and-selection-interview/index.phtml');
                $viewModel->setVariables([
                    'form'      => $form,
                    'vacancies' => $vacancies,
                    'formFile' => $formFile
                ]);

                return $viewModel ;
            }

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

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

        $request = $this->getRequest();
        $vacancy_uuid = $this->params()->fromRoute('vacancy_uuid');

        if ($request->isPost()) {
            $dataPost = $request->getPost()->toArray();
            $dataPost['vacancy_uuid'] = $vacancy_uuid;

            $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
            $vacancy = $vacancyMapper->fetchOneByUuid($vacancy_uuid);

            $candidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
            $candidate = $candidateMapper->fetchOneByUuid($dataPost['candidate_uuid']);

            $form = new RecruitmentSelectionInterviewFormForm($this->adapter, $currentCompany->id, $vacancy->id);

            $dataPost['status'] = isset($dataPost['status']) ? $dataPost['status'] : RecruitmentSelectionInterview::STATUS_REJECTED;
            $dataPost['type'] = RecruitmentSelectionInterview::STATUS_HUMAN_RESOURCE;

            $form->setData($dataPost);

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

                $hydrator = new ObjectPropertyHydrator();
                $recruitmentSelectionInterview = new RecruitmentSelectionInterview();
                $hydrator->hydrate($dataPost, $recruitmentSelectionInterview);

                if (!$recruitmentSelectionInterview->status) {
                    $recruitmentSelectionInterview->status = RecruitmentSelectionInterview::STATUS_REJECTED;
                }

                $recruitmentSelectionInterview->company_id = $currentCompany->id;
                $recruitmentSelectionInterview->vacancy_id = $vacancy->id;
                $recruitmentSelectionInterview->candidate_id = $candidate->id;
                $recruitmentSelectionInterview->user_id = $currentUser->id;

                $recruitmentSelectionInterviewMapper = RecruitmentSelectionInterviewMapper::getInstance($this->adapter);
                
                $interviews = $recruitmentSelectionInterviewMapper->fetchAllByCandidateIdAndVacancyId($candidate->id, $vacancy->id);

                if (count($interviews) > 0) {
                    $hasHumanResourcesInterview = false;

                    foreach($interviews as $interview) {
                        if ($interview->type === RecruitmentSelectionInterview::STATUS_HUMAN_RESOURCE) {
                            $hasHumanResourcesInterview = true;
                        }
                        if ($interview->type === RecruitmentSelectionInterview::STATUS_BOSS){
                            return new JsonModel([
                                'success' => false,
                                'data' => 'LABEL_BOSS_DONE'
                            ]); 
                        }
                    }

                    $recruitmentSelectionInterview->type = $hasHumanResourcesInterview
                        ? RecruitmentSelectionInterview::STATUS_BOSS
                        : RecruitmentSelectionInterview::STATUS_HUMAN_RESOURCE;
                }

                $result = $recruitmentSelectionInterviewMapper->insert($recruitmentSelectionInterview);
            

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

                    // Get record by id
                    $recruitmentSelectionInterviewMapper = RecruitmentSelectionInterviewMapper::getInstance($this->adapter);
                    $record = $recruitmentSelectionInterviewMapper->fetchOne($recruitmentSelectionInterview->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' => $recruitmentSelectionInterviewMapper->getError()
                    ];
                }

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

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

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

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

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

        $request = $this->getRequest();

        $vacancy_uuid = $this->params()->fromRoute('vacancy_uuid');

        if ($request->isGet()) {
            $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
            $vacancy = $vacancyMapper->fetchOneByUuid($vacancy_uuid);

            $jobDescriptionMapper = JobDescriptionMapper::getInstance($this->adapter);
            $jobDescription = $jobDescriptionMapper->fetchOne($vacancy->job_description_id);

            $jobDescriptionCompetencyMapper = JobDescriptionCompetencyMapper::getInstance($this->adapter);
            $jobDescriptionCompetencies = $jobDescriptionCompetencyMapper->fetchByJobDescriptionId($jobDescription->id);

            $candidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
            $activeCandidates = $candidateMapper->fetchAllActive($vacancy->id);

            $competencyTypeMapper = CompetencyTypeMapper::getInstance($this->adapter);
            $competencyMapper = CompetencyMapper::getInstance($this->adapter);
            $competencyBehaviorMapper = CompetencyBehaviorMapper::getInstance($this->adapter);
            $behaviorMapper = BehaviorMapper::getInstance($this->adapter);
    
            $data = [
                'candidates' => $activeCandidates,
                'job_description' => [
                    'uuid' => $jobDescription->uuid,
                    'name' => $jobDescription->name,
                    'functions' => $jobDescription->functions,
                    'objectives' => $jobDescription->objectives,
                    'competencies' => []
                ],
                'interview' => [
                    'type' => RecruitmentSelectionInterview::STATUS_HUMAN_RESOURCE,
                    'status' => RecruitmentSelectionInterview::STATUS_ACCEPTED,
                    'points' => 0,
                    'comment' => '',
                ],
                'vacancy' => $vacancy,
            ];

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

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

        $request = $this->getRequest();

        $candidate_uuid = $this->params()->fromRoute('candidate_uuid');

        if(!$request->isGet()){
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED',
            ]);            
        }

        $candidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
        $candidate = $candidateMapper->fetchOneByUuid($candidate_uuid);

        $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
        $vacancy = $vacancyMapper->fetchOne($candidate->vacancy_id);

        $recruitmentSelectionInterviewMapper = RecruitmentSelectionInterviewMapper::getInstance($this->adapter);      
        $interviews = $recruitmentSelectionInterviewMapper->fetchAllByCandidateIdAndVacancyId($candidate->id, $vacancy->id);
        if (count($interviews) === 2){
            return new JsonModel([
                'success' => true,
                'data' => 'Este candidato completo su ciclo de entrevistas'
            ]);
        } else if(count($interviews) === 1){
           return new JsonModel([
               'success' => true,
               'data' => 'Entrevista por el Jefe' ,
           ]);
        } else{
            return new JsonModel([
                'success' => true,
                'data' =>  'Entrevista por Recursos Humanos',
            ]);
        }
        
    }

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

        $request = $this->getRequest();
        $interview_uuid = $this->params()->fromRoute('interview_uuid');

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

            return new JsonModel($data);
        }

        $recruitmentSelectionInterviewMapper = RecruitmentSelectionInterviewMapper::getInstance($this->adapter);
        $interview = $recruitmentSelectionInterviewMapper->fetchOneByUuid($interview_uuid);

        $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
        $vacancy = $vacancyMapper->fetchOne($interview->vacancy_id);

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

           return new JsonModel($data);
        }

        if ($interview->company_id != $currentCompany->id) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }

        if ($request->isPost()) {
            $form = new RecruitmentSelectionInterviewFormForm($this->adapter, $currentCompany->id, $vacancy->id);
            $dataPost = $request->getPost()->toArray();
            $dataPost['vacancy_uuid'] = $vacancy->uuid;
            $dataPost['status'] = isset($dataPost['status']) ? $dataPost['status'] : RecruitmentSelectionInterview::STATUS_REJECTED;
            $dataPost['type'] = $interview->type;

            $form->setData($dataPost);

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

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

                if (!$interview->status) {
                    $interview->status = RecruitmentSelectionInterview::STATUS_REJECTED;
                }

                $candidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
                $candidate = $candidateMapper->fetchOneByUuid($dataPost['candidate_uuid']);

                $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
                $vacancy = $vacancyMapper->fetchOneByUuid($dataPost['vacancy_uuid']);

                $interview->company_id = $currentCompany->id;
                $interview->vacancy_id = $vacancy->id;
                $interview->candidate_id = $candidate->id;
                $interview->user_id = $currentUser->id;

                $result = $recruitmentSelectionInterviewMapper->update($interview);


                if ($result) {
                    $this->logger->info('Se edito correctamente la entrevista' . $interview->id, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    $data = [
                        'success' => true,
                        'data' => 'LABEL_RECORD_UPDATED'
                    ];
                } else {
                    $data = [
                        'success' => false,
                        'data' => $recruitmentSelectionInterviewMapper->getError()
                    ];
                }

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

                return new JsonModel([
                    'success' => false,
                    'data' => $messages
                ]);
            }
        } else if ($request->isGet()) {
            $hydrator = new ObjectPropertyHydrator();

            $candidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
            $candidate = $candidateMapper->fetchOne($interview->candidate_id);

            $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
            $vacancy = $vacancyMapper->fetchOne($candidate->vacancy_id);

            $jobDescriptionMapper = JobDescriptionMapper::getInstance($this->adapter);
            $jobDescription = $jobDescriptionMapper->fetchOne($vacancy->job_description_id);

            $jobDescriptionCompetencyMapper = JobDescriptionCompetencyMapper::getInstance($this->adapter);
            $jobDescriptionCompetencies = $jobDescriptionCompetencyMapper->fetchByJobDescriptionId($jobDescription->id);

            $competencyTypeMapper = CompetencyTypeMapper::getInstance($this->adapter);
            $competencyMapper = CompetencyMapper::getInstance($this->adapter);
            $competencyBehaviorMapper = CompetencyBehaviorMapper::getInstance($this->adapter);
            $behaviorMapper = BehaviorMapper::getInstance($this->adapter);

            $data = [
                'candidate' => [
                    'uuid' => $candidate->uuid,
                    'first_name' => $candidate->first_name,
                    'last_name' => $candidate->last_name,
                    'email' => $candidate->email
                ],
                'job_description' => [
                    'uuid' => $jobDescription->uuid,
                    'name' => $jobDescription->name,
                    'functions' => $jobDescription->functions,
                    'objectives' => $jobDescription->objectives,
                    'competencies' => []
                ],
                'interview' => [
                    'id' => $interview->uuid,
                    'status' => $interview->status,
                    'content' => $interview->content ? json_decode($interview->content) : [],
                    'type' => $interview->type,
                    'status' => $interview->status,
                    'points' => $interview->points,
                    'comment' => $interview->comment,
                ],
                'vacancy' => $vacancy,
            ];

            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 {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

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

        $request = $this->getRequest();
        $uuid = $this->params()->fromRoute('interview_uuid');

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

            return new JsonModel($data);
        }

        $recruitmentSelectionInterviewMapper = RecruitmentSelectionInterviewMapper::getInstance($this->adapter);
        $recruitmentSelectionInterview = $recruitmentSelectionInterviewMapper->fetchOneByUuid($uuid);
        if (!$recruitmentSelectionInterview) {
            $data = [
                'success' => false,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ];

            return new JsonModel($data);
        }

        if ($recruitmentSelectionInterview->company_id != $currentCompany->id) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }

        if ($request->isPost()) {

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

                $data = [
                    'success' => true,
                    'data' => 'LABEL_RECORD_DELETED'
                ];
            } else {

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

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

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

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

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

        $recruitmentSelectionInterviewMapper = RecruitmentSelectionInterviewMapper::getInstance($this->adapter);
        $recruitmentSelectionInterview = $recruitmentSelectionInterviewMapper->fetchOneByUuid($uuid);

        $recruitmentSelectionVacancyMapper = RecruitmentSelectionvacancyMapper::getInstance($this->adapter);
        $recruitmentSelectionVacancy = $recruitmentSelectionVacancyMapper->fetchOne($recruitmentSelectionInterview->vacancy_id);


        if (!$recruitmentSelectionInterview) {
            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($recruitmentSelectionVacancy->job_description_id);

            $content = json_decode($recruitmentSelectionInterview->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($recruitmentSelectionVacancy->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->renderPDF($currentCompany, $recruitmentSelectionInterview, $competencies);
        }

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

    /**
     * Render PDF
     * @param Company $currentCompany
     * @param recruitmentSelectionInterview $interviewEvaluation
     * @param array $competencies
     * @return mixed
     */
    public function renderPDF($company, $interviewEvaluation, $competencies) {

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

        //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();

        $recruitmentSelectionCandidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
        $recruitmentSelectionVacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
        $vacancy = $recruitmentSelectionVacancyMapper->fetchOne($interviewEvaluation->vacancy_id);
        $candidate = $recruitmentSelectionCandidateMapper->fetchOne($interviewEvaluation->candidate_id);

        switch ($interviewEvaluation->type) {
            case "r":
                $type = "Recursos Humanos";
                break;
            case "b":
                $type = "Jefe";
                break;
            default :
                $type = "ERROR";
                break;
        }

        switch ($interviewEvaluation->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' => $candidate ? ' ' . $candidate->first_name . ' ' . $candidate->last_name : 'No Aplica'
            ),
            array(
                'title' => 'Cargo: ',
                'content' => $vacancy ? ' ' . $vacancy->name : ' No aplica'
            ),
            array(
                'title' => 'Entrevistado por: ',
                'content' => $currentUser ? ' ' . $currentUser->first_name . ' ' . $currentUser->last_name : ' No Aplica '
            ),
            array(
                'title' => 'Estatus del candidato: ',
                'content' => $type
            ),
            array(
                'title' => 'Comentarios del entrevistador: ',
                'content' => $interviewEvaluation ? ' ' . $interviewEvaluation->comment : 'No Aplica'
            ),
            array(
                'title' => 'Porcentage de adaptibilidad ',
                'content' => $points
            )
        ];

        $pdf->borderTable('DATOS DE LA ENTREVISTA', $rows);
          
        $sections = json_decode($interviewEvaluation->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();
           
    }
}