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

	/*
	$doc_master_id 		= $_GET['doc_master_id'];
		
	$conn = get_dbconnection();
	
	$answer = "<documents>";
	
	if ( $conn )
	{
		$sql ="select document.id, label, comment, revision, to_char(creation_date,'DD/MM/YYYY') as creation_date, documentstatus.status_id, begdate, enddate, statuslist.status_name, document.removed from document,documentstatus, statuslist where document.id=documentstatus.doc_id and documentstatus.status_id=statuslist.id and document.removed=false and doc_master_id=".$doc_master_id.";";

		error_log ( "get_document_version : " .$sql );

		if ( $query = pg_query($conn,$sql) )
		{
			while ( $row = pg_fetch_row($query) )
			{
				$answer .= "<document id=\"".$row[0]."\" label=\"".$row[1]."\" comment=\"".$row[2]."\" revision=\"".$row[3]."\" creation_date=\"".$row[4]."\" status_name=\"".$row[8]."\"></document>";
			}
		}
	}
	
	$answer .= "</documents>";

	header ('Content-type: text/xml' );
	
	echo $answer;
	*/


	$result = array (
			"status"	=> 'KO',
			"results"	=> array ()
	);

	$doc_master_id 		= $_POST['doc_master_id'];

	$pdo = getPDO ();

	if ( $pdo )
	{
		$sql ="select document.id, label, comment, revision, to_char(creation_date,'DD/MM/YYYY') as creation_date, documentstatus.status_id, to_char(begdate, 'DD/MM/YYYY HH24:MI') as begdate, to_char(enddate, 'DD/MM/YYYY HH24:MI') as enddate, statuslist.status_name, document.removed, document.type as extension from document,documentstatus, statuslist where document.id=documentstatus.doc_id and documentstatus.status_id=statuslist.id and document.removed=false and doc_master_id=:doc_master_id order by revision desc, enddate desc;";

		error_log ( "sql : " .$sql );
		error_log ( "doc_master_id : " .$doc_master_id );
		
		$s0 = $pdo->prepare ( $sql );
		$s0->bindParam ( ":doc_master_id", $doc_master_id );

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

			$d0 = $s0->fetchAll ( PDO::FETCH_ASSOC );
			error_log ( "count : ".count($d0) );
			for ( $i=0; $i<count ( $d0 ); $i++ )
				array_push ( $result['results'], array ( 	'doc_id' 			=> $d0[$i]['id'],
															'label'				=> $d0[$i]['label'],
															'comment'			=> $d0[$i]['comment'],
															'revision'			=> $d0[$i]['revision'],
															'creation_date'		=> $d0[$i]['creation_date'],
															'status_begin_date'	=> $d0[$i]['begdate'],
															'status_end_date'	=> $d0[$i]['enddate'],
															'status_name'		=> $d0[$i]['status_name'],
															'extension'			=> $d0[$i]['extension'],
															'status_id'			=> $d0[$i]['status_id'] ) );
		}
	}
	
	header('Content-type: application/json');
	
	echo json_encode ( $result );
?>