<?php
require_once "../../config/settings.inc.php";
define("IEM_APPID", 41);
require_once "../../include/network.php";
require_once "../../include/myview.php";
require_once "../../include/forms.php";
require_once "../../include/database.inc.php";
require_once "../../include/mlib.php";

$t = new MyView();
$nt = new NetworkTable("WFO");
$mesosite = iemdb("mesosite");

$network = get_str404("network", 'IA_COOP');
$wfo = get_str404("wfo", null);
$sortcol = get_str404("sortcol", 'ts');
$sortdir = get_str404("sortdir", 'desc');
if ($sortdir != "asc" && $sortdir != "desc") $sortdir = "desc";

/**
 * Format precipitation values, 0.0001 is a trace, negative is missing
 * @param string|float $val
 * @return string
 */
function precip_formatter($val)
{
    if ($val === '') return '';
    if ($val === 0.0001) return 'T';
    if ($val < 0) return 'M';
    return $val;
}

/**
 * Make a table row for the given station data
 * @param array $dict
 * @param bool $oddrow
 * @return string
 */
function make_row($dict, $oddrow)
{
    $s = "<tr";
    if ($oddrow) $s .= ' bgcolor="#EEEEEE"';
    $s .= ">";

    $sitesurl = sprintf(
        "/sites/site.php?station=%s&network=%s",
        $dict["sid"],
        $dict["network"]
    );

    $s .= <<<EOM
    <td><input type="checkbox" name="st[]" value="{$dict["sid"]}" aria-label="Add {$dict['sid']} to favorites"/></td>
    <td><a href="/p.php?pid={$dict["raw"]}" class="btn btn-small" aria-label="View source text for {$dict['sid']}"><i class="bi bi-paperclip" aria-hidden="true"></i><span class="visually-hidden">Source Text</span></a>
    </td>
EOM;
    $s .= "<td><a href=\"cat.phtml?station=" . $dict["sid"] . "&network=" . $dict["network"] . "\">" . $dict['sid'] . "</a></td>";
    $s .= "<td><a href=\"$sitesurl\">" . $dict["name"] . ", " . $dict["state"] . "</a></td>";
    $s .= "<td>" . $dict["county"] . "</td>";

    $fmt = (date("Ymd") != date("Ymd", $dict["ts"])) ? 'd M Y h:i A' : 'h:i A';
    $s .= "<td>" . date($fmt, $dict["lts"]) . "</td>";

    $s .= sprintf(
        "<td>%s</td><td><span style=\"color: #F00;\">%s</span></td>
    <td><span style=\"color: #00F;\">%s</span></td>",
        $dict["tmpf"] != "" ? $dict["tmpf"] : "M",
        $dict["max_tmpf"] != "" ? $dict["max_tmpf"] : "M",
        $dict["min_tmpf"] != "" ? $dict["min_tmpf"] : "M"
    );

    $s .= sprintf(
        "<td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td>",
        precip_formatter($dict["pday"]),
        precip_formatter($dict["snow"]),
        precip_formatter($dict["ratio"]),
        precip_formatter($dict["snowd"]),
        precip_formatter($dict["snoww"])
    );

    $s .= "</tr>\n";
    return $s;
}

if (is_null($wfo)) {
    $arr = array(
        "network" => $network,
    );
    $baseurl = "current.phtml?network=$network";
} else {
    $arr = array(
        "networkclass" => "COOP",
        "wfo" => $wfo,
    );
    $baseurl = "current.phtml?wfo=$wfo";
}
$jobj = iemws_json("currents.json", $arr);

