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

$dbconn = getDBConnection();

$action = $_GET['action'];

if ($action == 'checkurl' ) {
    $url = $_POST['url'];
    $query = "SELECT exists (SELECT 1 FROM cams WHERE url = '{$url}')";
    $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);
    pg_free_result($result);
}

if ($action == 'newcam' ) {
    $url = $_POST['url'];
    $lat = $_POST['lat'];
    $lon = $_POST['lon'];
    $desc = $_POST['description'];
    $method = $_POST['method'];
    $permission = $_POST['permission'];
    $owner = $_POST['owner'];
    $email = $_POST['email'];

    $query = "INSERT into cams (url,lat,lon,description,interval,method,active,permission,owner,email,keephours) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)";
    $result = pg_query_params($query, Array($url,$lat,$lon,$desc,'10',$method,'t',$permission,$owner,$email,'240')) or die('Query failed: ' . pg_last_error());

    $status = pg_result_status($result);
    echo json_encode($status);
    pg_free_result($result);

    shell_exec('python3 /var/www/html/work/runallgeom.py');
}

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