<?php
/**
 * Klasa obsĹ‚ugi tablicy linkow
 *
 */
class MfLinkDAL extends DefaultDAL {


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

	public static function Save( $obj) {

		if($obj->GetId()==-1) {
			return self::Insert($obj);

		} else {
			return self::Update($obj);
		}
	}

	/**
     * @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) {
		$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);
	}

	public static function UpdateSourceId($idNew,$id,$type) {
		$db = Registry::Get('db');

		$sql = "UPDATE mf_link SET id_source=$idNew WHERE id_source=$id AND source_type='$type'";

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


	public static function GetById($id) {
		return self::DefaultGetById(self::GetOptClass(), self::GetObjClassTable(), self::GetObjClassName(), self::GetObjClassTablePK(), $id);
	}


	public static function GetArrayObjAll() {

	}


	public static function GetResult($data,$queryFields = array(),$limit = 0, $sortBy = null,$count = null,$groupBy = null) {

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

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

		$queryCacheName = __CLASS__. "_" .__FUNCTION__. "_" .md5(implode($queryFields));
		if($count == true)
		$queryCacheName.="_count";
		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 " : "").
		//( $groupBy ? " GROUP BY $groupBy " : "").
		( $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;

	}

	/**
	 * Pobiera z tabeli liste slowek i cacheuje
	 *
	 * @param integer $cacheTime
	 * @return Array
	 */
	public static function GetAllVariables($lang, $cacheTime) {
		$db = Registry::Get('db');
		$sql = "SELECT keyword, replacement FROM ".self::$objClassTable." WHERE lang='".$lang."'";

		$stmt=$db->execute($sql);
		$stmt->CacheStart($cacheTime);
		$array = $stmt->FetchAllAssoc();

		$returnArray = array();
		foreach ($array as $keyword => $value) {

			$returnArray[$keyword] = $value;
		}
		return $returnArray;

	}

	public static function DeleteFromLink($idSource = null, $sourceType = null, $idDestination = null, $destinationType = null) {

		$db = Registry::Get('db');
		$sql = "DELETE FROM `mf_link` WHERE 1=1 ";

		if($idSource!= null )
		$sql.= " AND id_source = :01 ";

		if($sourceType!= null)
		$sql.= " AND source_type = :02 ";

		if($idDestination!= null)
		$sql.= " AND id_destination = :03 ";

		if($destinationType!= null)
		$sql.= " AND destination_type = :04 ";

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

		if($idSource!= null )
		$stmt->bindParam('01', $idSource);

		if($sourceType!= null)
		$stmt->bindParam('02', $sourceType);

		if($idDestination!= null)
		$stmt->bindParam('03', $idDestination);
		if($destinationType!= null)
		$stmt->bindParam('04', $destinationType);
		$stmt->execute();
		//Utils::ArrayDisplay($stmt);
	}

	public static function SortLink($idSource,$sortedLinks,$sourceType,$destinationType)
	{
		$db = Registry::Get('db');

		foreach ($sortedLinks as $weight => $idDestination)
		{
			$sql = "UPDATE mf_link SET weight = $weight WHERE id_source=:01 AND id_destination =:02 AND source_type=:03 AND destination_type=:04";

			$stmt=$db->prepare($sql)
			->bindParam("01", $idSource)
			->bindParam("02", $idDestination)
			->bindParam("03", $sourceType)
			->bindParam("04", $destinationType)
			->execute();
		}
	}

	public static function SortLink2($sortedLinks)
	{
		$db = Registry::Get('db');

		foreach ($sortedLinks as $weight => $idDestination)
		{
			$sql = "UPDATE mf_link SET weight = $weight WHERE id_mf_link=:01";

			$stmt=$db->prepare($sql)
			->bindParam("01", $idDestination)
			->execute();
		}
	}

