<?php

declare(strict_types=1);

namespace App\Controller\Portal;

/**
 * Controlador de autenticación del portal de clientes (login/logout).
 */
class PortalController extends PortalAppController
{
    public function beforeFilter(\Cake\Event\EventInterface $event)
    {
        parent::beforeFilter($event);

        $this->Authentication->addUnauthenticatedActions(['login']);
    }

    public function login()
    {
        $this->viewBuilder()->setLayout('portal_login');
        $this->request->allowMethod(['get', 'post']);

        $result = $this->Authentication->getResult();

        if ($result->isValid()) {
            $identity = $this->request->getAttribute('identity');

            if (!$identity->get('activo')) {
                $this->Authentication->logout();
                $this->Flash->error('Tu cuenta está inactiva. Contacta con nosotros.');
                return $this->redirect(['prefix' => 'Portal', 'controller' => 'Portal', 'action' => 'login']);
            }

            return $this->redirect(['prefix' => 'Portal', 'controller' => 'Dashboard', 'action' => 'index']);
        }

        if ($this->request->is('post') && !$result->isValid()) {
            $this->Flash->error('Email o contraseña incorrectos.');
        }
    }

    public function logout()
    {
        $result = $this->Authentication->getResult();
        if ($result->isValid()) {
            $this->Authentication->logout();
        }

        return $this->redirect(['prefix' => 'Portal', 'controller' => 'Portal', 'action' => 'login']);
    }
}
