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

	$dep_id 	= -1;
	if(isset($_GET['dep_id']) &&  $_GET['dep_id'] != '' && is_int($_GET['dep_id']+1))
		$dep_id	= $_GET['dep_id'];

	$date = '';
	if (isset($_GET['date']) )
		$date = "and coalesce(device_installation.removeddate::date,to_timestamp('31/12/2999','DD/MM/YYYY')::date) >= to_timestamp('{$_GET['date']}','DD/MM/YYYY')::date and device_installation.installdate::date <= to_timestamp('{$_GET['date']}','DD/MM/YYYY')::date";

			
	$conn = get_dbconnection();
	
	$answer = "<devices>";
	
	if ( $conn )
	{
		$sql = "select device.name as name, device.id as id from device,device_installation where device.id = device_installation.device_id and device_installation.removed = false
		 and device_installation.dep_id = {$dep_id} {$date}";

		if(!isset($_GET['noundef']) || $_GET['noundef'] == '0')
			$sql.= " union select device.name as name,device.id from device where id = -1";

		if ( $query = pg_query($conn,$sql) )
		{
			while ( $row = pg_fetch_row($query) )
			{
				$answer .= "<device device=\"".$row[0]."\" id=\"".$row[1]."\"></device>";
			}
		}
	}
	
	$answer .= "</devices>";

	header ('Content-type: text/xml' );
	
	echo $answer;
?>