<?php
	require_once '../../autoload.php';
	
	// RightsCheck ("VIEW_LOGINROLE");
	
	$acc_id		 		= -1;
	$lastname 			= "";
	$firstname 			= "";
	$login 				= "";
	$password 			= "";
	$email	 			= "";
	$role	 			= -1;
	$lro_id	 			= -1;
	$afg_id				= -1;
	$operator			= "";
		
	
	if ( isset ( $_REQUEST['acc_id'] ) 			)	$acc_id	 		= $_REQUEST['acc_id'];
	if ( isset ( $_REQUEST['lastname'] )		)	$lastname	 	= $_REQUEST['lastname'];
	if ( isset ( $_REQUEST['firstname'] )		)	$firstname	 	= $_REQUEST['firstname'];
	if ( isset ( $_REQUEST['password'] )		)	$password	 	= $_REQUEST['password'];
	if ( isset ( $_REQUEST['login'] )			)	$login		 	= $_REQUEST['login'];
	if ( isset ( $_REQUEST['email'] )			)	$email		 	= $_REQUEST['email'];
	if ( isset ( $_REQUEST['role'] )			)	$role		 	= $_REQUEST['role'];
	if ( isset ( $_REQUEST['lro_id'] )			)	$lro_id		 	= $_REQUEST['lro_id'];
	if ( isset ( $_REQUEST['afg_id'] )			)	$afg_id		 	= $_REQUEST['afg_id'];
	if ( isset ( $_REQUEST['operator'] )		)	$operator	 	= $_REQUEST['operator'];
				
	$conn = get_dbconnection();
	
	$response = -1;
	
	if ( $conn )
	{
		$sql = '';

		if ( $acc_id == -1 )
			$sql = "insert into account(username,role) values ('NewAccount'||'_'||currval(pg_get_serial_sequence('account', 'acc_id')),0) returning acc_id;";
		else
		{
			$sql = "update account";
  			$sql .= " set username = '".$login."'";
  			if($password != '.xim4216:37.')
  			{
    			$password = pg_escape_literal($conn,password_hash($password, PASSWORD_BCRYPT));
    			error_log ( "password : " .$password );
    			$sql .= ",password = ".$password;
  			}

  			$sql .= ",firstname = '".$firstname."'";
  			$sql .= ",lastname = '".$lastname."'";
  			$sql .= ",mail = '".$email."'";
  			$sql .= ",role = '".$role."'";
  			if ( $lro_id == '')
    			$sql .= ",loginrole_id = null";
  			else
    			$sql .= ",loginrole_id = ".$lro_id;

    		if($afg_id == '')
      			$sql .= ",alertfilter_group_id = null";
    		else
      			$sql .= ",alertfilter_group_id = ".$afg_id;

  			$sql .= ",operator = ".$operator."::boolean";
  			$sql .= " where acc_id =  ".$acc_id.";commit;";
		}

		error_log ( "sql : " .$sql);
		
		$result = pg_query ( $conn, $sql );
		
		if ( $result )
		{
			if ( $acc_id == -1 )
			{
				if ( $row = pg_fetch_row($result) )
					$response = $row [0];
			}
			else
				$response = $acc_id;
		}
	}
	
	header ('Content-type: text/xml' );
	
	echo $response;
?>