<?php

namespace Diamond\Modules\AdminUsers;


use ActiveTable\DataTableEngine;
use Core\Helpers\Date;
use Diamond\Domain\User\Contracts\UserEntityInterface;
use Diamond\Domain\UserGroup\UserGroupCollection;
use Diamond\Helpers\Form;
use Diamond\Infrastructure\Models\Stat\StatQuery;
use DiamondTable\CommandFactory;
use Propel\Runtime\ActiveQuery\Criteria;

trait FormTrait
{


    /**
     * @param DataTableEngine $table
     * @param UserGroupCollection $userGroups
     * @return string
     */
    public function buildForm(DataTableEngine $table, UserGroupCollection $userGroups)
    {

        $contrBuilder = $this->controlBuilder;

        //FORM forgotten pasword
        if ($this->request->query->get('type') === 'password') {

            $table
                ->getCommandFactory()
                ->addCommand(
                    CommandFactory::FORM_SAVE,
                    new ChangePasswordCommand(
                        $this->securePolicy,
                        $this->request,
                        $this->notification,
                        $this->userRepository,
                        admin_path('/diamond/system/users')
                    )
                );

            return
                $table
                    ->addField(
                        $contrBuilder->buildFormHeader('Смена пароля')
                    )
                    ->addField(
                        $contrBuilder->buildInputPassword('new_password'), true,'Новый пароль'
                    )
                    ->addField(
                        $contrBuilder
                            ->buildCheckbox('notify','Y')
                            ->setClass('magic-checkbox'), false,'Отправить уведомление по email'
                    )

                    ->render();


        } else {
            //STANDART TABLE
            $table
                ->addField(
                    $contrBuilder->buildTextLabel('createdAt')->setFn(function (UserEntityInterface $userEntity){
                        return self::createdAt($userEntity);
                    })
                )
                ->addField(
                    $contrBuilder->buildTextLabel('lastUsedTime')->setFn(function (UserEntityInterface $userEntity){
                        return self::lastUsedTime($userEntity);
                    })
                )
                ->addField(
                    $contrBuilder->buildInput('name'), true,null,'ФИО'
                )
                ->addField(
                    $contrBuilder->buildInput('email'), true, null, 'Будет использоваться как логин для входа систему'
                )
                ->addField(
                    $contrBuilder->buildHidden('password')->setValue(md5(time()))
                )
                ->addField(
                    $contrBuilder->buildDropdownUniform('groupId', Form::prepareDropdown($userGroups)), true, null, 'Для настройки прав доступа'
                )
                ->addField(
                    $this->controlBuilder->buildNiftySimpleSwitchery('usrDelete',1,0,'#e33a4b'), true
                );

            return $table->render();
        }
    }

    public static function lastUsedTime(UserEntityInterface $userEntity): string
    {
        $last =  StatQuery::create()->filterByAdminUser($userEntity->getId())->orderByDatetime(Criteria::DESC)->limit(1)->findOne();

        if(!$last){
            return '';
        }

        return $last->getDatetime()->format(\Diamond\Helpers\Date::formatDisplay());
    }

    public static function createdAt(UserEntityInterface $userEntity): string
    {
        return (string)$userEntity->getCreatedAt()?->format(Date::formatDisplay());
    }

}