<?php
	require_once '../autoload.php';
	
	function ColorAlert($tab)
  	{
		$level = 4;
		$conn = get_dbconnection();

		switch($tab)
		{
			case 'VIEW_AUDIT'  :
						$level = 0;
						$sql = "select level from v_alert_audit left join tag_link tli on tli.type = 'institution' and tli.ext_id = inst_id left join tag_link tld on tld.type='department' and tld.ext_id = dep_id
						where  coalesce(tld.tag_id,tli.tag_id) = any('{{$_SESSION['alltagidallow']}}'::integer[]) order by level desc limit 1";
						break;
			case 'VIEW_DEVICE' :
						$level = 0;
						$sql = "select level from v_alert_device_inspection alert,v_device_actif_by_deptagid vdabd where alert.id = vdabd.device_id
						and tag_id = any('{{$_SESSION['alltagidallow']}}'::integer[]) order by level desc limit 1";
						break;
			case 'VIEW_STAFF'  :
						$level = 0;
						$sql = "select level from v_alert_staff_formation vf,v_staffmember_taglistdep_active_staffjob vm
						where vm.staff_id  = vf.staff_id and taglistdep_id && '{{$_SESSION['alltagidallow']}}'::integer[] order by level desc limit 1";
						break;
			case 'VIEW_DOSIMETRY':
						$level = 0;
						$sql = "select level from v_alert_afcnsend vaa left join tag_link on tag_link.type = 'department'
						and tag_link.ext_id = vaa.dep_id, department where department.id = vaa.dep_id and vaa.dep_id != -1 and tag_id = any('{{$_SESSION['alltagidallow']}}'::integer[])order by level desc limit 1";
						break;
			case 'VIEW_INCIDENTREPORTING':
						$level = 0;
						$sql = "select severity from v_alert_report left join v_taglink_instdep on v_alert_report.dep_id = v_taglink_instdep.dep_id
						where tagdepid is null or tagdepid = any('{{$_SESSION['alltagidallow']}}'::integer[]) order by severity desc limit 1";
						break;
			case 'VIEW_SCHEDULEDTASK':
						$level = 0;
						$sql = "select level from v_alert_action vac left join tag_link on tag_link.type = 'department' and tag_link.ext_id = vac.dep_id, department where
						department.id = vac.dep_id and (department.removed  = false or department.id = -1) and (department.id = -1 or tag_id = any('{{$_SESSION['alltagidallow']}}'::integer[])) order by level desc limit 1";
						break;
			default:	$level = -1;																							break;
		}

		if(empty($sql) == FALSE)
		{
			if($query = pg_query($conn,$sql))
			{
				while($row = pg_fetch_row($query))
				{
					$level = $row[0];
				}
			}
		}

		$arr = array ( 'Alert' => $level );

		return json_encode ( $arr );
  	}

  	$tab = $_POST ['tab'];

  	echo ColorAlert ( $tab );
?>