<?php

$OL = "10.7.0";
require_once "../../config/settings.inc.php";
define("IEM_APPID", 15);
require_once "../../include/mlib.php";
force_https();
require_once "../../include/myview.php";
require_once "../../include/iemprop.php";
require_once "../../include/forms.php";

/**
 * Ensure the network string matches the station prefix.
 * If the station is set and its prefix does not match the network,
 * update the network to match the station's prefix.
 *
 * @param string $station Station identifier (e.g., 'IA0001')
 * @param string $network Network string (e.g., 'IACLIMATE')
 * @return string Corrected network string
 */
function match_network_to_station($station, $network) {
    if ($station !== "" && substr($station, 0, 2) !== substr($network, 0, 2)) {
        return sprintf("%sCLIMATE", substr($station, 0, 2));
    }
    return $network;
}

$report = sprintf("%02d", get_int404("report", 1));
$station = strtoupper(get_str404("station", "", 6));
$network = strtoupper(get_str404('network', 'IACLIMATE', 9));
$network = match_network_to_station($station, $network);

if (isset($_GET["id"])) {
    $station = substr(xssafe($_GET["id"]), 0, 6);
}

$xref = array(
    "01" => "110/",
    "02" => "111/",
    "03" => "112/",
    "04" => "113/var:maxmin::",
    "05" => "113/var:precip::",
    "06" => "113/var:range::",
    "07" => "113/var:means::",
    "08" => "114/",
    "09" => "10/threshold:32::varname:low::direction:below::",
    "10" => "10/threshold:30::varname:low::direction:below::",
    "11" => "10/threshold:28::varname:low::direction:below::",
    "12" => "10/threshold:26::varname:low::direction:below::",
    "13" => "10/threshold:24::varname:low::direction:below::",
    "14" => "115/var:avg_high::",
    "15" => "115/var:avg_low::",
    "16" => "115/var:avg_temp::",
    "17" => "115/var:precip::",
    "18" => "116/var:hdd::",
    "19" => "116/var:cdd::",
    "20" => "117/",
    "21" => "118/var:precip_days::",
    "22" => "119/",
    "23" => "120/",
    "24" => "121/",
    "25" => "118/var:snow_days::",
    "26" => "122/",
    "27" => "123/",
    "28" => "124/",
    "29" => "115/var:snow::",
);

if (isset($_GET["dl"])) {
    if (array_key_exists($report, $xref)) {
        $uri = sprintf(
            "%s/plotting/auto/plot/%sstation:%s::network:%s.txt",
            $INTERNAL_BASEURL,
            $xref[$report],
            $station,
            $network
        );
        header("Content-type: text/plain");
        header(sprintf(
            "Content-Disposition: attachment;Filename=%s_%s.txt",
            $station,
            $report
        ));
        echo file_get_contents($uri);
        die();
    }
}
if (isset($_GET["xlsx"])) {
    if (array_key_exists($report, $xref)) {
        $uri = sprintf(
            "%s/plotting/auto/plot/%sstation:%s::network:%s.xlsx",
            $INTERNAL_BASEURL,
            $xref[$report],
            $station,
            $network
        );
        header("Content-type: application/vnd.ms-excel");
        header("Content-Disposition: attachment;Filename=iem.xlsx");
        echo file_get_contents($uri);
        die();
    }
}

$coop_archive_end = strtotime(get_iemprop("iaclimate.end"));
$t = new MyView();
$t->iemselect2 = TRUE;
$t->iem_resource = "CLIMODAT";
$t->title = "Climodat Reports";

if ($station == "" || !is_file("/mesonet/share/climodat/reports/{$station}_$report.txt")) {
    $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" />
<link type="text/css" href="index.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;
}
$enddate = date('d M Y', $coop_archive_end);
$nselect = networkSelect($network, ($station == "") ? "IATAME" : $station);

$ar = array(
    "Precipitation" => array(
        "05" => "Daily Maximum Precipitation",
        "17" => "Monthly + Yearly Precipitation Total",
        "21" => "Monthly Rainy Days",
        "28" => "Precipitation Events by Month &amp; Year",
        "01" => "Precipitation Events per Climate Week",
        "02" => "Top 30 Rainfall Events",
    ),
    "Temperature" => array(
        "04" => "Daily Record Highs and Lows",
        "06" => "Daily Record High and Low Ranges",
        "07" => "Daily Mean Highs and Lows",
        "27" => "High/Low Consecutive Day Streaks",
        "14" => "Monthly Average Maximum Temperatures",
        "15" => "Monthly Average Minimum Temperatures",
        "16" => "Monthly Average Mean Temperatures",
        "18" => "Monthly Heating Degree Days",
        "19" => "Monthly Cooling Degree Days",
        "08" => "Number of Days Each Year Min &gt;= 32",
        "20" => "Heat Stress Variables",
        "26" => "Yearly Temperature Exceedance Histograms",
    ),
    "Growing Season" => array(
        "03" => "Growing Degree Days",
        "09" => "Last Spring / First Fall / Length of Season Base=32",
        "10" => "Last Spring / First Fall / Length of Season Base=30",
        "11" => "Last Spring / First Fall / Length of Season Base=28",
        "12" => "Last Spring / First Fall / Length of Season Base=26",
        "13" => "Last Spring / First Fall / Length of Season Base=24",
        "22" => "First Fall Freeze Probabilities",
        "23" => "Last Spring Freeze Probabilities",
        "24" => "Freeze/Thaw Cycles",
    ),
    "Snow" => array(
        "25" => "Monthly Snowy Days",
        "29" => "Monthly + Yearly Snow Total",
    )
);

