.
if (!defined('EG')) die('Direct access not allowed!');
class GenericController extends BaseController
{
	protected $_controllerName = null; //as in the URL
	
	public $orderPopup;
	
	public function __construct($model, $controller, $queryString) {
		parent::__construct($model, $controller, $queryString);
		
		$this->model('UsersModel');
		
		$popup = new Popup();
		$popup->name = gtext('sort by');
		switch ($this->controller)
		{
			case 'wifi':
				$popup->itemsName = array('last inserted','alphabetically','alphabetically desc');
				$popup->itemsValue = array('last-inserted','alphabetically','alphabetically-desc');
				break;
			case 'videocards':
				$popup->itemsName = array('last inserted','alphabetically','alphabetically desc');
				$popup->itemsValue = array('last-inserted','alphabetically','alphabetically-desc');
				break;
			default:
				$popup->itemsName = array('last inserted','alphabetically','alphabetically desc','compatibility');
				$popup->itemsValue = array('last-inserted','alphabetically','alphabetically-desc','compatibility');
				break;
		}
		
		$this->orderPopup = $popup;
		
	}
	
	protected function insert($lang = 'en', $token = '')
	{
		$this->shift(2);
		
		$clean['token'] = sanitizeAlphanum($token);
		
		$data['notice'] = null;
		$data['tree'] = $this->getSpecHardLink() . " »  " . " insert";
		
		$this->s['registered']->checkStatus();
		
		if ($this->s['registered']->status['status'] === 'logged')
		{
			if (!$this->s['registered']->checkCsrf($clean['token'])) $this->redirect($this->controller.'/catalogue/'.$this->lang,2,'wrong token..');
			
			if ($this->m['UsersModel']->isBlocked($this->s['registered']->status['id_user'])) $this->redirect('my/home/'.$this->lang,2,'your account has been blocked..');
			
			if (isset($_POST['insertAction']))
			{
				if ($this->checkDist())
				{
					$pci_id = $this->request->post('pci_id','','sanitizeAll');
					if (strcmp($pci_id,'') !== 0)
					{
						$this->m['HardwareModel']->databaseConditions['insert']['+checkUnique'] = 'pci_id|VendorID:ProductID is already present in the database. This means that the device you are trying to insert is already in the database';
					}
						
					//insert the new device
					$this->m['HardwareModel']->updateTable('insert');
					
					if ($this->m['HardwareModel']->queryResult)
					{
						if (strcmp($this->controller,'notebooks') === 0)
						{
							session_start();
							$_SESSION['notebook_inserted'] = 'yes';
						}
					}
					
					$this->viewRedirect($this->m['HardwareModel']->lastId);
				}
			}
			
			$data['notice'] = $this->m['HardwareModel']->notice;
			
			$data['submitName'] = "insertAction";
			$data['hiddenInput'] = null;
			
			$data['values'] = $this->m['HardwareModel']->getFormValues('insert','sanitizeHtml');
			$this->append($data);
			
			$this->load('top_left');
			$this->load('license_notice');
			$this->load('form');
			$this->load('bottom_left');
			$this->right();
		}
		else
		{
			$this->redirect('users/login/'.$this->lang.'/'.$this->controller.'/catalogue',0);
		}
	}
	
