<?php
define("IEM_APPID", 32);

require_once "../../../../config/settings.inc.php";
require_once "../../../../include/database.inc.php";
require_once "../../../../include/forms.php";
require_once "../../../../include/network.php";
require_once "../../../../include/myview.php";
$coopdb = iemdb("coop");

$t = new MyView();

$var = get_str404("var", "gdd50");
$year = get_int404("year", date("Y", time() - 86400));
$smonth = get_int404("smonth", 5);
$sday = get_int404("sday", 1);
$emonth = get_int404("emonth", date("m", time() - 86400));
$eday = get_int404("eday", date("d", time() - 86400));
$network = get_str404("network", "IACLIMATE", 9);

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

$sts = new DateTime("{$year}-{$smonth}-{$sday}");
$ets = new DateTime("{$year}-{$emonth}-{$eday}");

$imgurl = sprintf(
    "gsplot.php?network=%s&smonth=%s&sday=%s&var=%s&emonth=%s&eday=%s&year=%s",
    $network,
    $smonth,
    $sday,
    $var,
    $emonth,
    $eday,
    $year
);

$t->title = "NWS COOP Growing Season Data";

$tr = sprintf(
    "# IEM Estimated COOP Accumulations (start: %s to inclusive date: %s)\n",
    $sts->format("Y-m-d"),
    $ets->format("Y-m-d")
);
$eburl = IEMConfig::EXTERNAL_BASEURL;
$tr .= "# Download From: {$eburl}/GIS/apps/coop/gsplot.phtml
# Download Date: " . date("d M Y") . "
# CLIM_ values are based on climatology 1951-today
# Data Contact: Daryl Herzmann akrherz@iastate.edu 515.294.5978
#-----------------------snip------------------\n";

$state = substr($network, 0, 2);

/* Query the obs */
$stname = iem_pg_prepare($coopdb, <<<EOM
WITH data as (
  SELECT station,
  sum(precip) as s_rainfall,
  sum(gddxx(32, 86, high, low)) as s_gdd32,
  sum(gddxx(41, 86, high, low)) as s_gdd41,
  sum(gddxx(46, 86, high, low)) as s_gdd46,
  sum(gddxx(48, 86, high, low)) as s_gdd48,
  sum(gddxx(50, 86, high, low)) as s_gdd50,
  sum(gddxx(51, 86, high, low)) as s_gdd51,
  sum(gddxx(52, 86, high, low)) as s_gdd52,
  sum(cdd(high, low, 65)) as s_cdd65,
  sum(hdd(high, low, 65)) as s_hdd65,
  sum(sdd86(high,low)) as s_sdd86,
  min(low) as s_mintemp,
  max(high) as s_maxtemp from alldata_{$state}
  WHERE year = $3 and sday >= $1 and sday <= $2 GROUP by station, year
), climo as (
  SELECT station,
  sum(precip) as c_rainfall,
  sum(gdd32) as c_gdd32,
  sum(gdd41) as c_gdd41,
  sum(gdd46) as c_gdd46,
  sum(gdd48) as c_gdd48,
  sum(gdd50) as c_gdd50,
  sum(gdd51) as c_gdd51,
  sum(gdd52) as c_gdd52,
  sum(sdd86) as c_sdd86,
  sum(cdd65) as c_cdd65,
  sum(hdd65) as c_hdd65
  from climate WHERE
  station in (select station from data) and
  valid >= $4 and valid <= $5 GROUP by station
)
SELECT d.*, c_rainfall, c_gdd32, c_gdd41, c_gdd46, c_gdd48, c_gdd50,
c_gdd51, c_gdd52, c_sdd86, c_cdd65, c_hdd65
from data d JOIN climo c on (d.station = c.station)
EOM
);

$rs = pg_execute($coopdb, $stname, array(
    $sts->format("md"),
    $ets->format("md"),
    $year,
    sprintf("2000-%s", $sts->format("m-d")),
    sprintf("2000-%s", $ets->format("m-d")),
));


