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

$dbconn = getDBConnection();

//no gets, current point outage info
if (empty(array_diff_key($_GET, array('service' => '')))) {
    try {
        $query = "
            SELECT
                stationid,
                lat,
                lon,
                tempf,
                dewpt,
                preciptotal,
                winddir,
                windspd,
                windgust,
                elev,
                adm1,
                adm2,
                neighborhood,
                maxt,
                mint,
                pressure,
                lastob,
                county,
                rain24,
                rain3,
                rain6,
                windmax,
                cwa
            FROM (
                SELECT DISTINCT ON (stationid) *
                FROM wusites
                WHERE active = TRUE
                    AND cwa = 'RLX'
                    AND lastob BETWEEN timezone('utc', NOW()) - INTERVAL '0.5 hours'
                        AND timezone('utc', NOW())
            ) p
            ORDER BY lastob DESC
        ";

        $result = pg_query($dbconn, $query);
        if ($result === false) {
            throw new Exception('Query failed: ' . pg_last_error());
        }

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

        header('Content-Type: application/json');
        echo json_encode($results);

        pg_free_result($result);
    } catch (Exception $e) {
        if (isset($result)) {
            pg_free_result($result);
        }
        header('Content-Type: application/json');
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
        exit;
    }
}

if (isset($_GET['outsideold'])) {
    $query = "SELECT stationid, lat, lon, tempf, dewpt,preciptotal,winddir,windspd,windgust,elev,adm1,adm2,neighborhood,maxt,mint,pressure,lastob,county,rain24,rain3,rain6,windmax,cwa FROM (SELECT DISTINCT ON (stationid) * FROM wusites WHERE (active = TRUE) and lastob BETWEEN timezone('utc', now()) - INTERVAL '.5 HOURS'AND timezone('utc', now())) p ORDER BY lastob desc;";
    $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;
    }
    echo json_encode($array);

    // Free resultset
    pg_free_result($result);
}

if (isset($_GET['outside'])) {
    try {
        $query = "
            SELECT
                stationid,
                lat,
                lon,
                tempf,
                dewpt,
                preciptotal,
                winddir,
                windspd,
                windgust,
                elev,
                adm1,
                adm2,
                neighborhood,
                maxt,
                mint,
                pressure,
                lastob,
                county,
                rain24,
                rain3,
                rain6,
                windmax,
                cwa
            FROM (
                SELECT DISTINCT ON (stationid) *
                FROM wusites
                WHERE active = TRUE
                    AND lastob BETWEEN timezone('utc', NOW()) - INTERVAL '0.5 hours'
                        AND timezone('utc', NOW())
            ) p
            ORDER BY lastob DESC
        ";

        $result = pg_query($dbconn, $query);
        if ($result === false) {
            throw new Exception('Query failed: ' . pg_last_error());
        }

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

        header('Content-Type: application/json');
        echo json_encode($results);

        pg_free_result($result);
    } catch (Exception $e) {
        if (isset($result)) {
            pg_free_result($result);
        }
        header('Content-Type: application/json');
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
        exit;
    }
}

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