	public function GetMaxWeight($idSource,$sourceType)
	{
		$db = Registry::Get('db');

		$sql = "SELECT MAX(weight) as max FROM mf_link WHERE id_source=:01 AND source_type=:02";

		$stmt = $db->prepare($sql)
		->bindParam("01",$idSource)
		->bindParam("02",$sourceType)
		->execute();

		$array = $stmt->fetchAllAssoc();

		return  $array[0]['max'];
	}

	public static function UpdateType(MfLink $obj)
	{
		$db = Registry::Get('db');
		$sql = "UPDATE mf_link SET link_type='" . $obj->GetLinkType() . "' WHERE source_type='" . $obj->GetSourceType(). "' AND id_source='" . $obj->GetIdSource() .  "' AND id_destination='" . $obj->GetIdDestination() . "' AND destination_type='" . $obj->GetdestinationType() . "'";
		$stmt = $db->prepare($sql)
		->execute();
	}

	public function GetCount($idSource,$sourceType,$destinationType)
	{
		$db = Registry::Get('db');

		$sql = "SELECT count(weight) as max FROM mf_link WHERE id_source=:01 AND source_type=:02 AND destination_type=:03";

		$stmt = $db->prepare($sql)
		->bindParam("01",$idSource)
		->bindParam("02",$sourceType)
		->bindParam("03",$destinationType)
		->execute();

		$array = $stmt->fetchAllAssoc();

		return  $array[0]['max'];
	}

	public static function GetCountDestination($sourceType,$destinationType)
	{

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

		$sql="SELECT count( id_destination ) as countDestination, id_source as id_source
			FROM `mf_link`
			WHERE `source_type` = :01
			AND `destination_type` = :02
			GROUP BY id_source
			";

		$stmt = $db->prepare($sql)
		->bindParam("01",$sourceType)
		->bindParam("02",$destinationType)
		->execute();

		$array = $stmt->fetchAllAssoc();

		$returnArray = array();
		foreach($array as $key => $value)
		{
			$returnArray[$value['id_source']] = $value['countDestination'];
		}
		return $returnArray;
	}

	public function ReCountWeight($idSource,$sourceType,$destinationType)
	{
		$db = Registry::Get('db');
		$mfLinkArray = self::GetResult(array("id_source" => $idSource, "source_type" => "'" . $sourceType . "'", "destination_type" => "'" . $destinationType. "'"),array(),null,"weight");
		$weight = 0;
		foreach ($mfLinkArray as $key => $value)
		{
			$value->SetWeight($weight);
			MfLinkDAL::Update($value);
			$weight++;
		}
	}


	public static function GetQuerySourceIds($sourceType,$destinationType,$idDestination = array(),$limit = null,$cacheTime = 360)
	{
		$db = Registry::Get('db');
		$arrayReturn = array();
		$idDestnationSql = "";
		if(count($idDestination) > 1)
		{
			foreach($idDestination as $key => $value)
			{
				$idDestnationSql.=$value . ",";
			}
			$idDestnationSql = substr($idDestnationSql, 0,strlen($idDestnationSql)-1);
			$idDestnationSql = " IN (" . $idDestnationSql . ")";
		}
		else if(isset($idDestination[0]) && is_numeric($idDestination[0]))
		{
			$idDestnationSql="=" . $idDestination[0];
		}

		$sql = "";
		if($idDestnationSql != "")
		{
			$sql = "SELECT id_source from mf_link WHERE source_type='$sourceType'
			AND destination_type='$destinationType' AND id_destination$idDestnationSql ORDER BY id_source DESC";
			if($limit != null)
			$sql .=" LIMIT $limit";
			$stmt = $db->prepare($sql);
			$stmt->CacheStart($cacheTime);
			$stmt->execute();
			$array =  $stmt->FetchAllAssoc();
			if(count($array)  == 1)
			return  array($array[0]['id_source']);
			else if( count($array) > 1)
			{
				foreach ($array as $key => $value)
				{
					$arrayReturn[]=$value['id_source'];
				}
			}
		}
		return $arrayReturn;
	}





