<?php
/**
 * Permission level View Helper
 *
 */
App::uses('ClassRegistry', 'Utility');
App::uses('AppHelper', 'View/Helper');
App::uses('Hash', 'Utility');


/**
 * Permission helper
 *
 * Add your application-wide methods in the class below, your helpers
 * will inherit them.
 *
 * @package       app.View.Helper
 */
 
class PermissionHelper extends AppHelper {
	
	public $helpers = array('Html', 'Form');
	//public $components = array('Session','Auth', 'Cookie');
	
	public function link($title, $url = null, $options = array(), $confirmMessage = false, $extra = array()){
		
		$chech = $this->_checkallow($url);
		
		if($chech){
			if (!empty($extra['enclose'])){
				$activeClass = '';
				$urlcheck = $this->params['controller']."/".$this->action;
				if (is_array($url) ){
					if($url['controller'] == $this->params['controller'] && $url['action'] == $this->action){
						$activeClass = 'class="active"';
					}
				}else{
					
					if('/'.$this->params->url == $url){
						$activeClass = 'class="active"';
					}
				}
				return '<'.$extra['enclose'].' '.$activeClass.'>'.$this->Html->link($title, $url,$options,  $confirmMessage).'</'.$extra['enclose'].'>';
			}else{
				return $this->Html->link($title, $url, $options,  $confirmMessage);
			}
		}else{
			return false;
		}
	}
	
	public function postLink($title, $url = null, $options = array (), $confirmMessage = false){
		$chech = $this->_checkallow($url);
		if($chech){
			return $this->Form->postLink($title, $url, $options, $confirmMessage);
		}else{
			return false;
		}
	}
	
	function _checkallow($url){
		$checkUrl = $url;
		if(is_array($url)){
			$checkUrl = $url['controller'].'/'.$url['action'];
		}
		$checkUrl = preg_replace('/^[\/]/', '', $checkUrl);
		$user = $this->_View->viewVars['user'];
		if(!empty($user['permission'])){
			if( in_array($checkUrl, $user['permission']) || (!empty($user['role_id']) && ($user['role_id'] == 1 || $user['role_id'] == 9)) ){
				return true;
			}else{
				return false;
				//return true;
			}
		}else{
			return true;
		}
	}
	
	public function Viewlink($title, $url = null, $options = array(), $confirmMessage = false, $extra = array()){
		
		$chech = $this->_checkallow($url);
		
		if($chech){
			if (!empty($extra['enclose'])){
				$activeClass = '';
				$urlcheck = $this->params['controller']."/".$this->action;
				if (is_array($url) ){
					if($url['controller'] == $this->params['controller'] && $url['action'] == $this->action){
						$activeClass = 'class="active"';
					}
				}else{
					
					if('/'.$this->params->url == $url){
						$activeClass = 'class="active"';
					}
				}
				return '<'.$extra['enclose'].' '.$activeClass.'>'.$this->Html->link($title, $url,$options,  $confirmMessage).'</'.$extra['enclose'].'>';
			}else{
				return $this->Html->link($title, $url, $options,  $confirmMessage);
			}
		}else{
			return $title;
		}
	}
}
