<?php

class ParentItemsManagerView extends Slot {

	var $itemtype = array();

	var $SectionID = 18;
	var $ModuleID = 2;
	var $colors = array(
		'red' => '#DC143C',
		'yellow' => '#FF8C00',
		'green' => '#006400',
		'black' => '#000000',
		'blue' => '#4169E1',
	);
	var $terminated = false;

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

	function init() {
		global $TOOLS_PATH;
		$undo = 0;
		$this->parentitems = $this->Action->Server->getGuide('parentitem');
		switch(@$this->LocalTarget[0]) {
			case 'ViewAll': {
				if($this->server_type=='dev') {
					$request = $this->LocalTarget;
					$request['pageRecordsQty'] = 20;
					$request['curPageNumber'] = isset($this->LocalTarget[2])? $this->LocalTarget[2]+1 : 1;
					$this->Action->processEvent($this->SectionID,'select_parentitemcomments',$request,$this);
					if(!empty($this->PreparedTemplates['_error'])) $this->Scheme = 'message';
					else {
						$this->getPageControl($this->Home.'/Registar/ParentItemsManager/ViewAll/'.$this->LocalTarget[1]);
						if(empty($this->PreparedTemplates['curPage'])) $this->Scheme = 'empty';
					}
					$this->Scheme = 'viewall';
				}
				else $this->Scheme = 'default';
			break;
			}
			case 'Add': {
				$this->Action->processEvent($this->SectionID,'item_open',array('id' => 0),$this);
				$this->Scheme = 'action';
				break;
			}
			case 'Update': case 'Duplicate': case 'Delete': {
				if($this->server_type=='dev') {
					if(!empty($this->LocalTarget[3]) && validate(intval($this->LocalTarget[3])) && $this->LocalTarget[2]=='Undo')
						$undo = 1;
					else $undo = 0;
					if(!empty($this->LocalTarget[1]) && in_array($this->LocalTarget[1],array_keys($this->parentitems))) {
						$array = array('id' => $this->LocalTarget[1]);
						if($undo == 1) $array['undo'] = $this->LocalTarget[3];
						$this->Action->processEvent($this->SectionID,'getlock',array('parentitem' => $this->LocalTarget[1],'member' => $this->Action->Security->currentuser->id),$this);
						if(!empty($this->PreparedTemplates['access_flag']) && $this->PreparedTemplates['access_flag'] != $this->Action->Security->currentuser->id) {
							header('Location: '.$this->Home.'/Registar/ParentItemsManager'.$this->SID);
							$this->terminated = true;
							return;
						}
						else {
							if(empty($this->PreparedTemplates['access_flag'])) {
								$this->Action->processEvent($this->SectionID,'lock',array('parentitem' => $this->LocalTarget[1],'member' => $this->Action->Security->currentuser->id),$this);
							}
							$this->Action->processEvent($this->SectionID,'item_open',$array,$this);
							if(!empty($this->PreparedTemplates['_error'])) header('Location: '.$this->Home.'/Registar/ParentItemsManager'.$this->SID);
							else $this->Scheme = 'action';
						}
					}
					else header('Location: '.$this->Home.'/Registar/ParentItemsManager'.$this->SID);
				}
				else header('Location: '.$this->Home.'/Registar/ParentItemsManager'.$this->SID);
			break;
			}
			case 'Unlock': {
				if($this->server_type=='dev') {
					$this->Action->processEvent($this->SectionID,'getlock',array('parentitem' => $this->LocalTarget[1],'member' => $this->Action->Security->currentuser->id),$this);
					if(!empty($this->PreparedTemplates)){
						$this->Action->processEvent($this->SectionID,'unlock',array('parentitem' => $this->LocalTarget[1],'member' => $this->Action->Security->currentuser->id),$this);
					}	
					header('Location: '.$this->Home.'/Registar/ParentItemsManager'.$this->SID);
				}
				else $this->Scheme = 'default';
			break;
			}
			case 'Sort': {
				$this->Action->processEvent($this->SectionID,'item_list',array('full' => 0),$this);
				$this->Scheme = 'sort';
			break;
			}
			default: {
				if(!empty($this->LocalTarget[0])){
					header('Location: '.$this->Home.'/Registar/ParentItemsManager'.$this->SID);
					$this->terminated = true;
					return;
				}
				$this->Action->processEvent($this->SectionID,'item_list',array('full' => 1),$this);
				$this->Scheme = 'default';
			break;
			}
		}
		if(!empty($this->Request)) {
			printArray($this->_errors);
			switch($this->getRequestField('step')) {
				case 'add': case 'edit':
					$this->Request['form']['id_user']=$this->Action->Security->currentuser->id;
					if($undo ==1) $this->Request['form']['_undo_'] = $this->LocalTarget[3];
					$this->validateForm()
					and $this->Action->processEvent($this->SectionID,'item_save',$this->getRequestField('form'),$this)
					and header('Location: '.$this->Home.'/Registar/ParentItemsManager'.$this->SID);
				break;
				case 'delete':
					$this->Action->processEvent($this->SectionID,'item_delete',$this->getRequestField('form'),$this)
					and $this->clearUndo($this->getRequestFormField('id'))
					and header('Location: '.$this->Home.'/Registar/ParentItemsManager'.$this->SID);
				break;
				case 'sort': {
					$this->sortingPages()
					and $this->Action->processEvent($this->SectionID,'sort',$this->getRequestField('form'),$this)
					and header('Location: '.$this->Home.'/Registar/ParentItemsManager/Sort'.$this->SID);
				break;
				}
			}
		}
		$this->setSchemeTemplate($this->Scheme);
	}

