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

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

		error_log ( "dep_id : " .$dep_id );

		$s0 = null;

		if ( $dep_id == -1 )
		{
			$sql = "insert into department ( inst_id, name ) values (:inst_id, 'New department') returning dep_id;";

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

			$s0->bindParam ( ':inst_id', 	$inst_id 	);
		}
		else
		{
			$sql = 'update department';
 			$sql .= ' set name = :name';
			$sql .= ' ,type = :type';
			$sql .= ' ,contact_acc_id = :contact';
			$sql .= ' ,radiophysicist_acc_id = :radiophy';
			$sql .= ' where dep_id = :dep_id';

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

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