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

	require( '../GetDataFromDB.php' );


	$toProcess = true;

	// $pat_id		 	= $_GET ['pat_id'];

	$draw			= $_GET ['draw'];
	$start			= $_GET ['start'];
	$length			= $_GET ['length'];

	$orderby 		= "";
	if ( isset ( $_GET ['columns'] ) )
	{
		$columns 		= $_GET ['columns'];
		$order			= $_GET ['order'];

		$orderCol		= $order [0]['column'];
		$orderDir		= $order [0]['dir'];
		$orderColName	= $columns [$orderCol]['data'];
		$orderby		= " ORDER BY ".$orderColName." ".$orderDir;

	}

	$limit = '';


	if ( isset($_GET['start']) && $_GET['length'] != -1 )
	{
		$limit = " OFFSET ".intval($_GET['start'])." LIMIT ".intval($_GET['length']);
	}

	$from = $_GET['from'];
	$to = $_GET['to'];

	$studymaster_filter = '';
	$imc_filter = '';
	$age_filter = '';
	$modality_filter = '';

	if($_GET['mstuid'] != '')
	{
		$mstuid = urldecode ( $_GET['mstuid'] );

  		$studymaster_filter = " and mstud_id_auto in ({$mstuid})";
	}

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

	if($_GET['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($_GET['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) . ")";
	}

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

	/*
	if(isset($_SESSION['filter_modalitylist']) && $_SESSION['filter_modalitylist'] != '')
	{
    	$modality_filter .= " and mod_id in ({$_SESSION['filter_modalitylist']})";
	}
	*/

	$conn = get_dbconnection();

  	$psql = 'select *  from v_export_csv where studydate::date >= to_date(\''.$from.'\',\'YYYY-MM-DD\') and studydate::date <= to_date(\''.$to.'\',\'YYYY-MM-DD\')
  '.$studymaster_filter.$imc_filter.$age_filter.$modality_filter;



		$recordsTotal 		= 1000;
		$recordsFiltered	= 0;

		$data				= Array ();

		if ( $toProcess == true )
				$data = GetDataFromDB ( $psql, $recordsFiltered, $limit, $orderby );

		$arr = array (
				"draw"            => intval( $draw ),
				"recordsTotal"    => intval( $recordsTotal ),
				"recordsFiltered" => intval( $recordsFiltered ),
				"data"            => $data
			);

		$result = json_encode ( $arr );

		echo $result;

?>