	public function GetArrayId($source , $destination, $idDestination) {
		$db = Registry::Get('db');
		$sql = "SELECT id_source FROM `mf_link` WHERE `source_type` = '$source' AND `destination_type` = '$destination' AND `id_destination` = $idDestination";
		//Utils::ArrayDisplay($sql);
		$stmt=$db->prepare($sql)
		->execute();
		//$stmt->CacheStart($cacheTime);
		$returnArray = array();
		while(($row = $stmt->FetchArray())) {
			$returnArray[] = $row['id_source'];
		}
		return $returnArray;
	}

	public static function GetIdString($source , $destination, $idDestination, $idDestinationNotIN = null) {
		$db = Registry::Get('db');
		$sql = "SELECT id_source FROM `mf_link` WHERE `source_type` = '$source' AND `destination_type` = '$destination' ".
						($idDestination ? " AND `id_destination` = $idDestination " : "").
						($idDestinationNotIN ? " AND `id_destination` NOT IN ($idDestinationNotIN) " : "").
						" GROUP BY id_source ";
		$stmt=$db->prepare($sql)->execute();

		//Utils::ArrayDisplay($sql);
		if ($stmt->NumRows() > 0) {

		}
		//$stmt->CacheStart($cacheTime);
		$ids = '( ';
		$returnArray = array();
		while(($row = $stmt->FetchArray())) {
			$returnArray[] = $row['id_source'];
		}
		if (count($returnArray) > 0) {
			$ids .= implode(',', $returnArray);
		} else {
			$ids .= '-1';
		}
		$ids .= ' )';
		return $ids;
	}

	public function GetIdStringClear($source , $destination, $idDestination) {
		$db = Registry::Get('db');
		$sql = "SELECT id_source FROM `mf_link` WHERE `source_type` = '$source' AND `destination_type` = '$destination' AND `id_destination` IN ( $idDestination ) GROUP BY id_source";
		$stmt=$db->prepare($sql)->execute();

		//Utils::ArrayDisplay($sql);
		if ($stmt->NumRows() > 0) {

		}
		//$stmt->CacheStart($cacheTime);
		$ids = '';
		$returnArray = array();
		while(($row = $stmt->FetchArray())) {
			$returnArray[] = $row['id_source'];
		}
		if (count($returnArray) > 0) {
			$ids .= implode(',', $returnArray);
		} else {
			$ids .= '-1';
		}
		//$ids .= ' )';
		return $ids;
	}

	public function GetIdStringForDestinationArray($source , $destination, $destinationIds, $excludedSourceIds = "(-1)") {
		$db = Registry::Get('db');
		$sql = "SELECT id_source FROM `mf_link` WHERE `source_type` = '$source' AND `destination_type` = '$destination' AND `id_destination` IN $destinationIds AND id_source NOT IN $excludedSourceIds GROUP BY id_source";
		$stmt=$db->prepare($sql)->execute();

		//Utils::ArrayDisplay($sql);
		if ($stmt->NumRows() > 0) {

		}
		//$stmt->CacheStart($cacheTime);
		$ids = '( ';
		$returnArray = array();
		while(($row = $stmt->FetchArray())) {
			$returnArray[] = $row['id_source'];
		}
		if (count($returnArray) > 0) {
			$ids .= implode(',', $returnArray);
		} else {
			$ids .= '-1';
		}
		$ids .= ' )';
		return $ids;
	}

	public function GetArrayIdDestinaion($source , $destination, $idSource) {
		$db = Registry::Get('db');
		$sql = "SELECT `id_destination` FROM `mf_link` WHERE `source_type` = '$source' AND `destination_type` = '$destination' AND `id_source`  = $idSource";
		//Utils::ArrayDisplay($sql);
		$stmt=$db->prepare($sql)
		->execute();
		//$stmt->CacheStart($cacheTime);
		$returnArray = array();
		while(($row = $stmt->FetchArray())) {
			$returnArray[$row['id_destination']] = $row['id_destination'];
		}
		return $returnArray;
	}