	public function del($lang = 'en', $token = '')
	{
		header('Content-type: text/html; charset=UTF-8');
		
		$this->shift(2);
		
		$this->clean();
		
		$clean['token'] = sanitizeAlphanum($token);
		
		if ($this->s['registered']->status['status'] === 'logged')
		{
			if (!$this->s['registered']->checkCsrf($clean['token'])) die("wrong token");
			
			if ($this->m['UsersModel']->isBlocked($this->s['registered']->status['id_user'])) die("your account has been blocked");
			
			$clean['id_user'] = (int)$this->s['registered']->status['id_user'];
			$clean['id_hard'] = $this->request->post('id_hard',0,'forceInt');
			
			$this->model("DeletionModel");
			
			$numb = $this->m['DeletionModel']->where(array("id_hard"=>$clean['id_hard'],"created_by"=>$clean['id_user']))->rowNumber();
			if ($numb === 0)
			{
				$id_dup = $this->request->post('id_duplicate',0,'forceInt');
				$object = $this->request->post('object','','sanitizeAll');
				
				if ($id_dup === 0 and strcmp($object,'duplication') === 0)
				{
					echo "you have no specified the device duplicated by this model";
				}
				else
				{
					$this->m['DeletionModel']->setFields('id_hard:forceInt,object,message,id_duplicate:forceInt','sanitizeAll');
					$this->m['DeletionModel']->values['created_by'] = $clean['id_user'];
					
					$this->m['DeletionModel']->updateTable('insert');
					if ($this->m['DeletionModel']->queryResult)
					{
						$hard = new HardwareModel();
						$c = $hard->where(array('id_hard'=>$clean['id_hard'],'ask_for_del'=>'yes'))->rowNumber();
						if ($c < 1)
						{
							$hard->db->update('hardware','ask_for_del',array('yes'),'id_hard='.$clean['id_hard']);
						}
						echo "operation executed";
					}
					else
					{
						echo "one error occurred, please try later";
					}
				}
			}
			else
			{
				echo "you have already asked for the deletion of this device";
			}
		}
	}
	
	protected function update($lang = 'en', $token = '')
	{
		$this->shift(2);
		
		$clean['token'] = sanitizeAlphanum($token);
		
		$data['notice'] = null;
		$this->s['registered']->checkStatus();
		
		if (isset($_POST['id_hard']))
		{
			//get the id
			$clean['id_hard'] = isset($_POST['id_hard']) ? (int)$_POST['id_hard'] : 0;
				
			if ($this->s['registered']->status['status'] === 'logged')
			{			
				if (!$this->s['registered']->checkCsrf($clean['token'])) $this->redirect($this->controller.'/catalogue/'.$this->lang,2,'wrong token..');
				
				if ($this->m['UsersModel']->isBlocked($this->s['registered']->status['id_user'])) $this->redirect('my/home/'.$this->lang,2,'your account has been blocked..');
				
				$deleted = $this->m['HardwareModel']->select("hardware.deleted")->where(array("id_hard"=>$clean['id_hard']))->limit(1)->toList('deleted')->send();
				
				if (strcmp($deleted[0],'no') === 0)
				{
					$ne_name = $this->m['HardwareModel']->getTheModelName($clean['id_hard']);
					$name = encodeUrl($ne_name);
					$data['name'] = $name;
					$data['ne_name'] = $ne_name;
					$data['tree'] = $this->getSpecHardLink() . " »  " . $this->getViewLink($clean['id_hard'],$name) . " » edit";
					if (isset($_POST['updateAction']))
					{
						if ($this->checkDist())
						{
							$pci_id = $this->request->post('pci_id','','sanitizeAll');
							if (strcmp($pci_id,'') !== 0)
							{
								$this->m['HardwareModel']->databaseConditions['update']['+checkUniqueCompl'] = 'pci_id|VendorID:ProductID is already present in the database. This means that the device you are trying to insert is already in the database';
							}
							
							//carry out the update database action
							$this->m['HardwareModel']->updateTable('update');
							
							$this->viewRedirect($this->m['HardwareModel']->lastId);
						}
					}
					
					$data['notice'] = $this->m['HardwareModel']->notice;
					
					$data['id_hard'] = $clean['id_hard'];
					$data['submitName'] = "updateAction";
		// 			echo $this->m['HardwareModel']->fields;
					$data['values'] = $this->m['HardwareModel']->getFormValues('update','sanitizeHtml');
					$data['hiddenInput'] = "\n";
					
					$this->append($data);
					
					$this->load('top_left');
					$this->load('license_notice');
					$this->load('form');
					$this->load('bottom_left');
					$this->right();
				}
				else
				{
					$this->redirect($this->controller.'/catalogue/'.$this->lang,2,'deleted..');
				}
			}
			else
			{
				$this->redirect('users/login/'.$this->lang.'/'.$this->controller.'/view/'.$clean['id_hard'],0);
			}
		}
		else
		{
			$this->redirect($this->controller.'/catalogue/'.$this->lang);
		}
	}
	
