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

$t = new MyView();
define("IEM_APPID", 31);
$smonth = get_int404("smonth", 0);
$emonth = get_int404("emonth", 0);
$sday = get_int404("sday", 0);
$eday = get_int404("eday", 0);
$valid_sortcols = array(
    "year",
    "avg_temp",
    "avg_high",
    "avg_low",
    "sum_precip",
    "sum_snow",
);
$sortcol = get_str404("sortcol", "avg_high");
if (!in_array($sortcol, $valid_sortcols, true)) {
    $sortcol = "avg_high";
}
$station = get_str404('station', 'IA0000', 6);
$network = get_str404("network", "IACLIMATE", 9);

$nt = new NetworkTable($network);

$t->title = "Time period comparisons";

$table = '<div class="alert alert-secondary mb-0" role="status">Select a station and start/end dates to build a yearly comparison table.</div>';
if ($sday > 0) {
    $sts = mktime(0, 0, 0, $smonth, $sday, 2000);
    $ets = mktime(0, 0, 0, $emonth, $eday, 2000);

    $coop = iemdb("coop");
    $sname = $nt->table[$station]['name'];
    $link = "periods.phtml?station={$station}&amp;network={$network}&amp;sday=$sday&eday=$eday&smonth=$smonth&emonth=$emonth&sortcol=";
    $nicedate = sprintf("%s - %s", date("d M", $sts), date("d M", $ets));
    $table .= <<<EOM
         <div class="alert alert-info mb-3" role="status">
             Yearly averages for <strong>{$sname}</strong> [{$station}] between <strong>{$nicedate}</strong>, inclusive.
         </div>
         <div id="comparison-results" class="table-responsive">
         <table class="table table-striped table-sm table-bordered align-middle mb-0">
         <thead class="table-light">
         <tr>
             <th scope="col"><a href="{$link}year">Year</a></th>
             <th scope="col"><a href="{$link}avg_temp">Avg Temp (F)</a></th>
             <th scope="col"><a href="{$link}avg_high">Avg High Temp (F)</a></th>
             <th scope="col"><a href="{$link}avg_low">Avg Low Temp (F)</a></th>
             <th scope="col"><a href="{$link}sum_precip">Precip Total (inch)</a></th>
             <th scope="col"><a href="{$link}sum_snow">Snow Total (inch)</a></th>
             </tr>
             </thead>
             <tbody>
EOM;
    $mytable = sprintf("alldata_%s", substr($station, 0, 2));
    $stname = iem_pg_prepare($coop, "select year,
             sum(precip) as sum_precip, sum(snow) as sum_snow,
             avg(high) as avg_high, avg(low) as avg_low,
             avg((high+low)/2.0) as avg_temp from {$mytable}
             WHERE station = $1 and sday >= $2 and sday <= $3
             GROUP by year ORDER by {$sortcol} DESC");

    $rs = pg_execute($coop, $stname, array(
        $station, date("md", $sts),
        date("md", $ets)
    ));
    while ($row = pg_fetch_assoc($rs)) {
        $table .= sprintf(
            "<tr><th scope=\"row\">%s</th><td>%.2f</td><td>%.2f</td><td>%.2f</td><td>%.2f</td><td>%.1f</td></tr>",
            $row["year"],
            $row["avg_temp"],
            $row["avg_high"],
            $row["avg_low"],
            $row["sum_precip"],
            $row["sum_snow"]
        );
    }
    $table .= "</tbody></table></div>";
}

$smonthselect = monthSelect($smonth, "smonth");
$sdayselect = daySelect($sday, "sday");
$emonthselect = monthSelect($emonth, "emonth");
$edayselect = daySelect($eday, "eday");
$nselect = networkSelect($network, $station);
$sselect = selectNetworkType("CLIMATE", $network);
$t->content = <<<EOM
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="/COOP/">NWS COOP</a></li>
        <li class="breadcrumb-item active" aria-current="page">Yearly time period averages</li>
    </ol>
</nav>

<div class="alert alert-warning" role="status">
    <strong>Notice of deprecation:</strong> This legacy app is very much redundant
    with <a href="/plotting/auto/?q=107">Autoplot 107</a>.  Unless objections are
    <a href="/info/contact.php">raised</a>, this page will be removed in the next year or so.
</div>


<header class="mb-4">
    <h1 class="h3 mb-3">COOP Yearly Summary Between Two Dates</h1>
    <p class="mb-2">This application summarizes station data for a date period of your choice, by year and by station.</p>
    <p class="mb-0">Not all stations reported snowfall each year, so snow totals should be reviewed carefully before use.</p>
</header>

<div class="alert alert-info" role="status">
    Choose a state network first, then select a station and date range to compare yearly temperature and precipitation summaries.
</div>

<section class="card shadow-sm mb-4" aria-labelledby="network-controls-heading">
    <div class="card-header bg-body-tertiary">
        <h2 id="network-controls-heading" class="h5 mb-0">State Selection</h2>
    </div>
    <div class="card-body">
        <form name="ssswitch" method="GET" class="row g-3 align-items-end mb-0">
            <div class="col-md-8 col-lg-6">
                <label for="network" class="form-label">Data is available from the following states</label>
                {$sselect}
            </div>
            <div class="col-md-4 col-lg-3">
                <button type="submit" class="btn btn-outline-primary w-100">Select State</button>
            </div>
        </form>
    </div>
</section>

<section class="card shadow-sm mb-4" aria-labelledby="comparison-controls-heading">
    <div class="card-header bg-body-tertiary">
        <h2 id="comparison-controls-heading" class="h5 mb-0">Comparison Controls</h2>
    </div>
    <div class="card-body">
        <form name="switcher" method="GET" class="row g-3 align-items-end mb-0">
            <input type="hidden" name="network" value="{$network}" />
            <div class="col-lg-5">
                <label for="station" class="form-label">Select Station</label>
                {$nselect}
            </div>
            <div class="col-sm-6 col-lg-3">
                <label class="form-label d-block">Start Date</label>
                <div class="row g-2">
                    <div class="col-6">{$smonthselect}</div>
                    <div class="col-6">{$sdayselect}</div>
                </div>
            </div>
            <div class="col-sm-6 col-lg-3">
                <label class="form-label d-block">End Date</label>
                <div class="row g-2">
                    <div class="col-6">{$emonthselect}</div>
                    <div class="col-6">{$edayselect}</div>
                </div>
            </div>
            <div class="col-lg-1 d-grid">
                <button type="submit" class="btn btn-primary">Run</button>
            </div>
        </form>
    </div>
</section>

<section class="card shadow-sm mb-4" aria-labelledby="comparison-results-heading">
    <div class="card-header bg-body-tertiary">
        <h2 id="comparison-results-heading" class="h5 mb-0">Yearly Comparison</h2>
    </div>
    <div class="card-body">
        {$table}
    </div>
</section>

<div class="alert alert-secondary" role="note">
    You can usually highlight the entire results table and copy-paste it into a spreadsheet program.
</div>

<p class="text-body-secondary mb-0">Errors exist in this dataset and you should evaluate the observations before using them.</p>
EOM;
$t->render('single.phtml');
