<?php

class TemplateHandler extends Handler{

	function __construct(){
		parent::__construct('TemplateHandler');
	}

	function createTemplate(){
		$template = new Template();
		$template->items = new ObjectsList();
		$template->items->type = new TemplateItem();
		$template->items->type->conds = new ObjectsList();
		$template->items->type->conds->type = new TemplateItemCond();
		$template->items->type->conds->type->params = new ObjectsList();
		$template->items->type->conds->type->params->type = new TemplateItemCondParam();
		return $template;
	}

	function selectTemplates($request = array()){
		$presets = array();
		$selected = $this->DB->SelectAny('SELECT id, name FROM preset');
		$presets_count = count($selected);
		for ($i = 0; $i < $presets_count; $i++) $presets[$selected[$i]['id']] = $selected[$i]['name'];
//		$result = $this->DB->SelectAny('SELECT id, name, date_changed, (\'now\'::date - date_changed::date) AS unmodified, access_flag, date_locked FROM template ORDER BY id');
		$result = $this->DB->SelectAny('SELECT id, name, date_changed, TIMESTAMPDIFF(day,date_changed,NOW()) AS unmodified, access_flag, date_locked FROM template ORDER BY id');
		$packages = array();
		$hostpaths = array();
		$usernames = array();
		$count = count($result);
		for($i = 0; $i < $count; $i++){
			$date_changed = explode('.', $result[$i]['date_changed']);
			$result[$i]['date_changed'] = $date_changed[0];
			$date_locked = explode('.', $result[$i]['date_locked']);
			$result[$i]['date_locked'] = $date_locked[0];
			$result[$i]['username'] = $result[$i]['access_flag'] ? $this->getUserName(array('type' => 1, 'userid' => $result[$i]['access_flag'])) : '';
			$result[$i]['publish'] = array();
			$query = 'SELECT packagepublish.id, packagepublish.ownerid as package_id, packagepublish.host, packagepublish.userid, packagepublish.date_published FROM packagepublish WHERE packagepublish.type = 1 AND packagepublish.successful = 1 AND packagepublish.date_published > \''.$result[$i]['date_changed'].'\' AND packagepublish.ownerid IN (SELECT DISTINCT packageitem.ownerid FROM packageitem WHERE packageitem.type = 6 AND packageitem.object = \''.$result[$i]['id'].'\') ORDER BY packagepublish.date_published DESC';
			$packagepublish = $this->DB->SelectAny($query);
			$presets_unique = array();
			$c = count($packagepublish);
			$index = 0;
			for ($j = 0; $j < $c; $j++){
				if(isset($presets_unique[$packagepublish[$j]['host']])) continue;
				$presets_unique[$packagepublish[$j]['host']] = true;
				$result[$i]['publish'][$index] = $packagepublish[$j];
				$date_published = explode ('.', $packagepublish[$j]['date_published']);
				$result[$i]['publish'][$index]['date_published'] = $date_published[0];
				if(!isset($packages[$packagepublish[$j]['package_id']])){
					$sel = $this->DB->SelectAny('SELECT name FROM package WHERE id = '.$packagepublish[$j]['package_id'].' LIMIT 1');
					$packages[$packagepublish[$j]['package_id']] = empty($sel) ? '[deleted]' : $sel[0]['name'];
				}
				$result[$i]['publish'][$index]['package_name'] = $packages[$packagepublish[$j]['package_id']];
				if(!isset($hostpaths[$packagepublish[$j]['host']])){
					$sel = $this->DB->SelectAny('SELECT name FROM preset WHERE id = '.$packagepublish[$j]['host'].' LIMIT 1');
					$hostpaths[$packagepublish[$j]['host']] = empty($sel) ? '[unknown]' : $sel[0]['name'];
				}
				$result[$i]['publish'][$index]['hostpath'] = $hostpaths[$packagepublish[$j]['host']];
				if(!isset($usernames[$packagepublish[$j]['userid']])){
					$sel = $this->DB->SelectAny('SELECT username FROM member WHERE id = '.$packagepublish[$j]['userid'].' LIMIT 1');
					$usernames[$packagepublish[$j]['userid']] = empty($sel) ? '[unknown]' : $sel[0]['username'];
				}
				$result[$i]['publish'][$index]['username'] = $usernames[$packagepublish[$j]['userid']];
				$index++;
			}
			$result[$i]['published_count'] = count($result[$i]['publish']).'/'.$presets_count;
		}
		return $result;
	}
	
	function getLock($request = array('id' => 1)){
		$query = 'SELECT template.access_flag, template.date_locked, member.username FROM template, member WHERE template.id = '.$request['id'].' AND member.id = template.access_flag LIMIT 1';
		$selected = $this->DB->SelectAny($query);
		return empty($selected[0]) ? array() : $selected[0];
	}

