<?php

namespace backend\controllers;

use Yii;
use common\models\User;
use backend\models\UserSearch;
use backend\models\UserCreate;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\base\Object;
use backend\models\UserUpdate;
use common\models\Account;
use common\models\UserAccountAssignment;
use common\components\RoleDefinition;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends \backend\controllers\BackendController
{
	

	public function behaviors()
	{
		return [
			'access' => [
				'class' => \yii\filters\AccessControl::className(),
				'rules' => [
					// allow authenticated users
					[
					'actions' => [ 'index','view' ,'role'],
					'allow' => true,
					'roles' => ['employee','admin' ],
					],
					// allow authenticated users
					[
					'actions' => [ 'create', 'update'],
					'allow' => true,
					'roles' => ['admin'],
					],
				// everything else is denied
				],
			],
		];
	}
	
	
    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new UserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        
        

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new UserCreate();
        
        $accounts = Account::readAccounts();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
        	
        	$this->updateAccountAssignments($model);
        	
            return $this->redirect(['index' ]);
            
        } 
        
            return $this->render('create', [
                'model' => $model,
            	'accounts' => $accounts,
            ]);
    }
    
    public function updateAccountAssignments($model){
    		
    		echo "saving accounts";
    		UserAccountAssignment::deleteAll(['id_user' => $model->id]);
        	foreach ( $model->selected_accounts as $id_account ){
        		echo "saving account";
        		$uaa = new UserAccountAssignment();
        		$uaa->id_user = $model->id;
        		$uaa->id_account = $id_account;
        		$uaa->save();
        	}
        	
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model =  UserUpdate::findOne(['id' => $id]);
        
        if ( Yii::$app->authManager->checkAccess($model->id, 'admin')){
        	$model->role = 'admin';
        } else if ( Yii::$app->authManager->checkAccess($model->id, 'employee')){
        	$model->role = 'employee';
        }else if ( Yii::$app->authManager->checkAccess($model->id, 'reception')){
        	$model->role = 'reception';
        }
        
        if ( $model == null ){
        	throw new NotFoundHttpException('The requested page does not exist.');
        }
        
        $accounts = Account::readAccounts();
        
        $this->applyAccounts($model);

        

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
        	$this->updateAccountAssignments($model);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
        }
            return $this->render('update', [
                'model' => $model,
                'accounts' => $accounts,
            ]);
    }
    
    private function applyAccounts($model ){
    	$assignedAccounts = $model->userAccountAssignments;
    	foreach ($assignedAccounts as $acc ){
    		$model->selected_accounts[] = $acc->id_account;
    	}
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {

    	$user = $this->findModel($id);
    	
    	$user->updateAttributes(['status' => User::STATUS_DELETED]);

        return $this->redirect(['index']);
    }
    
    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionRole()
    {
    	$model = new  \backend\models\RoleForm();
    
    		$model->availablePermissions = [
    				[
	    				'name' =>  "reception.transfers",
    					'description' => 'Tranzakciók'
    				]
    		];
    
    		
    		
    		
    	if ($model->load(Yii::$app->request->post())   ) {
    		if ( $model->validate() &&  $model->save()){
    			Yii::$app->session->setFlash('success', 'Jogosultságok elmentve');
	    		return $this->redirect(['role' ]);
    		}
    	}else{
	    	$am = Yii::$app->authManager;
	    	$children = $am->getChildren(User::ROLE_RECEPTION);
	    	$model->permissions = [];
	    	foreach ($children as $child){
	    		$model->permissions[] = $child->name;
	    	}
    	}
    
    	return $this->render('role', [
    			'model' => $model,
    	]);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
