<?php
// Summary of monthly data from IEMAccess
require_once "../../config/settings.inc.php";
require_once "../../include/database.inc.php";
define("THROTTLE_APP", "sites/obhistory");
define("THROTTLE_LIMIT", 16);
// sites calls throttle
require_once "../../include/sites.php";
require_once "../../include/myview.php";
require_once "../../include/forms.php";

$month = get_int404("month", date("m"));
$year = get_int404("year", date("Y"));

$ctx = get_sites_context();
$station = $ctx->station;
$network = $ctx->network;
$metadata = $ctx->metadata;

$t = new MyView();
$t->iemselect2 = true;
$t->title = "Monthly Summaries";
$t->sites_current = "monthsum";

$pgconn = iemdb("iem");
$stname = iem_pg_prepare($pgconn, "SELECT extract(year from day) as year," .
    "extract(month from day) as month, sum(pday) as precip, " .
    "avg(avg_rh) as avg_rh, avg(max_tmpf) as avg_high, " .
    "avg(avg_sknt) * 1.15 as avg_wind_mph, " .
    "avg(min_tmpf) as avg_low, avg((max_tmpf + min_tmpf) / 2.) as avg_temp " .
    "from summary s " .
    "JOIN stations t on (s.iemid = t.iemid) WHERE t.id = $1 and t.network = $2 " .
    "GROUP by year, month ORDER by year, month");
$rs = pg_execute($pgconn, $stname, array($station, $network));
$data = array();
$minyear = 3000;
$maxyear = 1000;
while ($row = pg_fetch_assoc($rs)) {
    if ($minyear > $row["year"]) $minyear = $row["year"];
    if ($maxyear < $row["year"]) $maxyear = $row["year"];
    $key = sprintf("%s_%s", $row["year"], $row["month"]);
    $data[$key] = $row;
}
$climo = array();
$pgconn = iemdb("coop");
$stname = iem_pg_prepare($pgconn, "SELECT " .
    "extract(month from valid) as month, avg(high) as avg_high, " .
    "avg(low) as avg_low, avg((high+low)/2.) as avg_temp, " .
    "sum(precip) as precip from ncei_climate91 WHERE station = $1" .
    " GROUP by month ORDER by month ASC");
$rs = pg_execute($pgconn, $stname, array($metadata["ncei91"]));
while ($row = pg_fetch_assoc($rs)) {
    $climo[$row["month"]] = $row;
    $climo[$row["month"]]["avg_wind_mph"] = null;
}

function f($data, $key1, $key2, $fmt)
{
    if (
        !array_key_exists($key1, $data) ||
        !array_key_exists($key2, $data[$key1])
    ) {
        return "M";
    }
    $val = $data[$key1][$key2];
    if ($val === NULL) return "M";
    return sprintf($fmt, $val);
}
function f2($data, $key, $fmt)
{
    if (!array_key_exists($key, $data)) {
        return "M";
    }
    $val = $data[$key];
    if (is_null($val)) return "M";
    return sprintf($fmt, $val);
}

function make_table($data, $key, $minyear, $maxyear, $fmt, $climo)
{
    $table = '<table class="table table-ruled table-bordered">' .
        '<thead class="sticky">' .
        '<tr><th>Year</th><th>Jan</th><th>Feb</th><th>Mar</th>' .
        '<th>Apr</th><th>May</th><th>Jun</th><th>Jul</th><th>Aug</th>' .
        '<th>Sep</th><th>Oct</th><th>Nov</th><th>Dec</th></tr></thead>' .
        '<tbody>';
    for ($year = $minyear; $year <= $maxyear; $year++) {
        $table .= sprintf(
            "<tr><td>%s</td><td>%s</td><td>%s</td>" .
                "<td>%s</td><td>%s</td><td>%s</td><td>%s</td>" .
                "<td>%s</td><td>%s</td><td>%s</td><td>%s</td>" .
                "<td>%s</td><td>%s</td></tr>",
            $year,
            f($data, sprintf("%s_1", $year), $key, $fmt),
            f($data, sprintf("%s_2", $year), $key, $fmt),
            f($data, sprintf("%s_3", $year), $key, $fmt),
            f($data, sprintf("%s_4", $year), $key, $fmt),
            f($data, sprintf("%s_5", $year), $key, $fmt),
            f($data, sprintf("%s_6", $year), $key, $fmt),
            f($data, sprintf("%s_7", $year), $key, $fmt),
            f($data, sprintf("%s_8", $year), $key, $fmt),
            f($data, sprintf("%s_9", $year), $key, $fmt),
            f($data, sprintf("%s_10", $year), $key, $fmt),
            f($data, sprintf("%s_11", $year), $key, $fmt),
            f($data, sprintf("%s_12", $year), $key, $fmt)
        );
    }
    if (sizeof($climo) > 0) {
        $table .= sprintf(
            "<tr><td>%s</td><td>%s</td><td>%s</td>" .
                "<td>%s</td><td>%s</td><td>%s</td><td>%s</td>" .
                "<td>%s</td><td>%s</td><td>%s</td><td>%s</td>" .
                "<td>%s</td><td>%s</td></tr>",
            "NCEI Climatology",
            f2($climo["1"], $key, $fmt),
            f2($climo["2"], $key, $fmt),
            f2($climo["3"], $key, $fmt),
            f2($climo["4"], $key, $fmt),
            f2($climo["5"], $key, $fmt),
            f2($climo["6"], $key, $fmt),
            f2($climo["7"], $key, $fmt),
            f2($climo["8"], $key, $fmt),
            f2($climo["9"], $key, $fmt),
            f2($climo["10"], $key, $fmt),
            f2($climo["11"], $key, $fmt),
            f2($climo["12"], $key, $fmt)
        );
    }
    $table .= "</tbody></table>";
    return $table;
}

