<?php

namespace Diamond\Modules\AdminProfilePassword;

use Core\Form\Simpleform;
use Diamond\Application\User\UserService;
use Diamond\Repositories\User;
use Core\Form\ControlBuilder;
use Core\Form\FormBuilder;
use Diamond\Services\Auth;

/**
 * Description of AdminProfilePassword
 *
 * @author Diamond Code Generator
 */
class AdminProfilePassword extends \Diamond\Modules\AdminUserPassword\AdminUserPassword
{

    public function __construct(User $userRepo,
                                ControlBuilder $controlBuilder,
                                FormBuilder $form,
                                private UserService $authService)
    {
        parent::__construct($userRepo, $controlBuilder, $form);
    }

    public function process(): string
    {

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

        $form->setClass('panel-body form-horizontal form-padding');
        $form->addField($contrBuilder->buildInputPassword("current_password")->setClass('form-control'), "Текущий пароль", "required");
        $form->addField($contrBuilder->buildInputPassword("password")->setClass('form-control'), "Новый пароль", "required");

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

    public function changePassword($data, Simpleform $form): bool
    {

        $user = $this->authService->getAuthUser();

        if($user->getPassword() !== md5($data['current_password'])){
            $form->addCustomMessage('Пароль не верный' , Simpleform::MESSAGE_ERROR);
            $form->addBuffer($form->generateForm($data));
            return false;
        }

        $this->authService->changeUserPassword($user->getId(), $data['password']);
        $form->setBackUrl(admin_path("/diamond/profile/main"));
        $form->addCustomMessage('Пароль успешно изменен.'. $form->createReturnLink(), Simpleform::MESSAGE_SUCCESS);
        return true;
    }
}               