<?php
class Tree_model extends Model {

    var $title   = '';
    var $content = '';
    var $date    = '';
	var $encryption_key = "i:Dvv%^uJKK9)_K<";
	var $CI;
	var $lang_nr;

    function Tree_model()
    {
        // Call the Model constructor
        parent::Model();
        
        $CI = &get_instance();
        
        $this->lang_nr = $CI->lang_nr;
        
        $this->load->helper("log");
    }

	function checkId($id) {
		$query = $this->db->get_where('tree', array('ID_tree' => $id));
		if($query && $query->num_rows()>0){
			return TRUE;
		} else return FALSE;
	}
	
	function getRootId($userId){
		$query = $this->db->get_where('tree', array('tree_user_id' => $userId, 'tree_path' => 'root', 'tree_deleted' => 0, 'tree_lang' => $this->lang_nr));
		if($query->num_rows()>0){
			$row = $query->row();
			return $row->ID_tree;
		} else return NULL;
	}
    
	function getNode($nodeId){
		$sql="SELECT * FROM tree WHERE ID_tree=".$nodeId." and tree_deleted=0 and tree_lang='".$this->lang_nr."'";
		$query = $this->db->query($sql);
		if ($query->num_rows() > 0){
			$row = $query->row();
			return $row;
		} else return NULL;
	}
	
	function getNodeData($nodeDataId){
		$sql = "SELECT * FROM nodes WHERE ID_nodes=".$nodeDataId." ";// and nodes_lang='".$this->lang_nr."'";
		$query = $this->db->query($sql);
		if ($query->num_rows() > 0){
			$row = $query->row();
			return $row;
		} else return NULL;
	}
	
	function getNodeChildsCount($path, $userId){
		//$sql="SELECT * FROM tree WHERE tree_path REGEXP '^".$path.".((\.)([0-9]+))?$' and tree_user_id=".$userId." and tree_deleted=0 and tree_lang='".$this->lang_nr."'";
		$sql="SELECT * FROM tree WHERE tree_path REGEXP '^".$path.".(([0-9]+))?$' and tree_user_id=".$userId." and tree_deleted=0 and tree_lang='".$this->lang_nr."'";
		$result = $this->db->query($sql);
		if($result->num_rows()>0)
		{
			return $result->num_rows();
		}
		else return 0;
	}
	
	function getNodeFirtLevelChilds($path, $userId) {
		//$sql="SELECT * FROM tree WHERE tree_path REGEXP '^".$path.".((\.)([0-9]+))?$' and tree_user_id=".$userId." and tree_deleted=0 and tree_lang='".$this->lang_nr."' order by tree_node_order ";
		$sql="SELECT * FROM tree WHERE tree_path REGEXP '^".$path.".(([0-9]+))?$' and tree_user_id=".$userId." and tree_deleted=0 and tree_lang='".$this->lang_nr."' order by tree_node_order ";
		$result= $this->db->query($sql);
		return $result;
	}
	
