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

$station = get_str404("station", "", 5);
$network = get_str404("network", "IA_COOP", 7);
$date = get_str404("date", "", 10);
$sortvar = get_str404("sortvar", "", 10);
$year = get_int404("year", date("Y"));

if ($date == "" && $station == "") $station = "AMSI4";
$t = new MyView();
$t->title = "NWS COOP Observations by Date by Site";

$content = <<<EOM
  <nav aria-label="breadcrumb">
    <ol class="breadcrumb bg-light px-3 py-2 mb-4 rounded">
      <li class="breadcrumb-item"><a href="/COOP/">NWS Cooperative Observers</a></li>
      <li class="breadcrumb-item active" aria-current="page">View Reports by Date or Site</li>
    </ol>
  </nav>
  <div class="card mb-4">
    <div class="card-body">
      <p>This page presents the raw observations of daily high and low temperature 
      along with precipitation and snow when available.  The dates shown are the 
      date when the observation was reported.  For observations made at 7 AM, this 
      would be a for a 24 hour period up until that time and not for that local date.
      The timestamps shown are valid for the local timezone of that reporting station.</p>
      <div class="alert alert-info mb-0"><strong>Hint:</strong> You should be able to 
        highlight the values in the table and then copy + paste these values into a 
        spreadsheet program like Excel. A 
        <a class="alert-link" href="/request/daily.phtml?network={$network}">download interface</a> does exist for these
        observations.</div>
    </div>
  </div>
  <form name="switchnwsli" action="cat.phtml" method="GET" class="row g-3 align-items-end mb-4 bg-white p-3 rounded shadow-sm">
EOM;

// SCENARIO 1: Print out data for year for station
if (strlen($station) > 0) {
    $link = "cat.phtml?year=$year&station=$station&network=$network&sortvar=";
    if ($sortvar == "") $sortvar = "day";
    $stationselect = networkSelect($network, $station);
    $content .= <<<EOM
      <div class="col-md-6">
        <h3 class="h5 mb-2">COOP obs listed by station</h3>
        <div class="mb-2"><i>Click on a date to get all obs for a particular date.</i></div>
        {$stationselect}
        <label for="year" class="form-label">Select Year:</label>
EOM;
    $content .= yearSelect(2004, $year, "year");
    $content .= "</div>";
}

// SCENARIO 2: Print out all stations for network and date
if (strlen($date) > 0) {
    $year = substr($date, 0, 4);
    $link = "cat.phtml?date=$date&network=$network&sortvar=";
    if ($sortvar == "") $sortvar = "station";
    $content .= <<<EOM
      <div class="col-md-6">
        <h3 class="h5 mb-2">COOP obs listed by date</h3>
        <div class="mb-2"><i>Click on the NWSLI to view all obs from one station.</i></div>
        <label for="date" class="form-label">Enter Date:</label>
        <input type="date" name="date" value="{$date}" class="form-control mb-2">
      </div>
EOM;
}

$netselect = selectNetworkType("COOP", $network);

$content .= <<<EOM
      <div class="col-md-6">
        <label for="network" class="form-label">Select Network:</label>
        {$netselect}
        <button type="submit" class="btn btn-primary mt-2">View Data</button>
        <button id="rowshower" type="button" class="btn btn-outline-secondary mt-2 ms-2">Hide rows without data</button>
      </div>
    </form>

    <div class="table-responsive">
      <table class="table table-striped table-bordered table-sm align-middle">
        <thead class="sticky">
          <tr>
            <th><a href="{$link}station">NWSLI:</a></th>
            <th><a href="{$link}sname">Site Name:</a></th>
            <th><a href="{$link}day">Date:</a></th>
            <th><a href="{$link}coop_tmpf">Temp at Ob</a></th>
            <th><a href="{$link}max_tmpf">Max Air Temp</a></th>
            <th><a href="{$link}min_tmpf">Min Air Temp</a></th>
            <th><a href="{$link}pday">Precip</a></th>
            <th><a href="{$link}snow">Snowfall</a></th>
            <th><a href="{$link}snowd">Snow Depth</a></th>
            <th><a href="{$link}snoww">Snow Water Equiv</a></th>
          </tr>
        </thead>
EOM;

$nt = new NetworkTable($network);
$cities = $nt->table;
$iemdb = iemdb("iem");

$sortdir = "ASC";
if (
    $sortvar == "pday" || $sortvar == "snow" || $sortvar == "snowd" ||
    $sortvar == "max_tmpf" || $sortvar == "snoww"
)
    $sortdir = "DESC";
