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

	$result = array (
			"status"	=> 'KO',
			"results"	=> -1
	);
	
	$pdo = getPDO ();
		
	if ( $pdo )
	{
		$inst_id 	= -1;
		$name 		= "";
		$prefix		= "";
		$address	= "";
		$contact	= NULL;
		$radiophy	= NULL;
		
		if ( isset($_POST['inst_id']) )		$inst_id 	= $_POST['inst_id'];
		if ( isset($_POST['name']) )		$name 		= $_POST['name'];
		if ( isset($_POST['prefix']) )		$prefix 	= $_POST['prefix'];
		if ( isset($_POST['address']) )		$address 	= $_POST['address'];
		if ( isset($_POST['contact']) )		$contact	= $_POST['contact'];
		if ( isset($_POST['radiophy']) )	$radiophy	= $_POST['radiophy'];

		error_log ( "inst_id : " .$inst_id );

		if ( $inst_id == -1 )
		{
			$sql = "insert into institution ( name ) values ('New institution') returning inst_id;";

			$s0 = $pdo->prepare ( $sql );
		}
		else
		{
			$sql = 'update institution';
 			$sql .= ' set name = :name';
			$sql .= ' ,prefix_id = :prefix';
			$sql .= ' ,address = :address';
			$sql .= ' ,contact_acc_id = :contact';
			$sql .= ' ,radiophysicist_acc_id = :radiophy';
			$sql .= ' where inst_id = :inst_id';

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

			$s0->bindParam ( ':inst_id', 	$inst_id 	);
			$s0->bindParam ( ':name', 		$name 		);
			$s0->bindParam ( ':prefix',		$prefix		);
			$s0->bindParam ( ':address',	$address	);
			$s0->bindParam ( ':contact', 	$contact 	);
			$s0->bindParam ( ':radiophy', 	$radiophy 	);
		}	

		
		
		if ( $s0->execute () == true )
		{
			$result['status'] = 'OK';
			if ( $inst_id == -1 )
				$result['results'] = $s0->fetchColumn ();
			else
				$result['results'] = $inst_id;
		}
	}
	
	header('Content-type: application/json');
	
	echo json_encode ( $result );
?>