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

	$result = array (
			"status"	=> 'KO',
			"results"	=> array ()
	);
	

	$pdo = getPDO ();
	
	if ( $pdo )
	{
		$s0 = $pdo->prepare ( "select id, name from staff_role where removed = false order by name" );

		if ( $s0->execute () )
		{
			$result['status'] ='OK';

			$jobs = array ();

			$d0 = $s0->fetchAll ( PDO::FETCH_ASSOC );

			for ( $i=0; $i<count($d0); $i++ )
			{	
				$job = array ( 	"id" 	=> $d0[$i]['id'],
								"name"	=> $d0[$i]['name'] );

				array_push ( $jobs, $job );
			}

			$s1 = $pdo->prepare ( "select id, name from institution where removed = false order by name" );

			if ( $s1->execute () )
			{
				$d1 = $s1->fetchAll ( PDO::FETCH_ASSOC );

				for ( $i=0; $i<count($d1); $i++ )
				{
					$inst_id = $d1 [$i]['id'];

					$res = array (		"text" => $d1[$i]['name'],
										// "ident"	=> $inst_id,
										"expanded" => true,
										"checked" => true,
										"nodes" => array() );

					$s2 = $pdo->prepare ( "select id, name from department where inst_id=:inst_id and removed = false order by name" );
					$s2->bindParam ( ':inst_id', $inst_id );

					if ( $s2->execute () )
					{	
						$d2 = $s2->fetchAll ( PDO::FETCH_ASSOC );

						for ( $j=0; $j<count($d2); $j++ )
						{
							$r2 = array ( 	"text" => $d2[$j]['name'],
											// "ident" => $d2[$j]['id'],
											"expanded" => true,
											"nodes" => array () );

							for ( $k=0; $k<count($jobs); $k++ )
							{
								$ident = $d2[$j]['id'] . "_" . $jobs[$k]['id'] ;
								array_push ( $r2['nodes'], array ( "text" => $jobs[$k]['name'], "ident" => $ident ) );
							}

							array_push ( $res['nodes'], $r2 );
						}
					}

					array_push ( $result['results'], $res );
				}
			}
		}
	}





	header('Content-type: application/json');
	
	echo json_encode ( $result );
?>