<?php
function fn_assettype_c($aql)
{
	$data = $aql->Consume(1);
	
	global $db;
	$apool = array();
	
	$mt = microtime(true);
	
	$existing = array();
	
	global $debug;
	if ($debug == true) echo '[ Getting Assets By Type';
		
	$extra = "";
	if (count($existing) > 0) 
	{
		$extra = " AND childasset IN (".implode(",",$existing).')';
	}
	
	$items = array($data[0]->value);
		
	$query = $db->query("SELECT name,id FROM assets WHERE type=1".$extra);
	$typelist = array();
	while($row = $query->fetch(PDO::FETCH_ASSOC)) 
	{
		$typelist[strtolower($row['name'])] = $row['id'];
	}
	
	$hits = array();

	$unmatched = array();
	$text = array_keys($typelist);
	foreach($items as $i)
	{
		if (in_array(strtolower($i),$text))
		{
			#echo("Found Type: ".$i);
			$hits[] = $typelist[$i];
		}
		else
		{
			$unmatched[] = strtolower($i);
		}
	}
	
	$remainder = array();
	foreach($unmatched as $i)
	{
		if ($i[strlen($i)-1] == 's')
		{
			$i = substr($i,0,strlen($i)-1);
			if ($i[strlen($i)-1] == 'e')
			{
				$i = substr($i,0,strlen($i)-1);
			}
		}
		if (in_array(strtolower($i),$text))
		{
			$hits[] = $typelist[$i];
			echo("Found Type: ".$text);
		}
		else
		{
			$remainder[] = strtolower($i);
		}
	}
	
	if (count($hits) > 0)
	{
		$extra = "";
		if (count($existing) > 0) 
		{
			$extra = " AND childasset IN (".implode(",",$existing).')';
		}
				
		$query = $db->query("SELECT childasset FROM assetrelclosures WHERE relationship=3 AND parentasset IN (".implode(',',$hits).")".$extra);
				
		while($row = $query->fetch(PDO::FETCH_ASSOC)) 
		{
			$apool[] = $row['childasset'];
		}
	}
	
	if (count($remainder) > 0)
	{
		#echo 'Leftovers!';
		print_r($remainder);
	}
		
	$a = new AQLStackElement();
	$a->typename = "assetlist";
	$a->islist = true;
	$a->value = $apool;
	array_push($aql->stack,$a);

}
?>