<?php

class CustomerReviewManagerView extends Slot {

	var $SectionID = 6;
	var $ModuleID = 4;
	var $colors = array(
		'red' => '#DC143C',
		'yellow' => '#FF8C00',
		'green' => '#006400',
		'black' => '#000000',
		'blue' => '#4169E1',
	);
	var $cr = array();

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

	function init() {
		global $TOOLS_PATH;
		$undo = 0;
		$this->cr = $this->Action->Server->getGuide('customerreview');
		$this->Scheme = 'default';
		switch(@$this->LocalTarget[0]) {
			case 'Spellcheck': $this->Scheme = $this->server_type=='dev'? 'spellcheck' : 'default'; break;
			case 'Spellword': $this->Scheme = $this->server_type=='dev'? 'spellword' : 'default'; break;
			case 'Spelladd': $this->Scheme = $this->server_type=='dev'? 'spelladd' : 'default'; break;
			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_crcomments',$request,$this);
					if(!empty($this->PreparedTemplates['_error'])) $this->Scheme = 'message';
					else {
						$this->getPageControl($this->Home.'/Registar/CustomerReviewManager/ViewAll/'.$this->LocalTarget[1]);
						if(empty($this->PreparedTemplates['curPage'])) $this->Scheme = 'empty';
					}
					$this->Scheme = 'viewall';
				}
				else $this->Scheme = 'default';
			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->cr))) {
						$array = array('id' => $this->LocalTarget[1]);
						if($undo == 1) $array['undo'] = $this->LocalTarget[3];
						$this->Action->processEvent($this->SectionID,'getlock_cr',array('cr' => $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/CustomerReviewManager'.$this->SID);
						}
						else{
							if(empty($this->PreparedTemplates['access_flag'])) 
								$this->Action->processEvent($this->SectionID,'lock_cr',array('cr' => $this->LocalTarget[1],'member' => $this->Action->Security->currentuser->id),$this);
							$this->Action->processEvent($this->SectionID,'open_cr',$array,$this);
							if(!empty($this->PreparedTemplates['_error'])) header('Location: '.$this->Home.'/Registar/CustomerReviewManager'.$this->SID);
							$this->Scheme = 'action';
						}
					}
					else header('Location: '.$this->Home.'/Registar/CustomerReviewManager'.$this->SID);
				}
				else header('Location: '.$this->Home.'/Registar/CustomerReviewManager'.$this->SID);
			break;
			case 'Add':
				if($this->server_type=='dev') $this->Scheme = 'action';
				else $this->Scheme = 'default';
			break;
			case 'Unlock':
				if($this->server_type=='dev') {
					$idLyaout=$this->LocalTarget[1];
					$this->Action->processEvent($this->SectionID,'getlock_cr',array('cr' => $idLyaout,'member' => $this->Action->Security->currentuser->id),$this);
					if(!empty($this->PreparedTemplates)){
						$this->Action->processEvent($this->SectionID,'unLock_cr',array('cr' => $idLyaout,'member' => $this->Action->Security->currentuser->id),$this);
					}	
					header('Location: '.$this->Home.'/Registar/CustomerReviewManager'.$this->SID);
				}
				else $this->Scheme = 'default';
			break;
			default: $this->Action->processEvent($this->SectionID, 'select_cr', array(), $this); break;
		}
		if(!empty($this->Request)) {
			//printArray($this->Request);
			switch(@$this->LocalTarget[0]) {
				case 'Add': case 'Update': case 'Duplicate':
					if($this->server_type=='dev') {
						$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,'save_cr',$this->getRequestField('form'),$this)
						and header('Location: '.$this->Home.'/Registar/CustomerReviewManager'.$this->SID);
					}
					else header('Location: '.$this->Home.'/Registar/CustomerReviewManager'.$this->SID);
				break;
				case 'Delete':
					if($this->server_type=='dev') {
						$this->Action->processEvent($this->SectionID,'delete_cr',$this->getRequestField('form'),$this)
						and $this->clearUndo($this->getRequestFormField('id'))
						and header('Location: '.$this->Home.'/Registar/CustomerReviewManager'.$this->SID);
					}
					else header('Location: '.$this->Home.'/Registar/CustomerReviewManager'.$this->SID);
				break;
			}
		}
		$this->setSchemeTemplate($this->Scheme);
	}

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

	function validateForm() {
		global $REGISTRY;
		if(!is_FullText($this->getRequestFormField('name'),1,256)) $this->errors['name'] = 'Name is not valid';
		if(!is_FullText($this->getRequestFormField('short_description'),1,1024)) $this->errors['short_description'] = 'Short Description is not valid';
		if(!is_FullText($this->getRequestFormField('full_description'),1,8192)) $this->errors['full_description'] = 'Full Description is not valid';
		if(!is_FullText($this->getRequestFormField('ext_link_name'),1,256)) $this->errors['ext_link_name'] = 'External Link Name is not valid';
		$url = checkURL($this->getRequestFormField('ext_link'));
		if(empty($url)) $this->errors['ext_link'] = 'External Link URL is not valid';
		else $this->Request['form']['ext_link'] = $url;
		if($this->LocalTarget[0] != 'Add' && $this->LocalTarget[0] != 'Duplicate') if(!is_AdvCleanText($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 fillElements() {
		switch($this->Scheme) {
			case 'default': default: $this->fillSelect(); break;
			case 'action': $this->fillAction(); break;
			case 'viewall': $this->fillViewAll(); break;
			case 'spellcheck': $this->fillSpellcheck(); break;
			case 'spellword': $this->fillSpellword(); break;
			case 'spelladd': $this->fillSpelladd(); break;
		}
	}

	function fillSpelladd() {
		$word = @$this->LocalTarget[1];
		global $REGISTRY, $CORE_PATH;
		require_once($CORE_PATH.'/Tools/spell_checker.php');
		$cp = new PSpell();
		$cp->addWord($word);
	}

	function fillSpellword() {
		global $REGISTRY, $CORE_PATH;
		$word = @$this->LocalTarget[1];
		$this->TempFillEls['word'] = $word;
		$this->TempFillEls['check'] = $check = $REGISTRY['Request']['Query']['check'];
		$this->TempFillEls['id'] = $REGISTRY['Request']['Query']['id'];
		$this->TempFillEls['div'] = $REGISTRY['Request']['Query']['div'];
		require_once($CORE_PATH.'/Tools/spell_checker.php');
		$cp = new PSpell();
		if(empty($this->LocalTarget[2])) {
			$words = $cp->getSuggestions($word);
			foreach($words as $value) $this->TempFillEls['suggestion'][0]['words'][]['value'] = makeLink('javascript:void(0);',$value,array(),'','style="text-decoration:none;font-weight:normal" onclick="replaceWord(\''.addslashes($word).'\',\''.addslashes($value).'\',\''.$check.'\','.$this->TempFillEls['id'].',\''.$this->TempFillEls['div'].'\')"');
		}
		else $this->TempFillEls['open_edit'][0]['link'] = makeLink($REGISTRY['Request']['Query']['url'],'Go to edit this mistake',array(),'','target="_blank" style="text-decoration:none;color:red"');
	}

	function fillSpellcheck() {
		global $REGISTRY, $CORE_PATH, $ROOT_PATH;
		require_once($CORE_PATH.'/Tools/spell_checker.php');
		//printArray($this->Request);
		$cp = new PSpell();
		$cp->spellCheck($this->Request['name'],'Name');
		$cp->spellCheck($this->Request['short_description'],'Short');
		$cp->spellCheck($this->Request['full_description'],'Full');
		if(!empty($cp->count)) {
			$this->TempFillEls['error'] = array(array());
			$i = 1;
			$check = 0;
			if(!empty($this->Request['check']) && $this->Request['check']=='submit') $check = 1;
			foreach($cp->errorMsg as $key => $value) {
				if(!empty($value['count'])) {
					$div = eregi_replace(' ','',$key);
					$this->TempFillEls['objects'][$key] = array(
						'object' => $key,
						'count'  => $value['count'],
						'objecttype' => $div,
						'div' => $i,
					);
					//printArray($value['errors']);
					foreach($value['errors'] as $error) {
						$this->TempFillEls['objects'][$key]['errors'][] = array(
							'url_word' => urlencode($error['word']).'?&check='.$check.'&div='.$div.'&id='.$i,
							'word' => $error['word'],
							'string' => $error['string'],
							'div' => $i,
						);
						$i++;
					}
				}
			}
		}
		else {
			$this->TempFillEls['ok'] = array(array());
			if(!empty($this->Request['check']) && $this->Request['check']=='submit') $this->TempFillEls['submit'] = array(array());
		}
	}

	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/customerreview/'.$this->PreparedTemplates[1].'/'.$val['version'].'.inc')? array(array('id' => $this->PreparedTemplates[1],'version' => $val['version'])) : array(),
			);
		}
	}

	function fillSelect() {
		$this->TempFillEls['addBut'] = $btnEdit_vis = $this->server_type == 'dev' ? 'visible' : 'hidden';
		$this->TempFillEls['pubBut'] = $this->server_type == 'pro' ? 'hidden' : 'visible';
		$count = count($this->PreparedTemplates);
		for ($i = 0; $i < $count; $i++){
			$locked = empty($this->PreparedTemplates[$i]['access_flag']) || $this->PreparedTemplates[$i]['access_flag'] == $this->Action->Security->currentuser->id ? false : true;
			$presets_count = explode('/', $this->PreparedTemplates[$i]['published_count']);
			$c = count($this->PreparedTemplates[$i]['publish']);
			$this->TempFillEls['CustomerReviews'][$i] = array(
				'id' => $this->PreparedTemplates[$i]['id'],
				'name' => $this->PreparedTemplates[$i]['name'],
				'name_color' => $this->colors[($this->PreparedTemplates[$i]['unmodified'] > 30 ? 'black' : ($this->PreparedTemplates[$i]['unmodified'] > 14 && $this->PreparedTemplates[$i]['unmodified'] <= 30 ? 'green' : ($this->PreparedTemplates[$i]['unmodified'] > 7 && $this->PreparedTemplates[$i]['unmodified'] <= 14 ? 'yellow' : 'red')))],
				'published_count' => $this->PreparedTemplates[$i]['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' => $this->PreparedTemplates[$i]['date_changed'],
				'btnUnlock_vis' => $this->PreparedTemplates[$i]['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' => $this->PreparedTemplates[$i]['username'],
				'date_locked' => $this->PreparedTemplates[$i]['date_locked'],
			);
			$this->TempFillEls['CustomerReviews'][$i]['publish'][]['variable'] = 'CustomerReviews['.$this->PreparedTemplates[$i]['id'].']=[];';
			$this->TempFillEls['CustomerReviews'][$i]['publish'][]['variable'] = 'CustomerReviews['.$this->PreparedTemplates[$i]['id'].']["publish"]=[];';
			for($j = 0; $j < $c; $j++){
				$this->TempFillEls['CustomerReviews'][$i]['publish'][]['variable'] = 'CustomerReviews['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']=[];';
				$this->TempFillEls['CustomerReviews'][$i]['publish'][]['variable'] = 'CustomerReviews['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["package_id"]='.$this->PreparedTemplates[$i]['publish'][$j]['package_id'].';';
				$this->TempFillEls['CustomerReviews'][$i]['publish'][]['variable'] = 'CustomerReviews['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["package_name"]="'.$this->PreparedTemplates[$i]['publish'][$j]['package_name'].'";';
				$this->TempFillEls['CustomerReviews'][$i]['publish'][]['variable'] = 'CustomerReviews['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["username"]="'.$this->PreparedTemplates[$i]['publish'][$j]['username'].'";';
				$this->TempFillEls['CustomerReviews'][$i]['publish'][]['variable'] = 'CustomerReviews['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["hostpath"]="'.$this->PreparedTemplates[$i]['publish'][$j]['hostpath'].'";';
				$this->TempFillEls['CustomerReviews'][$i]['publish'][]['variable'] = 'CustomerReviews['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["date_published"]="'.$this->PreparedTemplates[$i]['publish'][$j]['date_published'].'";';
			}
		}
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select');
	}

	function fillNoDelete() {
		$this->TempFillEls['id'] = $this->PreparedTemplates['id'];
		$this->TempFillEls['sec_name'] = '" '.$this->PreparedTemplates['name'].' "';
		empty($this->check) and $this->check = array();
		foreach($this->check as $key => $value) {
			$this->TempFillEls['Pages'][0]['pitems'][] = array(
				'item' => makeLink($this->Home.$value['path'],$value['name']),
				'id' => $value['id'],
			);
		}
	}

	function fillAction() {
		global $CORE_PATH, $ROOT_PATH;
		//printArray($this->PreparedTemplates);
		$this->TempFillEls['action'] = $this->LocalTarget[0];
		if(!empty($this->LocalTarget[3]) && validate(intval($this->LocalTarget[3])) && $this->LocalTarget[2]=='Undo')
			$this->TempFillEls['undo'] = '(Undo v.'.$this->LocalTarget[3].')';
		$this->TempFillEls['sec_name'] = !empty($this->Request)? ($this->LocalTarget[0]!='Duplicate'? '" '.$this->getRequestFormField('name').' "' : '" '.$this->PreparedTemplates['name'].' "') : ($this->LocalTarget[0]!='Add'? '" '.$this->PreparedTemplates['name'].' "' : '');
		$this->TempFillEls['id'] = $this->LocalTarget[0]!='Add' && $this->LocalTarget[0]!='Duplicate'? $this->PreparedTemplates['id'] : '';
		if($this->LocalTarget[0]=='Duplicate') $this->TempFillEls['duplicate_id'] = $this->PreparedTemplates['id'];
		$this->TempFillEls['name'] = inputTextArea('form[name]',(!empty($this->Request)? $this->getRequestFormField('name') : ($this->LocalTarget[0]!='Add'? $this->PreparedTemplates['name'] : '')),100,2,'style="width:700px;"'.($this->LocalTarget[0]=='Delete'? ' readonly=true' : ''));
		$this->TempFillEls['short_description'] = inputTextArea('form[short_description]',(!empty($this->Request)? $this->getRequestFormField('short_description') : ($this->LocalTarget[0]!='Add'? $this->PreparedTemplates['short_description'] : '')),100,5,'style="width:700px;"'.($this->LocalTarget[0]=='Delete'? ' readonly=true' : ''));
		$this->TempFillEls['full_description'] = inputTextArea('form[full_description]',(!empty($this->Request)? $this->getRequestFormField('full_description') : ($this->LocalTarget[0]!='Add'? $this->PreparedTemplates['full_description'] : '')),100,20,'style="width:700px;"'.($this->LocalTarget[0]=='Delete'? ' readonly=true' : ''));
		$this->TempFillEls['ext_link'] = inputText('form[ext_link]',(!empty($this->Request)? $this->getRequestFormField('ext_link') : ($this->LocalTarget[0]!='Add'? $this->PreparedTemplates['ext_link'] : '')),100,'style="width:700px;"'.($this->LocalTarget[0]=='Delete'? ' readonly=true' : ''));
		$this->TempFillEls['ext_link_name'] = inputText('form[ext_link_name]',(!empty($this->Request)? $this->getRequestFormField('ext_link_name') : ($this->LocalTarget[0]!='Add'? $this->PreparedTemplates['ext_link_name'] : '')),100,'style="width:700px;"'.($this->LocalTarget[0]=='Delete'? ' readonly=true' : ''));
		if($this->LocalTarget[0] == 'Update'){
			$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/CustomerReviewManager/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 lc.*,m.username as member from customerreviewcomment 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)) {
				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/customerreview/'.$this->PreparedTemplates['id'].'/'.$val['version'].'.inc')? array(array('id' => $this->PreparedTemplates['id'],'version' => $val['version'])) : array(),
					);
				}
			}
		}
		else if($this->LocalTarget[0] == 'Delete'){
			$selected = $this->Db->SelectAny("select lc.*,m.username as member from customerreviewcomment 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/CustomerReviewManager/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/customerreview/'.$this->PreparedTemplates['id'].'/'.$val['version'].'.inc')? array(array('id' => $this->PreparedTemplates['id'],'version' => $val['version'])) : array(),
					);
				}
			}
		}
		$this->TempFillEls['spell'] = $this->LocalTarget[0]=='Delete'? array() : array(array());
		$this->TempFillEls['spell_checked'] = $this->getSpellCookie()? 'checked' : '';
		!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 setSpellCookie($value) {
		setcookie("spell_check",$value,time()+86400*365,"/");
	}

	function getSpellCookie() {
		return isset($_COOKIE['spell_check']) && $_COOKIE['spell_check']==1? TRUE : FALSE;
	}

}
?>