<?php

namespace app\controllers\general;

use Yii;
use yii\filters\AccessControl;
use yii\helpers\Url;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\data\ActiveDataProvider;
use app\models\User;
use app\models\GeneralSideMenu;
use app\models\UserForm;

class UsersController extends Controller {

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['delete'],
                        'allow' => true,
                        'roles' => ['general_deleteUser'],
                    ],
                    [
                        'actions' => ['update'],
                        'allow' => true,
                        'roles' => ['general_updateUser'],
                    ],
                    [
                        'actions' => ['create'],
                        'allow' => true,
                        'roles' => ['general_createUser'],
                    ],
                    [
                        'actions' => ['view'],
                        'allow' => true,
                        'roles' => ['general_viewUser'],
                    ],
                    [
                        'actions' => ['index'],
                        'allow' => true,
                        'roles' => ['general_deleteUser', 'general_updateUser',
                            'general_createUser', 'general_viewUser'],
                    ],
                    [
                        'actions' => [],
                        'allow' => true,
                        'roles' => ['admin'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    protected function populateRolesArray() {
        $auth = Yii::$app->authManager;
        $rawRoles = $auth->getRoles();
        $roles = [];
        foreach ($rawRoles as $name => $value) {
            $roles[$name] = $name;
        }
        return $roles;
    }

    protected function getSelected($user = NULL) {
        $auth = Yii::$app->authManager;
        $currentRole = $user ? $auth->getRolesByUser($user->getId()) : NULL;
        $selected = null;
        if ($currentRole != NULL) {
            foreach ($currentRole as $value) {
                $selected = $value->name;
            }
        }
        return $selected;
    }

    public function actionIndex() {
        $users = new User();
        $list = new ActiveDataProvider([
            'query' => $users->listAll(),
            'key' => 'username',
            'sort' => [
                'attributes' => [
                    'username', 'email',
                ],
            ],
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);
        $menu = new GeneralSideMenu();
        return $this->render('index', [
                    'list' => $list,
                    'menu' => $menu->getMenu(),
        ]);
    }

    public function actionDelete() {
        $user = User::findOne(['username' => Yii::$app->request->get('id')]);
        if ($user->id != 1 && $user->getId()) {
            $auth = Yii::$app->authManager;
            $auth->revokeAll($user->getId());
            $user->delete();
        }
        return $this->redirect(Url::toRoute('general/users/index'));
    }

    public function actionUpdate() {
        $model = new UserForm(['scenario' => 'update']);
        $user = new User(User::findByUsername(Yii::$app->request->get('id')));
        $model->oldusername = $model->username = $user->username;
        $model->oldemail = $model->email = $user->email;
        $model->mikrotik = $user->mikrotik;
        $roles = $this->populateRolesArray();
        $selected = $this->getSelected($user);
        $menu = new GeneralSideMenu();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->update()) {
                return $this->redirect(Url::toRoute('general/users/index'));
            }
        }
        return $this->render('update', [
                    'isadmin' => $user->getId() == 1 ? true : false,
                    'roles' => $roles,
                    'selected' => $selected,
                    'model' => $model,
                    'menu' => $menu->getMenu(),
        ]);
    }

    public function actionCreate() {
        $model = new UserForm(['scenario' => 'create']);
        $menu = new GeneralSideMenu();
        $roles = $this->populateRolesArray();
        $selected = $this->getSelected();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->create()) {
                return $this->redirect(Url::toRoute('general/users/index'));
            }
        }
        return $this->render('create', [
                    'roles' => $roles,
                    'selected' => $selected,
                    'model' => $model,
                    'menu' => $menu->getMenu(),
        ]);
    }

    public function actionView() {
        $menu = new GeneralSideMenu();
        $model = new UserForm(['scenario' => 'view']);
        $user = User::findByUsername(Yii::$app->request->get('id'));
        $roles = $this->populateRolesArray();
        $selected = $this->getSelected($user);
        $model->username = $user->username;
        $model->email = $user->email;
        $model->mikrotik = $user->mikrotik;
        return $this->render('view', [
                    'roles' => $roles,
                    'selected' => $selected,
                    'model' => $model,
                    'menu' => $menu->getMenu(),
        ]);
    }

}
