<?php
	require_once '../../autoload.php';
	
	require( '../GetDataFromDB.php' );

	// session_start();	


	$toProcess = true;
	
	$draw			= $_GET ['draw'];
	$start			= $_GET ['start'];
	$length			= $_GET ['length'];
	
	$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']);
	}

	$whereclause = '';
  
  	$status_id		= -1;
  	if(isset($_GET['status_id']))			$status_id = $_GET['status_id'];

  	$title 			= '';
  	if(isset($_GET['title']))  				$title 	= $_GET['title'];

  	/*
  	$begindatefrom 	= '';
  	$begindateto 	= '';

  	if(isset($_GET['begindatefrom']))  		$begindatefrom 	= $_GET['begindatefrom'];
  	if(isset($_GET['begindateto']))  		$begindateto 	= $_GET['begindateto'];

  	if ( $begindatefrom != '' )
  		$whereclause .= " and audit.date >= to_timestamp('{$begindatefrom} 00:00:00', 'DD/MM/YYYY HH24:MI:SS')";
  	if ( $begindateto != '' )
  		$whereclause .= " and audit.date <= to_timestamp('{$begindateto} 23:59:59', 'DD/MM/YYYY HH24:MI:SS')";
  	*/

  	if ( $status_id != -1 )
  		$whereclause .= " and status=".$status_id;


	$psql = "select sub.id, title, sub.type, status, to_char(begindate,'YYYYMMDD') as begindate, to_char(enddate,'YYYYMMDD') as enddate, description, comment, conclusion, survey_type.name as survey_type, statuslist.status_name as status_name, listofactiondescription from (select * from survey left join (select ext_id,string_agg('&#x2022; '||description,'\n') as listofactiondescription from action,action_link where action.id = action_link.action_id and action_link.scope = 'survey' group by ext_id) actionlink on actionlink.ext_id = survey.id) sub,survey_type,statuslist where sub.removed =false and sub.type=survey_type.id and sub.status=statuslist.id and title ilike '%".$title."%' $whereclause";

	error_log ( "psql : " .$psql );

	$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,
			"sql"			  => $psql.$orderby.$limit
	);

	$result = json_encode ( $arr );

	echo $result;
	
 
?>