<?php
App::uses('UsersController', 'Users.Controller');

class AppUsersController extends UsersController {
	public $name = 'AppUsers';

	public function admin() {
		if ($this->Auth->user()) {
			if ($this->Auth->user('role') == 'admin') {
				return $this->redirect(array(
					'plugin' => 'users',
					'controller' => 'users',
					'action' => 'index',
					'admin' => true
				));
			} else {
				$this->Session->setFlash(__('Sorry! You doesn\'t have access to administrator area'));
				return $this->redirect(array(
					'plugin' => 'users',
					'controller' => 'users',
					'action' => 'index',
					'admin' => false
				));
			}
		}
	}

	protected function _setupAuth() {
		parent::_setupAuth();
                $role = $this->Auth->user('role');
		$this->getEventManager()->attach(function ($event) use ($role) {
			if ($role == 'admin') {
				// set Auth login redirect to /admin/users
			} else {
				// set Auth login redirect to /users
			}
			
		}, 'Users.Controller.Users.afterLogin');
	}

	public function beforeFilter() {
		parent::beforeFilter();
		$this->User = ClassRegistry::init('AppUser');
		$this->set('model', 'AppUser');
	}

	public function beforeRender() {
		parent::beforeRender();
		$this->response->disableCache();
	}

	public function render($view = null, $layout = null) {
		if (is_null($view)) {
			$view = $this->action;
		}

		$viewPath = substr(get_class($this), 0, strlen(get_class($this)) - 10);
		if (!file_exists(APP . 'View' . DS . $viewPath . DS . $view . '.ctp')) {
			$this->plugin = 'Users';
			$this->viewPath = 'Users';
		} else {
			$this->viewPath = $viewPath;
		}

		return parent::render($view, $layout);
	}
}