<?php
namespace frontend\components;

use yii\base\Behavior;
use yii\web\Controller;
use common\models\Account;
use common\models\AccountState;

class CassaOpenBehavior extends Behavior
{
	// ...

	public function events()
	{
		return [
				Controller::EVENT_BEFORE_ACTION => 'validateCassaOpen',
		];
	}

	public function validateCassaOpen($event){
		
		$cassaOpen = AccountState::readLast(null, \Yii::$app->user->id, Account::readDefault() );
		
		if ( !isset($cassaOpen) ){
			return $this->redirectToCassaOpen($event);
		}else if ( !$cassaOpen->isTypeOpen() ){
			return $this->redirectToCassaOpen($event);
		}
	}
	
	protected function redirectToCassaOpen($event ) {
		\Yii::$app->session->setFlash ( 'error', 'Nem nyitottál kasszát!');
		 $this->owner->redirect([ 'account-state/open' ]);
		 $event->isValid = false;
		 $event->handled = true;
	}
}