$vselect = make_select("report", $report, $ar);
$sselect = selectNetworkType("CLIMATE", $network);

$content = <<<EOM
<h3>IEM "Climodat" Reports</h3>

<p>These "Climodat" reports provide some answers to the most common climatological
questions we get routinely asked.  Here are some important notes about the
products presented on this page.</p>

<ol>
<li>These reports are based on the daily
climate observations from the <a href="/COOP/">NWS COOP</a> network.  Some quality
control is done and estimating is done to create a complete time series without
missing data. You can <a href="/request/coop/fe.phtml">download the daily data</a>.</li>

<li>There is a <a href="monitor.php">station monitor app</a> that allows you to see
current summarized statistics for a station collection of your choice.</li>


<li>The <a href="/plotting/auto/">Automated Data Plotting</a> application on
this website contains charts and downloadable datasets that may interest you.</li>

</ol>

<p>Data is available from the following states:
<form name="sss" method="GET">
{$sselect}
<input type="submit" value="Select State">
</form>


<div>
<form method="GET" action="index.phtml" name="olselect">
<input type="hidden" name="network" value="{$network}" />

<table class="table table-sm">
<thead>
  <tr><th>Select Climate Station:</th><th>Select Report:</th><td></td></tr>
</thead>
<tbody>
<tr><td>{$nselect}
<br />or <a href="index.phtml?report={$report}">Select from map</a></td>

<td valign="top">
{$vselect}</td>
<td><input type="submit" value="View Report"></td></tr>
</tbody>
</table>
</form>
<p>
EOM;

if ($station != "") {
    $tokens = explode("/", $xref[$report]);
    $autoploturi = sprintf(
        "/plotting/auto/?q=%s&amp;station=%s&amp;network=%s&amp;_fmt=text",
        $tokens[0],
        $station,
        $network
    );
    $dluri = sprintf(
        "/climodat/?station=%s&amp;network=%s&amp;dl=yes&amp;report=%s",
        $station,
        $network,
        $report
    );
    $xluri = sprintf(
        "/climodat/?station=%s&amp;network=%s&amp;xlsx=yes&amp;report=%s",
        $station,
        $network,
        $report
    );
    $content .= <<<EOM
<p>
<a href="{$dluri}" class="btn btn-primary"><i class="bi bi-journal-bookmark" aria-hidden="true"></i> Download This Report</a>
<a href="{$xluri}" class="btn btn-primary"><i class="bi bi-download" aria-hidden="true"></i> Download This Report as Excel</a>
<a href="{$autoploturi}" class="btn btn-primary"><i class="bi bi-graph-up-arrow" aria-hidden="true"></i> View This Report in Autoplot App</a>
</p>
<pre>
EOM;
    if (array_key_exists($report, $xref)) {
        $uri = sprintf(
            "%s/plotting/auto/plot/%sstation:%s::network:%s.txt",
            $INTERNAL_BASEURL,
            $xref[$report],
            $station,
            $network
        );
        $content .= file_get_contents($uri);
    }
    $content .= "</pre>\n";
} else {
    $content .= <<<EOM

<p>Available stations are presented on the map below. Green dots indicate sites
that have data up until today.  Yellow dots have data, but not for a period
ending today.  Clicking on one of the dots will change the station select
form above.</p>

<div id="map" data-network="{$network}"></div>

<a name="ks"><h3 class="subtitle">"Kitchen Sink" Datafiles</h3></a>
<div>
While the climodat reports are useful, they only provide information for one variable and one site at a time.  These "kitchen sink" datafiles contain the raw information broken down by year and month for variables like high/low temperature and precipitation.

<p><strong>Download:</strong>
<br />You can <a href="ks/">browse a directory</a> to pick the individual files you want.

<p><strong>Format:</strong>
<br /><img src="/images/gisready.png" style="float: left;"> These text files are in a simple comma delimited format.  Two of the data columns contain the latitude
and longitude information which allows easy import into most GIS systems.

<p><strong>Details: <i>yearly file</i></strong>
<br />There is one yearly file (named <a href="ks/yearly.csv">yearly.csv</a>) which contains yearly summaries dating back to 1951.  Please consult the help file (named <a href="ks/yearly_ks.txt">yearly_ks.txt</a>) for further details.

<p><strong>Details: <i>monthly files</i></strong>
<br />For every year dating back to 1951, there is one file per year which
contains monthly summaries of high/low temperature and precipitation.  You
can browse <a href="ks/">this directory</a> to pick the files you want. Please
consult the help file (named <a href="ks/monthly_ks.txt">monthly_ks.txt</a>)
for further details.

<p>Did these reports help?  Please let <a href="/info/contacts.php">us know</a>
if you would like to see other variables in these files or have any other comments about them.  Enjoy!
</div>

<p><b>Disclaimer:</b> While we use care to provide accurate weather/climatic information, errors may occur because of equipment or other failure. We therefore provide this information without any warranty of accuracy. Users of this weather/climate data do so at their own risk, and are advised to use independent judgement as to whether to verify the data presented.</p>
</div>
EOM;
}
$t->content = $content;
$t->render("single.phtml");
