<?php
/**
 * Klasa do obs�ugi prostych artykulow
 *
 */
class SimpleArticle_MfArticleCategoryDAL extends DefaultDAL {

	protected static $objClassName;
	protected static $objClassTable;
	protected static $objClassTablePK;
	private static $optClass;

	public static function Save($obj) {
		return self::DefaultSave(self::GetObjClassTable(), self::GetObjClassTablePK(), $obj);
	}

	public static function Insert($obj) {
		return self::DefaultInsert(self::GetObjClassTable(), $obj);
	}

	public static function Update($obj) {
		self::DefaultUpdate(self::GetObjClassTable(), self::GetObjClassTablePK(), $obj);
	}

	public static function Delete($id) {

		SimpleArticle_MfArticleCategoryDescriptionDAL::DeleteByParentId($id);

		self::DefaultDelete(self::GetObjClassTable(), self::GetObjClassTablePK(), $id);
	}

	public static function GetById($id) {
		return self::DefaultGetById(self::GetOptClass(), self::GetObjClassTable(), self::GetObjClassName(), self::GetObjClassTablePK(), $id);
	}
	
	
	public static function GetEmptyObj() {
		//Utils::ArrayDisplay('tu jestem ');
		$obj = new SimpleArticle_MfArticleCategory(-1);
		$obj->SetArticleCategoryDescriptionObj(SimpleArticle_MfArticleCategoryDescriptionDAL::GetEmptyObj());
		return $obj;
	}

	/*
	 * Pobiera listę kategorii sortując je po wadze (pole weight) rosnąco
	 */
	public static function GetArrayObjAll() {
	    return self::GetResult(array(), array(), null, 'weight ASC');
	}

	public static function GetResult($data, $queryFields = array(), $limit = 0, $sortBy = null, $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(`id_mf_article_category`) 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 = 'id_mf_article';
			}

			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 GetList($limit = 20, $sortBy = 'id_mf_article') {
		return self::GetResult(array(), array('id_mf_article', 'date', 'url', 'weight'), $limit, $sortBy);
	}

	public static function GetByLink($sourceType, $sourceId, $lang) {

		$data = array('mf_link.source_type'=>'"'.$sourceType.'"', 'mf_link.id_source'=>$sourceId, 'mf_link.destination_type'=>'"'.self::GetObjClassTable().'"', 'mf_link.id_destination'=>self::GetObjClassTable().".".self::GetObjClassTablePK(), 'mf_link.id_mf_link'=>'mf_link_description.id_mf_link', 'mf_link_description.lang'=>'"'.$lang.'"');
		$sortBy = 'mf_link.link_type, mf_link.link_type';
		$queryFields = array();
		$limit = null;
		$count = null;

		$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, mf_link_description.description as mf_link_description, mf_link.weight as mf_link_weight, mf_link.link_type as mf_link_type FROM " . self::GetObjClassTable() . ", mf_link, mf_link_description 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);
			$obj->SetMfLinkDescription($array[$i]['mf_link_description']);
			$obj->SetMfLinkWeight($array[$i]['mf_link_weight']);
			$obj->SetMfLinkType($array[$i]['mf_link_type']);
			$obj->SetLang($lang);
			$done[] = $obj;
		}
		return $done;

	}

	public function SaveFromPost($_POST) {
		//Utils::ArrayDisplay($_POST);
		if (isset($_POST['Article']['idArticleCategory']) && $_POST['Article']['idArticleCategory'] > 0) {
			
			$objArticle = SimpleArticle_MfArticleCategoryDAL::GetById($_POST['Article']['idArticleCategory']);
			$objArticleDescription = SimpleArticle_MfArticleCategoryDescriptionDAL::GetResult(array('publication' => 1, 'lang' => $objArticle->GetLang(), 'id_mf_article' => $objArticle->GetId()), array('id_mf_article_description', 'title', 'description', 'shortnote'));
			$objArticleDescription = $objArticleDescription[0];
		} else {
			$objArticle = new SimpleArticle_MfArticle();
			$objArticleDescription = new SimpleArticle_MfArticleCategoryDescription();

		
		}

		//				var_dump($objArticleDescription->GetId());

		$objArticle->SetDate(date('Y-d-m'));
		$objArticle->SetWeight(10);
		//$objArticle->SetPublication(1);
		//Utils::ArrayDisplay($objArticle);
		$iid = SimpleArticle_MfArticleDAL::Save($objArticle);

		$objArticleDescription->SetLang('pl');
		$objArticleDescription->SetDescription($_POST['Article']['tresc']);
		$objArticleDescription->SetShortnote($_POST['Article']['zajawka']);
		$objArticleDescription->SetTitle($_POST['tytul']);
		$objArticleDescription->SetBrowserTitle($_POST['Article']['tytulWPrzegladarce']);
		$objArticleDescription->SetPublication($_POST['publication']);
		$objArticleDescription->SetIdMfArticle($iid);

		SimpleArticle_MfArticleDescriptionDAL::Save($objArticleDescription);
		
		return $iid;
	}

	/**
	 * Pusty konstruktor
	 *
	 */
	public function __construct() {

	}

	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;
	}

	public static function SaveSort($sortArray) {
	    $array = self::GetArrayObjAll();
	    foreach($array as $obj) {
		$obj->SetWeight($sortArray[$obj->GetId()]);
		self::Update($obj);
	    }
	}
	
	
	public static function GetCountAll() {

		$db = Registry::Get('db');
		$sql = " SELECT count(*) as ile ".
		" FROM ".self::GetObjClassTable();

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

		$array = $stmt->fetchAllAssoc();
		return $array[0]["ile"];
	}
	
	public static function CheckIsPublication($ids) {
		if(empty($ids)) {
			return false;
		}
		if(!is_array($ids)) {
			$ids = array($ids);
		}
		$sql = sprintf('SELECT count(publication) as count FROM mf_article_category WHERE id_mf_article_category IN (%s)', implode(',', $ids));
		$res = Registry::Get('db')->Prepare($sql)->Execute()->FetchAllAssoc();
		if($res[0]['count'] > 0) {
			return true;
		} else {
			return false;
		}
	}
	
	public static function GetCategoriesForArticles($type) {
	    $sql = 'SELECT '.SQL::ToSelect('MfArticleCategory').' FROM mf_article_category where id_mf_Article_category in (
					SELECT distinct mf_link.id_destination FROM `mf_article` 
					JOIN mf_link
					ON mf_link.source_type = \'mf_article\' AND  
					mf_link.destination_type= \'mf_article_category\' AND
					mf_article.id_mf_article = id_source
					WHERE mf_article.type = '.$type.'
					AND mf_article.`publication` = 1
				) AND publication=1 ORDER BY weight';
	    
	    $res = Registry::Get('db') -> prepare($sql) -> execute() -> FetchAllAssoc();
	    
	    $return = array();
	    
	    foreach($res AS $row) {
	        $obj = new MfArticleCategory();
	        $obj -> FromArray($row,1);
	        $return[] = $obj;
	    }
	    
	    return $return;
	}

}
?>