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

	RightsCheck ("VIEW_AUDIT");	

	error_log ( "### GetAudits ###");


	$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='';
  
  	$fromdate 	= '';
  	$todate		= '';

  	if(isset($_GET['fromdate']))  		$fromdate 	= $_GET['fromdate'];
  	if(isset($_GET['todate']))  		$todate 	= $_GET['todate'];

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

	$psql = "with t as (SELECT DISTINCT ON (audit.id) audit.id, coalesce(audit.inst_id,-1) as inst_id, institution.name as institution, coalesce(audit.dep_id,-1) as dep_id, department.name as department, to_char(date,'YYYYMMDD') as date,
	origine, status_id, statuslist.status_name as status, comment, title,audit.type as audit_type, maintype, to_char(start_date,'YYYYMMDD') as start_date,	to_char(end_date,'YYYYMMDD') as end_date from audit left join v_taglink_instdep on audit.removed = false and v_taglink_instdep.instordepremoved = false and (audit.dep_id = -1 or audit.dep_id = v_taglink_instdep.dep_id) and audit.inst_id = v_taglink_instdep.inst_id ,audit_type, institution, department, statuslist
	where audit.inst_id=institution.id and audit.dep_id=department.id and status_id=statuslist.id and audit.type=audit_type.id and audit.removed = false
	and (tagdepid = any('{{$_SESSION['alltagidallow']}}'::integer[]) or (audit.inst_id = -1 and audit.dep_id = -1) or (audit.inst_id != -1 and tagdepid= any('{{$_SESSION['alltagidallow']}}'::integer[]))) $whereclause ORDER BY audit.id, v_taglink_instdep.tagdepid) select * from t";


	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;
	
 
?>