<?php
require_once("../../base/php/startSession.php");
require_once( "../../base/php/Functions.php" );
require_once("../../base/php//classDatabase.php");

	
	$import_id = @$_POST["import_id"];
	if ($import_id == "") {
		$import_id = @$_GET["import_id"];
	}
	$import_id = $import_id + 0;
	
	$data_type = @$_POST["data_type"];
	if ($data_type == "") {
		$data_type = @$_GET["data_type"];
	}
	
	$data_type2 = $data_type;
	if ($data_type == "FCPLPP") {
		$data_type2 = "FCP";
	}
	
	$dbname = @$_POST["dbname"];
	if ($dbname == "") {
		$dbname = @$_GET["dbname"];
	}
	
	$dbuser = @$_POST["dbuser"];
	if ($dbuser == "") {
		$dbuser = @$_GET["dbuser"];
	}
	
	$dbpassword = @$_POST["dbpassword"];
	if ($dbpassword == "") {
		$dbpassword = @$_GET["dbpassword"];
	}
	
	
	if ($dbname == "") {
		$database = new Database("iCTI");
	}
	else {
		$database = new Database("*NODEF_PG", "localhost", 5432, $dbname, $dbuser, $dbpassword);
	}
	
	$ok_import = FALSE;
	$result  =  $database->exec("SELECT file_path FROM pmsi.p_imports_data WHERE import_id = $import_id AND data_type = '$data_type' AND data_num = 0");
	if ($result != false) {
		$record = $database->nextRecordInto();
		if ($record != FALSE) {
			$file_name = trim($record[0]);
			$ok_import = TRUE;
		}
	}
	
	if ($ok_import == TRUE) {
		if ($file_name == "") {
			$file_name = "$data_type.txt";
		}
	
		header("Pragma: public");
	    header("Expires: 0");
	    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
		header("Content-Type: text/plain");
		header("Content-Disposition: attachment;filename=\"" . basename($file_name) . "\"");

		
		$result = $database->exec("SELECT data FROM pmsi.p_imports_data WHERE import_id = $import_id AND data_type IN ('$data_type', '$data_type2') ORDER by data_num  ");
		$ok = TRUE;
		while ($ok == TRUE) {
			$ok = FALSE;
			$record = pg_fetch_array($result);
			if ($record != FALSE) {
				$ok = TRUE;
				$data = $record[0];
				
				echo  uncompress(pg_unescape_bytea($data));
				
			}
		}

	}
	else {
		header("X-PHP-Response-Code: 404", true, 404);
		echo "Pas de fichier $data_type pour le rapport n° $import_id ";
	}
	
	

             

?>