	function makeUnlocked($request = array('id' => 0)){
		$this->setLogEvent(3, 9, 4, 'Unlock Template ['.$request['id'].']',$request['id']);
		$this->DB->update('template', array('access_flag' => '0'), array('id' => $request['id'], 'access_flag' => $request['member']));
		
		$this->DB->commit();
		return $request;
	}

	function makeLocked($request = array('id' => 0, 'member' => 0)){
		$this->setLogEvent(3, 9, 3, 'Lock Template ['.$request['id'].']',$request['id']);
		$this->DB->update('template', array('access_flag' => $request['member'], 'date_locked' => 'now()'), array('id' => $request['id']),0);
		$this->DB->commit();
		return $request;
	}

	function openTemplate($request = array('id' => 1)){
		GLOBAL $ROOT_PATH, $TOOLS_PATH;
		if(empty($request['undo'])){
			$template = $this->createTemplate();
			$template->id = $request['id'];
			$this->DB->initObject($template);
			$template_comments = &$template->comments;
		}
		else{
			$Undo_field = array('type' => 6, 'id' => $request['id'], 'undo' => 0, 'version' => $request['undo']);
			include ($TOOLS_PATH.'/undo.php');
			$template = &$print_arr;
			$template_comments = &$template['comments'];
		}
		$template_comments = $this->DB->SelectAny('SELECT tc.*, m.username AS member FROM templatecomment tc, member m WHERE m.id = tc.member AND tc.ownerid = '.$request['id'].' ORDER BY tc.version DESC LIMIT 10 OFFSET 0');
		$count = count($template_comments);
		for ($i = 0; $i < $count; $i++) $template_comments[$i]['file'] = file_exists($ROOT_PATH.'/undo/template/'.$request['id'].'/'.$template_comments[$i]['version'].'.inc') ? true : false;
		return $template;
	}
	
	function saveTemplate($request = array()){
//printArray($request);exit;
		global $REGISTRY, $Server, $TOOLS_PATH;
		$default = false;
		$count = count($request['items']);
		for ($i = 0; $i < $count; $i++) {
			if(empty($request['items'][$i]['uid']) || @$request['action'] == 'Duplicate') $request['items'][$i]['uid'] = getUnique32();
			if($request['items'][$i]['default_item']) $default = true;
			$cond_count = count($request['items'][$i]['conds']);
			for ($j = 0; $j < $cond_count; $j++){
				$param_count = count($request['items'][$i]['conds'][$j]['params']);
				for ($k = 0; $k < $count; $k++){
					if(empty($request['items'][$i]['conds'][$j]['params'][$k]['name']) && empty($request['items'][$i]['conds'][$j]['params'][$k]['value'])) unset($request['items'][$i]['conds'][$j]['params'][$k]);
				}
				if(empty($request['items'][$i]['conds'][$j]['params'])) unset($request['items'][$i]['conds'][$j]);
			}
		}
		if(!$default) $request['items'][0]['default_item'] = 1;
		if(empty($request['id'])){
			$request['uid'] = getUnique32();
			$request['date_created'] = 'now';
		}
		else {
			$selected = $this->DB->SelectAny('SELECT id FROM template WHERE name = \''.$request['name'].'\' AND id != '.$request['id']);
			if(!empty($selected)){
				$this->DB->good = FALSE;
				$request['_error'] = 'Template with such name and different id already exists';
				return $request;
			}
		}
		if(empty($request['uid'])) $request['uid'] = getUnique32();
		$request['date_changed'] = 'now';
		$template = $this->createTemplate();
		$this->parseRequest($request, $template);
		$this->undo = '';
		if(empty($template->id)) $this->setLogEvent(3, 9, 11, 'Add Template "'.$template->name.'"');
		else {
			$this->setLogEvent(3, 9, 12, 'Edit Template "'.$template->name.'" ['.$template->id.']', $template->id);
			$Undo_field = array('type' => 6, 'id' => $template->id, 'undo' => 1);
			include($TOOLS_PATH.'\undo.php');
			$this->undo = $undo_handler->arr_obj;
		}
		$this->DB->processObject($template, 'save', array(), array(), TRUE);
		$this->DB->delete('deleted', array('uid' => $template->uid, 'type' => 6));
		$templatecomment = new TemplateComment();
		$templatecomment->version = 1;
		$templatecomment->value = 'Template has been created';
		$selected = $this->DB->SelectAny('SELECT version FROM templatecomment WHERE ownerid = '.$template->id.' ORDER BY date DESC LIMIT 1 OFFSET 0');
		if(!empty($selected[0]['version'])) {
			$templatecomment->version = ++$selected[0]['version'];
			$templatecomment->value = (!empty($request['undo']) ? 'Template has been undone up to '.$request['undo'].' version<br>'."\r\n" : '').htmlspecialchars($request['comment']);
		}
		$templatecomment->ownerid = $template->id;
		$templatecomment->member = $request['id_user'];
		$templatecomment->date = 'now';
		$this->DB->processObject($templatecomment, 'save', array(), array(), TRUE);
		if(!empty($request['undo'])) $this->setLogEvent(3, 9, 10, 'Template "'.$template->name.'" ['.$template->id.'] has been undone up to '.$request['undo'].' version', $template->id);
		$this->DB->commit();
		if($this->DB->good && !empty($this->undo)) 	$undo_handler->GetArrayInFile($this->undo, 'Undo_object', $ROOT_PATH.'/undo/'.$pub_type[0]['name'].'/'.$Undo_field['id'].'/'.($templatecomment->version > 1 ? $templatecomment->version - 1 : 1).'.inc');
		clearCache();
		return $template;
	}
	
