<?php

namespace Diamond\Modules\AdminProfileMain;

use Core\Form\Factory\SimpleValidationForm as FormFactory;
use Core\Form\Control as ControlForm;
use Core\Form\ControlBuilder;
use Diamond\Application\User\UserService;

/**
 * Description of AdminProfileMain
 *
 * @author Diamond Code Generator
 */
class AdminProfileMain extends \Core\ModuleController
{

    public function __construct(private ControlBuilder $contrBuilder,
                                private FormFactory    $formF,
                                private UserService    $authService)
    {
    }


    public function process(): string
    {

        $registry = $this->formF->build('main');
        $user = $this->authService->getAuthUser();

        $registry
            ->setClass('panel-body form-horizontal form-padding')
            ->addValidationSuccessEvent([$this, 'submit'])
            ->addField(
                $this
                    ->contrBuilder
                    ->buildInput('name')
                    ->setClass('form-control')
                    ->setValue($user->getName()
                    ),
                'Имя (ФИО)',
                'required'
            )
            ->addField(
                $this
                    ->contrBuilder
                    ->buildInput('email')
                    ->setClass('form-control')
                    ->setValue($user->getEmail()),
                'Email',
                'required'
            )
            ->addControl((new ControlForm\Submit('submit', 'Сохранить'))->setClass('btn btn-success'))
        ;

        return $registry->render();
    }

    /**
     * @param $data
     * @param \Core\Form\Simpleform $form
     * @return bool
     */
    public function submit($data, \Core\Form\Simpleform $form): bool
    {
        $user = $this->authService->getAuthUser();
        $user
            ->setName($data['name'])
            ->setEmail($data['email'])
            ->save();
        $form
            ->setBackUrl(admin_path('/diamond/profile/main'))
            ->addCustomMessage(
                'Данные успешно сохранены. ' .
                $form->createReturnLink(), \Core\Form\Simpleform::MESSAGE_SUCCESS);
        return true;
    }

    /**
     * @return string
     */
    private function getUrl(): string
    {
        return admin_path('/diamond/profile/password');
    }

}