<?php

class SecurityManagerView extends Slot {

	var $ModuleID = 4;
	var $SectionID = 3;
	var $Task = 'save';
	var $orderby = array(
		'Group' => array(
			'sortColumn' => 'role desc, id',
			'sortType' => 'asc',
		),
		'Username' => array(
			'sortColumn' => 'username',
			'sortType' => 'asc',
		),
		'LastActivity' => array(
			'sortColumn' => 'date_last_activity IS NOT NULL desc, date_last_activity',
			'sortType' => 'desc',
		),
	);
	var $sort_array = array();
	var $sortby = '';
	var $upload_formats = array(
		'image/gif' => 'gif',
		'image/jpeg' => 'jpg',
		'image/png' => 'png'
	);
	var $allowed_types = array(
		1 => 'Guest',
		2 => 'Administrator',
	);

	function __construct($pquery) {
		global $REGISTRY;
		parent::__construct($pquery);
	}

	function init() {
		global $PHP_SELF;
		$this->Scheme = $this->Action->setScheme($this->SectionID);
		if($this->Scheme!='finish' && $this->Scheme!='finish_save' && $this->Scheme!='finish_delete') {
			switch(@$this->LocalTarget[0]) {
				case 'Search':
					if(!empty($this->Request) && (!empty($this->Request['search_member']) || !empty($this->Request['search_first_name']))) {
						header("Location: ".$this->Home.'/Registar/SecurityManager/Search/'.(!empty($this->Request['search_member'])? urlencode($this->Request['search_member']) : '').'/'.(!empty($this->Request['search_first_name'])? urlencode($this->Request['search_first_name']) : '').$this->SID);
					}
					else if(isset($this->LocalTarget[1]) || isset($this->LocalTarget[2])) {
						if(!empty($this->LocalTarget[1])) $search['username'] = urldecode($this->LocalTarget[1]);
						if(!empty($this->LocalTarget[2])) $search['first_name'] = urldecode($this->LocalTarget[2]);
						$request = array('conditions' => $search,'pageRecordsQty'=>'10','curPageNumber'=>(isset($this->LocalTarget[3])? $this->LocalTarget[3]+1 : 1));
						$this->sortby = !empty($this->LocalTarget[4]) && in_array($this->LocalTarget[4],array_keys($this->orderby))? $this->LocalTarget[4] : 'Group';
						$request['sortColumn'] = $this->orderby[$this->sortby]['sortColumn'];
						$request['sortType'] = $this->orderby[$this->sortby]['sortType'];
						$this->Action->processEvent($this->SectionID,'select_members',$request,$this);
						if(!empty($this->PreparedTemplates['_error'])) $this->Scheme = 'message';
						else {
							$this->getPageControl($this->Home.'/Registar/SecurityManager/Search/'.$this->LocalTarget[1].'/'.(!empty($this->LocalTarget[2])? $this->LocalTarget[2] : ''),$this->sortby);
							if(empty($this->PreparedTemplates['curPage'])) $this->Scheme = 'empty';
						}
					}
					else header("Location: ".$this->Home.'/Registar/SecurityManager'.$this->SID);
				break;
				case 'View':
					if(!$this->Action->isAuthorizeAdmin()) header("Location: ".$this->Home.'/Registar'.$this->SID);
					else {
						if(!empty($this->LocalTarget[1]) && validate(intval($this->LocalTarget[1]))) {
							$this->Scheme = 'view';
							$this->Task = 'view';
							$this->Action->processEvent($this->SectionID,'open_admin',array('id' => $this->LocalTarget[1]),$this);
							//printArray($this->PreparedTemplates);
							if(!empty($this->PreparedTemplates['_error'])) $this->Scheme = 'message';
							//else $this->Action->processEvent($this->SectionID,'open_member_levels',array('conditions' => array('level_type' => 1)),$this);
						}
						else header("Location: ".$this->Home.'/Registar/SecurityManager'.$this->SID);
					}
				break;
				case 'AddUser':
					if(!$this->Action->isAuthorizeAdmin()) header("Location: ".$this->Home.'/Registar'.$this->SID);
					else {
						$this->Scheme = 'view';
						$this->Task = 'view';
						//$this->Action->processEvent($this->SectionID,'open_member_levels',array('conditions' => array('level_type' => 1)),$this);
						if($this->Action->Security->currentuser->role->id!=3) $this->PreparedTemplates['_error'] = '5';
						if(!empty($this->PreparedTemplates['_error'])) $this->Scheme = 'message';
					}
				break;
				default:
					$this->Scheme = 'default';
					$this->Task = 'open';
					$request = array('pageRecordsQty'=>'10','curPageNumber'=>(isset($this->LocalTarget[0])? $this->LocalTarget[0]+1 : 1));
					$this->sortby = !empty($this->LocalTarget[1]) && in_array($this->LocalTarget[1],array_keys($this->orderby))? $this->LocalTarget[1] : 'Group';
					$request['sortColumn'] = $this->orderby[$this->sortby]['sortColumn'];
					$request['sortType'] = $this->orderby[$this->sortby]['sortType'];
					$this->Action->processEvent($this->SectionID,'select_admins',$request,$this);
					if(!empty($this->PreparedTemplates['_error'])) $this->Scheme = 'message';
					else {
						$this->getPageControl($this->Home.'/Registar/SecurityManager',$this->sortby);
						if(empty($this->PreparedTemplates['curPage'])) $this->Scheme = 'empty';
					}
				break;
				/*case 'ChangeMemberGroup':
					if(!$this->Action->isAuthorizeAdmin()) header("Location: ".$this->Home.'/Admin'.$this->SID);
					else {
						if(!empty($this->LocalTarget[1]) && validate(intval($this->LocalTarget[1]))) {
							$this->Scheme = 'level';
							$this->Task = 'level';
							$this->Action->processEvent($this->SectionID,'open_member_levels',array('conditions' => array('level_type' => 2)),$this);
							if(!empty($this->PreparedTemplates['_error'])) header("Location: ".$this->Home.'/Registar/SecurityManager'.$this->SID);
							else {
								$this->Action->processEvent($this->SectionID,'open_member',array('id' => $this->LocalTarget[1]),$this);
								if(!empty($this->PreparedTemplates['_error'])) header("Location: ".$this->Home.'/Registar/SecurityManager'.$this->SID);
								else if($this->PreparedTemplates['level']['level_type']=='1') header("Location: ".$this->Home.'/Registar/SecurityManager'.$this->SID);
							}
						}
						else header("Location: ".$this->Home.'/Registar/SecurityManager'.$this->SID);
					}
				break;*/
			}
		}
		if(!empty($this->Request)) {
			//printArray($this->Request);
			switch($this->getRequestField('step')) {
				case 'edit':
					$this->validateForm()
					and $this->Action->processEvent($this->SectionID,'edit_admin',$this->correctWords($this->getRequestField('form')),$this)
					and $this->Action->setPage($this->SectionID,'finish_save')
					and header("Location: ".$this->PHP_SELF.$this->SID);
				break;
				case 'delete':
					$this->Action->processEvent($this->SectionID, 'delete_admin', $this->getRequestField('form'), $this);
					header("Location: ".$this->Home.'/Registar/SecurityManager'.$this->SID);
				break;
				case 'add':
					$this->validateForm()
					and $this->Action->processEvent($this->SectionID,'add_admin',$this->correctWords($this->getRequestField('form')),$this)
					and $this->Action->setPage($this->SectionID, 'finish_save')
//					and header("Location: ".$this->Home.'/Registar/SecurityManager/View/'.$this->PreparedTemplates['id'].$this->SID);
					and header("Location: ".$this->Home.'/Registar/SecurityManager/View/'.$this->PreparedTemplates['id']);
				break;
			}
		}
		$this->setSchemeTemplate($this->Scheme);
	}

