<?php

declare(strict_types=1);

namespace apexl\Io\modules\userDisplay\controllers;

use apexl\Io\modules\component\Factories\GenericComponentFactory;
use apexl\Io\modules\display\controllers\DisplayController;
use apexl\Io\modules\display\services\Render;
use apexl\Io\modules\user\services\CurrentUserFactory;
use apexl\Io\services\Output;
use apexl\Io\services\RecursionFinderService;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class ForgotPasswordDisplayController extends DisplayController
{
    public function __construct(
        private CurrentUserFactory $currentUserFactory,
        GenericComponentFactory $componentFactory,
        Render $render,
        RecursionFinderService $recursionFinderService,
        Output $output,
    ) {
        parent::__construct(
            $componentFactory,
            $render,
            $recursionFinderService,
            $output
        );
    }

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        if ($this->currentUserFactory->get()->isLoggedIn()) {
            $this->output->addMetadata('user.login.redirect', 'redirect', '/');
            return $this->json($response);
        }

        $this->render->setActive('noUI');
        $this->render->setPageTitle('Forgotten Password');

        $form = new Form()
            ->setMethod('post')
            ->setActionUrl($this->routeManager->getRoutePattern('user.forgot-password'))
            ->setSubmitText('Get Reset Link')
            ->addField(
                new inputField('email')->setPlaceholder(
                    System::getVariable('user_login_email_placeholder') ?? 'Enter your email address'
                )->setLabel('Email Address')->setInputType('email')->isRequired()
            )
            ->title("Enter your email to reset your password.")
            ->addClass('forgotten-password-form')
            ->setID('forgottenPassword');

        $components[] = $form;

        $components[] = new BasicLink()->addClass('forgottenPasswordLink')->addRoute(
            $this->routeManager->getRoutePattern('user.display.login')
        )->addText(System::getVariable('user_login_return_login_text') ?? 'Return to login');

        $this->output->addResponse($request, $this->render->build($components));

        return $this->json($response);
    }
}


