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

	RightsCheck ("VIEW_DEVICE");

	error_log ( "========================================================================");
	error_log ( "=== GetDeviceList ===========================================================");

	// $included		= $_GET ['included'];	
	$type 			= $_GET ['type'];
	$name 			= $_GET ['name'];
	$brand 			= $_GET ['brand'];
	$modalitytype 	= $_GET ['modalitytype'];

	$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['excluded']) && $_GET['excluded'] == 1 ) 
		$whereclause = " and device.type != {$type}";
	else
		$whereclause = " and device.type = {$type}";
  	*/

	if ( isset($_GET['excluded']) && $_GET['excluded'] == 1 ) 
	{
		if ( $type == -1 )
			$whereclause = " and device.type != 0";
		else
			$whereclause = " and device.type = {$type}";
	}
	else
		$whereclause = " and device.type = {$type}";

  	if(isset($_GET['deviceid']))
  	{
     	$whereclause .= " and device.id = {$_GET['deviceid']}";
  	}

  	if(isset($_GET['taglist']) && $_GET['taglist'] != '')
  	{
    	if(isset($_GET['idtaglistand']) && $_GET['idtaglistand'] != '')
      		$whereclause .= "and ((alltagidallow||alltagidinducedallow)@> '{{$_GET['idtaglistand']}}'::integer[])";

    	if(isset($_GET['idtaglistor']) && $_GET['idtaglistor'] != '')
      		$whereclause .= " and tag_id = any('{{$_GET['idtaglistor']}}'::integer[])";
  	}
  	/*
	$psql = "select 
				id, 
				depname, 
				name, 
				type,
				typename, 
				brand, 
				model, 
				serialnumber, 
				ris_name, 
				pacs_name, 
				dacs_name, 
				modalitytype, 
				deviceactif 
			from ( 
				with temp as 
					(
					select 
						device.id,
						string_agg(distinct case when is_actif = true then depname else null end,', ') as depname , 
						device.name as name,
						device.type as type,
						device.brand as brand,
						device.model as model,
						device.serialnumber as serialnumber, 
						ris_name, 
						pacs_name, 
						dacs_name,
						modalitytype,
						coalesce(bool_or(v_device_actif_by_deptagid.tag_id = any ('{{$_SESSION['alltagidallow']}}'::integer[]) and is_actif)::integer,0) as deviceactif,
						devicetypelist.name as typename
					from 
						device 
					left join 
						devicetypelist
					on 
						device.type=devicetypelist.id 
					left join 
						v_device_actif_by_deptagid 
					on 
						device.id = v_device_actif_by_deptagid.device_id 
					left join
						v_device_historyinstallationdeptagidlist 
					on 
						v_device_historyinstallationdeptagidlist.device_id = device.id
					where 
						device.removed = false and 
						(depidlist is null or deptagidlist && '{{$_SESSION['alltagidallow']}}'::integer[]) {$whereclause}
					group by 
						device.id,
						device.name,
						device.brand,
						device.model,
						device.serialnumber, 
						ris_name, 
						pacs_name, 
						dacs_name, 
						modalitytype,
						deptagidlist,
						depidlist,
						typename
					) 
					select * from temp ) sub where modalitytype ilike '%".$modalitytype."%' and name ilike '%".$name."%' and brand ilike '%".$brand."%'";
	*/

	$psql = "with r as (select 
				id, 
				depname,
				depid, 
				name, 
				type,
				typename, 
				brand, 
				model, 
				serialnumber, 
				ris_name, 
				pacs_name, 
				dacs_name, 
				modalitytype, 
				deviceactif 
			from ( 
				with temp as 
					(
					select 
						device.id,
						string_agg(distinct case when is_actif = true then depname else null end,', ') as depname ,
						depidlist[1] as depid,
						device.name as name,
						device.type as type,
						device.brand as brand,
						device.model as model,
						device.serialnumber as serialnumber, 
						ris_name, 
						pacs_name, 
						dacs_name,
						modalitytype,
						coalesce(bool_or(v_device_actif_by_deptagid.tag_id = any ('{{$_SESSION['alltagidallow']}}'::integer[]) and is_actif)::integer,0) as deviceactif,
						devicetypelist.name as typename
					from 
						device 
					left join 
						devicetypelist
					on 
						device.type=devicetypelist.id 
					left join 
						v_device_actif_by_deptagid 
					on 
						device.id = v_device_actif_by_deptagid.device_id 
					left join
						v_device_historyinstallationdeptagidlist 
					on 
						v_device_historyinstallationdeptagidlist.device_id = device.id
					where 
						device.removed = false and 
						(depidlist is null or deptagidlist && '{{$_SESSION['alltagidallow']}}'::integer[]) {$whereclause}
					group by 
						device.id,
						device.name,
						device.brand,
						device.model,
						device.serialnumber, 
						ris_name, 
						pacs_name, 
						dacs_name, 
						modalitytype,
						deptagidlist,
						depidlist,
						typename
					) 
					select * from temp ) sub where modalitytype ilike '%".$modalitytype."%' and name ilike '%".$name."%' and brand ilike '%".$brand."%')
			select 
				r.id,
				institution.name as institution_name,
				institution.id as inst_id, 
				depname, 
				r.name, 
				type,
				typename, 
				brand, 
				model, 
				serialnumber, 
				ris_name, 
				pacs_name, 
				dacs_name, 
				modalitytype, 
				deviceactif
			from  
				r 
			left join 
				department
			on r.depid=department.id 
			left join
				institution
			on department.inst_id=institution.id";

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