<?php
/**
 * Klasa obsługi tablicy struktury menu 
 *
 */
class StructureDAL extends DefaultDAL {
	protected static $objClassName;
	protected static $objClassTable;
	protected static $objClassTablePK;
	private static $optClass;

	public static function Save( $obj) {
		$id = null;

		if($obj->GetId()==-1 || $obj->GetId()=='NULL') {

			$id = self::Insert($obj);
		} else {

			self::Update($obj);
			$id = $obj->GetId();
		}

		return $id;
	}


	/**
     * @param Feed $obj
     *
     */
	public static function Insert($obj) {

		$dalData = new DalData();
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObj($obj);
		$id = self::DefaultInsert($dalData);

		return $id;
	}
	/**
     * @param Text $obj
     *
     */
	public static function Update($obj) {
		//Utils::ArrayDisplay($obj);
		$dalData = new DalData();
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObjClassTablePK(self::GetObjClassTablePK());
		$dalData->setObj($obj);
		return self::DefaultUpdate($dalData);
	}

	/**
     *
     * @param integer $id
     *
     */
	public static function Delete($obj) {
		$dalData = new DalData();
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObjClassTablePK(self::GetObjClassTablePK());
		$dalData->setObj($obj);
		return self::DefaultDelete($dalData);
	}

	/**
     *
     * @param  $id
     */
	public static function GetById($id, $getContent = false) {
		$dalData = self::GetDalDataObj();
		$dalData->setCondition(array(self::GetObjClassTablePK()=>$id));
		$dalData->setLimit(1);
		if ($getContent) {
			$dalData->setJoin(array('SimpleArticle_MfArticleDescription' => ' LEFT JOIN mf_article_description ON mf_article_description.id_mf_article=mf_structure.id_content'));
		}

		$result = self::GetResult($dalData, false);
		if ((count($result) > 0) && (is_object($result[0]))) {
			return $result[0];
		} else {
			return false;
			//throw new Exception('Brak rekordu w tablicy '.self::GetObjClassTable().' o id <b>'.$id.'</b>!');
		}
	}

	public static function GetArrayObjAll() {
		return self::GetResult(array(), array());
	}

	public static function GetIdAndName() {
		$data = self::GetResult(array());
		$done = array();
		foreach($data as $value) {
			$done[$value->GetId()] = $value->GetName();
		}
		return $done;
	}

	public static function GetResult($dalData, $showSql = false) {
		return self::DefaultGetResult($dalData, $showSql);
	}

	public static function GetResultOld($data,$queryFields = array(),$limit = 0, $sortBy = 'sort',$count = null) {

		if(!is_array($data)){
			$data = array();
		}

		$db = Registry::Get('db');

		$queryCacheName = __CLASS__. "_" .__FUNCTION__. "_" .md5(implode($queryFields));

		if(isset(QueryCacheTemp::$cacheQuery[$queryCacheName]))
		{
			$sql = QueryCacheTemp::$cacheQuery[$queryCacheName];
		}
		else
		{
			if($count == true)
			$select = "count(*) as count";
			else
			$select =" " . SQL::ToSelect(self::GetOptClass(),$queryFields) . " ";

			$sql = " SELECT $select FROM " . self::GetObjClassTable() . " WHERE 1=1 ";
			$q = new QueryCache($queryCacheName,$sql);
		}

		foreach ($data as $key => $value)
		{
			if($key == "id")
			$key = $objId ;

			if(is_array($value))
			$sql .= ( is_numeric($value['value']) || $value ? " AND ".$key." ".$value['condition']." ". $value['value'] : "");
			else
			$sql .= ( is_numeric($value) || $value ? " AND ".$key." = '". $value ."'" : "");
		}

		$sql .= ( $sortBy ? " ORDER BY $sortBy " : "").
		( $limit ? " LIMIT " . $limit : "").
		" ";

		$stmt = $db->prepare($sql)
		->execute();


		$array = $stmt->fetchAllAssoc();

		if($count == true)
		return  $array[0]['count'];

		$done = array();

		for($i=0;$i<count($array);$i++)
		{
			$className=self::GetObjClassName();
			$obj = new $className();
			$obj->FromArray($array[$i],1);
			$done[] = $obj;
		}
		return $done;

	}