	function clearUndo($id) {
		global $ROOT_PATH;
		if(file_exists($ROOT_PATH.'/undo/parentitem/'.$id)) {
			chdir($ROOT_PATH.'/undo/parentitem/'.$id);
			$dir = dir('.');
			$dir->rewind();
			while($file = $dir->read()) if(is_file($file)) unlink($ROOT_PATH.'/undo/parentitem/'.$id.'/'.$file);
			rmdir($ROOT_PATH.'/undo/parentitem/'.$id);
			$dir->close();
		}
		return true;
	}

	function fillElements() {
		switch($this->Scheme) {
			case 'action': $this->fillAction(); break;
			case 'viewall': $this->fillViewAll(); break;
			case 'sort': $this->fillSort(); break;
			default: $this->fillDefault(); break;
		}
	}

	function fillSort() {
		if($this->terminated) return;
		$this->TempFillEls['addBut'] = $this->server_type == 'dev' ? 'visible' : 'hidden';
		$this->TempFillEls['pubBut'] = $this->server_type == 'pro' ? 'hidden' : 'visible';
		$this->setSortArray($this->PreparedTemplates);
	}

	function fillViewAll() {
		global $REGISTRY, $ROOT_PATH;
		foreach($this->PreparedTemplates['curPage'] as $ind => $val) {
			$tok = explode(".",$val['date']);
			$this->TempFillEls['comments'][] = array(
				'number' => ($this->PreparedTemplates['pageRecordsQty']*($this->PreparedTemplates['curPageNumber']-1))+($ind+1),
				'date' => $tok[0],
				'author' => $val['member'],
				'changed' => $val['value'],
				'version' => $val['version'],
				'button' =>  file_exists($ROOT_PATH.'/undo/parentitem/'.$this->PreparedTemplates[1].'/'.$val['version'].'.inc')? array(array('id' => $this->PreparedTemplates[1],'version' => $val['version'])) : array(),
			);
		}
	}

	function fillDefault() {
		if($this->terminated) return;
		$this->TempFillEls['addBut'] = $this->server_type == 'dev' ? 'visible' : 'hidden';
		$this->TempFillEls['pubBut'] = $this->server_type == 'pro' ? 'hidden' : 'visible';
		$this->setTargetArray($this->PreparedTemplates);
	}

	function validateForm() {
		if(!validate($this->getRequestFormField('name'))) $this->errors['name'] = 'Parent Item Name is empty';
		if(!validate($this->getRequestFormField('itemtype'))) $this->errors['itemtype'] = 'Parent Item Type is empty';
		if($this->LocalTarget[0] == 'Update')
			if(!is_FullText($this->getRequestFormField('comment'),5,4096)) $this->errors['comment'] = 'Comment is empty or is not valid';
		if(count($this->errors) > 0) return FALSE;
		return TRUE;
	}

