<?php

class CitiesManagerView extends Slot {

	var $ModuleID = 4;
	var $SectionID = 45;
	var $colors = array('red' => '#DC143C', 'yellow' => '#FF8C00', 'green' => '#006400', 'black' => '#000000', 'blue' => '#4169E1',);
	var $action;
	var $city;
	var $cur_city_url;
	var $cities = array();
	var $states= array();
	var $terminated = false;
	var $undo = 0;

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

	function init() {
		GLOBAL $TOOLS_PATH, $COMMON_VARS;
		$this->action = isset($this->LocalTarget[0]) ? $this->LocalTarget[0] : '';
		$this->cities = $this->Action->Server->getGuide('city');
		$this->states = mergeArrays(array('0' => ''),$this->Action->Server->getGuide('state'));
		if(!empty($this->action) && ((!is_numeric($this->action) && $this->action != 'Search' && $this->action != 'Add' && !array_key_exists(@$this->LocalTarget[1], $this->cities)) || ($this->server_type != 'dev' && $this->action != 'View'))) return $this->terminateAction();
		switch($this->action){
			case 'Add': {
				$this->city = $this->Action->Handler->_parseContent($this->Action->Handler->createCity());
				$this->city['web_link'] = '';
				$this->Scheme = 'action';
				break;
			}
			case 'Update': case 'Duplicate': case 'View': case 'Delete': {
				if($this->action != 'View'){
					$this->Action->processEvent($this->SectionID, 'get_lock', array('id' => $this->LocalTarget[1]), $this);
					if(empty($this->PreparedTemplates)) {
						if($this->action != 'Duplicate') $this->Action->processEvent($this->SectionID, 'lock', array('id' => $this->LocalTarget[1], 'member' => $this->Action->Security->currentuser->id), $this);
					}
					else if($this->PreparedTemplates['access_flag'] != $this->Action->Security->currentuser->id) return $this->terminateAction();
				}
				if($this->action == 'Update' && @$this->LocalTarget[2] == 'Undo' && @$this->LocalTarget[3] && is_numeric($this->LocalTarget[3])) $this->undo = $this->LocalTarget[3];
				$this->Action->processEvent($this->SectionID, 'open', array('id' => $this->LocalTarget[1], 'undo' => $this->undo), $this);
				$this->city = $this->PreparedTemplates;
				if($this->action == 'Duplicate') $this->city['id'] = '';
				if($this->action == 'Update') $this->cur_city_url = $this->city['name_in_url'];//printArray($this->cur_city_url);printArray($COMMON_VARS);
				$this->city['web_link'] = $COMMON_VARS['cities_path'].'/'.$this->city['name_in_url'];
				$this->Scheme = 'action';
				break;
			}
			case 'Unlock': {
				$this->Action->processEvent($this->SectionID, 'get_lock', array('id' => $this->LocalTarget[1]), $this);
				if(@$this->PreparedTemplates['access_flag'] == $this->Action->Security->currentuser->id) $this->Action->processEvent($this->SectionID, 'unlock', array('id' => $this->LocalTarget[1], 'member' => $this->Action->Security->currentuser->id), $this);
				return $this->terminateAction();
				break;
			}
			case 'FullHistory': {
				$this->Action->processEvent($this->SectionID, 'select_comments', array('id' => $this->LocalTarget[1]), $this);
				$this->Scheme = 'fullhistory';
				break;
			}
			case 'Search': {
				//printArray($this->Request);
				if(!empty($this->Request)) {
					header("Location: ".$this->Home.'/Registar/CitiesManager/Search/'.urlencode($this->getRequestField('search_name')).'/'.urlencode($this->getRequestField('search_state')).'/'.urlencode($this->getRequestField('search_code')));
				}
				else {
					$request['search_name'] = @$this->LocalTarget[1];
					$request['search_state'] = @$this->LocalTarget[2];
					$request['search_code'] = @$this->LocalTarget[3];
					$curPageNumber = isset($this->LocalTarget[4]) && is_numeric($this->LocalTarget[4])? $this->LocalTarget[4]+1 : 1;
					$this->Scheme = 'default';
					$this->Action->processEvent($this->SectionID,'search',array('request' => $request,'curPageNumber' => $curPageNumber), $this);
					$this->getPageControl($this->Home.'/Registar/CitiesManager/Search/'.$request['search_name'].'/'.$request['search_state'].'/'.$request['search_code']);
				}
				break;
			}
			default: {
				$curPageNumber = isset($this->action) && is_numeric($this->action)? $this->action+1 : 1;
				$this->Scheme = 'default';
				$this->Action->processEvent($this->SectionID, 'select', array('curPageNumber' => $curPageNumber), $this);
				$this->getPageControl($this->Home.'/Registar/CitiesManager');
				break;
			}
		}
		if(empty($this->Request)){
			$this->setSchemeTemplate($this->Scheme);
			return;
		}
		switch($this->action) {
			case 'Update': case 'Add': case 'Duplicate': {
				foreach($this->Request['form'] as $key => $value) $this->city[$key] = is_array($value) ? array_values($value) : $value;
				$this->city['name_in_url'] = strtolower($this->city['name_in_url']);
				if($this->validateCity()) {
					$this->city['action'] = $this->action;
					$this->city['id_user'] = $this->Action->Security->currentuser->id;
					if ($this->Action->processEvent($this->SectionID, 'save', $this->city, $this)) {
						if(!empty($this->city['id'])) $this->Action->processEvent($this->SectionID, 'unlock', array('id' => $this->city['id'], 'member' => $this->Action->Security->currentuser->id), $this);
						if($this->cur_city_url != $this->city['name_in_url']) {
							include_once($TOOLS_PATH.'/autochangeURL.inc');
							autochangeURL('/'.$COMMON_VARS['cities_path'].'/'.$this->cur_city_url, $COMMON_VARS['cities_path'].'/'.$this->city['name_in_url'], $this->Action->Security->currentuser->id);
						}
						return $this->terminateAction();
					}
					else $this->errors['validate'] = $this->PreparedTemplates['_error'];
				}
				break;
			}
			case 'Delete': {
				include($TOOLS_PATH.'/checker.php');
				$this->check = check_to_delete($this->city['id'], 'City');
				$check = true;
				foreach($this->check as $value)
					if(!empty($value)) {
						$check = false;
						break;
					}
				if ($check){
					$this->Action->processEvent($this->SectionID, 'delete', $this->city, $this)
					and $this->clearUndo($this->city['id'])
					and $this->terminateAction();
				}
				else {
					$this->Scheme = 'nodelete';
					$this->Action->processEvent($this->SectionID, 'unlock', array('id' => $this->city['id'], 'member' => $this->Action->Security->currentuser->id), $this);
				}
				break;
			}
		}
		$this->setSchemeTemplate($this->Scheme);
	}