	public function GetIdStringDestinaion($source , $destination, $idSource) {
		$ids = '(-1)';
		$db = Registry::Get('db');
		$sql = "SELECT id_destination FROM `mf_link` WHERE `source_type` = :01 AND `destination_type` = :02 AND `id_source` = :03";
		$stmt=$db->prepare($sql)
		->bindParam ('01', $source)
		->bindParam ('02', $destination)
		->bindParam ('03', $idSource)
		->execute();

		if ($stmt->NumRows() > 0) {
			//$stmt->CacheStart($cacheTime);
			$ids = '(';
			$returnArray = array();
			while(($row = $stmt->FetchArray())) {
				$returnArray[] = $row['id_destination'];
			}
			if (count($returnArray) > 0) {
				$ids .= implode(' ,', $returnArray);
			} else {
				$ids .= '-1';
			}
			$ids .= ' )';
			return $ids;

		}
		return $ids;
	}

	public static function DeleteAllLink($idSource, $sourceType, $destinationType) {
		$db = Registry::Get('db');
		$sql = "DELETE FROM `mf_link` WHERE id_source = :01 AND source_type = :02 AND destination_type = :04 ";

		$stmt=$db->prepare($sql)
		->bindParam ('01', $idSource)
		->bindParam ('02', $sourceType)
		->bindParam ('04', $destinationType)
		->execute();

	}

	public static function GetArrayList($table, $column, $destination, $lang = null, $source, $idSource, $where = '', $tableJoin = '', $limit = 0) {
		$array = array();
		$db = Registry::Get('db');

		$sql = " CHECK TABLE $table FAST QUICK";
		$stmt = $db->prepare($sql)->execute();
		$row = $stmt->FetchArray();

		if (isset($row['Msg_type']) && strtolower($row['Msg_type']) != 'error') {
			if (isset($row[0]['Msg_type']) && $row[0]['Msg_type'] != 'error') {

				$sql = 'SELECT '.$table.'.id_'.$destination.', '.$column.
				' FROM '.$table. ( $tableJoin ? " ,$tableJoin " : " ").
				' WHERE 1=1 '.
				$where . " " .
				( $limit ? " LIMIT " . $limit : "");
				//echo $sql;
				$stmt = $db->prepare($sql)->execute();
				//Utils::ArrayDisplay($sql);

				$ids = '';
				while(($row = $stmt->FetchArray())) {
					$array[$row['id_'.$destination.'']] = array( 'name' => $row[$column], 'checked' => '', 'description' => '', 'icon' => null);
					$icon = null;
					foreach(SimpleArticle_MfArticleCategory::$exts as $ext) {
						$path = PATH_STATIC_CONTENT."image".DS."Admin".DS."Categories".DS."Icons".DS.$row['id_'.$destination.''].".".$ext;
						$url = URL_STATIC_CONTENT."/image/Admin/Categories/Icons/".$row['id_'.$destination.''].".".$ext;
						if(file_exists($path)) {
							$icon = $url;
						}
						$array[$row['id_'.$destination.'']]['icon'] = $icon;
					}
					$ids .= $row['id_'.$destination.''].",";
				}

				$ids = substr($ids, 0, -1);
				$ids = !$ids ? "-1" : $ids;

				// stary sql
				$sql = "SELECT a.id_destination FROM mf_link a WHERE source_type = '$source' AND  destination_type = '$destination' ".
				" AND id_destination IN ($ids) AND id_source = '$idSource' ";
				//$sql = "SELECT id_desti//$sql =nation FROM mf_link a WHERE source_type = '$source' AND  destination_type = '$destination' AND id_source = '$idSource'";

				$stmt2 = $db->execute($sql);
				while(($row = $stmt2->FetchArray())) {
					$array[$row['id_destination']]['checked'] = 'checked';
				}
			}
		}
		//echo $where;
		return $array;
	}

