Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 6849 | 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\Form\UserProfile\SkillForm;
use LeadersLinked\Form\UserProfile\LanguageForm;

use LeadersLinked\Library\Functions;
use LeadersLinked\Mapper\UserProfileMapper;
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
use LeadersLinked\Model\UserProfile;
use LeadersLinked\Mapper\CompanyFollowerMapper;
use LeadersLinked\Mapper\LocationMapper;
use LeadersLinked\Model\UserLanguage;
use LeadersLinked\Mapper\UserLanguageMapper;
use LeadersLinked\Mapper\UserSkillMapper;

use LeadersLinked\Model\UserSkill;
use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Form\UserProfile\ExtendedForm;
use LeadersLinked\Form\UserProfile\LocationForm;
use LeadersLinked\Model\Location;
use LeadersLinked\Form\UserProfile\SocialNetworkForm;
use LeadersLinked\Form\UserProfile\EducationForm;
use LeadersLinked\Model\UserEducation;
use LeadersLinked\Mapper\UserEducationMapper;
use LeadersLinked\Mapper\DegreeMapper;
use LeadersLinked\Form\UserProfile\ExperienceForm;
use LeadersLinked\Mapper\AptitudeMapper;
use LeadersLinked\Mapper\LanguageMapper;
use LeadersLinked\Mapper\UserAptitudeMapper;
use LeadersLinked\Mapper\UserExperienceMapper;
use LeadersLinked\Mapper\IndustryMapper;
use LeadersLinked\Mapper\CompanySizeMapper;
use LeadersLinked\Model\UserExperience;
use LeadersLinked\Mapper\ConnectionMapper;
use LeadersLinked\Form\UserProfile\ImageForm;
use LeadersLinked\Library\Image;
use LeadersLinked\Form\UserProfile\CoverForm;
use LeadersLinked\Mapper\SkillMapper;
use LeadersLinked\Form\MyProfiles\CreateForm;
use LeadersLinked\Form\UserProfile\AptitudeForm;
use LeadersLinked\Model\UserAptitude;
use LeadersLinked\Form\UserProfile\HobbyAndInterestForm;
use LeadersLinked\Mapper\HobbyAndInterestMapper;
use LeadersLinked\Mapper\UserHobbyAndInterestMapper;
use LeadersLinked\Model\UserHobbyAndInterest;


