<?php
	require_once '../../autoload.php';

	$ins_id 	= -1;

	if ( isset($_GET['ins_id']) )
		$ins_id	= $_GET['ins_id'];

	$institution = ($ins_id == -1)? "" : " and institution.id=".$ins_id;
		
	$conn = get_dbconnection();
	
	$answer = "<departments>";
	
	if ( $conn )
	{
		error_log ( "#### get_taginstdep ####" );

		$sql = "select distinct institution.id as inst_id, institution.name, tag.id, '' as department, ('{'||(string_agg(department.id::text,',') over (partition by institution.id))||'}')::int[] <@ array[{$_SESSION['deplistid']}] as alldepininst from institution,tag,tag_link,department where tag_link.type = 'institution'	and tag_link.ext_id = institution.id and tag.id = tag_link.tag_id and tag.removed = false and department.inst_id = institution.id and department.removed = false order by institution.name;";

		error_log ( "sql 1 : " .$sql );
		
		if ( $query = pg_query($conn,$sql) )
		{
			while ( $row = pg_fetch_row($query) )
			{
				if($row[4]== 'f')
          			continue;

				$answer .= "<department inst_id=\"".$row[0]."\" institution=\"".$row[1]."\" tag_id=\"".$row[2]."\" department=\"".$row[3]."\" ></department>";
			}
		}

		$sql = "select department.inst_id,institution.name,tag.id,department.name from institution,department,tag,tag_link where department.id in({$_SESSION['deplistid']}) and institution.id =department.inst_id and tag_link.type = 'department' and tag_link.ext_id = department.id and tag.id = tag_link.tag_id and tag.removed = false and institution.removed = false and department.removed = false order by institution.name, tag.name";

		error_log ( "sql 2 : " .$sql );

		if ( $query = pg_query($conn,$sql) )
		{
			while ( $row = pg_fetch_row($query) )
			{
				$answer .= "<department inst_id=\"".$row[0]."\" institution=\"".$row[1]."\" tag_id=\"".$row[2]."\" department=\"".$row[3]."\" ></department>";
			}
		}
	}
	
	$answer .= "</departments>";

	header ('Content-type: text/xml' );
	
	echo $answer;
?>

