<?php
require_once "../../config/settings.inc.php";
define("IEM_APPID", 90);
require_once "../../include/myview.php";
require_once "../../include/database.inc.php";
require_once "../../include/forms.php";

$mesosite = iemdb('mesosite');

$t = new MyView();
$t->iemss = True;
$t->title = "Download Daily Summary Data";
$t->headextra = <<<EOM
<link rel="stylesheet" type="text/css" href="daily.css">
EOM;

$network = isset($_REQUEST["network"]) ? xssafe($_REQUEST["network"]) : "IA_ASOS";

$ar = Array();
$rs = pg_query(
    $mesosite,
    "SELECT id, name from networks where id !~* 'CLIMATE' "
    ."ORDER by name ASC"
);
for ($i = 0; $row = pg_fetch_assoc($rs); $i++) {
    $ar[$row["id"]] = $row["name"];
}
$nselect = make_select("network", $network, $ar);

$y1 = yearSelect(1900, date("Y"), "year1");
$m1 = monthSelect("", "month1");
$d1 = daySelect("", "day1");
$y2 = yearSelect(1900, date("Y"), "year2");
$m2 = monthSelect(date("m"), "month2");
$d2 = daySelect(date("d"), "day2");

$ar = Array(
    "None" => "Text string 'None'",
    "M" => "M",
    "blank" => "Empty string (blank)",
);
$naselect = make_select("na", "blank", $ar);

$ar = Array(
    "csv" => "Comma Seperated (csv)",
    "excel" => "Excel (xlsx)",
    "json" => "JSON",
);
$fmtselect = make_select("format", "csv", $ar);


$vars = array(
    "max_temp_f" => "Maximum Air Temperature [F].",
    "min_temp_f" => "Minimum Air Temperature [F].",
    "max_dewpoint_f" => "Maximum Dew Point [F].",
    "min_dewpoint_f" => "Minimum Dew Point [F].",
    "precip_in" => "Daily Precipitation [inch].",
    "avg_wind_speed_kts" => "Average Wind Speed [knots]",
    "avg_wind_drct" => "Average Wind Direction [deg]",
    "min_rh" => "Minimum Relative Humidity [%]",
    "avg_rh" => "Average Relative Humidity [%]: computed by time averaging the available reports, it is not average of the daily max/min.",
    "max_rh" => "Maximum Relative Humidity [%]",
    "climo_high_f" => "NCEI 1991-2020 Daily High Temperature Climatology [F]",
    "climo_low_f" => "NCEI 1991-2020 Daily Low Temperature Climatology [F]",
    "climo_precip_in" => "NCEI 1991-2020 Daily Precipitation Climatology [inch]",
    "snow_in" => "Reported Snowfall [inch]",
    "snowd_in" => "Reported Snow Depth [inch]",
    "min_feel" => "Minimum 'Feels Like' (either wind chill or heat index) temperature.  The value is always at least the air temperature.",
    "avg_feel" => "Average 'Feels Like' (either wind chill or heat index) temperature.  The value is always at least the air temperature. Value is a time weighted average.",
    "max_feel" => "Maximum 'Feels Like' (either wind chill or heat index) temperature.  The value is always at least the air temperature.",
    "max_wind_speed_kts" => "Maximum sustained wind speed in knots.",
    "max_wind_gust_kts" => "Maximum wind gust in knots.",
    "srad_mj" => "Daily Solar Radiation MJ/m2 (when available).",
);
$varform = "";
foreach($vars as $key => $val){
  // Bootstrap 5 form-check layout (do not alter name attr expected by backend)
  $varform .= sprintf(
    '<div class="col-12 col-sm-6 col-lg-4" role="listitem">'.
    '<div class="form-check small">'.
    '<input class="form-check-input" type="checkbox" name="var" value="%s" id="var_%s">'.
    '<label class="form-check-label" for="var_%s">[%s] %s</label>'.
    '</div></div>'."\n",
    $key, $key, $key, $key, $val
  );
}


$t->content = <<<EOM
<header class="mb-4">
  <h1 class="h3 mb-3">IEM Computed Daily Summary of Observations</h1>
  <p>This tool lets you download daily summaries computed from collected observations for a site or all sites in a network. For COOP networks the daily values reflect the once-daily reports. When requesting all stations, limit the date span to one year.</p>
  <p>The definition of a <strong>day</strong> usually follows the local calendar day for each station's timezone, but some stations provide standardized local-time summaries which override computed totals.</p>
  <p><a href="/cgi-bin/request/daily.py?help" class="btn btn-outline-info btn-sm"><i class="bi bi-file-text" aria-hidden="true"></i> Backend documentation</a></p>
</header>

<section aria-labelledby="networkSelectHeading" class="mb-4">
  <h2 id="networkSelectHeading" class="h5">1. Choose Network</h2>
  <form name="network" action="daily.phtml" class="row gy-2 gx-2 align-items-end" aria-describedby="networkHelp">
    <div class="col-auto">
      <label for="network" class="form-label">Network</label><br />
      {$nselect}
    </div>
    <div class="col-auto">
      <button type="submit" class="btn btn-primary btn-sm">Switch Network</button>
    </div>
    <div class="col-12"><p id="networkHelp" class="form-text mb-0">Switching networks updates available stations below.</p></div>
  </form>
</section>

<form target="_blank" name="iemss" action="/cgi-bin/request/daily.py" aria-labelledby="downloadHeading">
  <h2 id="downloadHeading" class="h5 mb-3">2. Select Stations, Dates, and Variables</h2>
  <div class="form2url mb-3"></div>
  <input type="hidden" value="{$network}" name="network" />

  <div class="row g-4">
    <div class="col-md-6">
      <h3 class="h6">Stations</h3>
      <div id="iemss" data-network="{$network}" aria-live="polite" aria-busy="false"></div>
    </div>
    <div class="col-md-6">
      <fieldset class="mb-4">
        <legend class="h6">Date Range (inclusive)</legend>
        <div class="row g-2 align-items-end">
          <div class="col-12 col-lg-6">
            <div class="border rounded p-2 h-100">
              <div class="fw-semibold small mb-1">Start Date</div>
              <div class="row g-2">
                <div class="col-4">{$y1}</div>
                <div class="col-4">{$m1}</div>
                <div class="col-4">{$d1}</div>
              </div>
            </div>
          </div>
          <div class="col-12 col-lg-6">
            <div class="border rounded p-2 h-100">
              <div class="fw-semibold small mb-1">End Date</div>
              <div class="row g-2">
                <div class="col-4">{$y2}</div>
                <div class="col-4">{$m2}</div>
                <div class="col-4">{$d2}</div>
              </div>
            </div>
          </div>
        </div>
        <p class="form-text mt-2 mb-0">For all stations limit span to <= 1 year for performance.</p>
      </fieldset>

      <fieldset class="mb-4" aria-describedby="varHelp">
        <legend class="h6">Variables</legend>
        <p id="varHelp" class="form-text">Values of <code>0.0001</code> inches represent trace precipitation.</p>
        <div class="row g-1" role="list">
          {$varform}
        </div>
      </fieldset>

      <div class="row g-3 mb-4">
        <div class="col-md-6">
          <label for="na" class="form-label">Missing Value Representation</label>
          {$naselect}
        </div>
        <div class="col-md-6">
          <label for="format" class="form-label">Download Format</label>
          {$fmtselect}
        </div>
      </div>

      <div>
        <button type="submit" class="btn btn-success">Request Data</button>
      </div>
    </div>
  </div>
</form>
EOM;
$t->render('full.phtml');