if (strlen($station) > 0) {
    $stname = iem_pg_prepare($iemdb, "SELECT c.*, s.id as station, 
     s.name as sname, c.coop_valid at time zone s.tzname as cts, c.report 
     from summary_$year c, stations s
     WHERE s.id = $1 and s.network = $2 and c.iemid = s.iemid 
     and c.day <= 'TODAY' ORDER by $sortvar $sortdir");
    $rs = pg_execute($iemdb, $stname, array($station, $network));
} else {
    $stname = iem_pg_prepare($iemdb, "SELECT c2.*, s.id as station, 
     s.name as sname, c2.coop_valid at time zone s.tzname as cts, c2.report
     from summary_$year c2, stations s
     WHERE c2.day = $1
     and s.network = $2 and c2.iemid = s.iemid ORDER by $sortvar $sortdir");
    $rs = pg_execute($iemdb, $stname, array($date, $network));
}

while ($row = pg_fetch_assoc($rs)) {
    $nwsli = $row["station"];
    $high = $row["max_tmpf"];
    if ($high == "-99" || $high == "") $high = "M";
    if ($high > 130 || $high < -90) $high = "M";


    $tmpf = $row["coop_tmpf"];
    if ($tmpf == "-99" || $tmpf == "") $tmpf = "M";
    if ($tmpf > 130 || $tmpf < -90) $tmpf = "M";

    $low = $row["min_tmpf"];
    if ($low == "99" || $low == "" || $low == -99) $low = "M";
    if ($low > 130 || $low < -90) $low = "M";

    $rain = $row["pday"];
    if ($rain == 0.0001) $rain = "T";
    else if ($rain == -99 || $rain == "") $rain = "M";
    else if ($rain > 30 || $rain < 0) $rain = "M";

    $snow = $row["snow"];
    if ($snow == 0.0001) $snow = "T";
    else if ($snow == -99 || $snow == "") $snow = "M";
    else if ($snow > 100 || $snow < 0) $snow = "M";

    $snowd = $row["snowd"];
    if ($snowd == 0.0001) $snowd = "T";
    else if ($snowd == -99 || $snowd == "") $snowd = "M";
    else if ($snowd > 1000 || $snowd < 0) $snowd = "M";

    $snoww = $row["snoww"];
    if ($snoww == 0.0001) $snoww = "T";
    else if ($snoww == -99 || $snoww == "") $snoww = "M";
    else if ($snoww > 1000 || $snoww < 0) $snoww = "M";

    $rowcontent = "<tr><td>";
    if (strlen($station) > 0) {
        $rowcontent .= $nwsli;
    } else {
        $rowcontent .= "<a href=\"cat.phtml?station=" . $nwsli . "&network=" . $network . "\">" . $nwsli . "</a>";
    }

    $rowcontent .= "</td><td>" . $cities[$nwsli]["name"] . "</td>";
    $dstring = $row["day"];

    if (
        $tmpf == "M" && $high == "M" && $low == "M" && $rain == "M"
        && $snow == "M" && $snowd == "M"
    ) {
        $dddd = "<a href=\"cat.phtml?date=" . $row["day"] . "&network=" . $network . "\">" . $dstring . "</a>";
        $rowcontent = str_replace("<tr>", "<tr class=\"nodata\">", $rowcontent) .
            "<td colspan=\"8\">No Observation Reported for $dddd</td></tr>";
    } else {
        $rowcontent .= "<td>";
        if ($row["cts"]) {
            $dstring = date("j M Y gA", strtotime(substr($row["coop_valid"], 0, 16)));
        }

        if (strlen($date) > 0) {
            $rowcontent .= $dstring;
        } else {
            $rowcontent .= "<a href=\"cat.phtml?date=" . $row["day"] . "&network=" . $network . "\">" . $dstring . "</a>";
        }
        $rowcontent .= "</td><td>" . $tmpf . "</td><td>" . $high . "</td><td>" . $low . "</td><td>" . $rain . "</td><td>" . $snow . "</td><td>" . $snowd . "</td><td>" . $snoww . "</td></tr>\n";
        if (!is_null($row["report"])) {
            $rowcontent .= sprintf(
                '<tr><td colspan="8">%s</td></tr>',
                $row["report"],
            );
        }
    }
    $content .= $rowcontent;
}

$content .= <<<EOM
      </table>
    </div>
    <p class="mt-4">Errors exist in this dataset and you should evaluate the observations
    before using...</p>
  </div>
EOM;
$t->content = $content;
$t->jsextra = '<script type="module" src="cat.module.js"></script>';
$t->render('full.phtml');