	function fillAction(){
		global $ROOT_PATH;
		$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID,'item_open');
		$this->TempFillEls['id'] = $this->LocalTarget[0]!='Add' && $this->LocalTarget[0]!='Duplicate'? $this->PreparedTemplates['id'] : '';
		$this->itemtype = mergeArrays(array('0' => ' ----------- Select Item Type ----------- '),$this->Db->SelectGuide(array('itemtype g'),array('g.id','g.name')));
		switch($this->LocalTarget[0]) {
			case 'Duplicate': {
				$this->TempFillEls['subaction'] = 'Duplicate';
				$this->TempFillEls['subprocess'] = 'duplicating';
				$this->TempFillEls['edit_id'] = '"'.$this->PreparedTemplates['name'].'" ['.$this->PreparedTemplates['id'].']';
				$this->TempFillEls['duplicate_id'] = $this->PreparedTemplates['id'];
				$this->TempFillEls['step'] = 'add';
				$this->TempFillEls['name'] = inputText('form[name]',(!empty($this->Request)? $this->Request['form']['name'] : $this->PreparedTemplates['name']),55,'style="width:250px;"');
				$this->TempFillEls['itemtype'] = inputSelect('form[itemtype]',$this->itemtype,(!empty($this->Request)? $this->getRequestFormField('itemtype') : $this->PreparedTemplates['itemtype']),'style="width:250px;"');
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID, 'item_save');
			break;
			}
			case 'Add': {
				$this->TempFillEls['subaction'] = 'Add';
				$this->TempFillEls['subprocess'] = 'adding';
				$this->TempFillEls['step'] = 'add';
				$this->TempFillEls['name'] = inputText('form[name]',@$this->Request['form']['name'],55,'style="width:250px;"');
				$this->TempFillEls['itemtype'] = inputSelect('form[itemtype]',$this->itemtype,$this->getRequestFormField('itemtype'),'style="width:250px;"');
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID, 'item_save');
			break;
			}
			case 'Update': {
				if(!empty($this->LocalTarget[3]) && validate(intval($this->LocalTarget[3])) && $this->LocalTarget[2]=='Undo')
					$this->TempFillEls['undo'] = '(Undo v.'.$this->LocalTarget[3].')';
				$this->TempFillEls['subaction'] = 'Update';
				$this->TempFillEls['subprocess'] = 'editing';
				$this->TempFillEls['edit_id'] = '"'.$this->PreparedTemplates['name'].'" ['.$this->PreparedTemplates['id'].']';
				$this->TempFillEls['step'] = 'edit';
				$this->TempFillEls['name'] = inputText('form[name]',(!empty($this->Request)? $this->Request['form']['name'] : $this->PreparedTemplates['name']),55,'style="width:250px;"');
				$this->TempFillEls['itemtype'] = inputSelect('form[itemtype]',$this->itemtype,(!empty($this->Request)? $this->getRequestFormField('itemtype') : $this->PreparedTemplates['itemtype']),'style="width:250px;"');
				$this->TempFillEls['textareaValidJS']='if(parseInt(document.getElementById("comment").value.length+"-")<5){
							//document.getElementById("comment").focus();
							alert("Comment is empty or is not valid");
							return false;
							}';
				$this->TempFillEls['ViewAllButton']='<input type="button" name="View_All" class=adminsubmit value="View All" onclick="open(\'/Registar/ParentItemsManager/ViewAll/'.$this->PreparedTemplates['id'].'\',\'displayWindow\',\'width=950,height=600,scrollbars=yes\');">';
				$this->TempFillEls['textareaComment']='<textarea name=form[comment] id=comment cols=80 rows=5>'.(!empty($this->Request['form']['comment'])? $this->Request['form']['comment'] : '').'</textarea>';
				$selected = $this->Db->SelectAny("select cc.*,m.username as member from parentitemcomment cc, member m where m.id=cc.member and cc.ownerid = ".$this->PreparedTemplates['id']." order by cc.version DESC LIMIT 10 OFFSET 0");
				if(!empty($selected)) {
					foreach($selected as $ind => $val) {
						$tok = explode(".",$val['date']);
						$this->TempFillEls['comment'][] = array(
							'number' => ($ind+1),
							'date' => $tok[0],
							'author' => $val['member'],
							'changed' => $val['value'],
							'version' => $val['version'],
							'button' => $ind!=0 && file_exists($ROOT_PATH.'/undo/parentitem/'.$this->PreparedTemplates['id'].'/'.$val['version'].'.inc')? array(array('id' => $this->PreparedTemplates['id'],'version' => $val['version'])) : array(),
						);
					}
				}
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID, 'item_save');
			break;
			}
			case 'Delete': {
				if(!empty($this->LocalTarget[3]) && validate(intval($this->LocalTarget[3])) && $this->LocalTarget[2]=='Undo')
					$this->TempFillEls['undo'] = '(Undo v.'.$this->LocalTarget[3].')';
				$this->TempFillEls['subaction'] = 'Delete';
				$this->TempFillEls['subprocess'] = 'deleting';
				$this->TempFillEls['edit_id'] = '"'.$this->PreparedTemplates['name'].'" ['.$this->PreparedTemplates['id'].']';
				$this->TempFillEls['step'] = 'delete';
				$this->TempFillEls['name'] = $this->PreparedTemplates['name'];
				$this->TempFillEls['itemtype'] = $this->itemtype[$this->PreparedTemplates['itemtype']];
				$selected = $this->Db->SelectAny("select lc.*,m.username as member from parentitemcomment lc, member m where m.id=lc.member and lc.ownerid = ".$this->PreparedTemplates['id']." order by lc.version DESC LIMIT 10 OFFSET 0");
				if(!empty($selected)) {
					$this->TempFillEls['ViewAllButton']='<input type="button" name="View_All" class=adminsubmit value="View All" onclick="open(\'/Registar/ParentItemsManager/ViewAll/'.$this->PreparedTemplates['id'].'\',\'displayWindow\',\'width=950,height=600,scrollbars=yes\');">';
					foreach($selected as $ind => $val){
						$tok = explode(".",$val['date']);
						$this->TempFillEls['comment'][] = array(
							'number' => ($ind+1),
							'date' => $tok[0],
							'author' => $val['member'],
							'changed' => $val['value'],
							'version' => $val['version'],
							'button' => $ind!=0 && file_exists($ROOT_PATH.'/undo/parentitem/'.$this->PreparedTemplates['id'].'/'.$val['version'].'.inc')? array(array('id' => $this->PreparedTemplates['id'],'version' => $val['version'])) : array(),
						);
					}
				}
				$this->PreparedTemplates = $this->Action->getTemplate($this->SectionID, 'item_delete');
			break;
			}
		}
		!empty($this->PreparedTemplates['_error']) 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'] = $this->printError($v).($k=='header'? '<p>' : '');
	}
	
	function setTargetArray($array = array()) {
		$btnEdit_vis = $this->server_type == 'dev' ? 'visible' : 'hidden';
		foreach($array as $value) {
			$locked = empty($value['access_flag']) || $value['access_flag'] == $this->Action->Security->currentuser->id ? false : true;
			$presets_count = explode('/', $value['published_count']);
			$c = count($value['publish']);
			$this->TempFillEls['pages'][$value['id']] = array(
				'id' => $value['id'],
				'name' => $value['name'],
				'name_color' => $this->colors[($value['unmodified'] > 30 ? 'black' : ($value['unmodified'] > 14 && $value['unmodified'] <= 30 ? 'green' : ($value['unmodified'] > 7 && $value['unmodified'] <= 14 ? 'yellow' : 'red')))],
				'published_count' => $value['published_count'],
				'published_count_cursor' => $c ? 'pointer' : 'auto',
				'published_count_color' => $this->colors[($presets_count[0] >= $presets_count[1] ? 'green' : (empty($presets_count[0]) ? 'red' : 'blue'))],
				'chbAdds_disabled' => $locked ? 'disabled' : '',
				'date_changed' => $value['date_changed'],
				'btnUnlock_vis' => $value['access_flag'] == $this->Action->Security->currentuser->id ? 'visible' : 'hidden',
				'btnEdit_vis' => $btnEdit_vis,
				'chbAdds_vis' => $this->TempFillEls['pubBut'],
				'btnUnlock_disp' => $locked ? 'none' : '',
				'btnEdit_disp' => $locked ? 'none' : '',
				'locked_message_disp' => $locked ? '' : 'none',
				'user_name' => $value['username'],
				'date_locked' => $value['date_locked'],
			);
		}
	}

	function sortingPages() {
		uasort($this->Request['form'],'by_order');
		$i = 1;
		foreach($this->Request['form'] as $key => $value) {
			$sort[$key]['sort_order'] = $i*10;
			$i++;
		}
		$this->Request['form'] = $sort;
		return true;
	}

	function setSortArray($array = array()) {
		foreach($array as $value) {
			$this->TempFillEls['pages'][$value['id']] = array(
				'id' => $value['id'],
				'name' => $value['name'],
				'sort_order' => $value['sort_order'],
				'name_color' => $this->colors[($value['unmodified'] > 30 ? 'black' : ($value['unmodified'] > 14 && $value['unmodified'] <= 30 ? 'green' : ($value['unmodified'] > 7 && $value['unmodified'] <= 14 ? 'yellow' : 'red')))],
			);
		}
	}

}
?>