class MyProfilesController 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;
    }

    /**
     * 
     * Generación del listado de perfiles
     * {@inheritDoc}
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
     */
    public function indexAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $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 = str_contains($raw, 'json');
                    }
                }
            }
            if ($isJson) {
                $search = Functions::sanitizeFilterString($this->params()->fromQuery('search'));


                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                $allowView = $acl->isAllowed($currentUser->usertype_id, 'profile/view');
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'profile/my-profiles/edit');
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'profile/my-profiles/delete');


                $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
                $records  = $userProfileMapper->fetchAllByUserIdAndSearch($currentUser->id, $search);


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

                    $item = [
                        'id' => $record->id,
                        'name' => $record->name,
                        'image' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $currentUser->uuid, 'filename' => $record->image]),
                        'link_view' => $allowView ? $this->url()->fromRoute('profile/view', ['id' => $record->uuid])  : '',
                        'link_edit' => $allowEdit ? $this->url()->fromRoute('profile/my-profiles/edit', ['id' => $record->uuid])  : '',
                        'link_delete' => $allowDelete && $record->public == UserProfile::PUBLIC_NO ? $this->url()->fromRoute('profile/my-profiles/delete', ['id' => $record->uuid]) : '',
                    ];

                    array_push($items, $item);
                }



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

                return new JsonModel($response);
            } else {
                $formAdd = new CreateForm();

                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/my-profiles/index.phtml');
                $viewModel->setVariables([
                    'formAdd' => $formAdd,

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



    /**
     * 
     * Agregar un nuevo perfil
     * @return \Laminas\View\Model\JsonModel
     */
    public function addAction()
    {
        $request = $this->getRequest();


        if ($request->isPost()) {
            $form = new  CreateForm();
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);

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

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

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

                $userProfile->uuid = Functions::genUUID();
                $userProfile->user_id = $currentUser->id;
                $userProfile->public = \LeadersLinked\Model\UserProfile::PUBLIC_NO;

                $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
                $result = $userProfileMapper->insert($userProfile);

                if ($result) {
                    $this->logger->info('Se agrego el perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

                    $data = [
                        'success'   => true,
                        'data'   => 'LABEL_RECORD_ADDED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $userProfile->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);
    }

    /**
     * 
     * Borrar un perfil excepto el público
     * @return \Laminas\View\Model\JsonModel
     */
    public function deleteAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

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

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

            return new JsonModel($data);
        }



        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
        $userProfile = $userProfileMapper->fetchOneByUuid($id);
        if (!$userProfile) {
            $data = [
                'success'   => false,
                'data'   => 'ERROR_RECORD_NOT_FOUND'
            ];

            return new JsonModel($data);
        }


        if ($currentUser->id != $userProfile->user_id) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }

        if (!$userProfile->public == UserProfile::PUBLIC_YES) {
            $data = [
                'success'   => false,
                'data'   => 'ERROR_PUBLIC_PROFILE'
            ];

            return new JsonModel($data);
        }

        if ($request->isPost()) {
            $result = $userProfileMapper->delete($userProfile);
            if ($result) {
                $this->logger->info('Se borro el perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

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

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

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

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

    /**
     * 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 editAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $flashMessenger = $this->plugin('FlashMessenger');


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


        if (!$id) {
            $flashMessenger->addErrorMessage('ERROR_INVALID_PARAMETER');
            return $this->redirect()->toRoute('dashboard');
        }



        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
        $userProfile = $userProfileMapper->fetchOneByUuid($id);

        if (!$userProfile) {
            $flashMessenger->addErrorMessage('ERROR_RECORD_NOT_FOUND');
            return $this->redirect()->toRoute('dashboard');
        }

        if ($currentUser->id != $userProfile->user_id) {
            $flashMessenger->addErrorMessage('ERROR_UNAUTHORIZED');
            return $this->redirect()->toRoute('dashboard');
        }


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

        if ($request->isGet()) {

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

                $formattedAddress = $location->formatted_address;
                $country = $location->country;
            } else {
                $formattedAddress = '';
                $country = '';
            }



            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOne($userProfile->user_id);

            $userLanguages = [];
            $languageMapper = LanguageMapper::getInstance($this->adapter);
            $userLanguageMapper = UserLanguageMapper::getInstance($this->adapter);
            $records = $userLanguageMapper->fetchAllByUserProfileId($userProfile->id);
            foreach ($records as $record) {
                $language = $languageMapper->fetchOne($record->language_id);
                $userLanguages[$language->id] = $language->name;
            }


            $locationMapper = LocationMapper::getInstance($this->adapter);
            $degreeMapper = DegreeMapper::getInstance($this->adapter);
            $userEducationMapper = UserEducationMapper::getInstance($this->adapter);
            $userEducations = $userEducationMapper->fetchAllByUserProfileId($userProfile->id);



            foreach ($userEducations  as &$userEducation) {
                $location = $locationMapper->fetchOne($userEducation->location_id);
                $degree = $degreeMapper->fetchOne($userEducation->degree_id);

                $userEducation = [
                    'university' => $userEducation->university,
                    'degree' => $degree->name,
                    'field_of_study' => $userEducation->field_of_study,
                    'grade_or_percentage' => $userEducation->grade_or_percentage,
                    'formatted_address' => $location->formatted_address,
                    'from_year' => $userEducation->from_year,
                    'to_year' => $userEducation->to_year,
                    'description' => $userEducation->description,
                    'link_edit' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'edit', 'user_education_id' => $userEducation->uuid]),
                    'link_delete' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'delete', 'user_education_id' => $userEducation->uuid]),
                ];
            }

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

            $userExperienceMapper = UserExperienceMapper::getInstance($this->adapter);
            $userExperiences = $userExperienceMapper->fetchAllByUserProfileId($userProfile->id);

            foreach ($userExperiences  as &$userExperience) {
                $location = $locationMapper->fetchOne($userExperience->location_id);
                $companySize = $companySizeMapper->fetchOne($userExperience->company_size_id);
                $industry = $industryMapper->fetchOne($userExperience->industry_id);

                $userExperience = [
                    'company' => $userExperience->company,
                    'industry' => $industry->name,
                    'size' => $companySize->name . ' (' . $companySize->minimum_no_of_employee . '-' . $companySize->maximum_no_of_employee . ')',
                    'title' => $userExperience->title,
                    'formatted_address' => $location->formatted_address,
                    'from_year' => $userExperience->from_year,
                    'from_month' => $userExperience->from_month,
                    'to_year' => $userExperience->to_year,
                    'to_month' => $userExperience->to_month,
                    'description' => $userExperience->description,
                    'is_current' => $userExperience->is_current,
                    'link_edit' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'edit', 'user_experience_id' => $userExperience->uuid]),
                    'link_delete' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'delete', 'user_experience_id' => $userExperience->uuid]),
                ];
            }


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

            $userAptitudes = [];
            $aptitudeMapper = AptitudeMapper::getInstance($this->adapter);
            $userAptitudeMapper = UserAptitudeMapper::getInstance($this->adapter);
            $records  = $userAptitudeMapper->fetchAllByUserProfileId($userProfile->id);
            foreach ($records as $record) {
                $aptitude = $aptitudeMapper->fetchOne($record->aptitude_id);
                if ($aptitude) {
                    $userAptitudes[$aptitude->uuid] = $aptitude->name;
                }
            }

            $userHobbiesAndInterests = [];
            $hobbyAndInterestMapper = HobbyAndInterestMapper::getInstance($this->adapter);
            $userHobbyAndInterestMapper = UserHobbyAndInterestMapper::getInstance($this->adapter);
            $records  = $userHobbyAndInterestMapper->fetchAllByUserProfileId($userProfile->id);
            foreach ($records as $record) {
                $hobbyAndInterest = $hobbyAndInterestMapper->fetchOne($record->hobby_and_interest_id);
                if ($hobbyAndInterest) {
                    $userHobbiesAndInterests[$hobbyAndInterest->uuid] = $hobbyAndInterest->name;
                }
            }


            $userSkills = [];
            $userSkillMapper = UserSkillMapper::getInstance($this->adapter);
            $skillMapper = SkillMapper::getInstance($this->adapter);
            $records  = $userSkillMapper->fetchAllByUserProfileId($userProfile->id);
            foreach ($records as $record) {
                $skill = $skillMapper->fetchOne($record->skill_id);
                $userSkills[$skill->uuid] = $skill->name;
            }


            $companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);
            $following = $companyFollowerMapper->getCountFollowing($user->id);

            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
            $follower = $connectionMapper->fetchTotalConnectionByUser($user->id);


            $image_size_cover = $this->config['leaderslinked.image_sizes.user_cover_upload'];
            $image_size_profile = $this->config['leaderslinked.image_sizes.user_upload'];


            if ($isJson) {

                $data = [
                    'following'         => $following,
                    'follower'          => $follower,
                    'user_id'           => $user->id,
                    'user_uuid'         => $user->uuid,
                    'full_name'         => trim($user->first_name . ' ' . $user->last_name),
                    'user_profile_id'   => $userProfile->id,
                    'user_profile_uuid' => $userProfile->uuid,
                    'image'             => $userProfile->image,
                    'cover'             => $userProfile->cover,
                    'overview'          => $userProfile->description,
                    'facebook'          => $userProfile->facebook,
                    'instagram'         => $userProfile->instagram,
                    'twitter'           => $userProfile->twitter,
                    'formatted_address' => $formattedAddress,
                    'country'           => $country,
                    'user_skills'       => $userSkills,
                    'user_languages'    => $userLanguages,
                    'user_educations'   => $userEducations,
                    'user_experiences'  => $userExperiences,
                    'user_aptitudes'                => $userAptitudes,
                    'user_hobbies_and_interests'    => $userHobbiesAndInterests,
                    'image_size_cover' =>  $image_size_cover,
                    'image_size_profile' => $image_size_profile
                ];

                $viewModel = new JsonModel($data);
            } else {
                $industries = [];
                $industryMapper = IndustryMapper::getInstance($this->adapter);

                $records = $industryMapper->fetchAllActive();
                foreach ($records as $record) {
                    $industries[$record->uuid] = $record->name;
                }

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

                $degrees = [];
                $degreeMapper = DegreeMapper::getInstance($this->adapter);
                $records = $degreeMapper->fetchAllActive();
                foreach ($records as $record) {
                    $degrees[$record->uuid] = $record->name;
                }

                $languages = [];
                $languageMapper = LanguageMapper::getInstance($this->adapter);
                $records = $languageMapper->fetchAllActive();
                foreach ($records as $record) {
                    $languages[$record->id] = $record->name;
                }

                $skills = [];
                $skillMapper = SkillMapper::getInstance($this->adapter);
                $records =  $skillMapper->fetchAllActive();
                foreach ($records as $record) {
                    $skills[$record->uuid] = $record->name;
                }

                $aptitudes = [];
                $aptitudeMapper = AptitudeMapper::getInstance($this->adapter);
                $records =  $aptitudeMapper->fetchAllActive();
                foreach ($records as $record) {
                    $aptitudes[$record->uuid] = $record->name;
                }


                $hobbiesAndInterests = [];
                $hobbyAndInterestMapper = HobbyAndInterestMapper::getInstance($this->adapter);
                $records =  $hobbyAndInterestMapper->fetchAllActive();
                foreach ($records as $record) {
                    $hobbiesAndInterests[$record->uuid] = $record->name;
                }



                $formSkill = new SkillForm($this->adapter);
                $formLanguage = new LanguageForm($this->adapter);
                $formLocation = new LocationForm();
                $formExtended = new ExtendedForm();
                $formExperience = new ExperienceForm($this->adapter);
                $formEducation = new EducationForm($this->adapter);
                $formSocialNetwork = new SocialNetworkForm();
                $formImage = new ImageForm($this->config);
                $formCover = new CoverForm($this->config);




                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/my-profiles/edit.phtml');
                $viewModel->setVariables([
                    'google_map_key'    => $google_map_key,
                    'following'         => $following,
                    'follower'          => $follower,
                    'user_id'           => $user->id,
                    'user_uuid' => $user->uuid,
                    'full_name'         => trim($user->first_name . ' ' . $user->last_name),
                    'user_profile_id'   => $userProfile->id,
                    'user_profile_uuid' => $userProfile->uuid,
                    'public'            => $userProfile->public,
                    'image'             => $userProfile->image,
                    'cover'             => $userProfile->cover,
                    'overview'          => $userProfile->description,
                    'facebook'          => $userProfile->facebook,
                    'instagram'         => $userProfile->instagram,
                    'twitter'           => $userProfile->twitter,
                    'formatted_address' => $formattedAddress,
                    'country'           => $country,
                    'user_skills'       => $userSkills,
                    'user_languages'    => $userLanguages,
                    'user_educations'   => $userEducations,
                    'user_experiences'  => $userExperiences,
                    'company_sizes'     => $companySizes,
                    'degrees'           => $degrees,
                    'industries'        => $industries,
                    'languages'         => $languages,
                    'skills'            => $skills,
                    'aptitudes'         => $aptitudes,
                    'hobbies_and_interests'         => $hobbiesAndInterests,

                    'user_aptitudes'                => $userAptitudes,
                    'user_hobbies_and_interests'    => $userHobbiesAndInterests,
                    'formLanguage'      => $formLanguage,
                    'formLocation'      => $formLocation,
                    'formSkill'         => $formSkill,
                    'formSocialNetwork' => $formSocialNetwork,
                    'formExtended'      => $formExtended,
                    'formExperience'    => $formExperience,
                    'formEducation'     => $formEducation,
                    'formImage'        => $formImage,
                    'formCover'         => $formCover,
                    'image_size_cover' =>  $image_size_cover,
                    'image_size_profile' => $image_size_profile
                ]);
            }
            return $viewModel;
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

    /**
     * Actualización de las habilidades
     * @return \Laminas\View\Model\JsonModel
     */
    public function skillAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $user_profile_id = $this->params()->fromRoute('id');
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);

        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
        if (!$userProfile) {
            $response = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($response);
        }

        if ($currentUser->id != $userProfile->user_id) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }



        $request = $this->getRequest();
        if ($request->isGet()) {
            $skillMapper = SkillMapper::getInstance($this->adapter);


            $userSkillMapper = UserSkillMapper::getInstance($this->adapter);
            $userSkills  = $userSkillMapper->fetchAllByUserProfileId($userProfile->id);

            $items = [];
            foreach ($userSkills as $userSkill) {
                $skill = $skillMapper->fetchOne($userSkill->skill_id);
                array_push($items, $skill->uuid);
            }

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

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

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

            $form->setData($dataPost);

            if ($form->isValid()) {
                $this->logger->info('Se actualizaron las habilidades del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

                $skillMapper = SkillMapper::getInstance($this->adapter);


                $userSkillMapper = UserSkillMapper::getInstance($this->adapter);
                $userSkillMapper->deleteByUserProfileId($userProfile->id);

                $dataPost = (array) $form->getData();
                $skills = $dataPost['skills'];
                foreach ($skills as $skill_uuid) {

                    $skill = $skillMapper->fetchOneByUuid($skill_uuid);



                    $userSkill = new UserSkill();
                    $userSkill->user_id = $userProfile->user_id;
                    $userSkill->user_profile_id = $userProfile->id;
                    $userSkill->skill_id =  $skill->id;

                    $userSkillMapper->insert($userSkill);
                }

                $items = [];

                $records = $userSkillMapper->fetchAllByUserProfileId($userProfile->id);
                foreach ($records as $record) {
                    $skill = $skillMapper->fetchOne($record->skill_id);
                    array_push($items,  ['value' => $skill->uuid, 'label' => $skill->name]);
                }

                return new JsonModel([
                    'success'   => true,
                    'data'   => $items
                ]);
            } 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 los idiomas
     * @return \Laminas\View\Model\JsonModel
     */
    public function languageAction()
    {

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

        $user_profile_id = $this->params()->fromRoute('id');
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);

        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
        if (!$userProfile) {
            $response = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($response);
        }


        if ($currentUser->id != $userProfile->user_id) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }



        $request = $this->getRequest();
        if ($request->isGet()) {
            $this->logger->info('Se actualizaron los idiomas del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

            $userLanguageMapper = UserLanguageMapper::getInstance($this->adapter);
            $languages  = $userLanguageMapper->fetchAllByUserProfileId($userProfile->id);

            $items = [];
            foreach ($languages as $language) {
                array_push($items, $language->language_id);
            }

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

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

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

            $form->setData($dataPost);

            if ($form->isValid()) {

                $languageMapper = LanguageMapper::getInstance($this->adapter);
                $userLanguageMapper = UserLanguageMapper::getInstance($this->adapter);
                $userLanguageMapper->deleteByUserProfileId($userProfile->id);

                $dataPost = (array) $form->getData();
                $languages = $dataPost['languages'];
                foreach ($languages as $language_id) {
                    $language = $languageMapper->fetchOne($language_id);

                    $userLanguage = new UserLanguage();
                    $userLanguage->user_id = $userProfile->user_id;
                    $userLanguage->user_profile_id = $userProfile->id;
                    $userLanguage->language_id = $language->id;

                    $userLanguageMapper->insert($userLanguage);
                }

                $items = [];
                $records = $userLanguageMapper->fetchAllByUserProfileId($userProfile->id);
                foreach ($records as $record) {
                    $language = $languageMapper->fetchOne($record->language_id);
                    array_push($items,  ['value' => $language->id, 'label' => $language->name]);
                }

                return new JsonModel([
                    'success'   => true,
                    'data'   => $items
                ]);
            } 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 extendedAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();


        $user_profile_id = $this->params()->fromRoute('id');
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);

        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
        if (!$userProfile) {
            $response = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($response);
        }

        if ($currentUser->id != $userProfile->user_id) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }



        $request = $this->getRequest();
        if ($request->isGet()) {
            $data = [
                'success' => true,
                'data' => [
                    'description' => $userProfile->description,
                ]
            ];

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


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

            $form->setData($dataPost);

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

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

                $userProfileMapper->updateExtended($userProfile);

                $this->logger->info('Se actualizo las descripción del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

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

        $user_profile_id = $this->params()->fromRoute('id');
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);

        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
        if (!$userProfile) {
            $response = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($response);
        }


        if ($currentUser->id != $userProfile->user_id) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }



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

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

            $form->setData($dataPost);

            if ($form->isValid()) {
                $this->logger->info('Se actualizaron la ubicación del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

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

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

                $location->id = $userProfile->location_id ? $userProfile->location_id : null;



                $locationMapper = LocationMapper::getInstance($this->adapter);
                if ($userProfile->location_id) {
                    $result = $locationMapper->update($location);
                } else {
                    $result = $locationMapper->insert($location);

                    if ($result) {
                        $userProfile->location_id = $location->id;
                        $userProfileMapper->updateLocation($userProfile);
                    }
                }

                if ($result) {
                    if ($userProfile->public == UserProfile::PUBLIC_YES) {
                        $currentUser->location_id = $location->id;

                        $userMapper = UserMapper::getInstance($this->adapter);
                        $userMapper->updateLocation($currentUser);
                    }


                    $response = [
                        'success'   => true,
                        'data' => [
                            'formatted_address' => $location->formatted_address,
                            'country' => $location->country,
                        ]
                    ];
                } else {
                    $response = [
                        'success'   => false,
                        'data' => 'ERROR_THERE_WAS_AN_ERROR'
                    ];
                }



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


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


        return new JsonModel($data);
    }

    /**
     * Actualización de las redes sociales
     * @return \Laminas\View\Model\JsonModel
     */
    public function socialNetworkAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $user_profile_id = $this->params()->fromRoute('id');
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);

        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
        if (!$userProfile) {
            $response = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($response);
        }


        if ($currentUser->id != $userProfile->user_id) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }



        $request = $this->getRequest();
        if ($request->isGet()) {
            $data = [
                'success' => true,
                'data' => [
                    'facebook' => $userProfile->facebook,
                    'instagram' => $userProfile->instagram,
                    'twitter' => $userProfile->twitter
                ]
            ];

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

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

            $form->setData($dataPost);

            if ($form->isValid()) {
                $this->logger->info('Se actualizaron las redes sociales del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

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

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

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

    /**
     * Actualización de los registros de estudios realizados
     * @return \Laminas\View\Model\JsonModel
     */
    public function  educationAction()
    {

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

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

        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);

        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
        if (!$userProfile) {
            $response = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($response);
        }


        if ($currentUser->id != $userProfile->user_id) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }



        $request = $this->getRequest();
        if ($request->isPost()) {
            $userEducationMapper = UserEducationMapper::getInstance($this->adapter);

            if ($operation == 'delete' || $operation == 'edit') {
                $userEducation = $userEducationMapper->fetchOneByUuid($user_education_id);


                if (!$userEducation) {

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

                    return new JsonModel($response);
                } else if ($userProfile->id != $userEducation->user_profile_id) {
                    $response = [
                        'success' => false,
                        'data' => 'ERROR_UNAUTHORIZED'
                    ];

                    return new JsonModel($response);
                }
            } else {
                $userEducation = null;
            }

            $locationMapper = LocationMapper::getInstance($this->adapter);
            if ($operation == 'delete') {
                $this->logger->info('Se borro un registro de educación del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

                $result = $userEducationMapper->delete($userEducation);
                if ($result) {
                    $locationMapper->delete($userEducation->location_id);
                }
            } else {


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

                $form->setData($dataPost);

                if ($form->isValid()) {

                    if (!$userEducation) {
                        $userEducation = new UserEducation();
                        $userEducation->user_id = $userProfile->user_id;
                        $userEducation->user_profile_id = $userProfile->id;
                    }

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

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

                    $degreeMapper = DegreeMapper::getInstance($this->adapter);
                    $degree = $degreeMapper->fetchOneByUuid($dataPost['degree_id']);
                    $userEducation->degree_id = $degree->id;




                    if ($userEducation->location_id) {
                        $location = $locationMapper->fetchOne($userEducation->location_id);
                    } else {
                        $location = new Location();
                    }

                    $hydrator->hydrate($dataPost, $location);
                    if ($userEducation->location_id) {
                        $this->logger->info('Se actualizo un registro de educación del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

                        $result = $locationMapper->update($location);
                    } else {
                        $this->logger->info('Se agrego un registro de educación del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

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

                        if ($result) {
                            $userEducation->location_id = $location->id;
                        }
                    }
                    if ($result) {
                        if ($userEducation->id) {
                            $result = $userEducationMapper->update($userEducation);
                        } else {
                            $result =  $userEducationMapper->insert($userEducation);
                        }
                    }
                } 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
                    ]);
                }
            }

            if ($result) {
                $degreeMapper = DegreeMapper::getInstance($this->adapter);
                $userEducations = $userEducationMapper->fetchAllByUserProfileId($userProfile->id);

                foreach ($userEducations  as &$userEducation) {
                    $location = $locationMapper->fetchOne($userEducation->location_id);
                    $degree = $degreeMapper->fetchOne($userEducation->degree_id);

                    $userEducation = [
                        'university' => $userEducation->university,
                        'degree' => $degree->name,
                        'field_of_study' => $userEducation->field_of_study,
                        'grade_or_percentage' => $userEducation->grade_or_percentage,
                        'formatted_address' => $location->formatted_address,
                        'from_year' => $userEducation->from_year,
                        'to_year' => $userEducation->to_year,
                        'description' => $userEducation->description,
                        'link_edit' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'edit', 'user_education_id' => $userEducation->uuid]),
                        'link_delete' => $this->url()->fromRoute('profile/my-profiles/education', ['id' => $userProfile->uuid, 'operation' => 'delete', 'user_education_id' => $userEducation->uuid]),
                    ];
                }

                $response = [
                    'success'   => true,
                    'data' => $userEducations
                ];
            } else {
                $response = [
                    'success'   => false,
                    'data' => 'ERROR_THERE_WAS_AN_ERROR'
                ];
            }



            return new JsonModel($response);
        } else if ($request->isGet() && $operation == 'edit') {
            $userEducationMapper = UserEducationMapper::getInstance($this->adapter);
            $userEducation = $userEducationMapper->fetchOneByUuid($user_education_id);

            if (!$userEducation) {

                $response = [
                    'success' => false,
                    'data' => 'ERROR_RECORD_NOT_FOUND'
                ];
            } else if ($userProfile->id != $userEducation->user_profile_id) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_UNAUTHORIZED'
                ];
            } else {
                $locationMapper = LocationMapper::getInstance($this->adapter);
                $location = $locationMapper->fetchOne($userEducation->location_id);

                $hydrator = new ObjectPropertyHydrator();
                $education = $hydrator->extract($userEducation);

                $degree = $degreeMapper = DegreeMapper::getInstance($this->adapter);
                $degree = $degreeMapper->fetchOne($education['degree_id']);
                $education['degree_id'] = $degree->uuid;

                $location = [
                    'address1' => $location->address1,
                    'address2' => $location->address2,
                    'city1' => $location->city1,
                    'city2' => $location->city2,
                    'country' => $location->country,
                    'formatted_address' => $location->formatted_address,
                    'latitude' => $location->latitude,
                    'longitude' => $location->longitude,
                    'postal_code' => $location->postal_code,
                    'state' => $location->state,
                ];

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

            return new JsonModel($response);
        }




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


        return new JsonModel($data);
    }

    /**
     * Actualización de los registros de la experiencia laboral
     * @return \Laminas\View\Model\JsonModel
     */
    public function  experienceAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

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

        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);

        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
        if (!$userProfile) {
            $response = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($response);
        }

        if ($currentUser->id != $userProfile->user_id) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }



        $request = $this->getRequest();
        if ($request->isPost()) {
            $userExperienceMapper = UserExperienceMapper::getInstance($this->adapter);

            if ($operation == 'delete' || $operation == 'edit') {
                $userExperience = $userExperienceMapper->fetchOneByUuid($user_experience_id);

                if (!$userExperience) {

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

                    return new JsonModel($response);
                } else if ($userProfile->id != $userExperience->user_profile_id) {
                    $response = [
                        'success' => false,
                        'data' => 'ERROR_UNAUTHORIZED'
                    ];

                    return new JsonModel($response);
                }
            } else {
                $userExperience = null;
            }

            $locationMapper = LocationMapper::getInstance($this->adapter);
            if ($operation == 'delete') {
                $this->logger->info('Se borro un registro de experiencia del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

                $result = $userExperienceMapper->delete($userExperience);
                if ($result) {
                    $locationMapper->delete($userExperience->location_id);
                }
            } else {


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


                $dataPost['is_current'] = isset($dataPost['is_current']) ? $dataPost['is_current'] : UserExperience::IS_CURRENT_NO;
                if ($dataPost['is_current']  == UserExperience::IS_CURRENT_YES) {
                    $dataPost['to_month'] = 12;
                    $dataPost['to_year'] = date('Y');
                }


                $form->setData($dataPost);

                if ($form->isValid()) {




                    if (!$userExperience) {
                        $userExperience = new UserExperience();
                        $userExperience->user_id = $userProfile->user_id;
                        $userExperience->user_profile_id = $userProfile->id;
                    }

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

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

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

                    $userExperience->company_size_id = $companySize->id;
                    $userExperience->industry_id = $industry->id;

                    if ($userExperience->is_current == UserExperience::IS_CURRENT_YES) {
                        $userExperience->to_month = null;
                        $userExperience->to_year = null;
                    }

                    if ($userExperience->location_id) {
                        $location = $locationMapper->fetchOne($userExperience->location_id);
                    } else {
                        $location = new Location();
                    }
                    $hydrator->hydrate($dataPost, $location);

                    if ($userExperience->location_id) {
                        $this->logger->info('Se actualizo un registro de experiencia del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

                        $result = $locationMapper->update($location);
                    } else {
                        $this->logger->info('Se agrego un registro de experiencia del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

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

                        if ($result) {
                            $userExperience->location_id = $location->id;
                        }
                    }
                    if ($result) {
                        if ($userExperience->id) {
                            $result = $userExperienceMapper->update($userExperience);
                        } else {
                            $result =  $userExperienceMapper->insert($userExperience);
                        }
                    }
                } 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,
                    ]);
                }
            }

            if ($result) {
                $industryMapper = IndustryMapper::getInstance($this->adapter);
                $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);
                $userExperiences = $userExperienceMapper->fetchAllByUserProfileId($userProfile->id);

                foreach ($userExperiences  as &$userExperience) {
                    $location = $locationMapper->fetchOne($userExperience->location_id);
                    $companySize = $companySizeMapper->fetchOne($userExperience->company_size_id);
                    $industry = $industryMapper->fetchOne($userExperience->industry_id);

                    $userExperience = [
                        'company' => $userExperience->company,
                        'industry' => $industry,
                        'size' => $companySize->name . ' (' . $companySize->minimum_no_of_employee . '-' . $companySize->maximum_no_of_employee . ') ',
                        'title' => $userExperience->title,
                        'formatted_address' => $location->formatted_address,
                        'from_year' => $userExperience->from_year,
                        'from_month' => $userExperience->from_month,
                        'to_year' => $userExperience->to_year,
                        'to_month' => $userExperience->to_month,
                        'description' => $userExperience->description,
                        'is_current' => $userExperience->is_current,
                        'link_edit' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'edit', 'user_experience_id' => $userExperience->uuid]),
                        'link_delete' => $this->url()->fromRoute('profile/my-profiles/experience', ['id' => $userProfile->uuid, 'operation' => 'delete', 'user_experience_id' => $userExperience->uuid]),
                    ];
                }

                $response = [
                    'success'   => true,
                    'data' => $userExperiences
                ];
            } else {
                $response = [
                    'success'   => false,
                    'data' => 'ERROR_THERE_WAS_AN_ERROR'
                ];
            }

            return new JsonModel($response);
        } else if ($request->isGet() && $operation == 'edit') {
            $userExperienceMapper = UserExperienceMapper::getInstance($this->adapter);
            $userExperience = $userExperienceMapper->fetchOneByUuid($user_experience_id);

            if (!$userExperience) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_RECORD_NOT_FOUND'
                ];
            } else if ($userProfile->id != $userExperience->user_profile_id) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_UNAUTHORIZED'
                ];
            } else {
                $hydrator = new ObjectPropertyHydrator();
                $experience = $hydrator->extract($userExperience);


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

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

                $experience['industry_id'] = $industry->uuid;
                $experience['company_size_id'] = $companySize->uuid;

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

                $response = [
                    'success' => true,
                    'data' => [
                        'location' => $hydrator->extract($location),
                        'experience' => $experience
                    ]
                ];
            }
            return new JsonModel($response);
        }

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

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

        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);

        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
        if (!$userProfile) {
            $response = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($response);
        }

        if ($currentUser->id != $userProfile->user_id) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }



        $request = $this->getRequest();
        if ($request->isPost()) {
            $target_path = $this->config['leaderslinked.fullpath.user'] . $currentUser->uuid;
            if ($operation == 'delete') {
                $this->logger->info('Se borro el image del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

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

                $userProfile->image = '';
                if (!$userProfileMapper->updateImage($userProfile)) {
                    return new JsonModel([
                        'success'   => false,
                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                    ]);
                }
            } else {
                $form = new ImageForm($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'
                        ]);
                    }

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

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

                    if (!Image::uploadImage($source, $target_path, $target_filename, $target_width, $target_height, $crop_to_dimensions)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }

                    $userProfile->image = $target_filename;
                    if (!$userProfileMapper->updateImage($userProfile)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }

                    if ($userProfile->public == UserProfile::PUBLIC_YES) {

                        $currentUser->image = $target_filename;

                        $userMapper = UserMapper::getInstance($this->adapter);
                        $userMapper->updateImage($currentUser);
                    }

                    $this->logger->info('Se actualizo el image del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_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
                    ]);
                }
            }
            return new JsonModel([
                'success'   => true,
                'data' => [
                    'user' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $currentUser->uuid, 'filename' => $currentUser->image]),
                    'profile' => $this->url()->fromRoute('storage', ['type' => 'user-profile', 'code' => $currentUser->uuid, 'filename' => $userProfile->image]),
                    'update_navbar' =>  $userProfile->public == UserProfile::PUBLIC_YES ? 1 : 0,

                ]
            ]);
        }


        $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()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

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

        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);

        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
        if (!$userProfile) {
            $response = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($response);
        }



        if ($currentUser->id != $userProfile->user_id) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }



        $request = $this->getRequest();
        if ($request->isPost()) {
            $target_path = $this->config['leaderslinked.fullpath.user'] . $currentUser->uuid;

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

                $this->logger->info('Se borro el cover del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);
                $userProfile->cover = '';
            } else {
                $form = new CoverForm($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 ($userProfile->cover) {
                        if (!Image::delete($target_path, $userProfile->cover)) {
                            return new JsonModel([
                                'success'   => false,
                                'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                            ]);
                        }
                    }

                    //echo '$target_path = ' . $target_path . ' cover =  ' . $userProfile->cover;
                    //exit;

                    list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.user_cover_size']);
                    $target_filename = 'user-cover-' . uniqid() . '.png';
                    $source = $files['cover']['tmp_name'];
                    $crop_to_dimensions = false;

                    if (!Image::uploadImage($source, $target_path, $target_filename, $target_width, $target_height, $crop_to_dimensions)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }

                    $userProfile->cover = $target_filename;


                    if (!$userProfileMapper->updateCover($userProfile)) {
                        return new JsonModel([
                            'success'   => false,
                            'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
                        ]);
                    }


                    $this->logger->info('Se actualizo el cover del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_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
                    ]);
                }
            }
            return new JsonModel([
                'success'   => true,
                'data' => $this->url()->fromRoute('storage', ['type' => 'user-cover', 'code' => $currentUser->uuid, 'filename' => $userProfile->cover])

            ]);
        }


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


        return new JsonModel($data);
    }

    /**
     * Actualización de las habilidades
     * @return \Laminas\View\Model\JsonModel
     */
    public function aptitudeAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $user_profile_id = $this->params()->fromRoute('id');
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);

        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
        if (!$userProfile) {
            $response = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($response);
        }

        if ($currentUser->id != $userProfile->user_id) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }



        $request = $this->getRequest();
        if ($request->isGet()) {
            $aptitudeMapper = AptitudeMapper::getInstance($this->adapter);


            $userAptitudeMapper = UserAptitudeMapper::getInstance($this->adapter);
            $userAptitudes  = $userAptitudeMapper->fetchAllByUserProfileId($userProfile->id);

            $items = [];
            foreach ($userAptitudes as $userAptitude) {
                $aptitude = $aptitudeMapper->fetchOne($userAptitude->aptitude_id);
                array_push($items, $aptitude->uuid);
            }

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

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

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

            $form->setData($dataPost);

            if ($form->isValid()) {
                $this->logger->info('Se actualizaron las habilidades del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

                $aptitudeMapper = AptitudeMapper::getInstance($this->adapter);


                $userAptitudeMapper = UserAptitudeMapper::getInstance($this->adapter);
                $userAptitudeMapper->deleteByUserProfileId($userProfile->id);

                $dataPost = (array) $form->getData();
                $aptitudes = $dataPost['aptitudes'];
                foreach ($aptitudes as $aptitude_uuid) {

                    $aptitude = $aptitudeMapper->fetchOneByUuid($aptitude_uuid);


                    $userAptitude = new UserAptitude();
                    $userAptitude->user_id = $userProfile->user_id;
                    $userAptitude->user_profile_id = $userProfile->id;
                    $userAptitude->aptitude_id =  $aptitude->id;

                    $userAptitudeMapper->insert($userAptitude);
                }

                $items = [];

                $records = $userAptitudeMapper->fetchAllByUserProfileId($userProfile->id);
                foreach ($records as $record) {
                    $aptitude = $aptitudeMapper->fetchOne($record->aptitude_id);
                    array_push($items,  ['value' => $aptitude->uuid, 'label' => $aptitude->name]);
                }

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

            $userAptitudeMapper = UserAptitudeMapper::getInstance($this->adapter);
        }


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


        return new JsonModel($data);
    }

    /**
     * Actualización de las habilidades
     * @return \Laminas\View\Model\JsonModel
     */
    public function hobbyAndInterestAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $user_profile_id = $this->params()->fromRoute('id');
        $userProfileMapper = UserProfileMapper::getInstance($this->adapter);

        $userProfile = $userProfileMapper->fetchOneByUuid($user_profile_id);
        if (!$userProfile) {
            $response = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($response);
        }

        if ($currentUser->id != $userProfile->user_id) {
            $response = [
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ];

            return new JsonModel($response);
        }



        $request = $this->getRequest();
        if ($request->isGet()) {
            $hobbyAndInterestMapper = HobbyAndInterestMapper::getInstance($this->adapter);


            $userHobbyAndInterestMapper = UserHobbyAndInterestMapper::getInstance($this->adapter);
            $userHobbyAndInterests  = $userHobbyAndInterestMapper->fetchAllByUserProfileId($userProfile->id);

            $items = [];
            foreach ($userHobbyAndInterests as $userHobbyAndInterest) {
                $hobbyAndInterest = $hobbyAndInterestMapper->fetchOne($userHobbyAndInterest->hobbyAndInterest_id);
                array_push($items, $hobbyAndInterest->uuid);
            }

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

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

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


            $form->setData($dataPost);

            if ($form->isValid()) {
                $this->logger->info('Se actualizaron las habilidades del perfil ' . ($userProfile->public == UserProfile::PUBLIC_YES ? 'público' : $userProfile->name), ['user_id' => $userProfile->user_id, 'ip' => Functions::getUserIP()]);

                $hobbyAndInterestMapper = HobbyAndInterestMapper::getInstance($this->adapter);


                $userHobbyAndInterestMapper = UserHobbyAndInterestMapper::getInstance($this->adapter);
                $userHobbyAndInterestMapper->deleteByUserProfileId($userProfile->id);

                $dataPost = (array) $form->getData();
                $hobbyAndInterests = $dataPost['hobbies_and_interests'];
                foreach ($hobbyAndInterests as $hobbyAndInterest_uuid) {

                    $hobbyAndInterest = $hobbyAndInterestMapper->fetchOneByUuid($hobbyAndInterest_uuid);


                    $userHobbyAndInterest = new UserHobbyAndInterest();
                    $userHobbyAndInterest->user_id = $userProfile->user_id;
                    $userHobbyAndInterest->user_profile_id = $userProfile->id;
                    $userHobbyAndInterest->hobby_and_interest_id =  $hobbyAndInterest->id;

                    $userHobbyAndInterestMapper->insert($userHobbyAndInterest);
                }

                $items = [];

                $records = $userHobbyAndInterestMapper->fetchAllByUserProfileId($userProfile->id);
                foreach ($records as $record) {
                    $hobbyAndInterest = $hobbyAndInterestMapper->fetchOne($record->hobby_and_interest_id);
                    array_push($items,  ['value' => $hobbyAndInterest->uuid, 'label' => $hobbyAndInterest->name]);
                }

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

            $userHobbyAndInterestMapper = UserHobbyAndInterestMapper::getInstance($this->adapter);
        }


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


        return new JsonModel($data);
    }
}