<?php

namespace Diamond\Modules\AdminUsers;

use ActiveTable\ColumnTable;
use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Core\Form\Control\MenuItem;
use Core\Form\Control\MenuItemWindow;
use Core\Form\Control\Switchery;
use Core\Form\ControlBuilder;
use Core\Form\FormBuilder;
use Core\Form\NiftyControlBuilder;
use Core\Helpers\Date;
use Core\ModuleController;
use Diamond\Application\Notification\NotificationService;
use Diamond\Application\User\UserService;
use Diamond\Domain\User\Contracts\UserEntityInterface;
use Diamond\Helpers\Form;
use Diamond\Infrastructure\Models\Stat\StatQuery;
use Diamond\Infrastructure\Models\User\User;
use Diamond\Repositories\User\UserCriteria;
use Diamond\Repositories\User\UserRepository;
use Diamond\Repositories\UserGroup\UserGroupCriteria;
use Diamond\Repositories\UserGroup\UserGroupRepository;
use DiamondTable\TableFactory;
use Propel\Runtime\ActiveQuery\Criteria;


/**
 * Description of AdminUsers
 *
 * @author Dmitriy
 */
class AdminUsers extends ModuleController implements RequestAwareInterface
{
    use RequestAwareTrait;
    use FormTrait;


    public function __construct(private UserRepository      $userRepository,
                                protected NiftyControlBuilder $controlBuilder,
                                private UserGroupRepository $userGroupRepo,
                                private TableFactory        $tableFactory,
                                private FormBuilder         $formBuilder,
                                private UserService         $securePolicy,
                                private NotificationService $notification)
    {}

    public function process(): string
    {
        $contrBuilder = $this->controlBuilder;

        $table = $this->tableFactory->buildAdminTable($this->userRepository, UserCriteria::create(), 'Добавить пользователя');

        $userGroups = $this->userGroupRepo->findByCriteria(UserGroupCriteria::create());

        $table
            ->setDefaultSortColumn('id', 'desc');

        $table
            //COLUMNS
            ->addColumn(
                (new ColumnTable('id', '№'))->setWidth(40)->setSorted(true)
            )
            ->addColumn(
                (new ColumnTable('name', 'Имя'))->setSorted(true)->setExported(true)
            )
            ->addColumn(
                (new ColumnTable('email', 'E-mail'))
                    ->setSorted(true)
            )
            ->addColumn(
                (new ColumnTable('phone', 'Тел.'))
                    ->setSorted(true)
            )
            ->addColumn(
                (new ColumnTable('groupId', 'Группа'))
                    ->setFormat($this, 'formatGroup')
                    ->setSorted(true)
            )
            ->addColumn(
                (new ColumnTable('createdAt', 'Дата создания'))
                    ->setFormat($this, 'formatCreatedAt')
            )
            ->addColumn(
                (new ColumnTable('lastUsedTime', 'Последний вход'))
                    ->setFormat($this, 'formatLastUsedTime')
            )
            ->addColumn(
                (new ColumnTable('access', 'Доступ в систему'))
                    ->setFormat($this, 'formatAccess')
            )
            ->addColumn(
                (new ColumnTable('usrDelete', 'Заблокирован'))
                    ->setFormat($this, 'formatDelete')
            )
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setWidth(120)
                    ->setFormat($this, 'formatActions')
            )
            //FILTERS
            ->addFilter(
                $contrBuilder->buildInput('filter_by_id')
            )
            ->addFilter(
                $contrBuilder->buildInput('search_by_name')
            )
            ->addFilter(
                $contrBuilder->buildInput('search_by_email')
            )
            ->addFilter(
                $contrBuilder->buildInput('search_by_phone')
            )
            ->addFilter(
                $contrBuilder->buildDropdownUniform('filter_by_groupId', Form::prepareDropdown($userGroups))
            );

        return $this->buildForm($table, $userGroups);
    }

    public function formatLastUsedTime(UserEntityInterface $userEntity): string
    {
        return self::lastUsedTime($userEntity);
    }

    public function formatCreatedAt(UserEntityInterface $userEntity): string
    {
        return self::createdAt($userEntity);
    }


    public function formatActions(UserEntityInterface $userEntity): string
    {
        $label = $userEntity->getPassword() > '' ? 'Изменить пароль' : 'Установить пароль';

        return $this->controlBuilder->buildActionMenuAdmin([
            new MenuItem(
                admin_path('/diamond/system/users').'?type=password&fn=edit&id=' . $userEntity->getId(), $label, 'demo-pli-lock-user'
            ),
            new MenuItemWindow(
                admin_path('/diamond/system/user_history_lite?id='. $userEntity->getId()), 'История', 'demo-pli-magnifi-glass'
            )
        ], (int)$userEntity->getId())->render();
    }

    /**
     * @param User $user
     * @return string
     */
    public function formatDelete(UserEntityInterface $user): string
    {
        $data = [
            'class' => self::class,
            'id' => $user->getId(),
            'fn' => 'changeBlocked'
        ];
        return (new Switchery($data, $user->getUsrDelete()))->setColor('#e33a4b')->render();
    }

    public function formatGroup(UserEntityInterface $user): string
    {
        return $user->getUserGroup()->getName();
    }

    public function changeBlocked(int $id, bool $checked): void
    {
        /**
         * @var User $user
         */
        $user = $this->userRepository->findById($id);
        $user->setUsrDelete($checked);
        $this->userRepository->save($user);
    }

    public function formatAccess(UserEntityInterface $user): string
    {
       if(empty($user->getPassword()) && !empty($user->getActivation())){
           return $this->controlBuilder->buildTableLabel( 'Подтверждение','warning')->render();
       }
        return $this->controlBuilder->buildTableLabel( 'Есть','success')->render();
    }

}