<?php
namespace controllers;

use services\authorization\AssignUserRoles;
/**
 * User controller
 * @author Jérôme Brilland
 * @version 2.1
 * @copyright (c) 2019-2022, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class UserController extends \CRUDController {

    protected $modelClassName = 'models\User';

    public function doList() {
        parent::doList();
        $authorization = \IoC::resolve( 'authorization' );
        $authorization->authorize( 'view_users' );
        $i18n = \IoC::resolve( 'i18n' );
        $this->title = $i18n->__( 'users' );
        $this->users = $this->models;
    }

    public function doSearch() {
        $this->where = ['username[~]' => $this->request->getParameters()->getString( 'username') ];
        $this->doList();
        $this->render( 'list.html' );
    }

    public function doAddform() {
        parent::doAddform();
        $authorization = \IoC::resolve( 'authorization' );
        $authorization->authorize( 'create_user' );
        $i18n = \IoC::resolve( 'i18n' );
        $this->title = $i18n->__( 'add_user' );
    }

    public function doAdd() {
        $authorization = \IoC::resolve( 'authorization' );
        $authorization->authorize( 'create_user' );
        parent::doAdd();
    }

    protected function afterAdd() {
        $assignRoles = new AssignUserRoles( $this->model->user_id, $this->request->getParameters()->getArray( 'roles' ) );
        $assignRoles->perform( $this );
        $this->redirect( BASE_URL . 'user/list' );
    }

    public function doUpdateform() {
        parent::doUpdateform();
        $authorization = \IoC::resolve( 'authorization' );
        $authorization->authorize( 'update_user' );
        $i18n = \IoC::resolve( 'i18n' );
        $this->title = $i18n->__( 'update_user' );
    }

    public function doUpdate() {
        $authorization = \IoC::resolve( 'authorization' );
        $authorization->authorize( 'update_user' );
        parent::doUpdate();
    }

    protected function afterUpdate() {
        $assignRoles = new AssignUserRoles( $this->model->user_id, $this->request->getParameters()->getArray( 'roles' ) );
        $assignRoles->perform( $this );
        $this->redirect( BASE_URL . 'user/list' );
    }

    public function doDelete() {
        $authorization = \IoC::resolve( 'authorization' );
        $authorization->authorize( 'delete_user' );
        parent::doDelete();
    }

}