	function validateForm() {
		switch($this->getRequestField('step')) {
			case 'edit': case 'add':
				if(!is_AlphaNumDefis($this->getRequestFormField('username'),2,32)) $this->errors['username'] = 'The username you entered is not a valid string';
				if(($this->getRequestField('step')=='add' || validate($this->getRequestFormField('password'))) && !is_AlphaNumDefis($this->getRequestFormField('password'),3,32)) $this->errors['passw'] = 'The password you entered is not a valid string';
				if(($this->getRequestField('step')=='add' || validate($this->getRequestFormField('password'))) && (!is_AlphaNumDefis($this->getRequestFormField('password'),3,32) || $this->getRequestFormField('password')!=$this->getRequestFormField('confirm_passw'))) $this->errors['confirm_passw'] = 'Password confirmation is incorrect.<br>Please re-enter password';
				if(validate($this->getRequestFormField('password')) && !is_AlphaNumDefis($this->getRequestFormField('password'),3,32)) $this->errors['passw'] = 'The password you entered is not a valid string';
				if(validate($this->getRequestFormField('password')) && (!is_AlphaNumDefis($this->getRequestFormField('password'),3,32) || $this->getRequestFormField('password')!=$this->getRequestFormField('confirm_passw'))) $this->errors['confirm_passw'] = 'Password confirmation is incorrect.<br>Please re-enter password';
				if(!is_CleanText($this->getRequestFormField('first_name'),2,255)) $this->errors['first_name'] = 'The first name you entered is not a valid string';
				if(!is_CleanText($this->getRequestFormField('last_name'),2,255)) $this->errors['last_name'] = 'The last name you entered is not a valid string';
				if(!is_Email($this->getRequestFormField('email'))) $this->errors['email'] = 'The e-mail address you entered is not valid';
				if(!is_AdvCleanText($this->getRequestFormField('pass_hint'),3,255)) $this->errors['pass_hint'] = 'The password question you entered is not a valid string';
				if(!is_AdvCleanText($this->getRequestFormField('pass_answ'),3,255)) $this->errors['pass_answ'] = 'The password answer you entered is not a valid string';
			break;
		}
		if(count($this->errors) > 0) return FALSE;
		return TRUE;
	}

