<?php
require_once __DIR__ . '/common.php';

$dbconn = getDBConnection();

$camid = getParam('camid');

if(getParam('dtg')){
    $endtime = getParam('dtg');
    if(isset($_GET['camimages'])){
        $camimages = $_GET['camimages'];
    }
    if(!isset($_GET['camimages'])){
        $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(!isset($_GET['dtg'])) {
if (!isset($_GET['dtg'])) {
    if(isset($_GET['camimages'])){
        $camimages = $_GET['camimages'];
    }

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

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

// Close database connection when needed
if (isset($dbconn)) {
    pg_close($dbconn);
}
?>