<?php
// Tell the browser/client that we are sending JSON data
header('Content-Type: application/json');

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

// 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
// SECURITY FIX: Changed to use $1 placeholder instead of direct variable injection
$query = "SELECT *, COALESCE(hydro, false) as hydro, COALESCE(airport, false) as airport FROM cams WHERE camid = $1";

// SECURITY FIX: 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;
}

// --- LOGGING SECTION START ---

// 1. Create a temporary copy for the logs
$logData = $array;

// 2. Remove the clutter fields from the copy
foreach ($logData as &$row) {
    unset($row['errorcode']); 
    // You can also uncomment the line below if you want to hide the long 'geom' string from logs
    unset($row['geom']);
}
unset($row); // Break the reference

// 3. Log the clean data
// error_log("Single.php response for camid $camid: " . json_encode($logData));

// --- LOGGING SECTION END ---

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

// Free resultset
pg_free_result($result);

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