	function fillElements() {
		switch($this->Scheme) {
			case 'empty': $this->fillEmpty(); break;
			case 'message': case 'finish': case 'finish_save': case 'finish_delete': $this->fillMessage(); break;
			case 'view': $this->fillView(); break;
			case 'default': $this->fillOpen(); break;
			case 'level': $this->fillGroup(); break;
		}
	}

	function fillOpen() {
		if(!empty($this->LocalTarget[0]) && $this->LocalTarget[0]=='Search')
			$this->sort_array = array(
				'username' => $this->sortby=='Username'? '<span class=first> Username </span>' : makeLink($this->Home.'/Registar/SecurityManager/Search/'.$this->LocalTarget[1].'/'.(!empty($this->LocalTarget[2])? $this->LocalTarget[2] : '').'/'.(validate(intval(@$this->LocalTarget[3]))? $this->LocalTarget[3] : 0).'/Username','Username'),
				'last_activity' => $this->sortby=='LastActivity'? '<span class=first> Last Activity </span>' : makeLink($this->Home.'/Registar/SecurityManager/Search/'.$this->LocalTarget[1].'/'.(!empty($this->LocalTarget[2])? $this->LocalTarget[2] : '').'/'.(validate(intval(@$this->LocalTarget[3]))? $this->LocalTarget[3] : 0).'/LastActivity','Last Activity'),
				'level' => $this->sortby=='Group'? '<span class=first> Group </span>' : makeLink($this->Home.'/Registar/SecurityManager/Search/'.$this->LocalTarget[1].'/'.(!empty($this->LocalTarget[2])? $this->LocalTarget[2] : '').'/'.(validate(intval(@$this->LocalTarget[3]))? $this->LocalTarget[3] : 0).'/Group','Group'),
		);
		else $this->sort_array = array(
			'username' => $this->sortby=='Username'? '<span class=first> Username </span>' : makeLink($this->Home.'/Registar/SecurityManager/'.(validate(intval(@$this->LocalTarget[0]))? $this->LocalTarget[0] : 0).'/Username','Username'),
			'last_activity' => $this->sortby=='LastActivity'? '<span class=first> Last Activity </span>' : makeLink($this->Home.'/Registar/SecurityManager/'.(validate(intval(@$this->LocalTarget[0]))? $this->LocalTarget[0] : 0).'/LastActivity','Last Activity'),
			'level' => $this->sortby=='Group'? '<span class=first> Group </span>' : makeLink($this->Home.'/Registar/SecurityManager/'.(validate(intval(@$this->LocalTarget[0]))? $this->LocalTarget[0] : 0).'/Group','Group'),
		);
		!empty($this->PreparedTemplates['_error']) and $this->TempFillEls['model_error'] = $this->printError($this->PreparedTemplates['_error']);
		$this->TempFillEls['search_member'] = inputText('search_member',(!empty($this->LocalTarget[0]) && $this->LocalTarget[0]=='Search'? urldecode($this->LocalTarget[1]) : ''),$this->correctSize('25'));
		$this->TempFillEls['search_first_name'] = inputText('search_first_name',(!empty($this->LocalTarget[0]) && $this->LocalTarget[0]=='Search' && !empty($this->LocalTarget[2])? urldecode($this->LocalTarget[2]) : ''),$this->correctSize('25'));
		$this->TempFillEls['url'] = $this->Target[1];
		$page = isset($this->LocalTarget[0]) && $this->LocalTarget[0]!='Search'? (!empty($this->LocalTarget[1]) && in_array($this->LocalTarget[1],array_keys($this->orderby))? $this->LocalTarget[0].'/'.$this->LocalTarget[1] : $this->LocalTarget[0]) : 0;
		foreach($this->PreparedTemplates['curPage'] as $key => $value) {
			$date_last_activity = explode('.', $value['date_last_activity']);
			$this->TempFillEls['Views'][$key] = array(
				'key' => $key,
				'id' => $value['id'],
				'level' => $value['role_name'],
				'type' => $value['type_name'],
				'page' => $page,
				'username' => makeLink($this->Home.'/Registar/SecurityManager/View/'.$value['id'].'/'.$page,$value['username']),
				'date_last_activity' => $date_last_activity[0],
			);
		}
		$this->TempFillEls['sort'][] = $this->sort_array;
		$this->TempFillEls['sort2'] = $this->TempFillEls['sort'];
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'select_admins');
	}

	function fillView() {
		global $PHP_SELF;
		$delete = $this->getRequestField('step') == 'delete'? 1 : 0;
		$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_admin');
		$page = isset($this->LocalTarget[2])? (!empty($this->LocalTarget[3]) && in_array($this->LocalTarget[3],array_keys($this->orderby))? $this->LocalTarget[2].'/'.$this->LocalTarget[3] : $this->LocalTarget[2]) : 0;
		//printArray($this->PreparedTemplates);
		$this->TempFillEls = array(
			'formaction' => $this->PHP_SELF,
			'page' => $page,
			'step' => $this->LocalTarget[0]=='AddUser'? 'add' : 'edit',
			'role' => $this->Action->Security->currentuser->role->id,
			'id' => inputHidden('form[id]', ($this->LocalTarget[0] != 'AddUser'? $this->PreparedTemplates['id'] : '')),
			'type' => implode('&nbsp;', radioButtons ($this->allowed_types, 'form[type]', ($this->LocalTarget[0] != 'AddUser'? ($delete ? $this->PreparedTemplates['type'] : $this->getRealValue('type')) : $this->getRequestFormField('type')))),
			'username' => inputText('form[username]',($this->LocalTarget[0]!='AddUser'? ($delete? $this->PreparedTemplates['username'] : $this->getRealValue('username')) : $this->getRequestFormField('username')),$this->correctSize('35')),
			'passw' => inputPassword('form[password]',$this->getRequestFormField('password'),$this->correctSize('35')),
			'confirm_passw' => inputPassword('form[confirm_passw]',$this->getRequestFormField('confirm_passw'),$this->correctSize('35')),
			'first_name' => inputText('form[first_name]',($this->LocalTarget[0]!='AddUser'? ($delete? $this->PreparedTemplates['first_name'] : $this->getRealValue('first_name')) : $this->getRequestFormField('first_name')),$this->correctSize('35')),
			'last_name' => inputText('form[last_name]',($this->LocalTarget[0]!='AddUser'? ($delete? $this->PreparedTemplates['last_name'] : $this->getRealValue('last_name')) : $this->getRequestFormField('last_name')),$this->correctSize('35')),
			'email' => inputText('form[email]',($this->LocalTarget[0]!='AddUser'? ($delete? $this->PreparedTemplates['email'] : $this->getRealValue('email')) : $this->getRequestFormField('email')),$this->correctSize('35')),
			'pass_hint' => inputText('form[pass_hint]',($this->LocalTarget[0]!='AddUser'? ($delete? $this->PreparedTemplates['pass_hint'] : $this->getRealValue('pass_hint')) : $this->getRequestFormField('pass_hint')),$this->correctSize('35')),
			'pass_answ' => inputText('form[pass_answ]',($this->LocalTarget[0]!='AddUser'? ($delete? $this->PreparedTemplates['pass_answ'] : $this->getRealValue('pass_answ')) : $this->getRequestFormField('pass_answ')),$this->correctSize('35')),
			'sbtSaveProfile_vis' => $this->Action->Security->currentuser->role->id == 3 ? 'visible' : 'hidden',
			'sbtDeleteProfile_vis' => $this->Action->Security->currentuser->role->id == 3 ? 'visible' : 'hidden',
			//'canceled' => inputCheckbox('form[canceled]',(!empty($this->Request) && !$delete? $this->getRequestFormField('canceled') : ($this->LocalTarget[0]!='AddUser'? ($delete? $this->PreparedTemplates['canceled'] : $this->getRealValue('canceled')) : $this->getRequestFormField('canceled')))),
		);
		$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'add_admin');
		!empty($this->PreparedTemplates['_error']) and $this->errors['model'] = $this->globalLangContent['error_model'][$this->PreparedTemplates['_error']];
		!empty($this->PreparedTemplates['_error']) and empty($this->errors['model']) and $this->errors['model'] = $this->PreparedTemplates['_error'];
		if(count($this->errors) > 0) $this->errors['header'] = 'There were some errors.<br>Please see below for details';
		foreach($this->errors as $k => $v) $this->TempFillEls[$k.'_error'] = $k=='header'? $this->printError($v).'<p>' : $this->printError($v);
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'add_admin');
		$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'edit_admin');
		!empty($this->PreparedTemplates['_error']) and $this->errors['model'] = $this->globalLangContent['error_model'][$this->PreparedTemplates['_error']];
		if(count($this->errors) > 0) $this->errors['header'] = 'There were some errors.<br>Please see below for details';
		foreach($this->errors as $k => $v) $this->TempFillEls[$k.'_error'] = $k=='header'? $this->printError($v).'<p>' : $this->printError($v);
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'edit_admin');
		$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'delete_admin');
		!empty($this->PreparedTemplates['_error']) and $this->errors['model'] = $this->globalLangContent['error_model'][$this->PreparedTemplates['_error']];
		if(count($this->errors) > 0) $this->errors['header'] = 'There were some errors.<br>Please see below for details';
		foreach($this->errors as $k => $v) $this->TempFillEls[$k.'_error'] = $k=='header'? $this->printError($v).'<p>' : $this->printError($v);
		if(!empty($this->PreparedTemplates['_error'])) $this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'delete_admin');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'open_admin');
	}

	function fillGroup() {
		global $PHP_SELF;
		$this->levels = $this->Action->getTemplate($this->SectionID,'open_member_levels');
		$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'open_member');
		$this->TempFillEls['formaction'] = $PHP_SELF;
		$this->TempFillEls['username'] = $this->PreparedTemplates['username'];
		$this->TempFillEls['id'] = inputHidden('form[id]',$this->PreparedTemplates['id']);
		$this->TempFillEls['level'] = $this->PreparedTemplates['level']['name'];
		$this->TempFillEls['levels'] = inputSelect('form[level][id]',$this->levels,(!empty($this->Request)? $this->Request['form']['level']['id'] : $this->PreparedTemplates['level']['id']));
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'open_admins');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'open_member_levels');
	}

	function fillEmpty() {
		$this->TempFillEls['search_member'] = inputText('search_member',(!empty($this->LocalTarget[0]) && $this->LocalTarget[0]=='Search'? urldecode($this->LocalTarget[1]) : ''),$this->correctSize('25'));
		$this->TempFillEls['search_first_name'] = inputText('search_first_name',(!empty($this->LocalTarget[0]) && $this->LocalTarget[0]=='Search' && !empty($this->LocalTarget[2])? urldecode($this->LocalTarget[2]) : ''),$this->correctSize('25'));
	}

	function fillMessage() {
		switch($this->Scheme) {
			case 'finish_delete': 
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID, 'delete_admin');
				$this->TempFillEls['message'] = sprintf($this->localLangContent['message']['delete'],$this->PreparedTemplates['username'],$this->Action->Security->currentuser->username,date("F d, Y H:i:s"));
				$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'delete_admin');
			break;
			case 'finish_save':
				$this->TempFillEls['message'] = 'Member Profile was successfully saved !';
				$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID,'save_admin');
			break;
			default: $this->TempFillEls['message'] = $this->printError($this->globalLangContent['error_model'][$this->PreparedTemplates['_error']]); break;
		}
	}
}
?>