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

header('Content-Type: application/json');

$dbconn = getDBConnection();

// Check if camid is actually set to avoid warnings
if (!isset($_GET['camid'])) {
    echo json_encode(array("error" => "No camid specified"));
    exit;
}

$camid = $_GET['camid'];

// Performing SQL query
$query = "SELECT *, COALESCE(hydro, false) as hydro, COALESCE(airport, false) as airport FROM cams WHERE camid = $1";

// Use pg_query_params to safely bind the $camid variable
$result = pg_query_params($dbconn, $query, array($camid))
    or die('Query failed: ' . pg_last_error());

// Processing results
$array = array();
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
    // Ensure hydro is a proper boolean
    $line['hydro'] = ($line['hydro'] === 't' || $line['hydro'] === true);
    // Ensure airport is a proper boolean
    $line['airport'] = ($line['airport'] === 't' || $line['airport'] === true);
    $array[] = $line;
}

// Output the ORIGINAL full array (including errorcode) to the client
echo json_encode($array);

// Free resultset
pg_free_result($result);

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