<?php

require_once '../../autoload.php';

header('Content-Type: application/json; charset=utf-8');

$conn = get_dbconnection();


$use_id=$_SESSION['id'];
$out = array();
$out['status']='KO';

if($conn)
{
	$stu_id=pg_escape_string($conn,$_REQUEST['stuid']);

	$comment=pg_escape_string($conn,$_REQUEST['comment']);
	if($comment !='')
	{
		$sql="insert into ackalert(comment,user_id,validated,stu_id) values ('{$comment}',{$use_id},true,{$stu_id}) returning id;";
	
		if($query=pg_query($conn,$sql))
		{
			if($row=pg_fetch_row($query))
			{
				$ack_id=$row[0];
			
				$sql2="update ackalert set removed=true where id in (select ack_id from alertwarning where stu_id={$stu_id} and removed=false);
				update alertwarning set ack_id={$ack_id} where stu_id={$stu_id} and removed=false;commit;";
		
				if($query2=pg_query($conn,$sql2))
				{
					$out['status']='OK';
				}
				
			}
		}
	}
	else{
		$sql="update ackalert set removed=true where id in (select ack_id from alertwarning where stu_id={$stu_id} and removed=false);
				update alertwarning set ack_id = null where stu_id={$stu_id} and removed=false;commit;";
		if($query=pg_query($conn,$sql))
		{
			$out['status']='OK';
		}
	}
	
}

echo json_encode($out);

?>