$tr .= sprintf(
    "%6s,%21s,%10s,%10s,%10s,%10s,%10s,%10s," .
        "%10s,%10s,%10s,%10s,%10s,%10s,%10s,%10s,%10s\n",
    'ID',
    'StationName',
    'Latitude',
    'Longitude',
    'GDD50',
    'GDD48',
    'SDD86',
    'PRECIP',
    'CLIM_GDD50',
    'CLIM_GDD48',
    'CLIM_PRECIP',
    'MAX_TEMP',
    'MIN_TEMP',
    'CDD65',
    'HDD65',
    'CLIM_CDD65',
    'CLIM_HDD65'
);
while ($row = pg_fetch_assoc($rs)) {

    $ukey = $row["station"];
    if (!isset($cities[$ukey])) continue;
    $tr .= sprintf(
        "%6s,%-21s,%10.4f,%10.4f,%10.0f,%10.0f,%10.0f," .
            "%10.2f,%10.0f,%10.0f,%10.2f,%10.0f,%10.0f,%10.2f,%10.2f" .
            ",%10.2f,%10.2f\n",
        $ukey,
        $cities[$ukey]['name'],
        $cities[$ukey]['lat'],
        $cities[$ukey]['lon'],
        $row["s_gdd50"],
        $row["s_gdd48"],
        $row["s_sdd86"],
        $row["s_rainfall"],
        $row["c_gdd50"],
        $row["c_gdd48"],
        $row["c_rainfall"],
        $row["s_maxtemp"],
        $row["s_mintemp"],
        $row["s_cdd65"],
        $row["s_hdd65"],
        $row["c_cdd65"],
        $row["s_hdd65"]
    );
}

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

$ar = array(
    "gdd32" => "Growing Degree Days (base=32)",
    "gdd41" => "Growing Degree Days (base=41)",
    "gdd46" => "Growing Degree Days (base=46)",
    "gdd48" => "Growing Degree Days (base=48)",
    "gdd50" => "Growing Degree Days (base=50)",
    "gdd51" => "Growing Degree Days (base=51)",
    "gdd52" => "Growing Degree Days (base=52)",
    "cdd65" => "Cooling Degree Days (base=65)",
    "hdd65" => "Heating Degree Days (base=65)",
    "prec" => "Precipitation",
    "sdd86" => "Stress Degree Days (base=86)",
    "mintemp" => "Minimum Temperature",
    "maxtemp" => "Maximum Temperature",
);
$vselect = make_select("var", $var, $ar);
$yselect = yearselect(1893, $year);
$m1select = monthSelect($smonth, 'smonth');
$d1select = daySelect($sday, 'sday');
$m2select = monthSelect($emonth, 'emonth');
$d2select = daySelect($eday, 'eday');

$t->content = <<<EOM
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="/COOP/">NWS Cooperative Network</a></li>
    <li class="breadcrumb-item active" aria-current="page">Custom Date Duration Charts</li>
  </ol>
</nav>

<p>With this application, you can total a parameter of your
choice over a duration of your choice.  The resulting data is presented
graphically as well as textually for use in a GIS.
<strong>The end date is inclusive to the data presented.</strong>
The raw daily data used for this application can be downloaded
from <a href="/request/coop/fe.phtml">here</a>.

<form method="GET" action="gsplot.phtml" name="theform">
<table class="table table-sm">
<thead>
 <tr>
   <th>Available State:</th>
   <th>Select Parameter:</th>
   <th>Year</th>
   <th>Month</th>
   <th>Day</th>
   <th></th>
  </tr>
  </thead>
  <tbody>
 <tr>
 <td rowspan="2">
 {$netselect}
 </td>
  <td rowspan="2">{$vselect}</td>
  <td>{$yselect}</td>
  <td>{$m1select}</td>
  <td>{$d1select}</td>
  <td rowspan=2><input type="submit" value="Make Plot" class="btn btn-primary"></td>
  </tr>
 <tr>
  <td>to inclusive date:</td>
  <td>{$m2select}</td>
  <td>{$d2select}</td>
  </tr>
  </tbody>
</table>
</form>

<p>*Note: Only a sub-sample of stations are plotted on the map due to
space restrictions.  The small four digit label is the station identifier used
in the data listing below (without the 2 character state identifier included).
<br />
  <img src="{$imgurl}" class="img img-fluid" />
  </p>

<h3> Data Listing</h3>
<pre>{$tr}</pre>

<p>You should be able to 'copy &amp; paste' this raw data listing into a simple
text editor and save the data file on your machine.  Most GIS systems can
then import this dataset as a layer.  You may have to omit the commented lines
(#) if your GIS has trouble importing the data.
EOM;
$t->render('full.phtml');
