<?php

class FeedManagerView extends Slot {

	var $SectionID = 46;
	var $ModuleID = 15;
	var $colors = array('red' => '#DC143C', 'yellow' => '#FF8C00', 'green' => '#006400', 'black' => '#000000', 'blue' => '#4169E1',);
	var $action;
	var $feeds = array();
	var $feed = array();
	var $terminated = false;
	var $undo = 0;
	var $default_validity_period = 1209600;
	var $feed_validity_periods = array(86400 => '1 Day', 172800 => '2 Days', 259200 => '3 Days', 604800 => '1 Week', 1209600 => '2 Weeks', 1814400 => '3 Weeks',);
	var $validity_periods = array();
	var $on_web_max_counts = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 10,);

	function __construct($pquery) {
		parent::__construct($pquery);
		$this->validity_periods = $this->feed_validity_periods;
		$this->validity_periods[0] = 'Feed';
		ksort($this->validity_periods);
	}

	function init() {
		GLOBAL $TOOLS_PATH;
		$this->action = isset($this->LocalTarget[0]) ? $this->LocalTarget[0] : '';
		$this->feeds = $this->Action->Server->getGuide('feed');
		if(!empty($this->action) && !is_numeric($this->action) && (($this->action != 'Add' && !array_key_exists(@$this->LocalTarget[1], $this->feeds)) || ($this->server_type != 'dev' && $this->action != 'View'))) return $this->terminateAction();
		switch($this->action){
			case 'Add': {
				$this->feed = $this->Action->Handler->_parseContent($this->Action->Handler->createFeed());
				$this->feed['items'][0] = $this->Action->Handler->_parseContent(new FeedItem());
				$this->Scheme = 'action';
				break;
			}
			case 'Update': case 'View': case 'Duplicate': 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->feed = $this->PreparedTemplates;
				if($this->action == 'Duplicate') $this->feed['id'] = '';
				if(empty($this->feed['items'])) $this->feed['items'][0] = $this->Action->Handler->_parseContent(new FeedItem());
				$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;
			}
			default: {
				$this->Scheme = 'default';
				$this->Action->processEvent($this->SectionID, 'select', array(), $this);
				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->feed[$key] = is_array($value) ? array_values($value) : $value;
				if($this->validateFeed()) {
					$this->feed['action'] = $this->action;
					$this->feed['id_user'] = $this->Action->Security->currentuser->id;
					if ($this->Action->processEvent($this->SectionID, 'save', $this->feed, $this)) {
						if(!empty($this->feed['id'])) $this->Action->processEvent($this->SectionID, 'unlock', array('id' => $this->feed['id'], 'member' => $this->Action->Security->currentuser->id), $this);
						return $this->terminateAction();
					}
					else $this->errors['validate'] = $this->PreparedTemplates['_error'];
				}
				break;
			}
			case 'Delete': {
				include($TOOLS_PATH.'/checker.php');
				$this->check = check_to_delete($this->feed['id'], 'Feed');
				if (empty($this->check)){
					$this->Action->processEvent($this->SectionID, 'delete', $this->feed, $this)
					and $this->clearUndo($this->feed['id'])
					and $this->terminateAction();
				}
				else {
					$this->Scheme = 'nodelete';
					$this->Action->processEvent($this->SectionID, 'unlock', array('id' => $this->feed['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() {
		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);
		for ($i = 0; $i < $count; $i++) {
			$this->TempFillEls['feeds'][$i] = $this->PreparedTemplates[$i];
			$date_locked = explode('.', $this->PreparedTemplates[$i]['date_locked']);
			$this->TempFillEls['feeds'][$i]['date_locked'] = $date_locked[0];
			if(empty($this->PreparedTemplates[$i]['_error'])) $this->TempFillEls['feeds'][$i]['img'] = 'bullet';
			else {
				$this->TempFillEls['feeds'][$i]['img'] = 'bullet2';
				$this->TempFillEls['feeds'][$i]['chbAdds_disabled'] = 'disabled';
			}
			$this->TempFillEls['feeds'][$i]['btnEdit_vis'] = $edit_vis;
			$this->TempFillEls['feeds'][$i]['chbAdds_vis'] = $pub_vis;
			if(!empty($this->PreparedTemplates[$i]['access_flag']) && $this->PreparedTemplates[$i]['access_flag'] != $this->Action->Security->currentuser->id) {
				$this->TempFillEls['feeds'][$i]['btnUnlock_disp'] = 'none';
				$this->TempFillEls['feeds'][$i]['btnEdit_disp'] = 'none';
				$this->TempFillEls['feeds'][$i]['btnDelete_disp'] = 'none';
			}
			else {
				$this->TempFillEls['feeds'][$i]['locked_message_disp'] = 'none';
				if($this->PreparedTemplates[$i]['access_flag'] != $this->Action->Security->currentuser->id) $this->TempFillEls['feeds'][$i]['btnUnlock_disp'] = 'none';
			}
			$presets_count = explode('/', $this->PreparedTemplates[$i]['published_count']);
			$c = count($this->PreparedTemplates[$i]['publish']);
			$this->TempFillEls['feeds'][$i]['published_count_cursor'] = $c ? 'pointer' : 'auto';
			$this->TempFillEls['feeds'][$i]['published_count_color'] = $this->colors[($presets_count[0] >= $presets_count[1] ? 'green' : (empty($presets_count[0]) ? 'red' : 'blue'))];
			$this->TempFillEls['feeds'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates[$i]['id'].']=[];';
			$this->TempFillEls['feeds'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates[$i]['id'].']["publish"]=[];';
			for($j = 0; $j < $c; $j++){
				$this->TempFillEls['feeds'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']=[];';
				$this->TempFillEls['feeds'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["package_id"]='.$this->PreparedTemplates[$i]['publish'][$j]['package_id'].';';
				$this->TempFillEls['feeds'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["package_name"]="'.$this->PreparedTemplates[$i]['publish'][$j]['package_name'].'";';
				$this->TempFillEls['feeds'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["username"]="'.$this->PreparedTemplates[$i]['publish'][$j]['username'].'";';
				$this->TempFillEls['feeds'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["hostpath"]="'.$this->PreparedTemplates[$i]['publish'][$j]['hostpath'].'";';
				$this->TempFillEls['feeds'][$i]['publish'][]['variable'] = 'publish_info['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["date_published"]="'.$this->PreparedTemplates[$i]['publish'][$j]['date_published'].'";';
			}
		}
		$this->clearAllTemplates();
	}

	function fillAction() {
		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->feed['name'];
		$this->TempFillEls['id'] = $this->feed['id'];
		$this->TempFillEls['link'] = '<a href="/'.$this->feed['link'].'">'.$this->feed['link'].'</a>';
		$this->TempFillEls['uid'] = $this->feed['uid'];
		$date_created = explode('.', $this->feed['date_created']);
		$this->TempFillEls['date_created'] = $date_created[0];
		$this->TempFillEls['form_name'] = inputText('form[name]', $this->feed['name'], 80, '', 128);
		$this->TempFillEls['form_title'] = inputText('form[title]', $this->feed['title'], 80, '', 256);
		$this->TempFillEls['form_description'] = inputTextArea('form[description]', $this->feed['description'], '', 5, 'style="width: 500px;"');
		$this->TempFillEls['form_validity_period'] = inputSelect ('form[validity_period]', $this->feed_validity_periods, $this->feed['validity_period'], 'style="width: 100px;"');
		$this->TempFillEls['form_on_web_max_count'] = inputSelect ('form[on_web_max_count]', $this->on_web_max_counts, $this->feed['on_web_max_count'], 'style="width: 100px;"');
		$count = count($this->feed['items']);
		for ($i = 0; $i < $count; $i++) {
			$this->TempFillEls['items'][$i] = array(
				'ident' => $i,
				'id' => @$this->feed['feeditems'][$i]['id'],
				'form_title' => inputText('form[items]['.$i.'][title]', $this->feed['items'][$i]['title'], 50, '', 256),
				'form_link' => inputText('form[items]['.$i.'][link]', $this->feed['items'][$i]['link'], 60),
				'form_description' => inputTextArea('form[items]['.$i.'][description]', $this->feed['items'][$i]['description'], '', 6, 'style="width: 420px;"'),
				'pubdate_form_name' => 'form[items]['.$i.'][pubdate]',
				'form_validity_period' => inputSelect ('form[items]['.$i.'][validity_period]', $this->validity_periods, $this->feed['items'][$i]['validity_period'], 'style="width: 100px;"'),
				'form_canceled' => inputHidden('form[items]['.$i.'][canceled]', '0').inputCheckbox('form[items]['.$i.'][canceled]', $this->feed['items'][$i]['canceled']),
			);
			$this->TempFillEls['items'][$i]['form_pubdate'] = inputText($this->TempFillEls['items'][$i]['pubdate_form_name'], str_replace(array(' 0', '-0', ':0'), array(' ', '-', ':'), $this->feed['items'][$i]['pubdate']), 19, 'id="'.$this->TempFillEls['items'][$i]['pubdate_form_name'].'" style="width: 130px;" readonly', 19);
			if(!empty($this->feed['items'][$i]['errors']) && is_array($this->feed['items'][$i]['errors']))
				foreach($this->feed['items'][$i]['errors'] as $key => $value) $this->TempFillEls['items'][$i][$key.'_error'] = $this->printError($value);
		}
		$this->TempFillEls['max_item_ident'] = $count - 1;
		if(empty($this->feed['id'])) {
			$this->TempFillEls['header_info_disp'] = 'none';
			$this->TempFillEls['link_disp'] = 'none';
			$this->TempFillEls['date_created_disp'] = 'none';
			$this->TempFillEls['uid_disp'] = 'none';
		}
		$this->TempFillEls['form_comment'] = inputTextarea('form[comment]', (isset($this->feed['comment']) ? $this->feed['comment'] : ''), '', 5, 'id="form[comment]" style="width: 500px;"');
		if(!empty($this->feed['comments'])) $this->fillFullHistory(false);
		if(!empty($this->feed['_error'])) $this->errors['model'] = $this->feed['_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->feed['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->feed['id'];
		$this->TempFillEls['name'] = $this->feed['name'];
		$count = count($this->check);
		for ($i = 0; $i < $count; $i++)
			$this->TempFillEls['Pages'][0]['pitems'][$i] = array(
				'item' => makeLink($this->Home.$this->check[$i]['path'], $this->check[$i]['name']),
				'id' => $this->check[$i]['id'],
			);
		$this->clearAllTemplates();
	}
	
	function validateFeed() {
		if(($id = array_search($this->feed['name'], $this->feeds)) !== false && $id != $this->feed['id']) $this->errors['name'] = 'Feed with such name already exists';
		if(!is_AlphaNumUnderDefis($this->feed['name'], 3, 128)) $this->errors['name'] = 'Feed name is not valid';
		if(!is_FullText($this->feed['description'], 6, 256)) $this->errors['description'] = 'Feed description is not valid';
		$count = count($this->feed['items']);
		if(!$count){
			$this->errors['item'] = 'Feed must contain at least 1 item';
			$this->feed['items'][0] = $this->Action->Handler->_parseContent(new FeedItem());
		}
		for ($i = 0; $i < $count; $i++) {
			if(!is_NumText($this->feed['items'][$i]['title'], 3, 256)) $this->feed['items'][$i]['errors']['title'] = 'Item Title is not valid';
			$link = checkURL($this->feed['items'][$i]['link']);
			if(empty($this->feed['items'][$i]['link']) || ($link != $this->feed['items'][$i]['link'] && !isWebPath($this->feed['items'][$i]['link']))) $this->feed['items'][$i]['errors']['link'] = 'Item Link is not valid';
			if(empty($this->feed['items'][$i]['description'])) $this->feed['items'][$i]['errors']['description'] = 'Item Description is not valid';
			if(empty($this->feed['items'][$i]['pubdate'])) $this->feed['items'][$i]['errors']['pubdate'] = 'Item PubDate is not valid';
			if(!isset($this->feed['items'][$i]['validity_period']) || !is_numeric($this->feed['items'][$i]['validity_period'])) $this->feed['items'][$i]['errors']['validity_period'] = 'Item Validity Period is not valid';
			if(!isset($this->feed['items'][$i]['canceled']) || !is_numeric($this->feed['items'][$i]['canceled'])) $this->feed['items'][$i]['errors']['canceled'] = 'Item Canceled value is not valid';
			if(!empty($this->feed['items'][$i]['errors'])) $this->errors['item'] = 'Some Item is 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/feed/'.$id;
		if(file_exists($path)) mysystem('rm -rf '.$path);
		return true;
	}
	
	function terminateAction(){
		$this->terminated = true;
		$this->clearAllTemplates();
		header('Location: '.$this->Home.'/Registar/FeedManager'.$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');
	}

}
?>