<?php
$OL = "10.9.0";
require_once "../../config/settings.inc.php";
define("IEM_APPID", 110);
require_once "../../include/mlib.php";
force_https();
require_once "../../include/myview.php";
$t = new MyView();
require_once "../../include/database.inc.php";
require_once "../../include/forms.php";

$day = get_int404("day", date("d"));
$month = get_int404("month", date("m"));
$year = get_int404("year", date("Y"));
$station = get_str404("station", null);
$shefvar = get_str404("shefvar", null);
$network = get_str404("network", 'IA_DCP', 9);

$ts = mktime(1, 0, 0, $month, $day, $year);

$hads = iemdb("hads");
$mesosite = iemdb("mesosite");

if (!is_null($station)) {
    /* Make sure this site is not both a DCP and COOP site, this would cause
     * the app to do a yearlong query, which is expensive.
     */
    $stname = iem_pg_prepare($mesosite, "SELECT network from stations
            WHERE id = $1 and (network ~* '_DCP' or network ~* '_COOP')");
    $rs = pg_execute($mesosite, $stname, array($station));
    $alone = (pg_num_rows($rs) == 1) ? TRUE : FALSE;

    if (preg_match('/_COOP/', $network) && $alone) {
        $table = sprintf("raw%s", date("Y", $ts));
        if (is_null($shefvar)) {
            $stname = iem_pg_prepare($hads, "SELECT * from $table WHERE
            station = $1 ORDER by valid ASC");
            $rs = pg_execute($hads, $stname, array($station));
        } else {
            $stname = iem_pg_prepare($hads, "SELECT * from $table WHERE
            station = $1 and key = $2 ORDER by valid ASC");
            $rs = pg_execute($hads, $stname, array($station, $shefvar));
        }
    } else {
        $table = sprintf("raw%s_%s", date("Y", $ts), date("m", $ts));
        if (is_null($shefvar)) {
            $stname = iem_pg_prepare($hads, "SELECT * from $table WHERE
                station = $1 and valid BETWEEN $2 and $3 ORDER by valid ASC");
            $rs = pg_execute(
                $hads,
                $stname,
                array($station, date("Y-m-d", $ts), date("Y-m-d", $ts + 86400))
            );
        } else {
            $stname = iem_pg_prepare($hads, "SELECT * from $table WHERE
                station = $1 and key = $2 and valid BETWEEN $3 and $4 ORDER by valid ASC");
            $rs = pg_execute(
                $hads,
                $stname,
                array($station, $shefvar, date("Y-m-d", $ts), date("Y-m-d", $ts + 86400))
            );
        }
    }

    $data = array();
    $cols = array();
    while ($row = pg_fetch_assoc($rs)) {
        $cols[$row["key"]] = 1;
        $data[strtotime(substr($row["valid"], 0, 16))][$row["key"]] = $row["value"];
    }
    $mycols = array_keys($cols);
    sort($mycols);
}

$t->title = "SHEF Data by Site by Day";
$t->iemselect2 = TRUE;
$t->headextra = <<<EOM
<link rel="stylesheet" href="site.css" type="text/css">
EOM;
if (is_null($station)) {
    $t->headextra .= <<<EOM
<link rel="stylesheet" href="/vendor/openlayers/{$OL}/ol.css" type="text/css">
<link type="text/css" href="/vendor/openlayers/{$OL}/ol-layerswitcher.css" rel="stylesheet" />
EOM;
    $t->jsextra = <<<EOM
<script src="/vendor/openlayers/{$OL}/ol.js" type="text/javascript"></script>
<script src='/vendor/openlayers/{$OL}/ol-layerswitcher.js'></script>
<script src="/js/olselect.js"></script>
EOM;
}

$nselect = '<select name="network" class="iemselect2">';
$rs = pg_query($mesosite, "SELECT id, name from networks " .
    "where id ~* '_DCP' or 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>";
$n2select = networkSelect($network, $station);

$ys = yearSelect(2002, $year);
$ms = monthSelect($month);
$ds = daySelect($day);

$extra = "";
if (is_null($station)) {
    $extra = <<<EOM
<i>Click on the dot to select your site:</i><br />
<div id="map" data-network="{$network}"></div>
EOM;
} else {
    if (!$alone) {
        $extra = <<<EOM
<div class="warning">
    Since this station identifier is dual listed as both a "COOP" and "DCP"
    type station, the page will only list one day worth of data.
</div>
EOM;
    }
    $extra .= "<br /><br />
    <table class=\"table table-striped table-bordered\" style=\"width: auto;\">";
    $theader = "<thead class=\"sticky\"><tr><th>Site:</th><th>Valid:</th>";
    foreach ($mycols as $k => $v) {
        $theader .= sprintf(
            '<th><a href="site.phtml?station=%s&amp;network=%s&amp;year=%s' .
                '&amp;month=%s&amp;day=%s&amp;shefvar=%s">%s</a></th>',
            $station,
            $network,
            date("Y", $ts),
            date("m", $ts),
            date("d", $ts),
            $v,
            $v,
        );
    }
    $theader .= "</tr></thead>";
    $extra .= $theader;

    $times = array_keys($data);
    if (sizeof($times) == 0) {
        $extra .= "<tr><td colspan=\"2\">No Data Found</td></tr>";
    }
    $colorme = True;
    $cnt = 0;
    foreach ($times as $k => $ts) {
        $extra .= sprintf(
            "<tr%s><td>%s</td><td><a href='cat.phtml?year=%s&month=%s&day=%s&hour=%s&minute=%s'>%s</a></td>",
            ($colorme) ? " style='background: #eee;'" : "",
            $station,
            date("Y", $ts),
            date("m", $ts),
            date("d", $ts),
            date("H", $ts),
            date("i", $ts),
            date("Y-m-d H:i", $ts)
        );
        $colorme = !$colorme;
        foreach ($mycols as $k => $v) {
            $extra .= sprintf("<td>%s</td>", $data[$ts][$v] ?? '');
        }
        $extra .= "</tr>";

        $cnt += 1;
    }

    $extra .= "</table>";
}

$t->content = <<<EOM
<nav aria-label="breadcrumb">
  <ol class="breadcrumb bg-light px-3 py-2 mb-4 rounded">
    <li class="breadcrumb-item"><a href="/DCP/">GOES DCP/HADS Mainpage</a></li>
    <li class="breadcrumb-item active" aria-current="page">List Obs by Date</li>
  </ol>
</nav>
<div class="row g-4 mb-4">
  <div class="col-12">
    <div class="card h-100">
      <div class="card-body">
        <h3 class="card-title mb-3">SHEF Site Observations by Date</h3>
        <ul class="mb-4">
          <li>Timestamps are presented in central standard or daylight time</li>
          <li>The column headings are the <a href="https://vlab.noaa.gov/web/mdl/shef-information">SHEF</a> encoded variable names.</li>
          <li>Archive begins on 1 Jan 2002 for Iowa, 9 Dec 2010 for other states. The archive is not complete for all the sites listed.</li>
          <li>The IEM classifies SHEF provided data into two classes on a state by state basis. The COOP network sites are mostly official once-daily cooperative observer sites. The DCP network is everybody else!</li>
          <li>If you select a COOP network site, you are provided observations for the entire year.</li>
        </ul>
        <form method="GET" name="chstate" class="row g-3 align-items-end mb-3">
          <div class="col-md-8">
            <label class="form-label fw-bold">Select Network:</label>
            {$nselect}
          </div>
          <div class="col-md-4">
            <button type="submit" class="btn btn-primary w-100">Select Network</button>
          </div>
        </form>
        <form method="GET" name="olselect" class="row g-3 align-items-end">
          <input type="hidden" name="network" value="{$network}" />
          <div class="col-md-3">
            <label class="form-label fw-bold">Station:</label>
            {$n2select}
            <div><a href="site.phtml?year={$year}&month={$month}&day={$day}&network={$network}">Select from map</a></div>
          </div>
          <div class="col-md-2">
            <label class="form-label fw-bold">Year:</label>
            {$ys}
          </div>
          <div class="col-md-2">
            <label class="form-label fw-bold">Month:</label>
            {$ms}
          </div>
          <div class="col-md-2">
            <label class="form-label fw-bold">Day:</label>
            {$ds}
          </div>
          <div class="col-md-3 d-flex align-items-end">
            <button type="submit" class="btn btn-success w-100">View Data</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
{$extra}
EOM;
$t->render('full.phtml');
