<?php

namespace Diamond\Modules\AdminAuth;

use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Core\Form\Control\ReCaptcha;
use Core\Template\Template;
use Diamond\Application\User\UserService;
use Diamond\Config\Main;
use Core\Form\Factory\SimpleValidationForm as FormFactory;
use Core\Form\Control\Input;
use Core\Form\Control\Button;
use Core\Form\Control\InputPassword;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * Description of AdminAuth
 *
 * @author Dmitriy
 */
class AdminAuth extends \Core\ModuleController implements RequestAwareInterface
{

    use RequestAwareTrait;

    /**
     * Лимит ошибочных вводов при котором необходимо активировать каптчу
     *
     * @var int
     */
    public $limit_auth = 3;

    protected $template;

    protected $config;

    protected $formFactory;

    protected $userService;

    protected $session;

    public function __construct(
        Template $template,
        Main $config,
        FormFactory $formFactory,
        UserService $userService,
        Session $session
    )
    {
        $this->template = $template;
        $this->config = $config;
        $this->formFactory = $formFactory;
        $this->userService = $userService;
        $this->session = $session;
    }

    /**
     * @return string
     * @throws \ReflectionException
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function process(): string
    {

        $form
            = $this
            ->buildForm()
            ->addValidationSuccessEvent([$this, 'submitForm']);

        $siteName = $this->config->getSite_name();

        return $this->render([
            'form' => $form->render(),
            'site_name' => $siteName ?? 'site.ru'
        ]);
    }

    private function buildForm()
    {
        $form = $this->formFactory
            ->build('admin_auth')
            ->setRequired_label(NULL);

        $form->setMessageBlank('<div class="alert alert-danger %s">%s</div>');

        $form
            ->addField(
                (new Input('user_name'))
                    ->setClass('form-control')
                    ->addAttr('placeholder','Логин')
                    ->addAttr('autofocus',1)
                , 'Логин', 'required|email')
        ;

        $form->addField(
            (new InputPassword('user_password'))
                ->setClass('form-control')
                ->addAttr('placeholder','Пароль')
            , 'Пароль',
                'required|valid_email')
            ->addControl(
                (new Button('submit', 'Войти'))
                    ->setClass('btn btn-primary btn-lg btn-block')
                );

        if ($this->session->get('auth_count') >= $this->limit_auth) {
            $this->template->addScript("<script src='https://www.google.com/recaptcha/api.js'></script>");

            $key = $this->config->getReCaptchaKey();
            $secret = $this->config->getSecretKey();
            $form
                ->addField(
                    new ReCaptcha('captcha',  $key,  $secret),'Проверочный код',['required', 'recaptcha']
                );

        }

        $form->setCustomTpl($this->includeTpl('form'));

        return $form;
    }


    /**
     * @param array $data
     * @param \Core\Form\Simpleform $form
     * @return bool
     */
    public function submitForm(array $data, \Core\Form\Simpleform $form): bool
    {
        if ($this->userService->authUser($data['user_name'],
            md5($data['user_password']),
            $this->request->request->get('remember') === '1')) {
            $response = new RedirectResponse('auth admin');
            $response->headers->set('Location',  admin_path());
            $this->session->set('auth_count', 0);
            $response->send();
            die();
        }

        $new = clone  $form;

        $new->addCustomMessage('Пользователь не найден');

        $form->addBuffer($new->generateForm());

        $c = (int)$this->session->get('auth_count');

        $c++;

        $this->session->set('auth_count', $c);

        return false;
    }

}
