<?php
include_once ("_dirinfo.php");

include_once (PATH_TO_ROOT."init.php");
include_once (PATH_TO_ROOT."_ajaxManipulators/_class/class.treeData.php");


$db->ChangeDatabase($_POST['database']);
$tableName = $_POST['RMtable'];

class permissionTreeManipulator extends TreeDataManipulator {
	function selectAction()
	{
		
		$parent = $_POST['node'];
		$sql = 'SELECT * FROM '.$this->table.' WHERE id_sup = '.$parent.' ';

		if (!$res = $this->db->SQLexecute($sql)){return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';}
		
		// display each child
		while ($row = $this->db->fetchAssoc($res)) {
			// Response parameters.
			$path = array();
			
			
			if($_REQUEST['boldRoots'] && $parent == 0)
			{
				$path['cls']		= 'treeFontBold';
				//$path['children'][] = array(text=>'1');
				//$path['children'][] = array(text=>'2');
			}
			
			$path['text']		= html_entity_decode($row['idLab']);
			
			$path['id']			= $row['id'];
			$path['origId']		= $row['id'];
			$path['position']	= $row['orderBy'];
			$path['leaf']		= false;
			$path['iconCls']	= 'folder';						
			$path['isUser']  	= false;
			$nodes[] = $path;
		}
		
		$sql = "SELECT * FROM ".DB_WARPIT_MAIN."._user WHERE permissionGroup = ".$parent;
		
		if (!$userRes = $this->db->SQLexecute($sql)) 
		{
			return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sql.'"}';
			exit;
		}
		
		while ($userRow = $this->db->fetchAssoc($userRes))  {
			
			$path['text']		= $userRow['Firstname']." ".$userRow['Surname'];				
			$path['id']			= $userRow['id'].'_user';
			$path['origId']		= $userRow['id'];
			$path['leaf']		= true;
			//$path['checked']	= false;
			$path['iconCls']	= 'file';
			$path['isUser']   	= true;						
			$nodes[] = $path;
		}
		
		//return $nodes;
		
		return json_encode($nodes);
	}

	function insertItemAction()
		{
			
		$parent = $_POST['parId'];
		$newId = $_POST['nodeId'];
		$text = $_POST['nodeText'];
		$closed = $_POST['closed'];
		$addLeaf = $_POST['addLeaf'];
		//$orderTree = $_POST['tPos'];
		//$orderGrid = $_POST['qPos'];
		

		$sql[] = "INSERT INTO $this->table(id_sup,$this->lab) VALUES( $parent ,'$text' ) ";

		if (!$this->db->SQLbegin())
		{
			return '{success:false,error:"Transakcije niso omogocone"}';	
		}
		foreach ($sql as $sqlStatemens) {
			If (!$this->db->SQLexecute($sqlStatemens)) {$this->db->SQLrollback();return '{success:false,error:"'.$this->db->GetError().'", STATEMENT: "'.$sqlStatemens.'"}';}	
		}
		
		$id = $this->db->GetLastInsertId();
		$this->db->SQLcommit();
		return '{success:true,insertId:'.$id .'}';	
	}

	function addUserAction()
	{
		if($_POST['userInfo']['password'])
		{
			$_POST['userInfo']['password'] = md5($_POST['userInfo']['password']);
		}
		else 
		{
			unset($_POST['userInfo']['password']); //we don't want to safe unedited password!
		}
		
		foreach ($_POST['userInfo'] as  $key=>$val) $tmp[] = $key." = '".$val."'";
		if($_POST['par'])
			$tmp[] = 'permissionGroup = '.$_POST['par'];
		
		$c = configLoader::loadConfig('multilanguage');
		$tmp[] = 'lng_admin = ' .$c['id_default_language'];
			
		$sql = "INSERT INTO " .DB_WARPIT_MAIN."._user SET ".implode(",",$tmp);
		if(!$this->db->SQLexecute($sql)) return "{success:false}";
		
		return "{success:true}";
	}
	//updates user with user properties
	function updateUserAction()
	{
		return $this->updateUserFunc(true);
	}
	//updates admin with editUser
	function editUserAction()
	{
			return $this->updateUserFunc(false);
	}
	
	//the same function is used for updating current user trough userproperties...or updating user with admin edit user
	function updateUserFunc($updateSession)
	{
		if($_POST['userInfo']['password'])
		{
			$_POST['userInfo']['password'] = md5($_POST['userInfo']['password']);
		}
		else 
		{
			unset($_POST['userInfo']['password']); //we don't want to safe unedited password!
		}
		
		foreach ($_POST['userInfo'] as  $key=>$val) $tmp[] = $key." = '".addslashes($val)."'";
	
		$sql = " UPDATE ".DB_WARPIT_MAIN."._user SET ".implode(",",$tmp)." WHERE id = ".$_POST['id'];
		//echo $sql;
		if(!$this->db->SQLexecute($sql)) return "{success:false}";
		if($updateSession)	
			foreach ($_POST['userInfo'] as  $key=>$val) $_SESSION['UserInfo'][$key] = $val;
		
		/*
			ImageStatus
			0 - no image
			1 - ok
			9 - wrong image format
		
		*/
		
		$imageStatus = 0;
		// uploading and preparing image
		if ($_FILES['avatarImage']['tmp_name']) {
			// 1. Check for image format (only jpg and png)
				$imageFormatTmp = explode(".",$_FILES['avatarImage']['name']);
				$imageFormat = strtolower($imageFormatTmp[count($imageFormatTmp)-1]);
				
				if ($imageFormat == "jpg" || $imageFormat == "png") {
					
					// loading image 
					if ($imageFormat == "jpg") $image = @imagecreatefromjpeg($_FILES['avatarImage']['tmp_name']); 
						else $image = @imagecreatefrompng($_FILES['avatarImage']['tmp_name']); 
					
					// create empty image 60x60px
					$thumb = @imagecreatetruecolor(60, 60);
					
					if ($image && $thumb) {
						// get information about original siye of image
						list($width, $height) = getimagesize($_FILES['avatarImage']['tmp_name']);
						
						// decide how to crop image
						// portrait
						if ($width < $height) imagecopyresized($thumb, $image, 0, 0, 0, 0, 60, 60, $width, $width);	
							// landscape
							elseif ($width > $height) imagecopyresized($thumb, $image, 0, 0, round(($width-$height)/2), 0, 60, 60, $height, $height);
							// q
							else  imagecopyresized($thumb, $image, 0, 0, 0, 0, 60, 60, $height, $height);
						
						// save image to user directory
						imagejpeg($thumb, WARPIT_ABSOLUTE."_img/users/user_".$_POST['id'].".jpg", 100);     
						
						// destroy images
						imagedestroy($image); 
						imagedestroy($thumb); 
						
						//return OK status
						$imageStatus = 1;
					} 
					// something is wrong with image opening 
					else $imageStatus = 8;
					
				}  else 
					// Returning image status 9 for invalid image format
					$imageStatus = 9;
			
		}
		
		return "{success:true, ImageStatus: '".$imageStatus ."', userLabel: '".addslashes($_POST['userInfo']['Firstname'])." ".addslashes($_POST['userInfo']['Surname'])."'}";
	}
	function removeUserAction()
	{
		$id = $_POST['id'];
		$sql = "DELETE FROM _user WHERE id = $id";
		$this->db->SQLexecute($sql);
		
		return "{success:true}";
	}
}



$manipulator = new permissionTreeManipulator($db,$tableName);
$comm = $_POST['action'].'Action';
if(method_exists($manipulator,$comm))
 	echo $manipulator->$comm();
else 
{
	
	Echo '{success:false,error:"Unknown action!"}';	
	
}
?>