Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17002 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php

/**
 * 
 * Controlador: Mis Perfiles 
 * 
 */

declare(strict_types=1);

namespace LeadersLinked\Controller;

use Laminas\Db\Adapter\AdapterInterface;

use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Log\LoggerInterface;
use Laminas\View\Model\ViewModel;
use Laminas\View\Model\JsonModel;

use LeadersLinked\Library\Functions;
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
use LeadersLinked\Library\Image;

use LeadersLinked\Mapper\CompanyLocationMapper;
use LeadersLinked\Form\CompanyProfile\ProfileSocialNetworkForm;
use LeadersLinked\Form\CompanyProfile\ProfileLocationForm;
use LeadersLinked\Form\CompanyProfile\ProfileExtendedForm;
use LeadersLinked\Form\CompanyProfile\ProfileImageForm;
use LeadersLinked\Form\CompanyProfile\ProfileCoverForm;
use LeadersLinked\Form\CompanyProfile\ProfileHeaderForm;
use LeadersLinked\Form\CompanyProfile\ProfileFooterForm;

use LeadersLinked\Form\CompanyProfile\ProfileIndustryForm;
use LeadersLinked\Form\CompanyProfile\ProfileCompanySizeForm;
use LeadersLinked\Form\CompanyProfile\ProfileFoundationYearForm;
use LeadersLinked\Form\CompanyProfile\ProfileWebsiteForm;
use LeadersLinked\Model\Location;
use LeadersLinked\Model\CompanyLocation;
use LeadersLinked\Model\CompanyUser;

