<?php
declare(strict_types=1);

namespace App\Controller\Admin;

use Cake\Event\EventInterface;
use Cake\Http\Response;

class SessionController extends AdminAppController
{
    public function beforeFilter(EventInterface $event): void
    {
        parent::beforeFilter($event);
        $this->Authentication->addUnauthenticatedActions(['login', 'logout']);
    }

    public function login(): ?Response
    {
        $this->viewBuilder()->setLayout('admin_bare');
        $result = $this->Authentication->getResult();

        if ($result && $result->isValid()) {
            $redirect = $this->request->getQuery('redirect', [
                'prefix' => 'Admin',
                'controller' => 'ContactMessages',
                'action' => 'index',
            ]);

            return $this->redirect($redirect);
        }

        if ($this->request->is('post') && !$result->isValid()) {
            $this->Flash->error('Invalid email or password.');
        }

        return null;
    }

    public function logout(): Response
    {
        $this->Authentication->logout();
        $this->Flash->success('You have been logged out.');

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