<?php
namespace Opentalent\OtCore\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use TYPO3\CMS\Core\Http\RedirectResponse;

/**
 * Check the existence of a 'login_failed' cookie and its value. If the cookie exists and if its value is
 * true, store the information as a global variable: `$_SESSION['login_failed']`.
 *
 * @internal
 */
class PostLoginFailureHandler implements MiddlewareInterface
{
    public function __construct() {}

    /**
     *
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if (isset($_COOKIE['login_failed'])) {
            $_SESSION['login_failed'] = (bool)$_COOKIE['login_failed'];

            // Remove cookie
            unset($_COOKIE['login_failed']);
            setcookie('login_failed', '', time() - 3600, '/');
        }

        // just pass the plate to the next middleware...
        return $handler->handle($request);
    }
}
