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

	$result = array (
			"status"	=> 'KO',
			"results"	=> array ()
	);
	
	$pdo = getPDO ();
		
	if ( $pdo )
	{
		$recdate_from			= '';
		$recdate_to				= '';
		$modalitytitle			= '';
		$patientname 			= '';
		$stationname 			= '';
		$status		 			= -1;
		$integration_error 		= '';
		$integration_message 	= '';

		if ( isset ($_POST ['recdate_from'] ) )			$recdate_from			= $_POST['recdate_from'];
		if ( isset ($_POST ['recdate_to'] ) )			$recdate_to				= $_POST['recdate_to'];
		if ( isset ($_POST ['modalitytitle'] ) )			$modalitytitle			= $_POST['modalitytitle'];
		if ( isset ($_POST ['patientname'] ) ) 			$patientname 			= $_POST['patientname'];
		if ( isset ($_POST ['stationname'] ) ) 			$stationname 			= $_POST['stationname'];
		if ( isset ($_POST ['status'] ) ) 				$status 				= $_POST['status'];
		if ( isset ($_POST ['integration_error'] ) ) 	$integration_error 		= $_POST['integration_error'];
		if ( isset ($_POST ['integration_message'] ) ) 	$integration_message	= $_POST['integration_message'];

		$whereclause = " and to_char(recdate,'YYYY-MM-DD') >= '{$recdate_from}'";
		$whereclause .= " and to_char(recdate,'YYYY-MM-DD') <= '{$recdate_to}'";
		if ( $stationname != "" )
			$whereclause .= " and source || '('|| stationname||')' ilike '%{$stationname}%'";
		if ( $modalitytitle != '' )
			$whereclause .= " and modalitytitle ilike '{$modalitytitle}%'";
		if ( $patientname != "" )
			$whereclause .= " and patientname ilike '{$patientname}%'";
		if ( $status != -1 )
			$whereclause .= " and status = {$status}";
		if ( $integration_error != "" )
			$whereclause .= " and integration_error ilike '{$integration_error}%'";
		if ( $integration_message != "" )
			$whereclause .= " and integration_message ilike '{$integration_message}%'";

		$sql =	"select 
					min(sto_id) as sto_id 
			from 
				storagelist 
			where 
				1=1 {$whereclause} group by stuid,source || '('|| stationname||')',modalitytitle,patientname,status,integration_error,integration_error,integration_message";

		error_log ( "LIST : " .$sql );

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

		if ( $s0->execute () )
		{
			$result['status'] ='OK';

			$d0 = $s0->fetchAll ();

			for ( $i=0; $i<count($d0); $i++ )
			{
				$res = array (	"sto_id" 			=> $d0[$i]['sto_id'] );

				array_push ( $result['results'], $res );
			}
		}
	}
	
	header('Content-type: application/json');
	
	echo json_encode ( $result );
?>