	public static function GetLinkedArticles($id, $data = array(), $queryFields = array(),$limit = 0, $sortBy = null,$count = null) {
		$data['mf_article.publication'] = array('value' => -1, 'condition' => '>');
		$data['mf_link.id_source'] = $id;
		$data['mf_link.destination_type'] = '\'mf_article\'';
		$data['mf_link.source_type'] = '\'mf_article\'';

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

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

		$queryCacheName = __CLASS__. "_" .__FUNCTION__. "_" .md5(implode($queryFields));
		if($count == true)
		$queryCacheName .="_count";

		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::ToSelect('MfArticle') . ", " . SQL::ToSelect('MfArticleDescription') . " ";

			$sql = " SELECT $select FROM " . self::GetObjClassTable() . " LEFT JOIN mf_article ON mf_article.id_mf_article=mf_link.id_destination LEFT JOIN mf_article_description ON mf_article.id_mf_article=mf_article_description.id_mf_article 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();

		//Utils::ArrayDisplay($sql);

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

		$done = array();

		for($i=0;$i<count($array);$i++) {
			$className = 'MfArticle';
			$obj = new $className();
			$obj->FromArray($array[$i], 1);

			$objDesc = new MfArticleDescription();
			$objDesc->FromArray($array[$i], 1);
			$obj->SetArticleDescriptionObj($objDesc);
			$done[] = $obj;
		}
		return $done;
	}

	public function IsLinked($idSource = null, $sourceType = null, $idDestination = null, $destinationType = null, $published = '-1', $idSourceSql = '=') {

		$db = Registry::Get('db');
		$sql = "SELECT count(id_mf_link) as count FROM `mf_link` WHERE 1=1 AND published NOT IN (".$published.") ";

		if($idSource!= null )
		$sql.= " AND id_source ".$idSourceSql." $idSource ";

		if($sourceType!= null)
		$sql.= " AND source_type = :02 ";

		if($idDestination!= null)
		$sql.= " AND id_destination ".$idSourceSql." $idDestination ";

		if($destinationType!= null)
		$sql.= " AND destination_type = :04 ";

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

		if($idSource!= null )
		$stmt->bindParam('01', $idSource);

		if($sourceType!= null)
		$stmt->bindParam('02', $sourceType);

		if($idDestination!= null)
		$stmt->bindParam('03', $idDestination);
		if($destinationType!= null)
		$stmt->bindParam('04', $destinationType);
		$stmt->execute();

		$array = $stmt->fetchAllAssoc();



		return $array[0]['count'];


	}


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


	public static function UpdateDestinationId($idNew,$id,$source, $destination) {
		$db = Registry::Get('db');

		$sql = "UPDATE mf_link SET id_destination=$idNew WHERE id_destination=$id AND source_type='$source' AND destination_type = '$destination'";

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

		//Utils::ArrayDisplay($sql);
	}

	public static function UpdatePublished($published = 1, $idSource = null, $sourceType = null, $destinationType = null, $idDestination = null, $idSourceSql = '=') {

		$db = Registry::Get('db');
		$sql = "UPDATE `mf_link` ";

		$sql.= " SET published = :05 ";

		$sql.= "WHERE 1=1 ";

		if($idSource!= null )
		$sql.= " AND id_source ".$idSourceSql." ".$idSource." ";

		if($sourceType!= null)
		$sql.= " AND source_type = :02 ";

		if($idDestination!= null)
		$sql.= " AND id_destination = :03 ";

		if($destinationType!= null)
		$sql.= " AND destination_type = :04 ";


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

		//if($idSource!= null )
		//$stmt->bindParam('01', $idSource);

		if($sourceType!= null)
		$stmt->bindParam('02', $sourceType);

		if($idDestination!= null)
		$stmt->bindParam('03', $idDestination);
		if($destinationType!= null)
		$stmt->bindParam('04', $destinationType);
		$stmt->bindParam('05', $published);
		$stmt->execute();
		//Utils::ArrayDisplay($stmt);
	}
}
?>