<?

namespace Shop\Modules\AdminShopManagers;

use Core\Registry\Column;
use Core\Registry\Field;

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

    protected $repo;
    protected $tableFactory;
    protected $cBuilder;
    protected $shopRepo;
    protected $userGroupRepo;
    protected $userService;

    function __construct(\Diamond\Factory\Table $tableFactory, \Core\Form\ControlBuilder $cBuilder,
                         \Shop\Repositories\ShopManager $repo, \Shop\Repositories\Shop $shopRepo, 
                            \Diamond\Repositories\UserGroup $userGroupRepo, \Diamond\Services\User $userService)
    {
        $this->tableFactory = $tableFactory;
        $this->repo = $repo;
        $this->cBuilder = $cBuilder;
        $this->shopRepo  = $shopRepo;
        $this->userGroupRepo = $userGroupRepo;
        $this->userService = $userService;
    }

    
    public function process() {
        
        $table = $this->tableFactory->buildAdminTable("managers", $this->repo);
        
        $table->addValidationSuccessEvent($this, "actionCreateUserAfterUpdate");
        $table->addValidationPrepareEvent($this, "actionManagerValidate");
        
        $userGroups = \Shop\Helpers\Form::prepareDropdownWithDef($this->userGroupRepo,null,"права доступа","getDropdownListWhitoutRoot");
        
        $table
                ->addColumn(new Column("id", "№", 20, false, true))
                ->addColumn(new Column("name", "ФИО", 120))
                ->addColumn(new Column("email", "Электронная почта", 70))
                ->addColumn(new Column("phone", "Телефон", 70))
                ->addColumn((new Column("comment", "Комментарий", 120))->setFn([$this, "formatComment"]))
                ->addColumn((new Column("shopId", "Торг.точка", 120))->setFn([$this, "formatShop"]))
                ->addColumn(
                        (new Column("user", "Системный пользователь", 90))
                        ->setAlign("center")
                        ->setFn([$this, "formatAccess"]))
        ;        
        
        $table
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildInput("name"), null, "required"
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildInput("email"), null, "required"
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildInput("phone")
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildTextArea("comment")
                ))
                ->addField(new Field(
                        $this->cBuilder
                        ->buildDropdownUniform("shopId", \Shop\Helpers\Form::prepareDropdown($this->shopRepo,"торг.точку")), null, "required"
                ))  
                ->addField(new Field(
                        $this->cBuilder
                        ->buildDropdownUniform("userGroupId", $userGroups) , "Права доступа",null,"персональный доступ к системе"
                ))
                ;
                
                
        return $table->render();
    }
    
    public function formatAccess(\Shop\Models\Manager\Manager $manager)
    {
        $user = \Diamond\Models\User\UserQuery::create()
                ->findOneByEmail($manager->getEmail());
        
        return !$user ? " - " : anchor("/admin/diamond/users?id=" . $user->getId() , "установлен");
    }
    
    /**
     * 
     * @param \Shop\Models\Manager\Manager $manager
     * @return type
     */
    public function formatComment(\Shop\Models\Manager\Manager $manager)
    {
        return \Shop\Helpers\Text::clearText($manager->getComment(), 120);
    }
    
    /**
     * 
     * @param \Shop\Models\Manager\Manager $manager
     * @return type
     */
    public function formatShop(\Shop\Models\Manager\Manager $manager)
    {
        $shop = $manager->getShop();
        return sprintf(
                "%s (%s)", $shop->getTitle(), \Shop\Helpers\Shop::getShopType($shop)
                );
    }    
    
    
    public function actionCreateUserAfterUpdate(array $data, \Core\Form\RepoForm $form)
    {
        try{
            if(!empty($data["userGroupId"])){

                $user = $this->userService->creatOrUpdateUser($data["name"], $data["email"], $data["userGroupId"]);
                
                $form->addCustomMessage(
                    "Пользователь системы успешно создан", 
                    \Core\Form\RepoForm::MESSAGE_SUCCESS
                    );
            }   
            
        } catch (\Diamond\Exceptions\UserException $ex) {
            
            $form->addCustomMessage(
                    "Не удалось создать пользователя системы, ошибка: " . $ex->getMessage(), 
                    \Core\Form\RepoForm::MESSAGE_ERROR
                    );
        }
        
        return true;
    }   
    
    /**
     * 
     * @param array $data
     * @param \Core\Form\RepoForm $form
     * @return boolean
     */
    public function actionManagerValidate(array $data, \Core\Form\RepoForm $form)
    {
        
        //редактирование записи, сразу выход
        if($form->getEntity()->getId() > 0){
            return $data;
        }
        
        $manager = \Shop\Models\Manager\ManagerQuery::create()
                ->findOneByEmail($data["email"])
                ;
        
        if(!$manager){
            return $data;
        }
        
        $form->addCustomMessage(sprintf(
                "Менеджер с указанным email `%s` уже существует, укажите другой email",$data["email"]
                ), \Core\Form\RepoForm::MESSAGE_ERROR );
        
        return false;
    }

}               