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

// Performing SQL query
//$query = "SELECT distinct on (camid) camid, filepath FROM camdb order by camid,dateutc desc";
//$query = "SELECT * FROM cams WHERE active <> false AND lastsuccess IS NOT NULL AND (EXTRACT(EPOCH FROM (current_timestamp - lastsuccess ))/60) < (interval + 20) order by elevation desc";
//$query = "SELECT cwa,lat,lon,lastimage,county,elevation,camid,state,description FROM cams WHERE active <> false AND lastsuccess IS NOT NULL AND (EXTRACT(EPOCH FROM (current_timestamp - lastsuccess ))/60) < (interval + 20) order by elevation desc";
//$query = "SELECT json_build_object('type', 'FeatureCollection','features', json_agg(json_build_object('type','Feature', 'geometry',  ST_AsGeoJSON(WITH subquery_points AS (SELECT geom AS point_geometry FROM cams WHERE active = true and totalfails < 50) SELECT ST_Buffer(point_geometry::geography, 8000) AS circle_geometry FROM subquery_points)))";
//"SELECT json_build_object('type', 'FeatureCollection','features', json_agg(json_build_object('type','Feature', 'geometry',  ST_AsGeoJSON(realgeom)::json,'properties',json_build_object('time',startguess,'county',county,'state',state,'outage',outagen,'lastchange',lastchange,'cause',cause))order by startguess asc)) FROM power WHERE cwa = $1 and active = true"
$query = "WITH subquery_points AS (
    SELECT geom AS point_geometry
    FROM cams
    WHERE active = true and  lastsuccess IS NOT NULL AND (EXTRACT(EPOCH FROM (current_timestamp - lastsuccess ))/60) < 60
)
SELECT jsonb_build_object(
    'type', 'FeatureCollection',
    'features', jsonb_agg(jsonb_build_object(
        'type', 'Feature',
        'geometry', ST_AsGeoJSON(ST_Buffer(point_geometry::geography, 8000))::jsonb
    ))
) AS feature_collection
FROM subquery_points";



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

// Printing results in HTML

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

}
print_r($array[0]['feature_collection']);

// Free resultset
pg_free_result($result);

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