	public static function GetTree($data,$queryFields = array(),$limit = 0, $sortBy = 'sort',$count = null) {

		if(!is_array($data)){
			$data = array();
		}


		$db = Registry::Get('db');

		$queryCacheName = __CLASS__. "_" .__FUNCTION__. "_" .md5(implode($queryFields));

		if(isset(QueryCacheTemp::$cacheQuery[$queryCacheName]))
		{
			$sql = QueryCacheTemp::$cacheQuery[$queryCacheName];
		}
		else
		{
			if($count == true)
			$select = "count(*) as count";
			else
			$select =" " . SQL::ToSelect(self::GetOptClass(),$queryFields) . " ";

			$sql = " SELECT $select FROM " . self::GetObjClassTable() . " WHERE 1=1 ";
			$q = new QueryCache($queryCacheName,$sql);
		}

		foreach ($data as $key => $value)
		{
			if($key == "id")
			$key = $objId ;


			if(is_array($value))
			$sql .= ( is_numeric($value['value']) || $value ? " AND ".$key." ".$value['condition']." ". $value['value'] : "");
			else
			$sql .= ( is_numeric($value) || $value ? " AND ".$key." = '". $value ."'" : "");
		}

		$sql .= ( $sortBy ? " ORDER BY $sortBy " : "").
		( $limit ? " LIMIT " . $limit : "").
		" ";

		$stmt = $db->prepare($sql)
		->execute();

		//Utils::ArrayDisplay($sql);

		$array = $stmt->fetchAllAssoc();

		if($count == true)
		return  $array[0]['count'];

		$done = array();

		for($i=0;$i<count($array);$i++)
		{
			$className=self::GetObjClassName();
			$obj = new $className();
			$obj->FromArray($array[$i],1);
			$done[$obj->GetId()] = $obj;
		}
		//
		//		foreach ($done as $key => $obj) {
		//			if ($obj->GetIdParent() == 0) {
		//				$arrayObjParent[] = $obj;
		//			}
		//		}

		foreach ($done as $key => $obj) {

			if ($obj->GetIdParent() != 0) {
				if (key_exists($obj->GetIdParent(), $done)) {
					$done[$obj->GetIdParent()]->SetHaveChildren(true);
					$done[$obj->GetIdParent()]->AddChildren(array($obj->GetId() => $obj));
				} else {
					$arrayTree[$key] = $obj;
				}

			}
			if ($obj->GetIdParent() == 0) {
				//Utils::ArrayDisplay('ones');
				$arrayTree[$key] = $obj;
			}
		}
		foreach ($done as $key => $obj) {

		}

		if (isset($arrayTree)) {

			return $arrayTree;

		}
	}

	public function CheckPublication($id) {
		$db = Registry::Get('db');

		$sql = "SELECT
		id_mf_structure
		FROM mf_structure WHERE id_mf_structure = $id AND publication = 1";

		$stmt = $db->prepare($sql)
		->execute($sql);

		if ($stmt->NumRows() > 0) {
			return true;
		} else {
			return false;
		}
	}

	public static function CheckChildren($idParent) {
		$db = Registry::Get('db');

		$sql = "SELECT
		id_mf_structure
		FROM mf_structure WHERE id_parent = $idParent ";

		$stmt = $db->prepare($sql)
		->execute($sql);

		if ($stmt->NumRows() > 0) {
			return true;
		} else {
			return false;
		}
	}

	public function GetArrayRouter() {
		$db = Registry::Get('db');

		$sql = "SELECT
		id_mf_router, name, url, controller, method, param, paramMatrix, matchUri, config
		FROM mf_router";

		$stmt = $db->prepare($sql)
		->execute($sql);

		while (($row = $stmt->FetchArray())) {


			$array[$row["id_mf_router"]] = array('name' =>$row["name"],
			'url' => $row["url"],
			'controller' => $row["controller"],
			'method' => $row["method"],
			'param' => $row["param"],
			'paramMatrix' => $row["paramMatrix"],
			'matchUri' => $row["matchUri"],
			'config' => $row["config"]
			);

		}
		return $array;
	}

	public static function GetLabel($id) {
		$db = Registry::Get('db');

		$sql = "SELECT url_label FROM mf_structure WHERE id_mf_structure = $id";

		$stmt = $db->prepare($sql)
		->execute($sql);

		$row = $stmt->FetchArray();
		return $row['url_label'];
	}


	public static function GetObjClassName() {
		if(self::$objClassName != '') {
			$class = self::$objClassName;
		} else {
			$class = str_replace('DAL', '', __CLASS__);
		}

		return $class;
	}

	public static function GetOptClass() {
		if(self::$optClass!=null) {
			return self::$optClass;
		} else {
			return self::GetObjClassName();
		}
	}

	public static function GetObjClassTablePK() {
		if(self::$objClassTablePK != '') {
			$return = self::$objClassTablePK;
		} else {
			$class = self::GetObjClassName();
			$classObj = new $class();
			$return = $classObj->GetClassTablePK();
		}
		return $return;
	}

	public static function GetObjClassTable() {
		if(self::$objClassTable!='') {
			$return = self::$objClassTable;
		} else {
			$class = self::GetObjClassName();
			$classObj = new $class();
			$return = $classObj->GetTableName();
		}

		return $return;
	}


	/**
	 *
	 * @return DalData $dalData
	 */
	public static function GetDalDataObj() {

		$dalData = new DalData();
		$dalData->setObjClassName(self::GetObjClassName());
		$dalData->setObjClassTable(self::GetObjClassTable());
		$dalData->setObjClassTablePK(self::GetObjClassTablePK());
		$dalData->setOptClass(self::GetOptClass());
		//$dalData->setDatabaseType('dbTemp');

		return $dalData;
	}



}
?>