$db = array();
foreach ($jobj["data"] as $bogus => $iemob) {
    $site = $iemob["station"];
    $db[$site] = array(
        'snow' => "", 'snowd' => "", 'ratio' => "", 'pday' => "",
        'min_tmpf' => "", 'max_tmpf' => "", 'tmpf' => "", 'snoww' => ""
    );
    $db[$site]['ts'] = strtotime($iemob["local_valid"]);
    $db[$site]['lts'] = strtotime($iemob["local_valid"]);
    $db[$site]['sid'] = $site;
    $db[$site]['name'] = $iemob["name"];
    $db[$site]['raw'] = $iemob["raw"];
    $db[$site]['state'] = $iemob["state"];
    $db[$site]['network'] = $iemob["network"];
    $db[$site]['county'] = $iemob["county"];
    if ($iemob["tmpf"] > -100) {
        $db[$site]['tmpf'] = $iemob["tmpf"];
    }
    if ($iemob["max_tmpf"] > -100) {
        $db[$site]['max_tmpf'] = $iemob["max_tmpf"];
    }

    if ($iemob["min_tmpf"] < 99) {
        $db[$site]['min_tmpf'] = $iemob["min_tmpf"];
    }

    $db[$site]['pday'] = $iemob["pday"];
    $db[$site]['snoww'] = $iemob["snoww"];
    $db[$site]['snow'] = ($iemob["snow"] >= 0) ? $iemob["snow"] : "";
    $db[$site]['snowd'] = ($iemob["snowd"] >= 0) ? $iemob["snowd"] : "";
    $db[$site]["ratio"] = -1;
    if ($db[$site]["snow"] > 0.0001 && $db[$site]["pday"] > 0.0001) {
        $db[$site]["ratio"] = intval($db[$site]["snow"] / $db[$site]["pday"]);
    }
}

$db = aSortBySecondIndex($db, $sortcol, $sortdir);

$oddrow = true;
$firstsection = "";
$lastsection = "";
foreach ($db as $site => $value) {
    $oddrow = !$oddrow;
    if (date("Ymd", $value["ts"]) == date("Ymd")) {
        $firstsection .= make_row($value, $oddrow);
    } else {
        $value["tmpf"] = "";
        $lastsection .= make_row($value, $oddrow);
    }
}

/**
 * Get the URL for sorting a column, if the column is currently sorted, reverse the sort direction
 * @param string $baseurl
 * @param string $column
 * @param string $sortCol
 * @param string $sortDir
 * @return string
 */
function get_sortdir($baseurl, $column, $sortCol, $sortDir)
{
    $newSort = ($sortDir == "asc") ? "desc" : "asc";
    if ($column == $sortCol) return "{$baseurl}&sortcol=$column&sortdir=$newSort";
    return "{$baseurl}&sortcol=$column&sortdir=$sortDir";
}

$t->title = "NWS COOP Current Sortables";

$cols = array(
    "ts" => "Valid", "county" => "County",
    "sid" => "Site ID", "name" => "Station Name",
    "ratio" => "Snow to Water Ratio",
    "tmpf" => "Ob Temperature", "max_tmpf" => "24 hour High",
    "min_tmpf" => "24 hour Low", "snow" => "24 hour Snowfall",
    "snowd" => "Snowfall Depth", "pday" => "24 hour rainfall",
    "phour" => "Rainfall One Hour", "snoww" => "Snow Water Equivalent"
);
if (!array_key_exists($sortcol, $cols)) {
    die405();
}
$t->current_network = "COOP";

$nselect = '<select name="network" id="network-select" aria-label="Select state network">';
$rs = pg_query($mesosite, "SELECT id, name from networks where id ~* 'COOP' ORDER by name ASC");
for ($i = 0; $row = pg_fetch_assoc($rs); $i++) {
    $sel = '';
    if ($network == $row["id"]) {
        $sel = " selected='SELECTED'";
    }
    $nselect .= sprintf(
        "<option value='%s'%s>%s</option>\n",
        $row["id"],
        $sel,
        $row["name"]
    );
}
$nselect .= "</select>";

$wselect = "<select name=\"wfo\" id=\"wfo-select\" aria-label=\"Select Weather Forecast Office\">";
foreach ($nt->table as $key => $value) {
    $wselect .= "<option value=\"$key\" ";
    if ($wfo == $key) $wselect .= "SELECTED";
    $wselect .= ">[" . $key . "] " . $nt->table[$key]["name"] . "\n";
}
$wselect .= "</select>";

