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

	RightsCheck ("VIEW_PROCEDURE");
			
	$id 	= $_POST['id'];

	$ret_id = -1;

	$conn = get_dbconnection();

	if ( $id == -1 )
	{
		$sql = 'insert into procedure(name_en,name_fr,name_nl,type) values(\'New procedure\',\'Nouvelle procédure\',\'Nieuwe procedure\',1) returning id;';

		if($query = pg_query($conn, $sql))
		{
			$row = pg_fetch_row($query);
			$ret_id = $row[0];
		}
		else
		{
			error_log("Error SQL {$sql}");
		}
	}
	else
	{
		$name_fr 	= (isset($_POST['name_fr']))? $_POST['name_fr'] : "";
		$name_en 	= (isset($_POST['name_en']))? $_POST['name_en'] : "";
		$name_nl 	= (isset($_POST['name_nl']))? $_POST['name_nl'] : "";
		$comment 	= (isset($_POST['comment']))? $_POST['comment'] : "";
		$type 		= (isset($_POST['type']))? $_POST['type'] : "";
		$listtagid	= (isset($_POST['listtagid']))? $_POST['listtagid'] : "";

		$sql = 'update procedure';
  		$sql .= ' set name_fr = \''.pg_escape_string ( $conn, $name_fr ).'\'';
  		$sql .= ' ,name_en = \''.pg_escape_string ( $conn, $name_en ).'\'';
  		$sql .= ' ,name_nl = \''.pg_escape_string ( $conn, $name_nl ).'\'';
  		$sql .= ' ,comment = \''.pg_escape_string ( $conn, $comment ).'\'';
  		$sql .= ' ,type = '.pg_escape_string ( $conn, $type );
  		$sql .= ' where id =  '.$id.';commit;';

  		$sql .= create_update ( $listtagid, $_SESSION['alltagidallow'], $_SESSION['alltagiddeny'], 'procedure', $id );

  		error_log ( "SaveProcedure : " .$sql );

  		if($query = pg_query($conn, $sql))
		{
			$ret_id = $id;
		}
		else
		{
			error_log("Error SQL {$sql}");
		}
	}

	
				
	header('Content-type: application/json');

	$arr = array (
			"id"          => $ret_id
	);
	
	$result = json_encode ( $arr );

	echo $result;
?>