	protected function checkDist()
	{
		if (array_key_exists('distribution',$_POST))
		{
			if (strcmp($_POST['distribution'],"") !== 0)
			{
				if (Distributions::check($_POST['distribution']))
				{
					return true;
				}
				else
				{
					$this->m['HardwareModel']->result = false;
					$this->m['HardwareModel']->notice = "
Distribution not allowed..
\n";
					return false;
				}
			}
			else
			{
				$this->m['HardwareModel']->result = false;
				$this->m['HardwareModel']->notice = "Distribution not defined..
\n";
				return false;
			}
		}
		$this->m['HardwareModel']->result = false;
		return false;
	}
	
	protected function viewRedirect($id)
	{
		$clean['id'] = (int)$id;
		
		if ($this->m['HardwareModel']->queryResult)
		{
			$name = encodeUrl($this->m['HardwareModel']->getTheModelName($clean['id']));
			$this->redirect($this->controller.'/view/'.$this->lang.'/'.$clean['id'].'/'.$name.$this->viewStatus);
		}
	}
	
	//load the view files
	protected function loadViewAll($viewName = null)
	{
		$this->load('top_left');
		$viewArray = explode(',',$viewName);
		foreach ($viewArray as $viewFile)
		{
			$this->load($viewFile);
		}
		$this->load('bottom_left');
		$this->right();
	}
	protected function catalogue($lang = 'en')
	{
		$data['title'] = $this->controller.' - '.Website::$generalName;
		
		Params::$nullQueryValue = 'undef';
		
		$data['tree'] = $this->controller;
		
		$this->mod->aWhere(array("deleted"=>"no"));
		
		$this->mod->popupBuild();
		$popup = $this->mod->popupArray;
		$popup['sort-by'] = $this->orderPopup;
		
		$this->helper('Popup',$this->controller.'/catalogue/'.$this->lang,$popup,'inclusive','page');
		//create the HTML of the popup
		$data['popup'] = $this->h['Popup']->render();
		
		$this->mod->orderBy = getOrderByClause($this->viewArgs['sort-by']);
		$recordNumber = $this->mod->rowNumber();
		$data['recordNumber'] = $recordNumber;
		
		//load the Pages helper
		$this->helper('Pages',$this->controller.'/catalogue/'.$this->lang,'page');
		$page = $this->viewArgs['page'];
		//set the limit clause
		$this->mod->limit = $this->h['Pages']->getLimit($page,$recordNumber,10);
		
		$data['table'] = $this->mod->getAll();
// 		echo $this->mod->getQuery();
		
		$data['pageList'] = $this->h['Pages']->render($page-3,7);
		
		$this->append($data);
		
		$this->loadViewAll('catalogue');
	}
	protected function view($lang = 'en', $id_hard = 0, $name = null)
	{
		$this->shift(3);
		
		//set the history_page to 1 in the viewStatus
		$this->viewArgs['history_page'] = 1;
		$this->buildStatus();
		
		$clean['id_hard'] = (int)$id_hard;
		$data['id_hard'] = $clean['id_hard'];
		$data['ne_name'] = null;
		$data['name'] = null;
		$data['tree'] = null;
		$data['isDeleted'] = 'no';
		if ($this->mod->checkType($clean['id_hard']))
		{
			$this->mod->setWhereQueryClause(array("id_hard" => $clean['id_hard']));
			$data['table'] = $this->mod->getAll();
			
			if (count($data['table']) > 0)
			{
				
				$data['talk_number'] = $this->m['TalkModel']->select('count(*) as numb,id_hard')->where(array('id_hard'=>$clean['id_hard'],'deleted'=>'no'))->rowNumber();
				
				$data['ne_name'] = $data['table'][0]['hardware']['model'];
				$data['name'] =  encodeUrl($data['ne_name']);
				$data['title'] = $data['ne_name'].' - '.Website::$generalName;
				$data['tree'] = $this->getSpecHardLink() . " » ".$data['ne_name']."";
				$data['isDeleted'] = $data['table'][0]['hardware']['deleted'];
				
				if (strcmp($data['isDeleted'],'yes') === 0)
				{
					$deletion = new DeletionModel();
					$data['deletion'] = $deletion->select()->where(array('id_hard'=>$clean['id_hard']))->send();
					$data['deletionUsers'] = $deletion->getList($data['deletion'],'created_by');
				}
			}
			
			$this->append($data);
			
			session_start();
			if ( isset($_SESSION['notebook_inserted']) and strcmp($this->controller,'notebooks') === 0 )
			{
				$viewFilesList = 'suggest_dialog,dialog,page,if_page_deleted';
				unset($_SESSION['notebook_inserted']);
			}
			else
			{
				$viewFilesList = 'dialog,page,if_page_deleted';
			}
			
			$this->loadViewAll($viewFilesList);
		}
		else
		{
// 			$this->redirect($this->_controller.'/'.);
		}
	}
	protected function history($lang = 'en', $id = 0)
	{
		$this->shift(2);
		$clean['id'] = (int)$id;
		$data['id'] = $clean['id'];
		$data['ne_name'] = $this->m['HardwareModel']->getTheModelName($clean['id']);
		$data['name'] = encodeUrl($data['ne_name']);
		$data['tree'] = $this->getSpecHardLink() . " »  " . $this->getViewLink($clean['id'],$data['name'])." » history";
		
		$data['title'] = 'history - '.Website::$generalName;
		
		//get the first revision
		$res = $this->m['RevisionsModel']->db->select('revisions','id_rev','id_hard='.$clean['id'],null,'id_rev',1);
		if (count($res) > 0)
		{
			$data['firstRev'] = $res[0]['revisions']['id_rev'];
		}
		
		$res1 = $this->m['HardwareModel']->db->select('hardware','update_date,updated_by','id_hard='.$clean['id']);
		
		$this->m['RevisionsModel']->setWhereQueryClause(array('id_hard' => $clean['id']));
		
		//load the Pages helper
		$this->helper('Pages',$this->controller.'/history/'.$this->lang.'/'.$clean['id'],'history_page');
		//get the number of records
		$recordNumber = $this->m['RevisionsModel']->rowNumber();
		$page = $this->viewArgs['history_page'];
		//set the limit clause
		$this->m['RevisionsModel']->limit = $this->h['Pages']->getLimit($page,$recordNumber,20);
		$res2 = $this->m['RevisionsModel']->getFields('update_date,updated_by,id_rev');
		
		$data['pageList'] = $this->h['Pages']->render($page-3,7);
		
		
		$data['rev1'] = $res1;
		$data['rev2'] = $res2;
		$this->append($data);
		$this->loadViewAll('history');
	}
	
