Proyectos de Subversion LeadersLinked - Backend

Rev

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

<?php

declare(strict_types=1);

namespace LeadersLinked\Controller;

use Laminas\Db\Adapter\AdapterInterface;


use Laminas\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\Model\DiscoveryContact;
use LeadersLinked\Mapper\DiscoveryContactMapper;
use LeadersLinked\Form\DiscoveryContact\ContactForm;
use LeadersLinked\Model\DiscoveryContactLog;
use LeadersLinked\Mapper\DiscoveryContactLogMapper;
use LeadersLinked\Form\DiscoveryContact\InteractionForm;
use PhpOffice\PhpSpreadsheet\IOFactory;
use LeadersLinked\Form\DiscoveryContact\ContactUploadForm;
use LeadersLinked\Mapper\DiscoveryContactInteractionMapper;
use LeadersLinked\Mapper\DiscoveryContactInteractionTypeMapper;
use LeadersLinked\Model\DiscoveryContactInteraction;
use LeadersLinked\Model\DiscoveryContactInteractionType;
use LeadersLinked\Cache\CacheInterface;
use LeadersLinked\Cache\CacheImpl;
use LeadersLinked\Mapper\DiscoveryContactBlackListMapper;


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

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

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


            $headers  = $request->getHeaders();

            $isJson = false;
            if ($headers->has('Accept')) {
                $accept = $headers->get('Accept');

                $prioritized = $accept->getPrioritized();

                foreach ($prioritized as $key => $value) {
                    $raw = trim($value->getRaw());

                    if (!$isJson) {
                        $isJson = strpos($raw, 'json');
                    }
                }
            }

            if ($isJson) {
                $search = $this->params()->fromQuery('search');
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);


                
                

                $page               = intval($this->params()->fromQuery('start', 1), 10);
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
                $order =  $this->params()->fromQuery('order', []);
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : Functions::sanitizeFilterString(filter_var($order[0]['dir']));

                $fields =  ['first_name', 'last_name', 'corporate_email', 'company', 'country', 'sector', 'scholarship'];
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'first_name';

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

                $discoveryContactBackListMapper = DiscoveryContactBlackListMapper::getInstance($this->adapter);
                $contact_ids = $discoveryContactBackListMapper->fetchAllContactIdsByCompanyId($currentCompany->id);


                $discoveryContactMapper = DiscoveryContactMapper::getInstance($this->adapter);
                $paginator = $discoveryContactMapper->fetchAllDataTableForCompanyIdWithOutContactIds($search, $currentCompany->id, $page, $records_x_page, $order_field, $order_direction, $contact_ids);

                $items = [];
                $records = $paginator->getCurrentItems();
                foreach ($records as $record) {

                    switch($record->scholarship)
                    {
                        case DiscoveryContact::SCHOLARSHIP_YES : 
                            $scholarship = 'LABEL_YES';
                            break;
                            
                        case DiscoveryContact::SCHOLARSHIP_NO :
                            $scholarship = 'LABEL_NO';
                            break;
                            
                        default :
                            $scholarship = 'LABEL_UNKNOW';
                            break;
                    }
                    

                    $item = [
                        'first_name' => $record->first_name,
                        'last_name' => $record->last_name,
                        'corporate_email' => $record->corporate_email,
                        'company' => $record->company,
                        'country' => $record->country,
                        'sector' => $record->sector,
                        'scholarship' => $scholarship,
                        'actions' => [
                            'link_edit' => $this->url()->fromRoute('discovery-contacts/edit', ['id' => $record->uuid]),
                            'link_delete' => $this->url()->fromRoute('discovery-contacts/delete', ['id' => $record->uuid]),
                            'link_view' => $this->url()->fromRoute('discovery-contacts/view', ['id' => $record->uuid]),
                        ],
                    ];

                    array_push($items, $item);
                }

                return new JsonModel([
                    'success' => true,
                    'data' => [
                        'items' => $items,
                        'total' => $paginator->getTotalItemCount(),
                    ]
                ]);
            } else {
                $exclude_id = 0;
                $form = new ContactForm($this->adapter, $currentCompany->id, $exclude_id);
                $formInteraction = new InteractionForm($this->adapter, $currentCompany->id);
                $contactUploadForm = new ContactUploadForm();


                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/discovery-contacts/index.phtml');
                $viewModel->setVariables([
                    'form' => $form,
                    'formInteraction' => $formInteraction,
                    'contactUploadForm' => $contactUploadForm,
                ]);
                return $viewModel;
            }
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);;
        }
    }

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

        $request = $this->getRequest();
        if ($request->isPost()) {
            $exclude_id = 0;
            $form = new ContactForm($this->adapter, $currentCompany->id, $exclude_id);
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);

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

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


                $discoveryContact->company_id = $currentCompany->id;


                $discoveryContactInteractionTypeMapper = DiscoveryContactInteractionTypeMapper::getInstance($this->adapter);
                $discoveryContactInteractionTypeDefault = $discoveryContactInteractionTypeMapper->fetchOneDefaultByCompanyId($currentCompany->id);
                if(!$discoveryContactInteractionTypeDefault) {
                    $discoveryContactInteractionTypeDefault = $discoveryContactInteractionTypeMapper->fetchOneFirstActiveByCompanyId($currentCompany->id);
                    $discoveryContactInteractionTypeDefault->default = DiscoveryContactInteractionType::DEFAULT_YES;
                    $discoveryContactInteractionTypeMapper->update($discoveryContactInteractionTypeDefault);
                }
                
                
                $discoveryContactMapper = DiscoveryContactMapper::getInstance($this->adapter);
                $result = $discoveryContactMapper->insert($discoveryContact);

                if ($result) {
                    $this->logger->info('Se agrego el Contacto : ' . $discoveryContact->first_name . ' ' . $discoveryContact->last_name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                    if($discoveryContactInteractionTypeDefault) {
                        $discoveryContactInteraction = new DiscoveryContactInteraction();
                        $discoveryContactInteraction->company_id  = $currentCompany->id;
                        $discoveryContactInteraction->user_id = $currentUser->id;
                        $discoveryContactInteraction->interaction_type_id = $discoveryContactInteractionTypeDefault->id;
                        
                        $discoveryContactInteractionMapper = DiscoveryContactInteractionMapper::getInstance($this->adapter);
                        $discoveryContactInteractionMapper->insert($discoveryContactInteraction);
                    }
                    
                    $discoveryContactLog = new DiscoveryContactLog();
                    $discoveryContactLog->company_id = $currentCompany->id;
                    $discoveryContactLog->contact_id = $discoveryContact->id;
                    $discoveryContactLog->user_id = $currentUser->id;
                    $discoveryContactLog->activity =  'LABEL_RECORD_CONTACT_ADDED';
                    $discoveryContactLog->details = 'LABEL_FIRST_NAME : ' . $discoveryContact->first_name  . PHP_EOL .
                        'LABEL_LAST_NAME : ' . $discoveryContact->last_name  . PHP_EOL .
                        'LABEL_CORPORATE_EMAIL : ' . $discoveryContact->corporate_email  . PHP_EOL .
                        'LABEL_COMPANY : ' . $discoveryContact->company  . PHP_EOL .
                        'LABEL_POSITION : ' . $discoveryContact->position  . PHP_EOL .
                        'LABEL_COUNTRY : ' . $discoveryContact->country  . PHP_EOL;


                    if ($discoveryContact->state) {
                        $discoveryContactLog->details .= 'LABEL_STATE : ' . $discoveryContact->state  . PHP_EOL;
                    }
                    if ($discoveryContact->city) {
                        $discoveryContactLog->details .= 'LABEL_CITY : ' . $discoveryContact->city  . PHP_EOL;
                    }
                    if ($discoveryContact->phone) {
                        $discoveryContactLog->details .= 'LABEL_PHONE : ' . $discoveryContact->phone  . PHP_EOL;
                    }
                    if ($discoveryContact->phone_extension) {
                        $discoveryContactLog->details .= 'LABEL_PHONE_EXTENSION : ' . $discoveryContact->phone_extension  . PHP_EOL;
                    }
                    if ($discoveryContact->personal_email) {
                        $discoveryContactLog->details .= 'LABEL_PERSONAL_EMAIL : ' . $discoveryContact->personal_email  . PHP_EOL;
                    }
                    if ($discoveryContact->celular) {
                        $discoveryContactLog->details .= 'LABEL_CELULAR : ' . $discoveryContact->celular  . PHP_EOL;
                    }
                    if ($discoveryContact->whatsapp) {
                        $discoveryContactLog->details .= 'LABEL_WHATSAPP : ' . $discoveryContact->whatsapp  . PHP_EOL;
                    }
                    if ($discoveryContact->linkedin) {
                        $discoveryContactLog->details .= 'LABEL_LINKEDIN : ' . $discoveryContact->linkedin  . PHP_EOL;
                    }
                    if ($discoveryContact->scholarship) {
                        $discoveryContactLog->details .= 'LABEL_SCHOLARSHIP : ' . $discoveryContact->scholarship  . PHP_EOL;
                    }
                    
                    

                    $discoveryContactLogMapper = DiscoveryContactLogMapper::getInstance($this->adapter);
                    $discoveryContactLogMapper->insert($discoveryContactLog);

                    $data = [
                        'success'   => true,
                        'data'   => 'LABEL_RECORD_ADDED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $discoveryContactMapper->getError()
                    ];
                }

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

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

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

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

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

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


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

            return new JsonModel($data);
        }

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

            return new JsonModel($data);
        }

        $discoveryContactOld =  clone $discoveryContact;

        if ($request->isPost()) {

            $form = new ContactForm($this->adapter, $currentCompany->id, $discoveryContact->id);
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);

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

                $hydrator = new ObjectPropertyHydrator();
                $hydrator->hydrate($dataPost, $discoveryContact);
                $result = $discoveryContactMapper->update($discoveryContact);

                if ($result) {
                    $this->logger->info('Se actualizo el Contacto ' . $discoveryContact->first_name . ' ' . $discoveryContact->last_name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);


                    $discoveryContactLog = new DiscoveryContactLog();
                    $discoveryContactLog->company_id = $currentCompany->id;
                    $discoveryContactLog->contact_id = $discoveryContact->id;
                    $discoveryContactLog->user_id = $currentUser->id;
                    $discoveryContactLog->activity =  'LABEL_RECORD_CONTACT_UPDATED';
                    $discoveryContactLog->details = '';

                    if ($discoveryContactOld->first_name  != $discoveryContact->first_name) {
                        $discoveryContactLog->details .= 'LABEL_FIRST_NAME : ' . $discoveryContactOld->first_name . ' / ' . $discoveryContact->first_name  . PHP_EOL;
                    }
                    if ($discoveryContactOld->last_name  !=  $discoveryContact->last_name) {
                        $discoveryContactLog->details .= 'LABEL_LAST_NAME : ' . $discoveryContactOld->last_name . ' / ' . $discoveryContact->last_name  . PHP_EOL;
                    }
                    if ($discoveryContactOld->corporate_email != $discoveryContact->corporate_email) {
                        $discoveryContactLog->details .= 'LABEL_CORPORATE_EMAIL : ' . $discoveryContactOld->corporate_email . ' / ' . $discoveryContact->corporate_email  . PHP_EOL;
                    }
                    if ($discoveryContactOld->company != $discoveryContact->company) {
                        $discoveryContactLog->details .= 'LABEL_COMPANY : ' . $discoveryContactOld->company . ' / ' . $discoveryContact->company  . PHP_EOL;
                    }
                    if ($discoveryContactOld->position != $discoveryContact->position) {
                        $discoveryContactLog->details .= 'LABEL_POSITION : ' . $discoveryContactOld->position . ' / ' . $discoveryContact->position  . PHP_EOL;
                    }
                    if ($discoveryContactOld->country != $discoveryContact->country) {
                        $discoveryContactLog->details .= 'LABEL_COUNTRY : ' . $discoveryContactOld->country . ' / ' . $discoveryContact->country  . PHP_EOL;
                    }
                    if ($discoveryContactOld->state != $discoveryContact->state) {
                        $discoveryContactLog->details .= 'LABEL_STATE : ' . $discoveryContactOld->state . ' / ' . $discoveryContact->state  . PHP_EOL;
                    }
                    if ($discoveryContactOld->city != $discoveryContact->city) {
                        $discoveryContactLog->details .= 'LABEL_CITY : ' . $discoveryContactOld->city . ' / ' . $discoveryContact->city  . PHP_EOL;
                    }
                    if ($discoveryContactOld->phone != $discoveryContact->phone) {
                        $discoveryContactLog->details .= 'LABEL_PHONE : ' . $discoveryContactOld->phone . ' / ' . $discoveryContact->phone  . PHP_EOL;
                    }

                    if ($discoveryContactOld->phone_extension != $discoveryContact->phone_extension) {
                        $discoveryContactLog->details .= 'LABEL_PHONE_EXTENSION : ' . $discoveryContactOld->phone_extension . ' / ' . $discoveryContact->phone_extension  . PHP_EOL;
                    }
                    if ($discoveryContactOld->personal_email != $discoveryContact->personal_email) {
                        $discoveryContactLog->details .= 'LABEL_PERSONAL_EMAIL : ' . $discoveryContactOld->personal_email . ' / ' . $discoveryContact->personal_email  . PHP_EOL;
                    }
                    if ($discoveryContactOld->celular  !=  $discoveryContact->celular) {
                        $discoveryContactLog->details .= 'LABEL_CELULAR : ' . $discoveryContactOld->celular . ' / ' . $discoveryContact->celular  . PHP_EOL;
                    }
                    if ($discoveryContactOld->whatsapp != $discoveryContact->whatsapp) {
                        $discoveryContactLog->details .= 'LABEL_WHATSAPP : ' . $discoveryContactOld->whatsapp . ' / ' . $discoveryContact->whatsapp  . PHP_EOL;
                    }
                    if ($discoveryContactOld->linkedin != $discoveryContact->linkedin) {
                        $discoveryContactLog->details .= 'LABEL_LINKEDIN : ' . $discoveryContactOld->linkedin . ' / ' . $discoveryContact->linkedin  . PHP_EOL;
                    }
                    if ($discoveryContactOld->scholarship != $discoveryContact->scholarship) {
                        $discoveryContactLog->details .= 'LABEL_SCHOLARSHIP: ' . $discoveryContactOld->scholarship . ' / ' . $discoveryContact->scholarship  . PHP_EOL;
                    }
                    $discoveryContactLogMapper = DiscoveryContactLogMapper::getInstance($this->adapter);
                    $discoveryContactLogMapper->insert($discoveryContactLog);


                    $data = [
                        'success' => true,
                        'data' => 'LABEL_RECORD_UPDATED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $discoveryContactMapper->getError()
                    ];
                }

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

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


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

            $data['first_name'] = $data['first_name'] ? trim($data['first_name']) : '';
            $data['last_name'] = $data['last_name'] ? trim($data['last_name']) : '';
            $data['corporate_email'] = $data['corporate_email'] ? trim($data['corporate_email']) : '';
            $data['company'] = $data['company'] ? trim($data['company']) : '';
            $data['position'] = $data['position'] ? trim($data['position']) : '';
            $data['country'] = $data['country'] ? trim($data['country']) : '';
            $data['state'] = $data['state'] ? trim($data['state']) : '';
            $data['city'] = $data['city'] ? trim($data['city']) : '';
            $data['phone'] = $data['phone'] ? trim($data['phone']) : '';
            $data['phone_extension'] = $data['phone_extension'] ? trim($data['phone_extension']) : '';
            $data['personal_email'] = $data['personal_email'] ? trim($data['personal_email']) : '';
            $data['celular'] = $data['celular'] ? trim($data['celular']) : '';
            $data['whatsapp'] = $data['whatsapp'] ? trim($data['whatsapp']) : '';
            $data['linkedin'] = $data['linkedin'] ? trim($data['linkedin']) : '';
            $data['scholarship'] = $data['scholarship'] ? trim($data['scholarship']) : '';




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

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

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

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

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

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

            return new JsonModel($data);
        }

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

            return new JsonModel($data);
        }

        if ($request->isPost()) {
            $result = $discoveryContactMapper->delete($discoveryContact);
            if ($result) {
                $this->logger->info('Se borro el Contacto : ' . $discoveryContact->first_name . ' ' . $discoveryContact->last_name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

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

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

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

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

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

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


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

            return new JsonModel($data);
        }

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

            return new JsonModel($data);
        }



        if ($request->isGet()) {


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

            $data['first_name'] = $data['first_name'] ? trim($data['first_name']) : '';
            $data['last_name'] = $data['last_name'] ? trim($data['last_name']) : '';
            $data['corporate_email'] = $data['corporate_email'] ? trim($data['corporate_email']) : '';
            $data['company'] = $data['company'] ? trim($data['company']) : '';
            $data['position'] = $data['position'] ? trim($data['position']) : '';
            $data['country'] = $data['country'] ? trim($data['country']) : '';
            $data['state'] = $data['state'] ? trim($data['state']) : '';
            $data['city'] = $data['city'] ? trim($data['city']) : '';
            $data['phone'] = $data['phone'] ? trim($data['phone']) : '';
            $data['phone_extension'] = $data['phone_extension'] ? trim($data['phone_extension']) : '';
            $data['personal_email'] = $data['personal_email'] ? trim($data['personal_email']) : '';
            $data['celular'] = $data['celular'] ? trim($data['celular']) : '';
            $data['whatsapp'] = $data['whatsapp'] ? trim($data['whatsapp']) : '';
            $data['linkedin'] = $data['linkedin'] ? trim($data['linkedin']) : '';
            $data['scholarship'] = $data['scholarship'] ? trim($data['scholarship']) : '';


            $data['link_interactions'] = $this->url()->fromRoute('discovery-contacts/interactions', ['id' => $discoveryContact->uuid]);
            $data['link_interactions_add'] = $this->url()->fromRoute('discovery-contacts/interactions/add', ['id' => $discoveryContact->uuid]);
            $data['link_logs'] = $this->url()->fromRoute('discovery-contacts/logs', ['id' => $discoveryContact->uuid]);



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

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

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }


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

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

        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork = $currentNetworkPlugin->getNetwork();

        $request    = $this->getRequest();



        if ($request->isPost()) {
           
            $step = Functions::sanitizeFilterString($this->params()->fromPost('step'));
            if ($step == 'validation') {
                
    
                


                $form = new  ContactUploadForm();
                $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());

                $form->setData($dataPost);

                if ($form->isValid()) {

                    $file = $_FILES['file'];
                    $tmp_filename = $file['tmp_name'];
                    $final_filename =  'data/' . $file['name'];

                    if (!move_uploaded_file($tmp_filename, $final_filename)) {
                        return new JsonModel([
                            'success' => false,
                            'data' => 'ERROR_UPLOAD_FILE'
                        ]);
                    }


                    $emails = [];
                    $contacts = [];
                    $spreadsheet = IOFactory::load($final_filename);
                    $records = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);

                    foreach ($records as $record) {
                        /*
                        A = Nombre      
                        B = Apellido    
                        C = Correo Personal     
                        D = Correo Trabajo      
                        E = Empresa     
                        F = Puesto      
                        G = Pais        
                        H = Estado      
                        I = Ciudad      
                        J = Telefono    
                        K = Extensión  
                        L = Celular     
                        M = Whatsapp    
                        N = Linkedin
                        O = Sector

                         */


                        $first_name = Functions::sanitizeFilterString($record['A']);
                        $last_name = Functions::sanitizeFilterString($record['B']);
                        $email_personal = strtolower(Functions::sanitizeFilterString($record['C']));
                        $email_company = strtolower(Functions::sanitizeFilterString($record['D']));

                        $company =  isset($record['E']) ? Functions::sanitizeFilterString($record['E']) : '';
                        $position = isset($record['F']) ? Functions::sanitizeFilterString($record['F']) : '';
                        $country = isset($record['G']) ? Functions::sanitizeFilterString($record['G']) : '';
                        $state = isset($record['H']) ? Functions::sanitizeFilterString($record['H']) : '';
                        $city = isset($record['I']) ? Functions::sanitizeFilterString($record['I']) : '';


                        $phone = isset($record['J']) ? Functions::sanitizeFilterString(filter_var($record['J'])) : '';
                        $phone = preg_replace('/[^0-9]/', '', $phone);

                        $extension = isset($record['K']) ? Functions::sanitizeFilterString($record['K']) : '';
                        $extension = preg_replace('/[^0-9]/', '', $extension);

                        $movil = isset($record['L']) ? Functions::sanitizeFilterString($record['L']) : '';
                        $movil = preg_replace('/[^0-9]/', '', $movil);

                        $whatsapp = isset($record['M']) ? Functions::sanitizeFilterString($record['M']) : '';
                        $whatsapp = preg_replace('/[^0-9]/', '', $whatsapp);


                        $linkedin = isset($record['N']) ? trim(filter_var($record['N'], FILTER_SANITIZE_URL)) : '';
                        $sector = isset($record['O']) ? Functions::sanitizeFilterString($record['O']) : '';
                        $scholarship = isset($record['P']) ? strtolower(Functions::sanitizeFilterString($record['P'])) : '';
                        
                        if($scholarship == 'yes' || $scholarship == 'si') {
                            $scholarship = DiscoveryContact::SCHOLARSHIP_YES;
                        } else {
                            $scholarship = DiscoveryContact::SCHOLARSHIP_NO;
                        }
                        
                        
                        
                        
                        //||  empty($password)
                        if (empty($first_name) || empty($last_name) || !filter_var($email_company, FILTER_VALIDATE_EMAIL)) {
                            continue;
                        }

                        if (!in_array($email_company, $emails)) {

                            array_push($emails, $email_company);

                            array_push($contacts, [
                                'first_name' =>   $first_name,
                                'last_name' => $last_name,
                                'email_personal' => $email_personal,
                                'email_company' => $email_company,
                                'company' => $company,
                                'position' => $position,
                                'country' => $country,
                                'state' => $state,
                                'city' => $city,
                                'phone' => $phone,
                                'extension' => $extension,
                                'movil' => $movil,
                                'whatsapp' =>  $whatsapp,
                                'linkedin' => $linkedin,
                                'sector' => $sector,
                                'scholarship' => $scholarship,
                            ]);
                        }
                    }


                    $key = md5($currentUser->id . '-discovery-contacts-' . uniqid());
                    $this->cache->setItem($key, serialize($contacts));

                    return new JsonModel([
                        'success' => true,
                        'data' => [
                            'key' => $key,
                            'items' => $contacts,
                        ]
                    ]);
                } else {
                    $messages = [];
                    $form_messages = (array) $form->getMessages();
                    foreach ($form_messages  as $fieldname => $field_messages) {

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

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

   
                
                $key = Functions::sanitizeFilterString($this->params()->fromPost('key'));
                if (!$key) {
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_CACHE_KEY_EMPTY'
                    ]);
                }

                $value = $this->cache->getItem($key);
                if (!$value) {

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

                $records = unserialize($value);
                if (!$records) {
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_CACHE_INVALID'
                    ]);
                }
                
                
                $csv = "EMAIL|STATUS\r\n";


                $discoveryContactMapper = DiscoveryContactMapper::getInstance($this->adapter);
                $discoveryContactInteractionTypeMapper = DiscoveryContactInteractionTypeMapper::getInstance($this->adapter);

                $discoveryContactInteractionTypeMapper = DiscoveryContactInteractionTypeMapper::getInstance($this->adapter);
                $discoveryContactInteractionTypeDefault = $discoveryContactInteractionTypeMapper->fetchOneDefaultByCompanyId($currentCompany->id);
                if(!$discoveryContactInteractionTypeDefault) {
                    $discoveryContactInteractionTypeDefault = $discoveryContactInteractionTypeMapper->fetchOneFirstActiveByCompanyId($currentCompany->id);
                    $discoveryContactInteractionTypeDefault->default = DiscoveryContactInteractionType::DEFAULT_YES;
                    $discoveryContactInteractionTypeMapper->update($discoveryContactInteractionTypeDefault);
                }
                
                
                
                $discoveryContactInteractionMapper = DiscoveryContactInteractionMapper::getInstance($this->adapter);
                $discoveryContactLogMapper = DiscoveryContactLogMapper::getInstance($this->adapter);


                $new_contacts  = 0;
                $duplicate_contacts = 0;
                $error_contacts = 0;
                foreach ($records as $record) 
                {
                    $first_name =   $record['first_name'];
                    $last_name = $record['last_name'];
                    $email_personal = $record['email_personal'];
                    $email_company = $record['email_company'];
                    $company = $record['company'];
                    $position = $record['position'];
                    $country = $record['country'];
                    $state = $record['state'];
                    $city = $record['city'];
                    $phone = $record['phone'];
                    $extension = $record['extension'];
                    $movil = $record['movil'];
                    $whatsapp =  $record['whatsapp'];
                    $linkedin = $record['linkedin'];
                    $sector = $record['sector'];
                    $scholarship = $record['scholarship'];
                    
       
                    $discoveryContact = $discoveryContactMapper->fetchOneByCorporateEmailAndCompanyId($email_company, $currentCompany->id);
                    if ($discoveryContact) {
                        
                        $csv .= "$email_company|DUPLICATE\r\n";
                        $duplicate_contacts++;
                    } else {

                        $discoveryContact = new DiscoveryContact();
                        $discoveryContact->company_id = $currentCompany->id;
                        $discoveryContact->first_name = $first_name;
                        $discoveryContact->last_name = $last_name;
                        $discoveryContact->corporate_email = $email_company;
                        $discoveryContact->personal_email = $email_personal;
                        $discoveryContact->company = $company;
                        $discoveryContact->position = $position;
                        $discoveryContact->sector = $sector;
                        $discoveryContact->country = $country;
                        $discoveryContact->state = $state;
                        $discoveryContact->city = $city;
                        $discoveryContact->phone = empty($phone) ? '' : '+' . $phone;
                        $discoveryContact->phone_extension = $extension;
                        $discoveryContact->celular = empty($movil) ? '' : '+' . $movil;
                        $discoveryContact->whatsapp = empty($whatsapp) ? '' : '+' . $whatsapp;
                        $discoveryContact->linkedin = $linkedin;
                        $discoveryContact->scholarship = $scholarship;
                      
    
                        if($discoveryContactMapper->insert($discoveryContact)) {
                            $new_contacts++; 
                            
                            
                            if($discoveryContactInteractionTypeDefault) {
                                
                                $discoveryContactInteraction = new DiscoveryContactInteraction();
                                $discoveryContactInteraction->company_id = $currentCompany->id;
                                $discoveryContactInteraction->contact_id = $discoveryContact->id;
                                $discoveryContactInteraction->interaction_type_id = $discoveryContactInteractionTypeDefault->id;
                                $discoveryContactInteraction->user_id = $currentUser->id;

                                $discoveryContactInteractionMapper->insert($discoveryContactInteraction);
                            }
                            
                            $discoveryContactLog = new DiscoveryContactLog();
                            $discoveryContactLog->company_id = $currentCompany->id;
                            $discoveryContactLog->contact_id = $discoveryContact->id;
                            $discoveryContactLog->user_id = $currentUser->id;
                            $discoveryContactLog->activity =  'LABEL_RECORD_CONTACT_ADDED';
                            $discoveryContactLog->details = 'LABEL_FIRST_NAME : ' . $discoveryContact->first_name  . PHP_EOL .
                            'LABEL_LAST_NAME : ' . $discoveryContact->last_name  . PHP_EOL .
                            'LABEL_CORPORATE_EMAIL : ' . $discoveryContact->corporate_email  . PHP_EOL .
                            'LABEL_COMPANY : ' . $discoveryContact->company  . PHP_EOL .
                            'LABEL_POSITION : ' . $discoveryContact->position  . PHP_EOL .
                            'LABEL_COUNTRY : ' . $discoveryContact->country  . PHP_EOL;
                            
                            
                            if ($discoveryContact->state) {
                                $discoveryContactLog->details .= 'LABEL_STATE : ' . $discoveryContact->state  . PHP_EOL;
                            }
                            if ($discoveryContact->city) {
                                $discoveryContactLog->details .= 'LABEL_CITY : ' . $discoveryContact->city  . PHP_EOL;
                            }
                            if ($discoveryContact->phone) {
                                $discoveryContactLog->details .= 'LABEL_PHONE : ' . $discoveryContact->phone  . PHP_EOL;
                            }
                            if ($discoveryContact->phone_extension) {
                                $discoveryContactLog->details .= 'LABEL_PHONE_EXTENSION : ' . $discoveryContact->phone_extension  . PHP_EOL;
                            }
                            if ($discoveryContact->personal_email) {
                                $discoveryContactLog->details .= 'LABEL_PERSONAL_EMAIL : ' . $discoveryContact->personal_email  . PHP_EOL;
                            }
                            if ($discoveryContact->celular) {
                                $discoveryContactLog->details .= 'LABEL_CELULAR : ' . $discoveryContact->celular  . PHP_EOL;
                            }
                            if ($discoveryContact->whatsapp) {
                                $discoveryContactLog->details .= 'LABEL_WHATSAPP : ' . $discoveryContact->whatsapp  . PHP_EOL;
                            }
                            if ($discoveryContact->linkedin) {
                                $discoveryContactLog->details .= 'LABEL_LINKEDIN : ' . $discoveryContact->linkedin  . PHP_EOL;
                            }
                            if ($discoveryContact->scholarship) {
                                $discoveryContactLog->details .= 'LABEL_SCHOLARSHIP : ' . $discoveryContact->scholarship  . PHP_EOL;
                            }
                            
                            
                            if($discoveryContactLogMapper->insert($discoveryContactLog)) {
                                $csv .= "$email_company|NEW\r\n";
                            } else {
                                $csv .= "$email_company|ERROR\r\n";
                            }
                            
                            
                            
                        } else {
                            $csv .= "$email_company|ERROR\r\n";
                            $error_contacts++;
                        }
                    }
                }           
                
                $csv_filename = 'discovery-contact-' . date('Y-m-d H:i') . '.csv';
                $csv_filename = str_replace(' ', '-', $csv_filename);


                return new JsonModel([
                    'success' => true,
                    'data' => [
                        'new_contacts' => $new_contacts,
                        'error_contacts' => $error_contacts,
                        'duplicate_contacts' => $duplicate_contacts,
                        'csv_filename' => $csv_filename,
                        'csv_base64_content' => base64_encode($csv),
                    ]
                ]);
            } else {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
                ]);
            }
        }

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