$preciptable = make_table(
    $data,
    "precip",
    $minyear,
    $maxyear,
    "%.2f",
    $climo
);
$windtable = make_table(
    $data,
    "avg_wind_mph",
    $minyear,
    $maxyear,
    "%.1f",
    $climo
);
$hightable = make_table(
    $data,
    "avg_high",
    $minyear,
    $maxyear,
    "%.2f",
    $climo
);
$lowtable = make_table(
    $data,
    "avg_low",
    $minyear,
    $maxyear,
    "%.2f",
    $climo
);
$temptable = make_table(
    $data,
    "avg_temp",
    $minyear,
    $maxyear,
    "%.2f",
    $climo
);
$noclimo = array();
$rhtable = make_table(
    $data,
    "avg_rh",
    $minyear,
    $maxyear,
    "%.1f%%",
    $noclimo
);

$timestamp = mktime(0, 0, 0, $month, 1, $year);
$lmonth = $timestamp - 5 * 86400;
$nmonth = $timestamp + 35 * 86400;
$llink = sprintf(
    "monthlysum.php?station=%s&amp;network=%s&amp;month=%s&amp;year=%s",
    $station,
    $network,
    date("m", $lmonth),
    date("Y", $lmonth)
);
$nlink = sprintf(
    "monthlysum.php?station=%s&amp;network=%s&amp;month=%s&amp;year=%s",
    $station,
    $network,
    date("m", $nmonth),
    date("Y", $nmonth)
);
$ltext = date("M Y", $lmonth);
$ntext = date("M Y", $nmonth);

$ms = monthSelect($month);
$minyear = is_null($metadata["archive_begin"]) ? 1929 : intval($metadata["archive_begin"]->format("Y"));
$ys = yearSelect($minyear, $year);

$plot1 = sprintf(
    "/plotting/auto/plot/17/month:%s"
        . "::year:%s::station:%s::network:%s::dpi:100.png",
    $month,
    $year,
    $station,
    $network
);
$plot2 = sprintf(
    "/plotting/auto/plot/17/month:%s::year:%s::station:%s" .
        "::network:%s::p:precip.png",
    $month,
    $year,
    $station,
    $network
);

$t->jsextra = '<script src="monthlysum.module.js" type="module"></script>';
$t->content = <<<EOM

<p><button id="gogogo" role="button" class="btn btn-primary"><i class="bi bi-arrow-down"></i> View Monthly Charts</button></p>

<p>The following tables present IEM computed monthly data summaries based on
daily data provided by or computed for the IEM. A <a href="/request/daily.phtml?network={$network}">download interface</a>
exists for the daily summary information.  The climatology is provided by the
nearest NCEI climate station (<a href="/sites/site.php?station={$metadata["ncei91"]}&amp;network=NCEI91">{$metadata["ncei91"]}</a>) within the current 1991-2020
dataset.</p>

<p><i class="bi bi-table"></i> To load shown data into Microsoft Excel,
highlight the table information with your mouse and then copy/paste into Excel.</p>

<h3><a name="precip"></a>Precipitation Totals [inch]</h3>

{$preciptable}

<h3><a name="avg_wind_mph"></a>Average Wind Speed [MPH]</h3>

{$windtable}

<h3><a name="avg_high"></a>Average Daily High Temperature [F]</h3>

{$hightable}

<h3><a name="avg_low"></a>Average Daily Low Temperature [F]</h3>

{$lowtable}

<h3><a name="avg_temp"></a>Average Daily Temperature (high+low)/2 [F]</h3>

{$temptable}

<h3><a name="avg_rh"></a>Average Relative Humidity [%]</h3>

<p>This value is computed via a simple average of available observations weighted
by the duration between observations.</p>

{$rhtable}

<h3 id="mycharts">Monthly Plots</h3>

<form method="GET" name="changemonth" action="monthlysum.php#plots">
 <input type="hidden" name="station" value="{$station}">
 <input type="hidden" name="network" value="{$network}">
 <h3>Select month and year:</h3>
 <div class="row">
 <div class="col-sm-3">
 <a href="{$llink}" class="btn btn-secondary">{$ltext} <i class="bi bi-arrow-left"></i></a>
    </div>
    <div class="col-sm-6">
  {$ms} {$ys}
 <input type="submit" value="Generate Plot">
 </div>
 <div class="col-sm-3">
 <a href="{$nlink}" class="btn btn-secondary"><i class="bi bi-arrow-right"></i> {$ntext}</a>
</div>
</div>
</form>

<div class="row">
<div class="col-md-12">
<img src="{$plot1}" alt="Monthly Plot" class="img-fluid">
</div>
</div>

<div class="row">
<div class="col-md-12">
<img src="{$plot2}" alt="Monthly Plot" class="img-fluid">
</div>
</div>

EOM;
$t->render('sites.phtml');