	function fillElements() {
		switch($this->Scheme) {
			case 'action': $this->fillAction(); break;
			case 'fullhistory': $this->fillFullHistory(); break;
			case 'nodelete': $this->fillNoDelete(); break;
			default: $this->fillDefault(); break;
		}
	}
	
	function fillDefault() {
		GLOBAL $COMMON_VARS;
		if($this->terminated) return false;
		$edit_vis = $this->server_type == 'dev' ? 'visible' : 'hidden';
		$pub_vis = $this->server_type == 'pro' ? 'hidden' : 'visible';
		$this->TempFillEls['pub_vis'] = $pub_vis;
		$this->TempFillEls['btnEdit_vis'] = $edit_vis;
		$count = count($this->PreparedTemplates['curPage']);
		//printarray($this->PreparedTemplates['curPage']);
		for ($i = 0; $i < $count; $i++) {
			$this->TempFillEls['cities'][$i] = $this->PreparedTemplates['curPage'][$i];
			$this->TempFillEls['cities'][$i]['web_link'] = $this->Home.'/'.$COMMON_VARS['cities_path'].'/'.$this->PreparedTemplates['curPage'][$i]['name_in_url'];
			$date_locked = explode('.', $this->PreparedTemplates['curPage'][$i]['date_locked']);
			$this->TempFillEls['cities'][$i]['date_locked'] = $date_locked[0];
			if(empty($this->PreparedTemplates['curPage'][$i]['_error'])) $this->TempFillEls['cities'][$i]['img'] = 'bullet';
			else {
				$this->TempFillEls['cities'][$i]['img'] = 'bullet2';
				$this->TempFillEls['cities'][$i]['chbAdds_disabled'] = 'disabled';
			}
			$this->TempFillEls['cities'][$i]['btnEdit_vis'] = $edit_vis;
			$this->TempFillEls['cities'][$i]['chbAdds_vis'] = $pub_vis;
			if(!empty($this->PreparedTemplates['curPage'][$i]['access_flag']) && $this->PreparedTemplates['curPage'][$i]['access_flag'] != $this->Action->Security->currentuser->id) {
				$this->TempFillEls['cities'][$i]['btnUnlock_disp'] = 'none';
				$this->TempFillEls['cities'][$i]['btnEdit_disp'] = 'none';
				$this->TempFillEls['cities'][$i]['btnDelete_disp'] = 'none';
			}
			else {
				$this->TempFillEls['cities'][$i]['locked_message_disp'] = 'none';
				if($this->PreparedTemplates['curPage'][$i]['access_flag'] != $this->Action->Security->currentuser->id) $this->TempFillEls['cities'][$i]['btnUnlock_disp'] = 'none';
			}
			$presets_count = explode('/', $this->PreparedTemplates['curPage'][$i]['published_count']);
			$c = count($this->PreparedTemplates['curPage'][$i]['publish']);
			$this->TempFillEls['cities'][$i]['published_count_cursor'] = $c ? 'pointer' : 'auto';
			$this->TempFillEls['cities'][$i]['published_count_color'] = $this->colors[($presets_count[0] >= $presets_count[1] ? 'green' : (empty($presets_count[0]) ? 'red' : 'blue'))];
			$this->TempFillEls['cities'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates['curPage'][$i]['id'].']=[];';
			$this->TempFillEls['cities'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates['curPage'][$i]['id'].']["publish"]=[];';
			for($j = 0; $j < $c; $j++){
				$this->TempFillEls['cities'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates['curPage'][$i]['id'].']["publish"]['.$j.']=[];';
				$this->TempFillEls['cities'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates['curPage'][$i]['id'].']["publish"]['.$j.']["package_id"]='.$this->PreparedTemplates['curPage'][$i]['publish'][$j]['package_id'].';';
				$this->TempFillEls['cities'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates['curPage'][$i]['id'].']["publish"]['.$j.']["package_name"]="'.$this->PreparedTemplates['curPage'][$i]['publish'][$j]['package_name'].'";';
				$this->TempFillEls['cities'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates['curPage'][$i]['id'].']["publish"]['.$j.']["username"]="'.$this->PreparedTemplates['curPage'][$i]['publish'][$j]['username'].'";';
				$this->TempFillEls['cities'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates['curPage'][$i]['id'].']["publish"]['.$j.']["hostpath"]="'.$this->PreparedTemplates['curPage'][$i]['publish'][$j]['hostpath'].'";';
				$this->TempFillEls['cities'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates['curPage'][$i]['id'].']["publish"]['.$j.']["date_published"]="'.$this->PreparedTemplates['curPage'][$i]['publish'][$j]['date_published'].'";';
			}
		}
		$this->TempFillEls['search_name'] = inputText('search_name',(!empty($this->LocalTarget[0]) && $this->LocalTarget[0]=='Search'? urldecode(@$this->LocalTarget[1]) : ''),25,'style="width:150px"');
		$this->TempFillEls['search_state'] = inputSelect('search_state',$this->states,(!empty($this->LocalTarget[0]) && $this->LocalTarget[0]=='Search' && !empty($this->LocalTarget[2])? urldecode($this->LocalTarget[2]) : ''),'style="width:150px"');
		$this->TempFillEls['search_code'] = inputText('search_code',(!empty($this->LocalTarget[0]) && $this->LocalTarget[0]=='Search'? urldecode(@$this->LocalTarget[3]) : ''),25,'style="width:150px"');
		$this->clearAllTemplates();
	}
	
	function fillAction() {
		GLOBAL $COMMON_VARS;
		if($this->terminated) return false;
		if($this->undo) $this->TempFillEls['undo'] = 'Undo up to '.$this->undo.' version';
		$this->TempFillEls['action'] = $this->action;
		$this->TempFillEls['name'] = $this->city['name'];
		$this->TempFillEls['id'] = $this->city['id'];
		$this->TempFillEls['web_link'] = '<a href="'.$this->Home.'/'.$this->city['web_link'].'">'.'/'.$this->city['web_link'].'</a>';
		$this->TempFillEls['uid'] = $this->city['uid'];
		$date_created = explode('.', $this->city['date_created']);
		$this->TempFillEls['date_created'] = $date_created[0];
		$this->TempFillEls['form_name'] = inputText('form[name]', $this->city['name'], 80, '', 128);
		$this->TempFillEls['form_name_in_url'] = inputText('form[name_in_url]', $this->city['name_in_url'], 80, '', 256);
		$this->TempFillEls['form_name_in_text'] = inputText('form[name_in_text]', $this->city['name_in_text'], 80, '', 256);
		$this->TempFillEls['form_state'] = inputSelect('form[state]', $this->states, $this->city['state'], 'style="width: 150px;"');
		$this->TempFillEls['form_meta_title'] = inputText('form[meta_title]', $this->city['meta_title'], 80, '', 512);
		$this->TempFillEls['form_meta_keywords'] = inputTextArea('form[meta_keywords]', $this->city['meta_keywords'], '', 2, 'style="width: 450px;"');
		$this->TempFillEls['form_description'] = inputTextArea('form[description]', $this->city['description'], '', 4, 'style="width: 450px;"');
		if(empty($this->city['area_codes'])) $area_codes = array();
		else {
			$area_codes = explode(',', str_replace(array('{', '}'), '', $this->city['area_codes']));
			sort($area_codes);
			$area_codes = array_combine(array_values($area_codes), $area_codes);
		}
		$this->TempFillEls['form_area_codes'] = inputSelect('form[area_codes]', $area_codes, 0, 'size=4 multiple="multiple" style="width: 80px;"');
		if(empty($this->city['id'])) {
			$this->TempFillEls['header_info_disp'] = 'none';
			$this->TempFillEls['web_link_disp'] = 'none';
			$this->TempFillEls['date_created_disp'] = 'none';
			$this->TempFillEls['uid_disp'] = 'none';
		}
		if($this->action != 'Update' && $this->action != 'Add' && $this->action != 'Duplicate') $this->TempFillEls['AreaCodeAction_vis'] = 'hidden';
		$this->TempFillEls['form_comment'] = inputTextarea('form[comment]', (isset($this->city['comment']) ? $this->city['comment'] : ''), '', 5, 'id="form[comment]" style="width: 500px;"');
		if(!empty($this->city['comments'])) $this->fillFullHistory(false);
		if(!empty($this->city['_error'])) $this->errors['model'] = $this->city['_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'] = $this->printError($v).($k == 'header' ? '<p>' : '');
		$this->clearAllTemplates();
	}
	
	function fillFullHistory($main = true) {
		if($this->terminated) return false;
		if($main) $history = &$this->PreparedTemplates['curPage'];
		else $history = &$this->city['comments'];
		$count = count($history);
		for ($i = 0; $i < $count; $i++){
			$date = explode('.', $history[$i]['date']);
			$this->TempFillEls['comments'][$i] = array(
				'number' => $main ? ($this->PreparedTemplates['pageRecordsQty'] * ($this->PreparedTemplates['curPageNumber'] - 1) + $i + 1) : ($i + 1),
				'date' => $date[0],
				'member' => $history[$i]['member'],
				'version' => $history[$i]['version'],
				'value' => wordwrap($history[$i]['value'], 30, '<br>', 1),
				'id' => $this->LocalTarget[1],
				'undo_vis' => $history[$i]['file'] ? 'visible' : 'hidden',
			);
		}
		if($main) {
			$this->TempFillEls['id'] = $this->PreparedTemplates['id'];
			$this->TempFillEls['name'] = $this->PreparedTemplates['name'];
			$this->clearAllTemplates();
		}
	}
	
	function fillNoDelete() {
		if($this->terminated) return false;
		$this->TempFillEls['id'] = $this->city['id'];
		$this->TempFillEls['name'] = $this->city['name'];
		foreach($this->check['pages'] as $key => $value) {
			$this->TempFillEls['Pages'][0]['pitems'][] = array(
				'item' => makeLink($this->Home.'/Registar/'.(empty($value['update_path']) ? (empty($value['js']) ? 'ContentManager' : 'MetaManager/Page').'/Update/'.$value['id'] : $value['update_path']), $value['name']),
				'id' => $value['id'],
				'path' => empty($value['path']) ? '&nbsp;' : makeLink($this->Home.$value['path'], 'View', array(), '', 'class=adminlink'),
			);
		}
		foreach($this->check['menues'] as $key => $value) {
			$this->TempFillEls['Menues'][0]['mitems'][] = array(
				'item' => makeLink($this->Home.'/Registar/MenuManager/'.$value['type'].'Menu/Update/'.$value['id'], $value['name']),
			);
		}
		foreach($this->check['templates'] as $key => $value) {
			$this->TempFillEls['Templates'][0]['titems'][] = array(
				'item' => makeLink($this->Home.'/Registar/TemplateManager/Update/'.$value['id'],$value['name']),
			);
		}
		foreach($this->check['layouts'] as $key => $value) {
			$this->TempFillEls['Layouts'][0]['litems'][] = array(
				'item' => makeLink($this->Home.'/Registar/LayoutManager/Update/'.$value['id'],$value['name']),
			);
		}
		$this->clearAllTemplates();
	}
	
	function validateCity() {
		if(($id = array_search($this->city['name'], $this->cities)) !== false && $id != $this->city['id']) $this->errors['name'] = 'City with such name already exists';
		if(!is_FullText($this->city['name'], 2, 128)) $this->errors['name'] = 'City name is not valid';
		if(!is_URLText($this->city['name_in_url'], 2, 512)) $this->errors['name_in_url'] = 'City name in URL is not valid';
		if(!is_FullText($this->city['name_in_text'], 2, 256)) $this->errors['name_in_text'] = 'City name in text is not valid';
		if(empty($this->city['state']) || !is_numeric($this->city['state']) || !array_key_exists($this->city['state'], $this->states)) $this->errors['state'] = 'State is not valid';
		if(!is_FullText($this->city['meta_title'], 5, 512)) $this->errors['meta_title'] = 'Meta title is not valid';
		if(!is_FullText($this->city['meta_keywords'], 5)) $this->errors['meta_keywords'] = 'Meta keywords are not valid';
		if(!is_FullText($this->city['description'], 5)) $this->errors['description'] = 'Description is not valid';
		if(!preg_match("/^\{([0-9]{3},)*[0-9]{3}\}$/", $this->city['area_codes'], $matches)) $this->errors['area_codes'] = 'Area codes are not valid';
		return empty($this->errors) ? true : false;
	}
	
	function clearUndo($id) {
		GLOBAL $ROOT_PATH, $TOOLS_PATH;
		include_once($TOOLS_PATH.'/func.php');
		$path = $ROOT_PATH.'/undo/city/'.$id;
		if(file_exists($path)) mysystem('rm -rf '.$path);
		return true;
	}
	
	function terminateAction(){
		$this->terminated = true;
		$this->clearAllTemplates();
		header('Location: '.$this->Home.'/Registar/CitiesManager'.$this->SID);
		return true;
	}
	
	function clearAllTemplates(){
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'get_lock');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'lock');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'unlock');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'open');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'save');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'delete');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_comments');
	}
}
?>