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

	RightsCheck ("VIEW_DEVICE");


	$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='';
  
  	if(isset($_GET['deviceid']))
  {
     $whereclause = "and device_id = {$_GET['deviceid']}";
  }else {
    $whereclause = "and device_id = -1";
  }

	$psql = "select device_inspection.id as id,s2.status_name as result_name,s1.status_name as status_name,device_id,to_char(inspection_date,'YYYYMMDD') as inspection_date,to_char(planned_date,'YYYYMMDD') as planned_date,result,device_inspection.type as type,status_id,comment,listofactiondescription from statuslist as s1, statuslist as s2,device_inspection 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 = 'device_inspection' group by ext_id) actionlink on actionlink.ext_id = device_inspection.id where s2.id = device_inspection.result and s1.id = device_inspection.status_id and device_inspection.removed = false {$whereclause}"
		;

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