	protected function revision($lang = 'en', $id_rev = 0)
	{
		$this->shift(2);
		$clean['id_rev'] = (int)$id_rev;
		
		$this->m['RevisionsModel']->setWhereQueryClause(array("id_rev" => $clean['id_rev']));
		$data['table'] = $this->m['RevisionsModel']->getAll();
		
		$data['id_hard'] = 0;
		$data['updated_by'] = null;
		$data['update_date'] = null;
		$data['name'] = null;
		$data['ne_name'] = null;
		$data['tree'] = null;
		$data['isDeleted'] = 'no';
		
		if (count($data['table']) > 0)
		{
			$data['id_hard'] = (int)$data['table'][0]['revisions']['id_hard'];
			$data['ne_name'] = $this->m['HardwareModel']->getTheModelName($data['id_hard']);
			$data['name'] = encodeUrl($data['ne_name']);
			$data['tree'] = $this->getSpecHardLink() . " »  " . $this->getViewLink($data['id_hard'],$data['name'])." » " . $this->getHistoryLink($data['id_hard']) . " » revision";
			
			$data['title'] = 'revision - '.Website::$generalName;
			
			$data['updated_by'] = $data['table'][0]['revisions']['updated_by'];
			$data['update_date'] = $data['table'][0]['revisions']['update_date'];
		}
		
		$this->append($data);
		$this->loadViewAll('page');
	}
	protected function differences($lang = 'en', $id_hard = 0, $id_rev = 0)
	{
		$this->shift(3);
		
		$data['title'] = 'differences - '.Website::$generalName;
		
		$clean['id_hard'] = (int)$id_hard;
		$clean['id_rev'] = (int)$id_rev;
		
		$data['id_hard'] = $clean['id_hard'];
		$data['name'] = encodeUrl($this->m['HardwareModel']->getTheModelName((int)$data['id_hard']));
		$data['tree'] = $this->getSpecHardLink() . " »  " . $this->getViewLink($data['id_hard'],$data['name'])." » " . $this->getHistoryLink($clean['id_hard']) . " » differences";
		
		$data['showDiff'] = false;
		
		$diffArray = array();
		
		if (strcmp($clean['id_hard'],0) !== 0 and strcmp($clean['id_rev'],0) !== 0)
		{
			$this->m['RevisionsModel']->setWhereQueryClause(array('id_hard' => $clean['id_hard'],'id_rev' => '<='.$clean['id_rev']));
			$this->m['RevisionsModel']->limit = 2;
			$res = $this->m['RevisionsModel']->getAll();
			if (count($res) > 1)
			{
				$newArray = $res[0]['revisions'];
				$oldArray = $res[1]['revisions'];
				
				$data['update_new'] = $newArray['update_date'];
				$data['update_old'] = $oldArray['update_date'];
				$data['updated_by'] = $newArray['updated_by'];
				
				$diffArray = $this->mod->getDiffArray($oldArray, $newArray);
				
				$data['showDiff'] = true;
			}
		}
		else if (strcmp($clean['id_hard'],0) !== 0 and strcmp($clean['id_rev'],0) === 0)
		{
			$this->mod->setWhereQueryClause(array('id_hard' => $clean['id_hard']));
			$lastRes = $this->mod->getAll();
			
			if (count($lastRes) > 0)
			{
				$this->m['RevisionsModel']->setWhereQueryClause(array('id_hard' => $clean['id_hard']));
				$this->m['RevisionsModel']->limit = 1;
				$revRes = $this->m['RevisionsModel']->getAll();
				
				if (count($revRes) > 0)
				{
					$newArray = $lastRes[0]['hardware'];
					$oldArray = $revRes[0]['revisions'];
					
					$data['update_new'] = $newArray['update_date'];
					$data['update_old'] = $oldArray['update_date'];
					$data['updated_by'] = $newArray['updated_by'];
				
					$diffArray = $this->mod->getDiffArray($oldArray, $newArray);
					
					$data['showDiff'] = true;
				}
			}
			
		}
		
		$data['fieldsWithBreaks'] = $this->mod->fieldsWithBreaks;
		$data['diffArray'] = $diffArray;
		
		$this->append($data);		
		$this->loadViewAll('differences');
	}
	protected function climb($lang = 'en', $id_rev = 0, $token = '')
	{
		$this->shift(3);
		
		$data['title'] = 'make current - '.Website::$generalName;
		
		$clean['token'] = sanitizeAlphanum($token);
		
		$clean['id_rev'] = (int)$id_rev;
		$clean['id_hard'] = (int)$this->m['RevisionsModel']->getIdHard($clean['id_rev']);
		
		if ($clean['id_hard'] !== 0)
		{
			$deleted = $this->m['HardwareModel']->select("hardware.deleted")->where(array("id_hard"=>$clean['id_hard']))->limit(1)->toList('deleted')->send();
			
			$data['isDeleted'] = $deleted[0];
			
			$data['id_rev'] = $clean['id_rev'];
			$data['id_hard'] = $clean['id_hard'];
			$data['ne_name'] = $this->m['HardwareModel']->getTheModelName($clean['id_hard']);
			$data['name'] = encodeUrl($data['ne_name']);
			$data['tree'] = $this->getSpecHardLink() . " »  " . $this->getViewLink($data['id_hard'],$data['name'])." » " . $this->getHistoryLink($clean['id_hard']) . " » make current";
			
			$data['notice'] = null;
			$this->s['registered']->checkStatus();
			
			if ($this->s['registered']->status['status'] === 'logged')
			{	
				if (!$this->s['registered']->checkCsrf($clean['token'])) $this->redirect($this->controller.'/catalogue/'.$this->lang,2,'wrong token..');
				if ($this->m['UsersModel']->isBlocked($this->s['registered']->status['id_user'])) $this->redirect('my/home/'.$this->lang,2,'your account has been blocked..');
				
				if (isset($_POST['confirmAction']))
				{				
					if (strcmp($deleted[0],'no') === 0)
					{
						$this->m['HardwareModel']->makeCurrent($clean['id_rev']);
						
						$this->viewRedirect($this->m['HardwareModel']->lastId);
					
						$data['notice'] = $this->m['HardwareModel']->notice;
					}
					else
					{
						$this->redirect($this->controller.'/catalogue/'.$this->lang,2,'deleted..');
					}
				}
				
				$this->append($data);
				$this->loadViewAll('climb');
			}
			else
			{
				$this->redirect('users/login/'.$this->lang.'/'.$this->controller.'/view/'.$clean['id_hard'],0);
			}
		}
	}
	protected function talk($lang = 'en', $id_hard = 0, $token = 'token')
	{		
		$this->shift(3);
		
		$this->m['TalkModel']->setFields('title,message','sanitizeAll');
		
		$data['title'] = 'talk - '.Website::$generalName;
		
		$clean['token'] = sanitizeAlphanum($token);
		$clean['id_hard'] = (int)$id_hard;
		$data['id_hard'] = $clean['id_hard'];
		$data['ne_name'] = $this->m['HardwareModel']->getTheModelName($clean['id_hard']);
		$data['name'] = encodeUrl($data['ne_name']);
		$data['tree'] = $this->getSpecHardLink() . " »  " . $this->getViewLink($clean['id_hard'],$data['name'])." » talk";
		
		if (isset($_POST['insertAction']))
		{
			if ($this->s['registered']->status['status'] === 'logged')
			{
				if (!$this->s['registered']->checkCsrf($clean['token'])) $this->redirect($this->controller.'/catalogue/'.$this->lang,2,'wrong token..');
				
				if ($this->m['UsersModel']->isBlocked($this->s['registered']->status['id_user'])) $this->redirect('my/home/'.$this->lang,2,'your account has been blocked..');
				
				$this->m['TalkModel']->values['created_by'] = $this->s['registered']->status['id_user'];
				$this->m['TalkModel']->values['id_hard'] = $clean['id_hard'];
				
				$this->m['TalkModel']->updateTable('insert');
			}
		}
		
		$data['table'] = $this->m['TalkModel']->select()->where(array('id_hard'=>$clean['id_hard']))->orderBy('id_talk')->send();
		
		$data['values'] = $this->m['TalkModel']->getFormValues('insert','sanitizeHtml');
		$data['notice'] = $this->m['TalkModel']->notice;
		
// 		javascript for moderator
		$data['md_javascript'] = "moderator_dialog(\"hide\",\"talk\");moderator_dialog(\"show\",\"talk\");";
		$data['go_to'] = $this->currPage."/".$this->lang."/".$clean['id_hard'];
		
		$this->append($data);
		$this->loadViewAll('talk,moderator_dialog');
	}
	
	protected function getViewLink($id,$name)
	{
		return "controller.'/view/'.$this->lang.'/'.$id.'/'.$name.$this->viewStatus."'>".urldecode($name)."";
	}
	protected function getHistoryLink($id)
	{
		return "controller.'/history/'.$this->lang.'/'.$id.'/'.$this->viewStatus."'>history";
	}
	protected function getSpecHardLink()
	{
		return "controller.'/catalogue/'.$this->lang.$this->viewStatus."'>".$this->controller."";
	}
}