<?php
require_once "../../config/settings.inc.php";
require_once "../../include/database.inc.php";
require_once "../../include/forms.php";
require_once "../../include/station.php";
require_once "../../include/myview.php";

$wepp = iemdb("wepp");
$iem = iemdb("iem");

$iem_stname = iem_pg_prepare($iem, "SELECT day, pday from 
      summary s JOIN stations t ON (t.iemid = s.iemid) WHERE
      t.id = $1 and day >= $2 and day < $3");
$wepp_stname = iem_pg_prepare($wepp, "select rainfall / 25.4 as inch, 
    valid from daily_rainfall
    WHERE hrap_i = $1 and valid >= $2 and valid < $3 ORDER by valid ASC");

$method = isset($_GET["method"]) ? xssafe($_GET["method"]) : "geocode";
$syear = get_int404("syear", 0);
$eyear = get_int404("eyear", 0);
if ($syear == 0 || $eyear == 0) {
    http_response_code(422);
    die("Please supply both syear and eyear.");
}
$view = isset($_GET["view"]) ? xssafe($_GET["view"]) : "online";

$d = array();
$sts = mktime(0, 0, 0, 1, 1, $syear);
$ets = mktime(0, 0, 0, 1, 1, $eyear + 1);
$today = mktime(0, 0, 0, date("m", time()), date("d", time()), date("Y", time()));
if ($today < $ets) $ets = $today;
$now = $sts;
while ($now < $ets) {
    $d[date("Y-m-d", $now)] = array("rain" => 0, "ob" => "M");
    $now += 86400;
}

$data = "# IEM Rainfall {$EXTERNAL_BASEURL} 
# Date Generated: " . date("r") . "\n";
if ($method == "geocode") {
    $s = isset($_GET["street"]) ? xssafe($_GET["street"]) : "100 Main Street";
    $c = xssafe($_GET["city"]) . ", IA";
    $data .= "# Request Method: Geocoded $s , $c\n";
    $u = sprintf("%s/cgi-bin/geocoder.py?street=%s&city=%s", $INTERNAL_BASEURL, $s, $c);
    $res = trim(file_get_contents(str_replace(" ", "%20", $u)));
    //echo "GEOCODER RESPONSE:::$res::: $u :::";
    if (substr($res, 0, 5) != "ERROR") {
        $tokens = explode(",", $res);
        $latitude = $tokens[0];
        $longitude = $tokens[1];
    } else {
        die("Geocoder failed for: $s, $c");
    }
} else if ($method == "id") {
    $id = strtoupper(xssafe($_GET["nwsli"]));
    $st = new StationData($id);
    $cities = $st->table;
    $latitude = round($cities[$id]["lat"], 4);
    $longitude = round($cities[$id]["lon"], 4);
    $data .= "# Request Method: Specified NWSLI $id \n";

    $rs = pg_execute($iem, $iem_stname, array(
        $id, date('Y-m-d', $sts),
        date('Y-m-d', $ets)
    ));
    while ($row = pg_fetch_assoc($rs)) {
        if ($row["pday"] >= 0) {
            $d[$row["day"]]["ob"] = $row["pday"];
        } else {
            $d[$row["day"]]["ob"] = 0;
        }
    }
} else if ($method == "latlon") {
    if (isset($_GET["lat"])) {
        $latitude = floatval($_GET["lat"]);
    };
    if (isset($_GET["lon"])) {
        $longitude = floatval($_GET["lon"]);
    };
    $data .= "# Request Method: Specified Lat $latitude Lon $longitude \n";
}

/* Cleanup Lat Lon values */
if ($longitude > 0) {
    $longitude = 0 - $longitude;
}
// Ensure values are ~ Iowa
if ($longitude < -102 || $longitude > -88) {
    die("Longitude outside of Iowa");
}
if ($latitude < 38 || $latitude > 44) {
    die("Longitude outside of Iowa");
}

$stname2 = iem_pg_prepare($wepp, "select hrap_i, ST_distance( the_geom, 
    ST_transform(ST_Point($1, $2, 4326), 26915) ) 
    from hrap_utm ORDER by st_distance ASC LIMIT 1");
$rs = pg_execute($wepp, $stname2, array($longitude, $latitude));
$row = pg_fetch_assoc($rs);
if ($row["st_distance"] > 25000) {
    echo sprintf(
        "ERROR: Point is %.1f km outside of data domain, abort.",
        $row["st_distance"] / 1000.0
    );
    die();
}

$hrap_i = $row["hrap_i"];
$data .= "# Latitude: $latitude Longitude: $longitude HRAP_I: $hrap_i
Date,Estimate,YearToDate";
if ($method == 'id') {
    $data .= ",Observation\n";
} else {
    $data .= "\n";
}

$rs = pg_execute($wepp, $wepp_stname, array(
    $hrap_i, date('Y-m-d', $sts),
    date('Y-m-d', $ets)
));

$tot = 0;
$otot = 0;
while ($row = pg_fetch_assoc($rs)) {
    $tot += $row["inch"];
    $ob = $d[$row["valid"]]["ob"];
    $otot += ($ob == "M") ? 0 : $ob;
    $d[$row["valid"]]["rain"] = $row["inch"];
}

$running = 0;
foreach ($d as $k => $v) {
    $running += $d[$k]["rain"];
    if ($method == "id") {
        $data .=  sprintf(
            "%s,%5.2f,%5.2f,%9s\n",
            $k,
            $d[$k]["rain"],
            $running,
            $d[$k]["ob"]
        );
    } else {
        $data .=  sprintf("%s,%5.2f,%5.2f\n", $k, $d[$k]["rain"], $running);
    }
}

if ($method == "id") {
    $data .= sprintf("%s,%4.2f,%4.2f,%9s\n", "Total", $tot, $running, $otot);
} else {
    $data .= sprintf("%s,%4.2f,%4.2f\n", "Total", $tot, $running);
}

if ($view == "download") {
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=iemrainfall.dat");
    echo $data;
    die();
}

$t = new MyView();
$t->title = "Rainfall by Point";
$t->content = <<<EOM
<pre>
{$data}
</pre>
EOM;
$t->render("single.phtml");
