<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Trees extends CI_Controller {
	
	public function browse_locale($table,$text_table,$id_field,$name_field,$join_field,$locale)
	{
		if(!$this->admin_auth->has_access($table,'browse')){
			message_handler(FALSE,'Access Denied','');
		}

		$sql          = ' Where locale = ? ';
		$id           = $this->input->get('node',TRUE);
		$custom_field = $this->input->get('custom_field',TRUE);
		$custom_value = $this->input->get('custom_value',TRUE);
		$sql_values   = array($locale);
		
		if($custom_field)
		{
			$sql          .= ' And '.$custom_field.' = ? ';
			$sql_values[] = $custom_value;
		}
		if(is_numeric($id))
		{
			$sql          .= ' And parent_id = ? ';
			$sql_values[] = $id;
		}
		else
		{
			$sql .= ' And parent_id = 0 ';
		}

		if($table == 'contents')
		{
			$fields = 'Select content_texts.content_id as id, content_texts.content_text_title as text, content_types.icon_class as iconCls, contents.self_children, contents.is_visible ';
			$join   = ' From contents Left Join content_texts On contents.content_id = content_texts.content_id Left Join content_types On contents.content_type_id = content_types.content_type_id ';
		}
		elseif($table == 'menus')
		{
			$fields = 'Select '.$text_table.'.'.$id_field.' as id, '.$text_table.'.'.$name_field.' as text, "link" as iconCls, '.$table.'.self_children, '.$table.'.is_visible ';
			$join   = ' From '.$table.' Left Join '.$text_table.' On '.$table.'.'.$id_field.' = '.$text_table.'.'.$id_field.' ';
		}
		else
		{
			$fields = 'Select '.$text_table.'.'.$id_field.' as id, '.$text_table.'.'.$name_field.' as text, "folder" as iconCls, '.$table.'.self_children, '.$table.'.is_visible ';
			$join   = ' From '.$table.' Left Join '.$text_table.' On '.$table.'.'.$id_field.' = '.$text_table.'.'.$id_field.' ';
		}

		if(is_numeric($id))
		{
			$query = $this->db->query($fields.$join.$sql.' Order by '.$table.'.sequence Asc',$sql_values);
		} 
		else 
		{
			$query = $this->db->query($fields.$join.$sql.' Order by '.$table.'.sequence Asc',$sql_values);
		}

		$result = $query->result_array();
		for($i=0; $i < sizeof($result); $i++)
		{ 
			$result[$i]['text']     = '<span class="visible-'.$result[$i]['is_visible'].'">'.strip_tags($result[$i]['text']).'</span>';
			$result[$i]['iconCls'] .= ' visible-'.$result[$i]['is_visible'];
		}
		echo json_encode($result);
	}

	public function insert_locale($table,$text_table,$id_field,$name_field)
	{
		if(!$this->admin_auth->has_access($table,'insert')){
			message_handler(FALSE,'Access Denied','');
		}

		$custom_field = $this->input->post('custom_field',TRUE);
		$custom_value = $this->input->post('custom_value',TRUE);
		
		if($custom_field && $custom_value)
		{
			$query = $this->db->query('Select Max(sequence) as max_sequence From '.$table.' Where parent_id = 0 And '.$custom_field.' = ? ',array($custom_value));
		}
		else
		{
			$query = $this->db->query('Select Max(sequence) as max_sequence From '.$table.' Where parent_id = 0');
		}
		$row      = $query->row_array();	
		$sequence = $row['max_sequence']+1;

		if($table == 'contents')
		{
			if($custom_field && $custom_value)
			{
				$this->db->query('Insert Into '.$table.' (created_at,parent_id,sequence,'.$custom_field.') Values (NOW(),0,?,?)',array($sequence,$custom_value));
			} 
			else 
			{
				$this->db->query('Insert Into '.$table.' (created_at,parent_id,sequence) Values (NOW(),0,?)',array($sequence));
			}
		}
		else
		{
			if($custom_field && $custom_value)
			{
				$this->db->query('Insert Into '.$table.' (parent_id,sequence,'.$custom_field.') Values (0,?,?)',array($sequence,$custom_value));
			} 
			else 
			{
				$this->db->query('Insert Into '.$table.' (parent_id,sequence) Values (0,?)',array($sequence));
			}
		}
		
		$id = $this->db->insert_id();

		$query = $this->db->query('Select * From locales');
		$locales = $query->result_array();
		foreach($locales as $l)
		{
			 $this->db->query('Insert Into '.$text_table.' (locale,'.$id_field.','.$name_field.') Values (?,?,?)',array($l['locale_code'],$id,'New Record - '.$id));
		}

		$result['success'] = true;
		$result['csrf_token'] = $this->security->get_csrf_hash();
		$result['id']      = $id;
		echo json_encode($result);
	}
	
	public function update_locale($table,$id_field)
	{
		if(!$this->admin_auth->has_access($table,'edit')){
			message_handler(FALSE,'Access Denied','');
		}

		$sql          = '';
		$id           = $this->input->post('id',TRUE);

		$query = $this->db->query('Select * From '.$table.' Where '.$id_field.' = ?',array($id));
		if($query->num_rows()>0)
		{
			$node = $query->row_array();

			$old_parent_id = $this->input->post('old_parent',TRUE);
			$new_parent_id = $this->input->post('new_parent',TRUE);
			$new_index     = $this->input->post('new_index',TRUE);

			$custom_field = $this->input->post('custom_field',TRUE);
			$custom_value = $this->input->post('custom_value',TRUE);
			
			if($custom_field)
			{
				$sql = ' And '.$custom_field.' = ? ';
			}

			// Same parent
			if($old_parent_id == $new_parent_id)
			{
				$new_sequence = $new_index+1;
				if($new_sequence > $node['sequence'])
				{
					$values1      = array($node['parent_id'], $node['sequence'], $new_sequence, $id);
					if($custom_field)
					{
						$values1[] = $custom_value;
					}
					$this->db->query('Update '.$table.' Set sequence = (sequence - 1) Where parent_id = ? And sequence > ? And sequence <= ? And '.$id_field.' <> ? '.$sql,$values1);
				}
				if($new_sequence < $node['sequence'])
				{
					$values2 = array($node['parent_id'], $new_sequence, $node['sequence'], $id);
					if($custom_field)
					{
						$values2[] = $custom_value;
					}
					$this->db->query('Update '.$table.' Set sequence = (sequence + 1) Where parent_id = ? And sequence >= ? And sequence < ? And '.$id_field.' <> ? '.$sql,$values2);
				}
				$this->db->query('Update '.$table.' Set sequence = ? Where '.$id_field.' = ?',array($new_sequence,$id));
			}
			else
			{
				if(!is_numeric($old_parent_id)){
					$old_parent_id = 0;
				}
				if(!is_numeric($new_parent_id)){
					$new_parent_id = 0;
				}
				$query        = $this->db->query('Select level From '.$table.' Where '.$id_field.' = ?',array($new_parent_id));
				$parent       = $query->row_array();
				$level        = $parent['level']+1;
				$new_sequence = $new_index+1;

				$values1 = array($node['parent_id'], $node['sequence']);
				if($custom_field)
				{
					$values1[] = $custom_value;
				}
				$values2 = array($new_parent_id, $new_sequence, $id);
				if($custom_field)
				{
					$values2[] = $custom_value;
				}
				$values3 = array($new_parent_id, $level, $new_sequence, $id);

				$this->db->query('Update '.$table.' Set sequence = (sequence - 1) Where parent_id = ? And sequence > ? '.$sql,$values1);
				$this->db->query('Update '.$table.' Set sequence = (sequence + 1) Where parent_id = ? And sequence >= ? And '.$id_field.' <> ? '.$sql,$values2);
				$this->db->query('Update '.$table.' Set parent_id = ?, level = ?, sequence = ? Where '.$id_field.' = ?',$values3);
				
			}	
		}

		$result['success'] = TRUE;
		$result['csrf_token'] = $this->security->get_csrf_hash();
		echo json_encode($result);
	}
	
	public function delete_locale($table,$text_table,$id_field)
	{
		if(!$this->admin_auth->has_access($table,'delete')){
			message_handler(FALSE,'Access Denied','');
		}

		$id = $this->input->post('id',TRUE);
		if($id)
		{
			$query = $this->db->query('Select * From '.$table.' Where '.$id_field.' = ?',array($id));
			if($query->num_rows()>0){
				$row = $query->row_array();
				$this->db->query('Update '.$table.' Set sequence = (sequence - 1) Where parent_id = ? And sequence > ?',array($row['parent_id'],$row['sequence']));
				$this->db->query('Delete From '.$table.' Where '.$id_field.' IN ('.$row['self_children'].')');
				$this->db->query('Delete From '.$text_table.' Where '.$id_field.' IN ('.$row['self_children'].')');
			}
		}

		$result['success'] = TRUE;
		$result['csrf_token'] = $this->security->get_csrf_hash();
		echo json_encode($result);
	}

	public function clone_locale($table,$text_table,$id_field,$text_id_field)
	{
		if(!$this->admin_auth->has_access($table,'insert')){
			message_handler(FALSE,'Access Denied','');
		}

		$id = $this->input->post('id',TRUE);
		if($id)
		{
			$query = $this->db->query('Select * From '.$table.' Where '.$id_field.' = ?',array($id));
			if($query->num_rows()>0)
			{
				$row = $query->row_array();

				$query = $this->db->query('Select sequence From '.$table.' Where level = 0 Order By sequence Desc Limit 1 ');
				$max   = $query->row_array();
				unset($row[$id_field]);
				$row['level']          = 0;
				$row['root_id']        = 0;
				$row['parent_id']      = 0;
				$row['self_children']  = '';
				$row['self_ancestors'] = '';
				$row['sequence']       = $max['sequence']+1;
				$row['is_visible']     = 0;

				// $result['data'] = $row;

				$this->db->insert($table,$row);
				$insert_id = $this->db->insert_id();

				if($insert_id)
				{
					$query = $this->db->query('Select * From '.$text_table.' Where '.$id_field.' = ?',array($id));
					$texts = $query->result_array();
					foreach ($texts as $t)
					{
						unset($t[$text_id_field]);
						$t[$id_field] = $insert_id;
						$this->db->insert($text_table,$t);
					}
				}
			}
		}

		$result['success'] = TRUE;
		$result['csrf_token'] = $this->security->get_csrf_hash();
		echo json_encode($result);
	}

	public function refresh($table,$text_table,$id_field,$name_field,$path_field,$join_field,$custom_field='',$custom_value='')
	{
		if(!$this->admin_auth->has_access($table,'browse')){
			message_handler(FALSE,'Access Denied','');
		}

		// $this->db->query('Update '.$table.' Set level = 999');
		
		$query = $this->db->query('Select * From locales');
		$locales = $query->result_array();

		$sql = '';
		if(strlen($custom_field)>0 && strlen($custom_field)>0)
		{
			$sql = ' And '.$custom_field.' = '.$custom_value.' ';
		}
		
		// Root, Self Ancestors, Level, Full Path
		foreach ($locales as $l) 
		{
			$level = 0;
			$max_level = 999;

			$query = $this->db->query('Select * From '.$table.' Left Join '.$text_table.' On '.$table.'.'.$join_field.' = '.$text_table.'.'.$join_field.' Where parent_id = 0 '.$sql.' And locale = ?',array($l['locale_code']));
			if($query->num_rows()>0)
			{
				$parents = $query->result_array();
				foreach ($parents as $parent) 
				{
					$this->db->query('Update '.$table.' Set self_ancestors = ?, level = 0, root_id = ? Where '.$id_field.' = ?',array($parent[$id_field], $parent[$id_field], $parent[$id_field]));
					$this->db->query('Update '.$text_table.' Set '.$path_field.' = ? Where '.$id_field.' = ? And locale = ?',array($parent[$name_field], $parent[$id_field], $l['locale_code']));
				}
				
				while($level < $max_level)
				{
					$query = $this->db->query('Select * From '.$table.' Left Join '.$text_table.' On '.$table.'.'.$join_field.' = '.$text_table.'.'.$join_field.' Where level = ? '.$sql.' And locale = ?',array($level, $l['locale_code']));
					$parents = $query->result_array();

					foreach($parents as $parent)
					{
						$query = $this->db->query('Select * From '.$table.' Left Join '.$text_table.' On '.$table.'.'.$join_field.' = '.$text_table.'.'.$join_field.' Where parent_id = ? And locale = ?',array($parent[$id_field], $l['locale_code']));
						$children = $query->result_array();

						foreach($children as $child)
						{
							$root_id         = $parent['root_id'];
							$child_level     = $parent['level']+1;
							$child_full_path = $parent[$path_field].'*'.$child[$name_field];
							$self_ancestors  = $parent['self_ancestors'].','.$child[$id_field];
							
							$this->db->query('Update '.$table.' Set root_id = ?, level = ?, self_ancestors = ? Where '.$id_field.' = ?',array($root_id, $child_level, $self_ancestors, $child[$id_field]));
							$this->db->query('Update '.$text_table.' Set '.$path_field.' = ? Where '.$id_field.' = ? And locale = ?',array($child_full_path, $child[$id_field], $l['locale_code']));
						}
					}
					$level++;
				}
			}
		}
		// Self Children
		$query = $this->db->query('Select Max(level) as max_level From '.$table);
		$row = $query->row_array();	
		$level = $row['max_level'];

		if(is_numeric($level))
		{
			while($level >= 0)
			{
				$query = $this->db->query('Select * From '.$table.' Where level = ?'.$sql,array($level));
				$rows = $query->result_array();

				foreach($rows as $row)
				{
					$self_children = $row[$id_field];
					$query = $this->db->query('Select * From '.$table.' Where parent_id = ?',array($row[$id_field]));
					if($query->num_rows()>0)
					{
						$children = $query->result_array();
						foreach ($children as $child) 
						{
							$self_children .= ','.$child['self_children'];
						}
					}
					$this->db->query('Update '.$table.' Set self_children = ? Where '.$id_field.' = ?',array($self_children, $row[$id_field]));
					
				}
				$level--;
			}
		}
		
		$result['success'] = TRUE;
		$result['csrf_token'] = $this->security->get_csrf_hash();
		echo json_encode($result);
	}
}
/* End of file admin/trees.php */
/* Location: ./system/application/controllers/admin/trees.php */