$sorts = array("asc" => "Ascending", "desc" => "Descending");

$one = get_sortdir($baseurl, "sid", $sortcol, $sortdir);
$two = get_sortdir($baseurl, "name", $sortcol, $sortdir);
$three = get_sortdir($baseurl, "county", $sortcol, $sortdir);
$four = get_sortdir($baseurl, "ts", $sortcol, $sortdir);
$five = get_sortdir($baseurl, "tmpf", $sortcol, $sortdir);
$six = get_sortdir($baseurl, "max_tmpf", $sortcol, $sortdir);
$seven = get_sortdir($baseurl, "min_tmpf", $sortcol, $sortdir);
$eight = get_sortdir($baseurl, "pday", $sortcol, $sortdir);
$nine = get_sortdir($baseurl, "snow", $sortcol, $sortdir);
$ten = get_sortdir($baseurl, "ratio", $sortcol, $sortdir);
$eleven = get_sortdir($baseurl, "snowd", $sortcol, $sortdir);
$twelve = get_sortdir($baseurl, "snoww", $sortcol, $sortdir);

$content = <<<EOM
<form method="GET" action="current.phtml" name="stctrl">
<input type="hidden" name="sortcol" value="{$sortcol}">
<label for="network-select">Option 1: <strong>View by State:</strong></label> {$nselect}
<input type="submit" value="Go!">
</form>

<form method="GET" action="current.phtml" name="wfoctrl">
<input type="hidden" name="sortcol" value="{$sortcol}">
<label for="wfo-select">Option 2: <strong>View by WFO:</strong></label> {$wselect}
<input type="submit" value="Go!">
</form>

<form method="GET" action="cat.phtml" name="cat">
<input type="hidden" name="network" value="{$network}">
<label for="report-date">Option 3: <strong>COOP Reports for Date:</strong></label>
<input type="date" name="date" id="report-date" aria-label="Select date for COOP reports">
<input type="submit" value="Go!">
</form>

<p>Sorted by: <strong>{$cols[$sortcol]} {$sorts[$sortdir]}</strong>.
Times are presented in the local time of the site. Click on the identifier to
get all daily observations for the site.  Click on the site name to get more
information on the site. Click on the column heading to sort the column, clicking
again will reverse the sort. A new <a href="/COOP/map/">interactive map</a> app
exists that plots this data on a map.</p>

<form name="st" action="/my/current.phtml" method="GET">
<table class="table table-striped table-sm table-bordered" aria-label="Current COOP observations">
<thead>
<tr>
  <th rowspan="2">Add:</th>
  <th rowspan="2">Source Text:</th>
  <th rowspan="2"><a href="{$one}">SiteID:</a></th>
  <th rowspan="2"><a href="{$two}">Station Name:</a></th>
  <th rowspan="2"><a href="{$three}">County:</a></th>
  <th rowspan="2"><a href="{$four}">Valid:</a></th>
  <th colspan="3">Temperatures [F]</th>
  <th colspan="5">Hydro</th></tr>

<tr>
  <th><a href="{$five}">At Ob</a></th>
  <th><a href="{$six}">24h High</a></th>
  <th><a href="{$seven}">24h Low</a></th>
  <th><a href="{$eight}">24hour Rain</a></th>
  <th><a href="{$nine}">Snowfall</a></th>
  <th><a href="{$ten}">Ratio</a></th>
  <th><a href="{$eleven}">Snow Depth</a></th>
  <th><a href="{$twelve}">SWE</a></th>
</tr></thead>
<tbody>
EOM;


$content .= <<<EOM
{$firstsection}
{$lastsection}
</tbody>
</table>
<input type="submit" value="Add to Favorites">
</form>
EOM;
$t->content = $content;
$t->render('sortables.phtml');