	function deleteTemplate($request = array('id' => 1)){
		global $REGISTRY, $Server;
		$template = $this->createTemplate();
		$this->parseRequest($request, $template);
		$this->DB->begin();
		$this->DB->initObject($template);
		$presets = $this->DB->SelectGuide(array('preset g'), '*', array());
		foreach($presets as $prekey => $prevalue) {
			$selected = $this->DB->SelectAny('SELECT id FROM deleted WHERE uid = \''.$template->uid.'\' AND preset = '.$prekey.' AND type = 6 LIMIT 1');
			if(empty($selected)) $this->DB->insert('deleted', array('uid' => $template->uid, 'preset' => $prekey, 'type' => 6));
		}
		$this->setLogEvent(3, 9, 13, 'Delete Template "'.$template->name.'" ['.$template->id.']',$template->id);
		$this->DB->processObject($template, 'delete', array(), array(), TRUE);
		$this->DB->delete('templatecomment', array('ownerid' => $template->id));
		$this->DB->commit();
		return $template;
	}

	function selectTemplateComments($request = array()){
		GLOBAL $ROOT_PATH;
		if(empty($request['curPageNumber'])) $request['curPageNumber'] = 1;
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty'] = 20;
		$template = $this->DB->SelectAny('SELECT name FROM template WHERE id = '.$request['id'].' LIMIT 1');
		$request['name'] = $template[0]['name'];
		$selected = $this->DB->SelectAny('SELECT tc.*, m.username AS member FROM templatecomment tc, member m WHERE m.id = tc.member AND tc.ownerid = '.$request['id'].' ORDER BY tc.version DESC LIMIT '.$request['pageRecordsQty'].' OFFSET '.(($request['curPageNumber'] - 1) * $request['pageRecordsQty']));
		$count = count($selected);
		for ($i = 0; $i < $count; $i++) $selected[$i]['file'] = file_exists($ROOT_PATH.'/undo/template/'.$request['id'].'/'.$selected[$i]['version'].'.inc') ? true : false;
		$count = $this->DB->SelectAny('SELECT count(id) AS count FROM templatecomment WHERE ownerid = '.$request['id']);
		$request['recordsTotal'] = $count[0]['count'];
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
		$request['curPage'] = $selected;
		return $request;
	}
	
	function openTemplateItem($request = array('id' => 1,)){
		$templateitem = new TemplateItem();
		if(!empty($request['id'])) $templateitem->id = $request['id'];
		else if(!empty($request['uid'])){
			$selected = $this->DB->SelectAny('SELECT id FROM templateitem WHERE uid = \''.$request['uid'].'\' LIMIT 1');
			if(empty($selected)){
				$template->_error = 'Item with uid = "'.$request['uid'].'" doesn\'t exist';
				return $templateitem;
			}
			$templateitem->id = $selected[0]['id'];
		}
		$this->DB->initObject($templateitem);
		if($templateitem->name === NULL) $templateitem->_error = 'Item with id = ['.$templateitem->id.'] doesn\'t exist';
		if(!empty($templateitem->ownerid)){
			$selected = $this->DB->SelectAny('SELECT name FROM template WHERE id = '.$templateitem->ownerid.' LIMIT 1');
			if(empty($selected)) $templateitem->_error = 'Template with id = ['.$templateitem->ownerid.'] doesn\'t exist';
			$templateitem->ownername = @$selected[0]['name'];
		}
		return $templateitem;
	}
	
	function getHostPath($request = array()){
		$selected = $this->DB->SelectAny('SELECT '.($request['type'] == 1 ? 'name' : 'host').' AS hostpath FROM '.($request['type'] == 1 ? 'preset' : 'publisher').' WHERE id = '.$request['host'].' LIMIT 1');
		$hostpath = empty($selected) ? '[undefined]' : $selected[0]['hostpath'];
		return $hostpath;
	}
	
	function getUserName($request = array()){
		$selected = $this->DB->SelectAny('SELECT username FROM '.($request['type'] == 1 ? 'member' : 'publisher_user').' WHERE id = '.$request['userid'].' LIMIT 1');
		$username = empty($selected) ? '[undefined]' : $selected[0]['username'];
		return $username;
	}
}
?>