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

	header("Content-Type: text/xml");

	set_time_limit(600);

	$from = '';
	if(isset($_POST['from']))
	{
		$from = $_POST['from'];
	}
	$to = '';
	if(isset($_POST['to']))
	{
		$to = $_POST['to'];
	}

	$fields = '';
	if(isset($_POST['fields']))
	{
		$fields = $_POST['fields'];
	}

	$excluded = "";
	if(isset($_POST['excluded']))
	{
		if ( $_POST['excluded'] != "" )
			$excluded = "and stu_id not in (".$_POST['excluded'].")";
	}

	$imc_filter = '';
	if($_POST['imc'] != '')
	{
		$imc = urldecode ($_POST['imc']);
  		$imc_filter = " and f_get_imc_id(pat_size,pat_weight) in ({$imc})";
	}

	$age_filter = '';
	if($_POST['age'] != '')
	{
    	$ageRanges = [
        	0 => ['min' => 16, 'max' => -1],
        	1 => ['min' => 11, 'max' => 15],
        	2 => ['min' => 6, 'max' => 11],
        	3 => ['min' => 1, 'max' => 5],
        	4 => ['min' => 0, 'max' => 1],
    	];

    	$selectedAges = explode(',', urldecode($_POST['age']) );
    	$ageConditions = [];

    	foreach ($selectedAges as $age) 
    	{
        	if (array_key_exists($age, $ageRanges)) 
        	{
            	$range = $ageRanges[$age];
            	$condition = '';

            	if ($range['min'] != -1) 
            	{
                	if (!empty($condition)) 
                	  	$condition .= " AND ";
                	$condition .= "EXTRACT(year FROM age(studydate,birthdate))::integer >= {$range['min']}";
            	}

            	if ($range['max'] != -1) 
            	{
                	if (!empty($condition)) 
                    	$condition .= " AND ";
                	$condition .= "EXTRACT(year FROM age(studydate,birthdate))::integer <= {$range['max']}";
            	}

            	if (!empty($condition)) 
                	$ageConditions[] = "($condition)";
        	}
    	}

    	if (!empty($ageConditions)) 
    	{
        	$age_filter .= " AND (" . implode(' OR ', $ageConditions) . ")";
    	}
	}

	$modality_filter = '';
	if($_POST['modid'] != '')
	{
		$modalities = urldecode( $_POST['modid'] );
  		$modality_filter = " and mod_id in ({$modalities})";
	}

	$studymaster_filter = '';
	if($_POST['mstuid'] != '')
	{
		$mstuid = urldecode ( $_POST['mstuid'] );
  		$studymaster_filter = " and mstud_id_auto in ({$mstuid})";
	}

	$order = "";
	if(isset($_POST['order']))
	{
		$order = $_POST['order'];
	}

	error_log ( "fields : " .$fields );
	error_log ( "excluded : " .$excluded );
	error_log ( "order : " .$order );

	
	$CSV_delimiter = "DELIMITER ';'";
	$file = 'exportstudy_'.date("Ymdhis").'.csv';
	$filepath = $tmpdir .'/'.$file;

	$sql = 'COPY  (select ' .$fields . ' from v_export_csv where studydate::date >= to_date(\''.$from.'\',\'YYYY-MM-DD\') and studydate::date <= to_date(\''.$to.'\',\'YYYY-MM-DD\')'.$excluded.$imc_filter.$age_filter.$modality_filter.$studymaster_filter.' order by '.$order.') TO \''.$filepath.'\' '.$CSV_delimiter.' CSV HEADER encoding \'latin1\';';

	$conn = get_dbconnection();

	error_log($sql);

	$res = array ( "status"	=> "error" );
	if ( pg_query($conn,$sql) )
	{
		$res = array ( "status"	=> "ok", "file" => $file );
	}
	


	header('Content-type: application/json');
	
	echo json_encode($res);
?>
