<?php
require_once "../../config/settings.inc.php";
define("IEM_APPID", 42);
require_once "../../include/myview.php";
$t = new MyView();

require_once "../../include/forms.php";
require_once "../../include/database.inc.php";
$coopdb = iemdb('coop');
$station = strtoupper(get_str404("station", 'IA0200', 6));
$month = get_int404("month", 12);
$day = get_int404("day", 25);

$ts = strtotime("2000-{$month}-{$day}");
$sday = date('md', $ts);

$stname1 = iem_pg_prepare($coopdb, "SELECT * from alldata_ia
      WHERE station = $1 and sday = $2 and snowd > 0 ORDER
      by year ASC");
$stname2 = iem_pg_prepare($coopdb, "SELECT min(day) as m from alldata_ia
      WHERE day > $1 and station = $2 and snowd = 0");

$table = <<<EOM
<table class="table table-striped table-bordered">
<tr><th>Start Day</th><th>Depth [inch]</th><th>End Date</th>
 <th>Duration [days]</th></tr>
EOM;

// Find all snow days for this date!
$rs = pg_execute($coopdb, $stname1, array($station, $sday));
$data = array();
while ($row = pg_fetch_assoc($rs)) {
    $rs2 = pg_execute($coopdb, $stname2, array($row["day"], $station));
    $row2 = pg_fetch_assoc($rs2, 0);
    $sts = strtotime($row["day"]);
    $endts = strtotime($row2["m"]);
    $days = ($endts - $sts) / 86400;
    $data[] = $days;
    $table .= sprintf(
        "<tr><td>%s</td><td>%s</td><td>%s</td><td>%.0f</td></tr>",
        date('Y M d', $sts),
        $row["snowd"],
        date('Y M d', $endts),
        $days
    );
}
if (pg_num_rows($rs) > 0) {
    $table .= sprintf("<tr><th colspan=\"3\" align=\"right\">Average</th><td>%.0f</td></tr>", (array_sum($data) / pg_num_rows($rs)));
}
$table .= "</table>";

$t->title = "COOP Snow Depth Duration";
$nselect = networkSelect("IACLIMATE", $station);
$mselect = monthSelect($month);
$dselect = daySelect($day);
$t->content = <<<EOM
<ol class="breadcrumb">
 <li><a href="/COOP/">NWS COOP Network</a></li>
 <li class="active">Snow Depth Duration</li>
</ol>

<h3>Snow Depth Duration</h3>

<p>This application creates a table of duration of snow cover for a given
day.  The default example answers the question, "When there is snow on the
ground for Christmas in Ames, how long does it stick around for?"</p>

<p>The dataset used for this application is based on NWS COOP observations, but
 also contains estimates when data is missing.</p>

<form method="GET" action="snowd_duration.phtml" name="Select">
<table class="table table-striped table-bordered">
<tr><th>Select Station</th><th>Month</th><th>Day</th><td></td></tr>
<tr>
  <td>{$nselect}</td>
  <td>{$mselect}</td>
  <td>{$dselect}</td>
  <td><input type="submit" value="Generate Table"></td>
</tr>
</table>
</form>

{$table}
EOM;
$t->render('single.phtml');
