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

$dbconn = getDBConnection();

// Get POST data
$camid = $_POST['camid'];
$field = $_POST['field'];
$value = $_POST['value'];

// Validate inputs
if (empty($camid) || empty($field)) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit;
}

// Check if the field is valid
if (!in_array($field, ['hydro', 'airport'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid field']);
    exit;
}

// Convert to proper boolean for PostgreSQL
// JavaScript sends true/false as strings 'true' or 'false'
$value_bool = ($value === 'true');

// Update the field value in the database - use boolean directly
// PostgreSQL accepts 't'/'f' for boolean values
$query = "UPDATE cams SET $field = $1 WHERE camid = $2";
$result = pg_query_params($dbconn, $query, array($value_bool ? 't' : 'f', $camid));

if ($result) {
    echo json_encode(['success' => true]);
} else {
    $error = pg_last_error($dbconn);
    echo json_encode(['success' => false, 'message' => $error]);
}

// Closing connection
if (isset($dbconn)) {
    pg_close($dbconn);
}
?>