use LeadersLinked\Mapper\LocationMapper;
use LeadersLinked\Mapper\CompanyFollowerMapper;
use LeadersLinked\Mapper\CompanyUserMapper;
use LeadersLinked\Mapper\CompanyMapper;
use LeadersLinked\Mapper\IndustryMapper;
use LeadersLinked\Mapper\CompanySizeMapper;
use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Library\Storage;

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



    /**
     * Presenta el perfil con las opciónes de edición de cada sección
     * @return \Laminas\Http\Response|\Laminas\View\Model\ViewModel|\Laminas\View\Model\JsonModel
     */
    public function indexAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $currentCompany = $currentUserPlugin->getCompany();


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

            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
            if ($sandbox) {
                $google_map_key  = $this->config['leaderslinked.google_map.sandbox_api_key'];
            } else {
                $google_map_key  = $this->config['leaderslinked.google_map.production_api_key'];
            }

            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOne($currentCompany->id);


            $companyLocationMapper = CompanyLocationMapper::getInstance($this->adapter);
            $records = $companyLocationMapper->fetchAllLocationByCompanyId($company->id);




            $locations = [];
            foreach ($records as $record) {
                $location =  [
                    'formatted_address'  => $record['formatted_address'],
                    'country' => $record['country'],
                    'is_main' => $record['is_main'],
                    'link_edit' => $this->url()->fromRoute('profile/location', ['operation' => 'edit', 'id' =>  $record['company_location_uuid']]),
                    'link_delete' => $this->url()->fromRoute('profile/location', ['operation' => 'delete', 'id' => $record['company_location_uuid']])

                ];

                array_push($locations, $location);
            }

            $industryMapper = IndustryMapper::getInstance($this->adapter);
            $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);

            $formSocialNetwork = new ProfileSocialNetworkForm();
            $formLocation = new ProfileLocationForm();
            $formExtended = new ProfileExtendedForm();
            $formFoundationYear = new ProfileFoundationYearForm();
            $formWebsite = new ProfileWebsiteForm();
            $formImage = new ProfileImageForm($this->config);
            $formCover = new ProfileCoverForm($this->config);
            $formHeader = new ProfileHeaderForm($this->config);
            $formFooter = new ProfileFooterForm($this->config);



            $formCompanySize = new ProfileCompanySizeForm($this->adapter);
            $formIndustry = new ProfileIndustryForm($this->adapter);

            $companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);
            $follower = $companyFollowerMapper->getCountFollowers($currentCompany->id);

            $image_size_cover = $this->config['leaderslinked.image_sizes.company_cover_upload'];
            $image_size_profile = $this->config['leaderslinked.image_sizes.company_image_upload'];
            $image_size_header = $this->config['leaderslinked.image_sizes.company_header_pdf_upload'];
            $image_size_footer = $this->config['leaderslinked.image_sizes.company_footer_pdf_upload'];


            $industry = $industryMapper->fetchOne($company->industry_id);
            $companySize = $companySizeMapper->fetchOne($company->company_size_id);


            $this->layout()->setTemplate('layout/layout-backend');
            $viewModel = new ViewModel();
            $viewModel->setTemplate('leaders-linked/profile/index.phtml');
            $viewModel->setVariables([
                'google_map_key'        => $google_map_key,
                'follower'              => $follower,
                'company_id'            => $currentCompany->id,
                'company_name'          => $company->name,
                'company_uuid'          => $company->uuid,
                'name'                  => trim($company->name),
                'image'                 => $company->image,
                'cover'                 => $company->cover,
                'header'                 => $company->header,
                'footer'                 => $company->footer,
                'overview'              => strip_tags($company->description, 'p'),
                'website'               => $company->website,
                'foundation_year'       => $company->foundation_year,
                'facebook'              => $company->facebook,
                'instagram'             => $company->instagram,
                'twitter'               => $company->twitter,
                'locations'             => $locations,
                'industry'              => $industry->name,
                'company_size'          => $companySize->name . ' (' . $companySize->minimum_no_of_employee . '-' . $companySize->maximum_no_of_employee . ')',
                'formLocation'          => $formLocation,
                'formSocialNetwork'     => $formSocialNetwork,
                'formExtended'          => $formExtended,
                'formImage'             => $formImage,
                'formCover'             => $formCover,
                'formHeader'             => $formHeader,
                'formFooter'             => $formFooter,
                'formFoundationYear'    => $formFoundationYear,
                'formWebsite'           => $formWebsite,
                'formIndustry'          => $formIndustry,
                'formCompanySize'       => $formCompanySize,
                'image_size_cover'      => $image_size_cover,
                'image_size_profile'    => $image_size_profile,
                'image_size_header'    => $image_size_header,
                'image_size_footer'    => $image_size_footer,
            ]);
            return $viewModel;
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }


    /**
     *
     * Borrar un perfil excepto el público
     * @return \Laminas\View\Model\JsonModel
     */
    public function deleteAction()
    {

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

        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $currentUser->id);

        if (!$companyUser || $companyUser->type != CompanyUser::CREATOR_YES) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }


        if ($request->isPost()) {
            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $result = $companyMapper->delete($companyUser->id);
            if ($result) {
                $this->logger->info('Se borro la empresa : ' .  $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

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

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

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

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }



    /**
     * Actualización de la descripción y cualquier otro campo extendido del perfil a futuro
     * @return \Laminas\View\Model\JsonModel
     */
    public function extendedAction()
    {

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

        $request = $this->getRequest();
        if ($request->isGet()) {
            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOne($currentCompany->id);

            $data = [
                'success' => true,
                'data' => [
                    'description' => $company->description,
                ]
            ];

            return new JsonModel($data);
        } else if ($request->isPost()) {
            $form = new ProfileExtendedForm();
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);

            if ($form->isValid()) {
                $companyMapper = CompanyMapper::getInstance($this->adapter);
                $company = $companyMapper->fetchOne($currentCompany->id);

                $dataPost = (array) $form->getData();

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

                $companyMapper->updateExtended($company);

                $this->logger->info('Se actualizo las descripción de la empresa ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                return new JsonModel([
                    'success'   => true,
                    'data' => [
                        'description' => strip_tags($company->description, 'p')
                    ]
                ]);
            } 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
                ]);
            }
        }


        $data = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];


        return new JsonModel($data);
    }

    /**
     * Actualización de la descripción y cualquier otro campo extendido del perfil a futuro
     * @return \Laminas\View\Model\JsonModel
     */
    public function websiteAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $currentCompany = $currentUserPlugin->getCompany();

        $request = $this->getRequest();
        if ($request->isGet()) {
            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOne($currentCompany->id);

            $data = [
                'success' => true,
                'data' => [
                    'website' => $company->website,
                ]
            ];

            return new JsonModel($data);
        } else if ($request->isPost()) {


            $form = new ProfileWebsiteForm();
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);

            if ($form->isValid()) {
                $companyMapper = CompanyMapper::getInstance($this->adapter);
                $company = $companyMapper->fetchOne($currentCompany->id);

                $dataPost = (array) $form->getData();

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

                $companyMapper->updateWebsite($company);

                $this->logger->info('Se actualizo el website de la empresa ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

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


        $data = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];


        return new JsonModel($data);
    }

    /**
     * Actualización de la descripción y cualquier otro campo extendido del perfil a futuro
     * @return \Laminas\View\Model\JsonModel
     */
    public function foundationYearAction()
    {

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



        $request = $this->getRequest();
        if ($request->isGet()) {
            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOne($currentCompany->id);

            $data = [
                'success' => true,
                'data' => [
                    'foundation_year' => $company->foundation_year,
                ]

            ];

            return new JsonModel($data);
        } else if ($request->isPost()) {


            $form = new ProfileFoundationYearForm();
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);

            if ($form->isValid()) {
                $companyMapper = CompanyMapper::getInstance($this->adapter);
                $company = $companyMapper->fetchOne($currentCompany->id);

                $dataPost = (array) $form->getData();

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

                $companyMapper->updateFoundationYear($company);

                $this->logger->info('Se actualizo el año de fundación de la empresa ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

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


        $data = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];


        return new JsonModel($data);
    }


    /**
     * Actualización de la ubucación
     * @return \Laminas\View\Model\JsonModel
     */
    public function locationAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $currentCompany = $currentUserPlugin->getCompany();

        $operation = $this->params()->fromRoute('operation');
        if ($operation == 'edit' || $operation == 'delete') {
            $id = $this->params()->fromRoute('id');
            if (!$id) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_INVALID_PARAMETER'
                ];

                return new JsonModel($response);
            }
        } else {
            $id = '';
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOne($currentCompany->id);

            $companyLocationMapper = CompanyLocationMapper::getInstance($this->adapter);


            $companyLocation = null;
            if ($id) {
                $companyLocation = $companyLocationMapper->fetchOneByUuid($id);
                if (!$companyLocation) {
                    $response = [
                        'success' => false,
                        'data' => 'ERROR_RECORD_NOT_FOUND'
                    ];

                    return new JsonModel($response);
                }

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

            $locationMapper = LocationMapper::getInstance($this->adapter);
            $response = [];



            if ($operation == 'delete' && $companyLocation) {

                if ($companyLocationMapper->delete($companyLocation->id)) {
                    $this->logger->info('Se borrar una ubicación de la empresa: ' . $company->name, ['user_id' => $currentUser->id,  'ip' => Functions::getUserIP()]);
                    $locationMapper->delete($companyLocation->location_id);
                } else {
                    $response = [
                        'success'   => false,
                        'data' => 'ERROR_THERE_WAS_AN_ERROR'
                    ];
                }
            } else {
                $form = new ProfileLocationForm();
                $dataPost = $request->getPost()->toArray();


                $dataPost['is_main'] = isset($dataPost['is_main']) ? $dataPost['is_main'] : CompanyLocation::IS_MAIN_NO;


                $form->setData($dataPost);

                if ($form->isValid()) {

                    if ($operation == 'edit') {
                        $location = $locationMapper->fetchOne($companyLocation->location_id);
                    } else {
                        $location = new Location();
                    }

                    $dataPost = (array) $form->getData();
                    $hydrator = new ObjectPropertyHydrator();
                    $hydrator->hydrate($dataPost, $location);

                    if ($operation == 'edit') {


                        $companyLocation->is_main = $dataPost['is_main'];
                        $companyLocationMapper->update($companyLocation);


                        $location = $locationMapper->update($location);
                        $this->logger->info('Se actualizo una ubicación de la empresa: ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    } else {

                        $result = $locationMapper->insert($location);

                        if ($result) {
                            $companyLocation = new CompanyLocation();
                            $companyLocation->company_id = $currentCompany->id;
                            $companyLocation->location_id = $location->id;
                            $companyLocation->is_main = $dataPost['is_main'];

                            $companyLocationMapper->insert($companyLocation);
                            $this->logger->info('Se agrego una ubicación a la empresa: ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                        } else {
                            $response = [
                                'success'   => false,
                                'data' => 'ERROR_THERE_WAS_AN_ERROR'
                            ];
                        }
                    }
                } else {
                    return new JsonModel([
                        'success'   => false,
                        'data'   =>   'ERROR_PLACED_AUTOCOMPLETE_DOES_NOT_CONTAIN_GEOMETRY'
                    ]);
                }
            }

            if (!$response) {
                $records = $companyLocationMapper->fetchAllLocationByCompanyId($currentCompany->id);


                $locations = [];
                foreach ($records as $record) {
                    $location =  [
                        'formatted_address'  => $record['formatted_address'],
                        'country' => $record['country'],
                        'is_main' => $record['is_main'],
                        'link_edit' => $this->url()->fromRoute('profile/location', ['id' => $record['company_location_uuid'], 'operation' => 'edit']),
                        'link_delete' => $this->url()->fromRoute('profile/location', ['id' => $record['company_location_uuid'], 'operation' => 'delete'])

                    ];

                    array_push($locations, $location);
                }

                $response = [
                    'success' => true,
                    'data' => $locations
                ];
            }

            return new JsonModel($response);
        } else if ($request->isGet() && $operation == 'edit') {



            $companyLocationMapper = CompanyLocationMapper::getInstance($this->adapter);
            $companyLocation = $companyLocationMapper->fetchOneByUuid($id);



            if (!$companyLocation) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_RECORD_NOT_FOUND'
                ];

                return new JsonModel($response);
            }

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

            $locationMapper = LocationMapper::getInstance($this->adapter);
            $location = $locationMapper->fetchOne($companyLocation->location_id);

            $hydrator = new ObjectPropertyHydrator();
            $data = $hydrator->extract($location);

            $data['is_main'] = $companyLocation->is_main;

            $response = [
                'success' => true,
                'data' =>  $data
            ];

            return new JsonModel($response);
        }

        $response = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];


        return new JsonModel($response);
    }

    /**
     * Actualización de las redes sociales
     * @return \Laminas\View\Model\JsonModel
     */
    public function socialNetworkAction()
    {


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



        $request = $this->getRequest();
        if ($request->isGet()) {
            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOne($currentCompany->id);

            $data = [
                'success' => true,
                'data' => [
                    'facebook' => $company->facebook,
                    'instagram' => $company->instagram,
                    'twitter' => $company->twitter
                ]
            ];

            return new JsonModel($data);
        } else if ($request->isPost()) {

            $form = new ProfileSocialNetworkForm();
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);

            if ($form->isValid()) {
                $companyMapper = CompanyMapper::getInstance($this->adapter);
                $company = $companyMapper->fetchOne($currentCompany->id);

                $this->logger->info('Se actualizaron las redes sociales de la empresa: ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                $dataPost = (array) $form->getData();

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

                $companyMapper->updateSocialNetwork($company);
                return new JsonModel([
                    'success'   => true,
                    'data' => [
                        'facebook' => $company->facebook,
                        'instagram' => $company->instagram,
                        'twitter' => $company->twitter
                    ]
                ]);
            } 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
                ]);
            }
        }


        $data = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];


        return new JsonModel($data);
    }



    /**
     * Cambio de la imagen del image del perfil
     * @return \Laminas\View\Model\JsonModel
     */
    public function imageAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $currentCompany = $currentUserPlugin->getCompany();

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





        $request = $this->getRequest();
        if ($request->isPost()) {
            $image = Image::getInstance($this->config);
            $target_company_path = $image->getStorage()->getPathCompany();
            $target_user_path = $image->getStorage()->getPathUser();
            
            
            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOne($currentCompany->id);

        
            
            if ($operation == 'delete') {
                $this->logger->info('Se borro la imagen de la empresa: ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                if ($company->image) {

                    if (!$image->getStorage()->deleteFile($target_company_path, $company->uuid, $company->image)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }
                }

                $company->image = '';
                if (!$companyMapper->updateImage($company)) {
                    return new JsonModel([
                        'success'   => false,
                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                    ]);
                }
                
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
                $companyUser = $companyUserMapper->fetchOwnerByCompanyId($company->id);
                
                if($companyUser) {
                    $userMapper = UserMapper::getInstance($this->adapter);
                    $user = $userMapper->fetchOne($companyUser->user_id);
                    if($user) {

                        if($user->image) {
                            $image->getStorage()->deleteFile($target_user_path, $user->uuid, $user->image);
                        }
                        
                        
                        
                        $user->image = '';
                        $userMapper->updateImage($user);
                        
                        if($company->name != $user->first_name) {
                            $user->first_name = $company->name;
                            $user->last_name = '';
                            $userMapper->updateFirstNameAndLastName($user);
                        }
                    }
                }
                
                
            } else {
                $form = new ProfileImageForm($this->config);
                $data     = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());

                $form->setData($data);

                if ($form->isValid()) {

                    $files = $request->getFiles()->toArray();
                    if (!empty($files['image']['error'])) {

                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_UPLOAD_FILE'
                        ]);
                    }
                    
                    $image = Image::getInstance($this->config);
                    $target_company_path = $image->getStorage()->getPathCompany();
                    $target_user_path = $image->getStorage()->getPathUser();


                    if ($company->image) {

                        if (!$image->getStorage()->deleteFile($target_company_path, $company->uuid, $company->image)) {
                            return new JsonModel([
                                'success'   => false,
                                'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                            ]);
                        }
                    }

                    list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.company_image_size']);
                    $source             = $files['image']['tmp_name'];
                    $target_filename    = 'company-image-' . uniqid() . '.png';
                    $crop_to_dimensions = true;
                    $unlink_source = false;

                    if(!$image->uploadProcessChangeSize($source, $target_company_path, $company->uuid, $target_filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }


                    $company->image = $target_filename;
                    if (!$companyMapper->updateImage($company)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }
                    
                    $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
                    $companyUser = $companyUserMapper->fetchOwnerByCompanyId($company->id);
                    
                    if($companyUser) {
                        $userMapper = UserMapper::getInstance($this->adapter);
                        $user = $userMapper->fetchOne($companyUser->user_id);
                        if($user) {
     
                            if($user->image) {
                                $image->getStorage()->deleteFile($target_user_path, $user->uuid, $user->image);
                            }
                            
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.user_image_size']);
                            $source             = $files['image']['tmp_name'];
                            $target_filename    = 'user-image-' . uniqid() . '.png';
                            $crop_to_dimensions = true;
                            $unlink_source = true;
                            
                            if(!$image->uploadProcessChangeSize($source, $target_company_path, $company->uuid, $target_filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
                                return new JsonModel([
                                    'success'   => false,
                                    'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                                ]);
                            }
                            
                            
                            
                            $user->image = $target_filename;
                            if(!$userMapper->updateImage($user)) {
                                return new JsonModel([
                                    'success'   => false,
                                    'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                                ]);
                                
                            }
                            
                            if($company->name != $user->first_name) {
                                $user->first_name = $company->name;
                                $user->last_name = '';
                                $userMapper->updateFirstNameAndLastName($user);
                            }
                        }
                    }
                    

                    $this->logger->info('Se actualizo la imagen de la empresa: ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                } 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
                    ]);
                }
            }
            
            $storage = Storage::getInstance($this->config, $this->adapter);
            
            return new JsonModel([
                'success'   => true,
                'data' => $storage->getCompanyImage($company->uuid)

            ]);
        }


        $data = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];


        return new JsonModel($data);
    }

    /**
     * Cambio de la imagen de fondo superior (cover) del perfil 
     * @return \Laminas\View\Model\JsonModel
     */
    public function coverAction()
    {
        $operation          = $this->params()->fromRoute('operation');


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




        $request = $this->getRequest();
        if ($request->isPost()) {
            
            $image = Image::getInstance($this->config);
            $target_path = $image->getStorage()->getPathCompany();

            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOne($currentCompany->id);

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


            

            if ($operation == 'delete') {
                if ($company->cover) {

                    if (!$image->getStorage()->deleteFile($target_path, $company->uuid, $company->cover)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }
                }

                $this->logger->info('Se borro el cover de la empresa ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                $company->cover = '';
                if (!$companyMapper->updateCover($company)) {
                    return new JsonModel([
                        'success'   => false,
                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                    ]);
                }
            } else {
                $form = new ProfileCoverForm($this->config);
                $data     = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());

                $form->setData($data);

                if ($form->isValid()) {


                    $files = $request->getFiles()->toArray();
                    if (!empty($files['cover']['error'])) {

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

                    if ($company->cover) {

                        if (!Image::delete($target_path, $company->cover)) {
                            return new JsonModel([
                                'success'   => false,
                                'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                            ]);
                        }
                    }

                    list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.company_cover_size']);
                    $source             = $files['cover']['tmp_name'];
                    $target_filename    = 'company-cover-' . uniqid() . '.png';
                    $crop_to_dimensions = false;
                    $unlink_source = true;
                    
                    if($image->uploadProcessChangeSize($source, $target_path, $company->uuid, $target_filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }


                    $company->cover = $target_filename;
                    if (!$companyMapper->updateCover($company)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }




                    $this->logger->info('Se actualizo el cover  de la empresa ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                } 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
                    ]);
                }
            }
            
            $storage = Storage::getInstance($this->config, $this->adapter);
            
            
            return new JsonModel([
                'success'   => true,
                'data' => $storage->getCompanyCover($company)

            ]);
        }


        $data = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];


        return new JsonModel($data);
    }



    /**
     * Cambio de la imagen de de la cabecera de los reportes 
     * @return \Laminas\View\Model\JsonModel
     */
    public function headerAction()
    {
        $operation = $this->params()->fromRoute('operation');


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




        $request = $this->getRequest();
        if ($request->isPost()) {

            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOne($currentCompany->id);

            $image = Image::getInstance($this->config);
            $target_path = $image->getStorage()->getPathCompany();



            if ($operation == 'delete') {
                if ($company->header) {

                    if (!$image->getStorage()->deleteFile($target_path, $company->uuid, $company->header)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }
                }

                $this->logger->info('Se borro el header  de la empresa ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                $company->header = '';
                if (!$companyMapper->updateHeader($company)) {
                    return new JsonModel([
                        'success'   => false,
                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                    ]);
                }
            } else {
                $form = new ProfileHeaderForm($this->config);
                $data   = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());

                $form->setData($data);

                if ($form->isValid()) {


                    $files = $request->getFiles()->toArray();
                    if (!empty($files['header']['error'])) {

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

                    if ($company->header) {

                        if (!$image->getStorage()->deleteFile($target_path, $company->uuid, $company->header)) {
                            return new JsonModel([
                                'success'   => false,
                                'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                            ]);
                        }
                    }

                    list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.company_header_pdf_size']);
                    $source             = $files['header']['tmp_name'];
                    $target_filename    = 'company-header-' . uniqid() . '.png';
                    $crop_to_dimensions = false;
                    $unlink_source = true;
                    
                    if($image->uploadProcessChangeSize($source, $target_path, $company->uuid, $target_filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }


                    $company->header = $target_filename;
                    if (!$companyMapper->updateHeader($company)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }


                    $this->logger->info('Se actualizo el header  de la empresa ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                } 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
                    ]);
                }
            }
            
            $storage = Storage::getInstance($this->config, $this->adapter);
            $path = $storage->getPathCompany();
            
            return new JsonModel([
                'success'   => true,
                'data' => $company->header ? $storage->getGenericImage($path, $company->uuid, $company->header) : '',

            ]);
        }


        $data = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];


        return new JsonModel($data);
    }


    /**
     * Cambio de la imagen de de la cabecera de los reportes 
     * @return \Laminas\View\Model\JsonModel
     */
    public function footerAction()
    {
        $operation          = $this->params()->fromRoute('operation');


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




        $request = $this->getRequest();
        if ($request->isPost()) {

            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOne($currentCompany->id);

            $image = Image::getInstance($this->config);
            $target_path = $image->getStorage()->getPathCompany();



            if ($operation == 'delete') {
                if ($company->footer) {

                    if (!$image->getStorage()->deleteFile($target_path, $company->uuid, $company->footer)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }
                }

                $this->logger->info('Se borro el footer  de la empresa ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                $company->footer = '';
                if (!$companyMapper->updateFooter($company)) {
                    return new JsonModel([
                        'success'   => false,
                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                    ]);
                }
            } else {
                $form = new ProfileFooterForm($this->config);
                $data   = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());

                $form->setData($data);

                if ($form->isValid()) {


                    $files = $request->getFiles()->toArray();
                    if (!empty($files['footer']['error'])) {

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

                    if ($company->footer) {

                        if (!$image->getStorage()->deleteFile($target_path, $company->uuid, $company->footer)) {
                            return new JsonModel([
                                'success'   => false,
                                'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                            ]);
                        }
                    }

                    list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.company_footer_pdf_size']);
                    $source             = $files['footer']['tmp_name'];
                    $target_filename    = 'company-footer-' . uniqid() . '.png';
                    $crop_to_dimensions = false;
                    $unlink_source = true;
                    
                    if($image->uploadProcessChangeSize($source, $target_path, $company->uuid, $target_filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) { 
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }


                    $company->footer = $target_filename;
                    if (!$companyMapper->updateFooter($company)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }




                    $this->logger->info('Se actualizo el footer  de la empresa ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                } 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
                    ]);
                }
            }
            
            $storage = Storage::getInstance($this->config, $this->adapter);
            $path = $storage->getPathCompany();
            
            return new JsonModel([
                'success'   => true,
                'data' => $company->footer ? $storage->getGenericImage($path, $company->uuid, $company->footer) : '',

            ]);
        }


        $data = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];


        return new JsonModel($data);
    }

    /**
     * Actualización de la descripción y cualquier otro campo extendido del perfil a futuro
     * @return \Laminas\View\Model\JsonModel
     */
    public function industryAction()
    {

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






        $request = $this->getRequest();
        if ($request->isGet()) {
            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOne($currentCompany->id);

            $industries = [];
            $industryMapper = IndustryMapper::getInstance($this->adapter);
            $records = $industryMapper->fetchAllActive();
            
            foreach ($records as $record)
            {
                $industries[$record->uuid] = $record->name;
            }
            
            $industry = $industryMapper->fetchOne($company->industry_id);
            
            
            

            $data = [
                'success' => true,
                'data' => [
                    'industry_id' => $industry->uuid,
                    'industries' => $industries
                ]
            ];

            return new JsonModel($data);
        } else if ($request->isPost()) {


            
            $form = new ProfileIndustryForm($this->adapter);
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);

            if ($form->isValid()) {
                $companyMapper = CompanyMapper::getInstance($this->adapter);
                $company = $companyMapper->fetchOne($currentCompany->id);

                $dataPost = (array) $form->getData();

                $industryMapper = IndustryMapper::getInstance($this->adapter);
                $industry = $industryMapper->fetchOneByUuid($dataPost['industry_id']);

                $company->industry_id = $industry->id;
                $companyMapper->updateIndustry($company);

                $this->logger->info('Se actualizo la industria de la empresa ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                $industryMapper = IndustryMapper::getInstance($this->adapter);
                $industry = $industryMapper->fetchOne($company->industry_id);

                return new JsonModel([
                    'success'   => true,
                    'data' =>  $industry->name,

                ]);
            } 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
                ]);
            }
        }


        $data = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];


        return new JsonModel($data);
    }

    /**
     * Actualización de la descripción y cualquier otro campo extendido del perfil a futuro
     * @return \Laminas\View\Model\JsonModel
     */
    public function companySizeAction()
    {

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




        $request = $this->getRequest();
        if ($request->isGet()) {
            $companyMapper = CompanyMapper::getInstance($this->adapter);
            $company = $companyMapper->fetchOne($currentCompany->id);

            $companySizes = [];
            
            $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);
            $records = $companySizeMapper->fetchAllActive();
            
            foreach($records as $record)
            {
                $companySizes[$record->uuid] = $record->name . ' (' . $record->minimum_no_of_employee . '-' . $record->maximum_no_of_employee . ')';
            }
            
            
            $companySize = $companySizeMapper->fetchOne($company->company_size_id);

            $data = [
                'success' => true,
                'data' => [
                    'company_size_id' => $companySize->uuid,
                    'company_sizes' => $companySizes
                ]
            ];

            return new JsonModel($data);
        } else if ($request->isPost()) {


            $form = new ProfileCompanySizeForm($this->adapter);
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);

            if ($form->isValid()) {
                $companyMapper = CompanyMapper::getInstance($this->adapter);
                $company = $companyMapper->fetchOne($currentCompany->id);

                $dataPost = (array) $form->getData();

                $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);
                $companySize = $companySizeMapper->fetchOneByUuid($dataPost['company_size_id']);

                $company->company_size_id = $companySize->id;
                $companyMapper->updateCompanySize($company);

                $this->logger->info('Se actualizo la industria de la empresa ' . $company->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);
                $companySize = $companySizeMapper->fetchOne($company->company_size_id);

                return new JsonModel([
                    'success'   => true,
                    'data' => $companySize->name . ' (' . $companySize->minimum_no_of_employee . '-' . $companySize->maximum_no_of_employee . ')',

                ]);
            } 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
                ]);
            }
        }


        $data = [
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ];


        return new JsonModel($data);
    }
}