<?php
class Lokality extends Dbmysql {

public $conn = null;

	function __construct() {
		parent::Model();
	}

	function loadById($id = '')
	{
		$query = $this->Dbmysql->db->query('SELECT * FROM lokality WHERE id = "'.$id.'"');
		$locs = $query->result_array();
		if(count($locs) > 0)return $locs;
	}
	
	function getPodlokality($id = 0)
	{
		$query = $this->Dbmysql->db->query('SELECT * FROM lokality WHERE parent_id = '.$id.' ORDER BY lokalita');
		return $query->result_array();
	}
	
	function getAllPodlokality($id = 0, &$res = array())
	{
		$query = $this->Dbmysql->db->query('SELECT * FROM lokality WHERE parent_id = '.$id);
		$tmp = $query->result_array();
		if(count($tmp)>0)
		{
			foreach($tmp as $v)
			{
				$res[] = $v;
				$tmpRes = $this->getAllPodlokality($v['id'], $res);
			}
		}
		return $res;
	}
	
	function getNadlokality($id = 0, &$res = array())
	{
		$query = $this->Dbmysql->db->query('SELECT * FROM lokality WHERE id = '.$id);
		$tmp = $query->result_array();
		if(count($tmp)>0)
		{
			foreach($tmp as $v)
			{
				$res[] = $v;
				$tmpRes = $this->getNadlokality($v['parent_id'], $res);
			}
		}
		return $res;
	}
	
	function getPodlokalityIds($id = '')
	{
		$query = $this->Dbmysql->db->query('SELECT kategoria_id FROM locality WHERE id = "'.$id.'"');
		$locs = $query->result();
		if(count($locs) > 0)return $locs;
	}
	
	function getAllPodlokalityIds($id = 0, &$res = array())
	{
		$query = $this->Dbmysql->db->query('SELECT id FROM lokality WHERE parent_id = '.$id);
		$tmp = $query->result_array();
		if(count($tmp)>0)
		{
			foreach($tmp as $v)
			{
				$res[] = $v['id'];
				$tmpRes = $this->getAllPodlokality($v['id'], $res);
			}
		}
		return $res;
	}
	
	function getCountPodlokalit($id = 0)
	{
		$query = $this->Dbmysql->db->query('SELECT COUNT(id) as pocet FROM lokality WHERE parent_id = '.$id);
		$count = $query->result_array();
		return $count[0]['pocet'];
	}
	
	function getHTMLoptions($id = 0, &$res = '', $selected = 0)
	{
		$lokality = $this->getPodlokality($id);
		foreach($lokality as $v)
		{
			$pocPod = $this->getCountPodlokalit($v['id']);
			if($pocPod == 0)
			{
				$res .= '<option value="'.$v['id'].'"';
				if($v['id'] == $selected)$res .= ' selected="selected"';
				$res .= '>'.$v['lokalita'].'</option>';
			}
			else $res .= '<optgroup label="'.$v['lokalita'].'">';
			$this->getHTMLoptions($v['id'], $res, $selected);
			if($pocPod > 0)$res .= '</optgroup>';
		}
		return $res;
	}

}
?>
