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

	RightsCheck ("VIEW_DOSIMETRY");

	function Add ( $sender )
	{
		$ret = -1;

		$conn = get_dbconnection();

		$sql = 'insert into afcnsend(title,senddate,sender,status_id,inst_id,dep_id) values (\'New sending\',now(),'.$sender.',3,-1,-1) returning id;';

		if($query = pg_query($conn, $sql))
		{
			$row = pg_fetch_row($query);
			$ret = $row[0];
		}
		else
		{
			error_log("Error SQL {$sql}");
		}

		return $ret;
	}


	function Update ( $id, $status_id, $title, $comment, $inst_id, $dep_id, $device_id, $senddate )
	{
		$ret = -1;

		$conn = get_dbconnection();

		$sql = 'update afcnsend';
		$sql .= ' set status_id = '.$status_id;
		$sql .= ' ,comment = \''.pg_escape_string ($conn,$comment).'\'';
		$sql .= ' ,title = \''.pg_escape_string ($conn,$title).'\'';

		if ( $inst_id != '-1' && $inst_id != '' )
		{
			$sql .= ' ,inst_id = '.$inst_id;
		}
		else
		{
			$sql .= ' ,inst_id = null';
		}

		if ( $dep_id != '-1' && $dep_id != '' )
		{
			$sql .= ' ,dep_id = '.$dep_id;
		}
		else
		{
			$sql .= ' ,dep_id = null';
		}

		if ( $senddate != '')
			$sql .= ' ,senddate = to_timestamp(\''.pg_escape_string ($conn, $senddate).'\',\'YYYY-MM-DD\')';
		else
		{
			$sql .= ' ,senddate = null';
		}

		if ( $device_id != '')
			$sql .= ' ,device_id = '.$device_id;
		else
		{
			$sql .= ' ,device_id = null';
		}

    	$sql .= ' where id =  '.$id.';commit;';
    	error_log ( "Sending update : " .$sql );
    	if($query = pg_query($conn, $sql))
    	{
    		$ret = $id;
    	}

    	return $ret;
	}



	$action = $_POST['action'];
	$ret_id = -1;

	switch ( $action )
	{
		case 'add':
			$ret_id = Add ( $_POST['sender'] );
			break;

		case 'update':
			$ret_id = Update ( $_POST['id'], $_POST['status_id'], $_POST['title'], $_POST['comment'], $_POST['inst_id'], $_POST['dep_id'], $_POST['device_id'], $_POST['send_date'] );	
			break;
	}

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

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

	echo $result;
?>