<?php

namespace Diamond\Modules\AdminUserPassword;

use Core\Form\ControlBuilder;
use Core\ModuleController;
use Diamond\Infrastructure\Models\User\User as User2;
use Diamond\Repositories\User;
use Core\Form\FormBuilder;

/**
 * Description of AdminUsers
 *
 * @author Dmitriy
 */
class AdminUserPassword extends ModuleController
{
    protected $formBuilder;
    protected $userRepo;
    protected $registry;
    protected $controlBuilder;
    protected $userGroupRepo;
    protected $form;

    public function __construct(User $userRepo, ControlBuilder $controlBuilder, FormBuilder $form)
    {
        $this->userRepo = $userRepo;
        $this->controlBuilder = $controlBuilder;
        $this->formBuilder = $form;
    }

    public function process(): string
    {

        $this->form = $form = $this->formBuilder->buildSimpleValidationForm("change-password",admin_path('/diamond/users'));
        $contrBuilder = $this->controlBuilder;

        $form->addField($contrBuilder->buildInputSmall("password"), "Новый пароль", "required");

        $form->addFieldControl($contrBuilder->buildSubmitButton("submit", "Сохранить"));
        $form->addValidationSuccessEvent([$this, 'changePassword']);
        return $form->render();
    }

    /**
     * @param User2 $user
     * @return string
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function formatGroup(User2 $user):string
    {
        return $user->getUserGroup()->getName();
    }

    /**
     * @param array $data
     * @param \Core\Form\Simpleform $form
     * @return bool
     */
    public function changePassword(array $data, \Core\Form\Simpleform $form): bool
    {

        $user = $this->userRepo->findById(input_get("id"));
        $user->setPassword(md5(input_post("password")));
        $user->save();
        $backUrl = admin_path('/diamond/users') . "?id=" . input_get("id");
        $this->form->setBackUrl($backUrl);

        $form->addCustomMessage('Пароль успешно изменен. ' . $this->form->createReturnLink(),
            \Core\Form\Simpleform::MESSAGE_SUCCESS);

        return true;
    }

}
