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

	RightsCheck ("VIEW_DEVICE");
	
	$id		 		= -1;
	$type 			= -1;
	$brand			= "";
	$name			= "";
	$serialnumber	= "";
	$model			= "";
	$ris_name		= "";
	$pacs_name		= "";
	$dacs_name		= "";
	$modalitytype	= "";
		
	if ( isset ( $_POST['id'] ) 			)	$id				 	= $_POST['id'];
	if ( isset ( $_POST['type'] )			)	$type			 	= $_POST['type'];
	if ( isset ( $_POST['brand'] )			)	$brand			 	= $_POST['brand'];
	if ( isset ( $_POST['name'] )			)	$name			 	= $_POST['name'];
	if ( isset ( $_POST['serialnumber'] )	)	$serialnumber	 	= $_POST['serialnumber'];
	if ( isset ( $_POST['model'] )			)	$model			 	= $_POST['model'];
	if ( isset ( $_POST['ris_name'] )		)	$ris_name		 	= $_POST['ris_name'];
	if ( isset ( $_POST['pacs_name'] )		)	$pacs_name		 	= $_POST['pacs_name'];
	if ( isset ( $_POST['dacs_name'] )		)	$dacs_name		 	= $_POST['dacs_name'];
	if ( isset ( $_POST['modalitytype'] )	)	$modalitytype	 	= $_POST['modalitytype'];

	$imageData = NULL;

	if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) 
	{
    	$fileTmpPath = $_FILES['image']['tmp_name'];
	   	$imageData = file_get_contents($fileTmpPath);
    }
			
	$pdo = getPDO ();
	
	$response = -1;
	
	if ( $pdo )
	{
		$sql = '';

		if ( $id == -1 )
		{
			$name = 'New device';
			$brand = 'Brand';
			$sql = 'insert into device(name,brand, type) values(:name,:brand,:type) returning id;';
			$stmt = $pdo->prepare ( $sql );
			$stmt->bindParam ( ':name', $name );
			$stmt->bindParam ( ':brand', $brand );
			$stmt->bindParam ( ':type', $type );
		}
		else
		{
			$sql = 'update device';
  			$sql .= ' set brand = :brand';
  			$sql .= ' ,name = :name';
  			$sql .= ' ,serialnumber = :serialnumber';
  			$sql .= ' ,model = :model';
  			$sql .= ' ,ris_name = :ris_name';
  			$sql .= ' ,pacs_name = :pacs_name';
  			$sql .= ' ,dacs_name = :dacs_name';
  			$sql .= ' ,modalitytype = :modalitytype';
  			$sql .= ' ,type = :type';
  			if ( $imageData  != NULL )
  				$sql .= ', photo = :imageData';
  			$sql .= ' where id =  :id;';

  			$stmt = $pdo->prepare ( $sql );

  			$stmt->bindParam ( ':brand',	 		$brand 			);
  			$stmt->bindParam ( ':name',		 		$name 			);
  			$stmt->bindParam ( ':serialnumber',		$serialnumber 	);
  			$stmt->bindParam ( ':model', 			$model 			);
  			$stmt->bindParam ( ':ris_name',			$ris_name		);
  			$stmt->bindParam ( ':pacs_name',		$pacs_name		);
  			$stmt->bindParam ( ':dacs_name',		$dacs_name		);
  			$stmt->bindParam ( ':modalitytype',		$modalitytype	);
  			$stmt->bindParam ( ':type',				$type			);
  			if ( $imageData  != NULL )
  				$stmt->bindParam ( ':imageData',	$imageData, PDO::PARAM_LOB	);
  			$stmt->bindParam ( ':id',				$id		);
  		}

		$stmt->execute ();
		if ( $id == -1 )
			$response = $stmt->fetchColumn ();
		else
			$response = $id;
	}
	
	header ('Content-type: text/xml' );
	
	echo $response;
?>