	function addChild($data, $order, $path, $userId, $photo, $x, $y){
		
		$filename = '';
		if(in_array($photo['type'], array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'))){
			$n=$photo['name'];
			$r=explode(".",$n);
			$nazwa_pliku=time().'.'.$r[count($r)-1];
			$folder = $this->db->get_where('users', array('ID_users' => $this->session->userdata('uzytkownik_id')))->row()->user_folder;
			if(@move_uploaded_file($photo['tmp_name'], 'pages/'.$folder.'/foto/nodes/'.$nazwa_pliku)){
				
				$config['maintain_ratio'] = TRUE;
				$config['create_thumb'] = TRUE;
				$config['thumb_marker'] = FALSE;
				$config['source_image'] = 'pages/'.$folder.'/foto/nodes/'.$nazwa_pliku;
				$config['new_image'] = 'pages/'.$folder.'/foto/nodes/thumb_'.$nazwa_pliku;//'/path/to/new_image.jpg';
				$config['image_library'] = 'gd2';
				$config['width'] = $x;
				$config['height'] = $y;
				$this->load->library('image_lib', $config); 
				$this->image_lib->resize();
				
				$filename = $nazwa_pliku;
	
			} 
		}
		
		$this->db->query('LOCK TABLES nodes WRITE');
		
		$this->db->set('nodes_photo', $filename);
		$this->db->set('nodes_added', 'sysdate()', FALSE);
		$this->db->insert('nodes', $data);
		$insertNodeId= $this->db->insert_id();
		
		
		
		$this->db->query('UNLOCK TABLES');
		
		action_log('Dodawanie elementu do drzewa', 'nodes', 'insert', $insertNodeId, $data['nodes_name']);
		
		$this->db->query('LOCK TABLES tree WRITE');
		//echo 'aaa'.$this->lang_nr.'bbb';
		$this->db->insert('tree',array(
			'tree_user_id' => $userId,
			'tree_node_order' => $order,
			'tree_node_id' => $insertNodeId,
			'tree_lang' => ''.$this->lang_nr
			));
		
		$insertTreeId= $this->db->insert_id();
		
		$this->db->query('UNLOCK TABLES');

		action_log('Dodawanie elementu do drzewa', 'tree', 'insert', $insertTreeId);
		
		$this->db->query('LOCK TABLES tree WRITE');
		
		$this->db->where('ID_tree', $insertTreeId);
		$this->db->update('tree', array('tree_path' => $path.'.'.$insertTreeId));
		
					
		$this->db->query('UNLOCK TABLES');
		
		action_log('Dodawanie elementu do drzewa', 'tree', 'update', $insertTreeId, $path.'.'.$insertTreeId);
		return $insertTreeId;
		
	}
	
	function getMaxOrder($path, $userId) {
		//$sql="SELECT MAX(tree_node_order) FROM tree WHERE tree_path REGEXP '^".$path.".(\.(.+))?$' and tree_user_id=".$userId." and tree_deleted=0 and tree_lang='".$this->lang_nr."'";
		$sql="SELECT MAX(tree_node_order) FROM tree WHERE tree_path REGEXP '^".$path.".((.+))?$' and tree_user_id=".$userId." and tree_deleted=0 and tree_lang='".$this->lang_nr."'";
		$result= $this->db->query($sql);
		if($result->num_rows()>0){
			$row = $result->row_array();
			return $row['MAX(tree_node_order)'];
		} else return 1;
	}
	
	function updateNodeText($data, $id){
		$node = $this->getNode($id);
		if($node){
			$this->db->where('ID_nodes', $node->tree_node_id);
			$this->db->update('nodes', $data);
			action_log('Edycja elementu drzewa - edycja tekstu', 'nodes', 'update', $node->tree_node_id, ''/*$node->nodeData['name']*/);
		}
	}
	
	function updateNode($data, $id, $photo, $x, $y, $delphoto){
		$node = $this->getNode($id);
		if($node){
			
			if($delphoto == 1){
				$query = $this->db->get_where('nodes', array('ID_nodes' => $node->tree_node_id));
				if($query->num_rows > 0){
					$row = $query->row();
					if($row->nodes_photo != ''){
						$folder = $this->db->get_where('users', array('ID_users' => $this->session->userdata('uzytkownik_id')))->row()->user_folder;
						unlink('pages/'.$folder.'/foto/nodes/'.$row->nodes_photo);
						unlink('pages/'.$folder.'/foto/nodes/thumb_'.$row->nodes_photo);
						$this->db->where('ID_nodes', $node->tree_node_id);
						$this->db->update('nodes', array('nodes_photo' => ''));
					}
				}
			}
			
			$filename = '';
			$q = $this->db->get_where('nodes', array('ID_nodes' => $node->tree_node_id));
			if($q->num_rows > 0){
				$r = $q->row();
				$filename = $r->nodes_photo;
			}
			if(in_array($photo['type'], array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'))){
				$n=$photo['name'];
				$r=explode(".",$n);
				$nazwa_pliku=time().'.'.$r[count($r)-1];
				$folder = $this->db->get_where('users', array('ID_users' => $this->session->userdata('uzytkownik_id')))->row()->user_folder;
				if(@move_uploaded_file($photo['tmp_name'], 'pages/'.$folder.'/foto/nodes/'.$nazwa_pliku)){
					
					$config['maintain_ratio'] = TRUE;
					$config['create_thumb'] = TRUE;
					$config['thumb_marker'] = FALSE;
					$config['source_image'] = 'pages/'.$folder.'/foto/nodes/'.$nazwa_pliku;
					$config['new_image'] = 'pages/'.$folder.'/foto/nodes/thumb_'.$nazwa_pliku;//'/path/to/new_image.jpg';
					$config['image_library'] = 'gd2';
					$config['width'] = $x;
					$config['height'] = $y;
					$this->load->library('image_lib', $config); 
					$this->image_lib->resize();
					
					if($filename != ''){
						unlink('pages/'.$folder.'/foto/nodes/'.$filename);
						unlink('pages/'.$folder.'/foto/nodes/thumb_'.$filename);
					}
					
					$filename = $nazwa_pliku;
		
				}
			}
			
			
			$this->db->where('ID_nodes', $node->tree_node_id);
			$this->db->set('nodes_photo', $filename);
			$this->db->set('nodes_updated', 'sysdate()', FALSE);
			$this->db->update('nodes', $data);
			action_log('Edycja elementu drzewa', 'nodes', 'update', $node->tree_node_id, $data['nodes_name']);
		}	
	}
	
	function deleteNode($path, $userId) {
		
		$this->load->model('Modul_model');
		$Modul_model = new Modul_model();
		//$sql="SELECT * FROM tree WHERE tree_path REGEXP '^".$path.".((\.)([0-9]+))?$' and tree_user_id=".$userId." and tree_lang='".$this->lang_nr."' ";
		$sql="SELECT * FROM tree WHERE tree_path REGEXP '^".$path.".(([0-9]+))?$' and tree_user_id=".$userId." and tree_lang='".$this->lang_nr."' ";
		$result = $this->db->query($sql);
		if($result && $result->num_rows()>0){
			foreach($result->result() as $row){
				$query = $this->db->get_where('modules', array('modules_tree_id' => $row->ID_tree));
				if($query && $query->num_rows()>0){
					foreach($query->result() as $q){
						$Modul_model->removemodule($q->ID_modules, $q->modules_type);
						action_log('Usuwanie elementu drzewa', 'modules', 'delete', $q->ID_modules, $q->modules_name);
					}
				}
								
				$this->deleteNode($row->tree_path, $userId);
				
				//$this->db->where('ID_nodes', $row->tree_node_id);
				//$this->db->delete('nodes');
				//action_log('Usuwanie elementu drzewa', 'nodes', 'delete', $row->tree_node_id);
				
				$this->db->where('ID_tree', $row->ID_tree);
				//$this->db->delete('tree');
				$this->db->update('tree', array('tree_deleted' => 1));
				action_log('Usuwanie elementu drzewa', 'tree', 'delete', $row->ID_tree, $row->tree_path);
			}
		}
		$sql="SELECT * FROM tree WHERE tree_path='".$path."' and tree_user_id=".$userId." and tree_lang='".$this->lang_nr."' ";
		$result = $this->db->query($sql);
		if($result && $result->num_rows()>0){
			foreach($result->result() as $row){
				$query = $this->db->get_where('modules', array('modules_tree_id' => $row->ID_tree));
				if($query && $query->num_rows()>0){
					foreach($query->result() as $q){
						$Modul_model->removemodule($q->ID_modules, $q->modules_type);
						action_log('Usuwanie elementu drzewa', 'modules', 'delete', $q->ID_modules, $q->modules_name);
					}
				}
				//$this->db->where('ID_nodes', $row->tree_node_id);
				//$this->db->delete('nodes');
				//action_log('Usuwanie elementu drzewa', 'nodes', 'delete', $row->tree_node_id);
				
				$this->db->where('ID_tree', $row->ID_tree);
				//$this->db->delete('tree');
				$this->db->update('tree', array('tree_deleted' => 1));
				action_log('Usuwanie elementu drzewa', 'tree', 'delete', $row->ID_tree, $row->tree_path);
			}
		}
	}
	
	function moveup($id, $path, $order, $userId){
		$order_1 = $order - 1;
		
		//$sql="SELECT * FROM tree WHERE tree_path REGEXP '^".$path.".((\.)([0-9]+))?$' and tree_user_id=".$userId." and tree_node_order=".$order_1." and tree_lang='".$this->lang_nr."' ";
		$sql="SELECT * FROM tree WHERE tree_path REGEXP '^".$path.".(([0-9]+))?$' and tree_user_id=".$userId." and tree_node_order=".$order_1." and tree_lang='".$this->lang_nr."' ";
		$result = $this->db->query($sql);
		if($result && $result->num_rows()>0){
		
			$row = $result->row();
			$this->db->where('ID_tree', $id);			
			$this->db->update('tree', array('tree_node_order'=>$order_1));
			action_log('Zmiana kolejności elementów drzewa', 'tree', 'update', $id, $row->tree_path);
			
			$this->db->where('ID_tree', $row->ID_tree);			
			$this->db->update('tree', array('tree_node_order'=>$order));
			action_log('Zmiana kolejności elementów drzewa', 'tree', 'update', $row->ID_tree, $row->tree_path);
		}
	}
	
	function movedown($id, $path, $order, $userId){
		$order_1 = $order + 1;
		
		//$sql="SELECT * FROM tree WHERE tree_path REGEXP '^".$path.".((\.)([0-9]+))?$' and tree_user_id=".$userId." and tree_node_order=".$order_1." and tree_lang='".$this->lang_nr."' ";
		$sql="SELECT * FROM tree WHERE tree_path REGEXP '^".$path.".(([0-9]+))?$' and tree_user_id=".$userId." and tree_node_order=".$order_1." and tree_lang='".$this->lang_nr."' ";
		$result = $this->db->query($sql);
		if($result && $result->num_rows()>0){
			$row = $result->row();
			$this->db->where('ID_tree', $id);			
			$this->db->update('tree', array('tree_node_order'=>$order_1));
			action_log('Zmiana kolejności elementów drzewa', 'tree', 'update', $id, $row->tree_path);
			
			$this->db->where('ID_tree', $row->ID_tree);			
			$this->db->update('tree', array('tree_node_order'=>$order));
			action_log('Zmiana kolejności elementów drzewa', 'tree', 'update', $row->ID_tree, $row->tree_path);
		}
	}
	
	function getMenu2Id($userId){
		//$sql = 'select * from tree, nodes where tree_user_id='.$userId.' and ID_nodes=tree_node_id and nodes_menu2=1 and tree_path REGEXP "^root.((\.)([0-9]+))?$" and tree_deleted=0 and tree_lang="'.$this->lang_nr.'"';
		$sql = 'select * from tree, nodes where tree_user_id='.$userId.' and ID_nodes=tree_node_id and nodes_menu2=1 and tree_path REGEXP "^root.(([0-9]+))?$" and tree_deleted=0 and tree_lang="'.$this->lang_nr.'"';
		$query = $this->db->query($sql);
		if($query->num_rows()>0){
			$row = $query->row();
			return $row->ID_tree;
		} else return NULL;
	}
	
	function refreshTreeOrder($path, $userId){
		
		//$sql="update tree  set tree_node_order=0 WHERE tree_path REGEXP '^".$path.".((\.)([0-9]+))?$' and tree_user_id=".$userId." and tree_deleted=1 and tree_lang='".$this->lang_nr."'";
		$sql="update tree  set tree_node_order=0 WHERE tree_path REGEXP '^".$path.".(([0-9]+))?$' and tree_user_id=".$userId." and tree_deleted=1 and tree_lang='".$this->lang_nr."'";
		$this->db->query($sql);
		
		
		//$sql = "select * from tree where tree_path REGEXP '^".$path.".((\.)([0-9]+))?$' and tree_user_id='".$userId."' and tree_deleted=0 and tree_lang='".$this->lang_nr."' order by tree_node_order asc ";
		$sql = "select * from tree where tree_path REGEXP '^".$path.".(([0-9]+))?$' and tree_user_id='".$userId."' and tree_deleted=0 and tree_lang='".$this->lang_nr."' order by tree_node_order asc ";
		$result = $this->db->query($sql);
		if($result->num_rows() > 0){
			$order = 1;
			foreach($result->result() as $row){
				$this->db->where('ID_tree', $row->ID_tree);
				$this->db->update('tree', array('tree_node_order' => $order++));
			}
		}
	}
	
	function getNodeOrderForId($id){
		return $this->db->get_where('tree', array('ID_tree' => $id))->row()->tree_node_order;
	}

}
?>