<?php
	require_once '../autoload.php';
	
	require( 'GetDataFromDB.php' );

	 $psql = "select theaccess.inst_id, v_fullinfo_department.inst_name, v_fullinfo_department.dep_name, access from (
	 select inst_id,taginstid = any('{{$_SESSION['alltagidallow']}}'::integer[]) as alldep,dep_id, sum((tagdepid = any('{{$_SESSION['alltagidallow']}}'::integer[]))::integer) over (partition by inst_id) as nbr, 1 as access
	 from v_taglink_instdep  where taginstid = any('{{$_SESSION['alltagidallow']}}'::integer[]) or tagdepid = any('{{$_SESSION['alltagidallow']}}'::integer[]) and instordepremoved  = false union select inst_id, taginstid = any('{{$_SESSION['alltagidallow']}}'::integer[]) as alldep,dep_id, sum((tagdepid = any('{{$_SESSION['alltagidallow']}}'::integer[]))::integer) over (partition by inst_id) as nbr, 0 as access
	 from v_taglink_instdep where taginstid not in ({$_SESSION['alltagidallow']}) and tagdepid not in ({$_SESSION['alltagidallow']}) and instordepremoved  = false) theaccess,v_fullinfo_department where theaccess.inst_id = v_fullinfo_department.inst_id and v_fullinfo_department.dep_id = theaccess.dep_id and instordepremoved = false order by v_fullinfo_department.inst_name, v_fullinfo_department.dep_name;";
	 
	$conn = get_dbconnection();

	$arr = array ();

	if ( $query = pg_query ( $conn, $psql) )
	{
		while ( $row = pg_fetch_row($query) )
		{
	        $res = array ( 
	        		"inst_id" 		=> $row [0],
	        		"institution" 	=> $row [1],
	        		"department" 	=> $row [2], 
	        		"access" 		=> $row [3]
	        	);

	        array_push ( $arr, $res );
		}
	}
	
	header('Content-type: application/json');
	
	$result = json_encode ( $arr );

	echo $result;
 
?>