<?php
$dbconn = pg_connect("host=localhost dbname=nws user=nws password=nws")
    or die('Could not connect: ' . pg_last_error());

$camid = pg_escape_string($_GET['camid'] ?? null);

if($_GET['dtg'] ?? null){
$endtime = pg_escape_string($_GET['dtg']);
if($_GET['camimages']){
$camimages = $_GET['camimages'];
}
if(!$_GET['camimages'] ?? null){
$camimages = 20;
}

$query = "SELECT camid, filepath, date_trunc('second', dateutc) as dateutc FROM camdb where camid = '{$camid}' and dateutc < '{$endtime}' order by dateutc desc limit '{$camimages}'";
} 

$camimages = 20;


//if(!$_GET['dtg'] ?? null){
//if ($_GET['dtg'] == null) {
if (!isset($_GET['dtg'])) {

if($_GET['camimages'] ?? null){
$camimages = $_GET['camimages'];
}


$query = "SELECT camid, filepath, date_trunc('second', dateutc) as dateutc FROM camdb where camid = '{$camid}' order by dateutc desc limit '{$camimages}'";
} 




//$query = "SELECT camid, filepath, date_trunc('second', dateutc) as dateutc FROM camdb where camid = '{$camid}' order by dateutc desc limit 20";

$result = pg_query($query) or die('Query failed: ' . pg_last_error());


while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
    $array[] = $line;

}
echo json_encode($array);

// Free resultset
pg_free_result($result);

// Closing connection
pg_close($dbconn);
?>
