<?php

	include '../../autoload.php';

	$sql = "update joblist set status = 1, starttime = to_char(now(),'YYYYMMDDHH24MISS'),response=null where job_id = {$_GET["jobid"]} returning info1;";
	$conn = get_dbconnection();
	$stuid = '-1';
	$status = '2';
	$data = '';
	if($query = pg_query($conn,$sql))
	{
		if($row = pg_fetch_row($query)){
				$stuid = $row[0];
			}else{
				error_log("failed:".$sql);
				$status = "3";
			}

	}else{
		$status = "3";
	}

	$command="-k|(0008,0052)=STUDY|-k|(0008,0061)|-k|PatientName|-k|PatientID|-k|PatientSex|-k|PatientBirthDate|-k|StudyDescription|-k|AccessionNumber|-k|Modality|-k|(0020,1209)|-k|StudyDate|-k|StudyInstanceUID=$stuid|-aet|".$GLOBALS['dacsquery_aet']."|-aec|".$GLOBALS['serverquery_aet']."|".$GLOBALS['serverquery_ip']."|".$GLOBALS['serverquery_port']."|\n";

	error_log($command);
	if( isset($GLOBALS['eoquery_ip'])){
		$address=$GLOBALS['eoquery_ip'];
	}else{
		$address="127.0.0.1";
	}

	$service_port=8975;
	if( isset($GLOBALS['eoquery_port'])){
		$service_port=$GLOBALS['eoquery_port'];
	}

	 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
	 if ($socket === false) {
	 		$status = "3";
	 }
	 $result = socket_connect($socket, $address, $service_port);
	 if ($result === false) {
		error_log("socket_connect() a échoué : raison : ($result) " . socket_strerror(socket_last_error($socket)) . "\n");
		//socket_shutdown($socket, 2);
		socket_close($socket);
		$status = "3";
	 }

	$buffer="<data>";
	if($status != "3")
	{
		 socket_write($socket, $command, strlen($command));
		 $xmlstr="";
		 while ($out = socket_read($socket, 2048)) {
				$xmlstr.=$out;
		 }
		 socket_shutdown($socket, 2);
	 	 socket_close($socket);
		//error_log($xmlstr);

		/*$xmlstr = '<responses type="C-FIND">
<data-set xfer="1.2.840.10008.1.2" name="Little Endian Implicit">
<element tag="0008,0020" vr="DA" vm="1" len="8" name="StudyDate">20200701</element>
<element tag="0008,0050" vr="SH" vm="1" len="10" name="AccessionNumber">43477408_1</element>
<element tag="0008,0052" vr="CS" vm="1" len="6" name="QueryRetrieveLevel">STUDY</element>
<element tag="0008,0054" vr="AE" vm="1" len="16" name="RetrieveAETitle">SynapseDicomSCP</element>
<element tag="0008,0060" vr="CS" vm="0" len="0" name="Modality"></element>
<element tag="0008,0061" vr="CS" vm="1" len="2" name="ModalitiesInStudy">CR</element>
<element tag="0010,0010" vr="PN" vm="1" len="22" name="PatientName">MEMIC NEE DURAKOVIC^AMIRA</element>
<element tag="0010,0020" vr="LO" vm="1" len="8" name="PatientID">585947685n</element>
<element tag="0010,0040" vr="CS" vm="1" len="2" name="PatientSex">F</element>
<element tag="0010,0030" vr="DA" vm="1" len="8" name="PatientBirthDate">19760106</element>
<element tag="0020,000d" vr="UI" vm="1" len="60" name="StudyInstanceUID">1.2.840.113845.11.1000000001951524609.20200810132430.5617178</element>
</data-set>
</responses>';*/

		//$xml=simplexml_load_string(utf8_encode($xmlstr));
		if (!preg_match('!!u', $xmlstr))
		{
		   // Definitely not UTF-8
		   $xmlstr = utf8_encode($xmlstr);
		}
		$xml=simplexml_load_string($xmlstr);
		$studies=$xml->xpath("//data-set");
		$i=0;
		$buffer2="<studies>";
		foreach ($studies as $study) {
		  	$acn=$study->xpath("element[@name='AccessionNumber']/text()")[0];
			$bdate=$study->xpath("element[@name='PatientBirthDate']/text()")[0];
			$pname=$study->xpath("element[@name='PatientName']/text()")[0];
			$patsex=$study->xpath("element[@name='PatientSex']/text()")[0];
			$patid=$study->xpath("element[@name='PatientID']/text()")[0];
			$suid=$study->xpath("element[@name='StudyInstanceUID']/text()")[0];
			$studydescription=$study->xpath("element[@name='StudyDescription']/text()")[0];
			$buffer2.="<study><id>{$suid}</id><acn>".htmlspecialchars($acn)."</acn>";
			$buffer2.="<patid>{$patid}</patid><sex>".$patsex."</sex><name>".htmlspecialchars($pname)."</name><birthdate>{$bdate}</birthdate><studydescription>".htmlspecialchars($studydescription)."</studydescription>";
			$buffer2.="</study>";
		}
		$buffer2.="</studies>";
		//error_log("buffer debut");
		//error_log($buffer2);
		//error_log("buffer fin");
		$xmlObject = simplexml_load_string($buffer2);

		if ($xmlObject === false) {
			error_log("Erreur lors du chargement de la chaîne XML en SimpleXMLElement");
			$status = 3;
		} else {

			$jsondata = json_encode($xmlObject, JSON_FORCE_OBJECT);

			if ($jsondata === null) {
				error_log("Erreur lors de l'encodage JSON");
				$status = 3;
			} else {
				/*$jsondata = json_encode(simplexml_load_string($buffer2),JSON_FORCE_OBJECT);
				$jsondata = str_replace('{}', '""', $jsondata);
				$jsondata = str_replace("'", "''", $jsondata);*/
				//$array = json_decode($jsondata,TRUE);
				$jsondata = str_replace('{}', '""', $jsondata);
				$jsondata = str_replace("'", "''", $jsondata);
				$buffer .= $buffer2;
				$sql = "update joblist set response='{$jsondata}' where job_id = {$_GET["jobid"]};";
				pg_query($conn,$sql);
				$sql = "select f_update_study_from_query({$_GET["jobid"]});";
				if($query = pg_query($conn,$sql))
				{
					if($row = pg_fetch_row($query))
					{
						$data .= "<dbupdatemessage>".$row[0]."</dbupdatemessage>";
					}
				}else{
					error_log("Failed to execute:".$sql);
					$status = 3;
				}
			}
		}

	}

	$sql = "update joblist set status = {$status}, endtime = to_char(now(),'YYYYMMDDHH24MISS'),remaining = coalesce(remaining-1,0) where job_id = {$_GET["jobid"]}";
	pg_query($conn,$sql);


	$buffer.="<status>{$status}</status>";
	$data .= "<jobid>".$_GET["jobid"]."</jobid>";
	$buffer.= $data;
	$buffer.= "</data>";

	$data =	htmlspecialchars($data);

	header('Content-Type: text/xml; charset=UTF-8');
	echo $buffer;
	// $jsondata = json_encode(simplexml_load_string($buffer));
	// echo  $jsondata;
	// $array = json_decode($jsondata,TRUE);

?>
