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

$access = iemdb("coop");

$t = new MyView();
$t->title = "CoCoRaHS Observations";

$station = get_str404("station", null);
$network = get_str404("network", "IA_COCORAHS");
$datestr = get_str404("date", date("Y-m-d"));
$sortvar = get_str404("sortvar", "precip");
$year = get_int404("year", date("Y"));

$single_station_mode = !is_null($station);

if ($year < 2000 || $year > (intval(date("Y")) + 1)) {
    die405();
}

try {
    $dt = new DateTime($datestr);
} catch (Exception $e) {
    die405();
}
if ($sortvar == "pday") {
    $sortvar = "precip";
}
$opts = array("precip", "snow", "snowd", "station");
if (!in_array($sortvar, $opts)) {
    $sortvar = "precip";
}
$sortdir = "ASC";
if (
    $sortvar == "precip" || $sortvar == "snow" ||
    $sortvar == "snowd" || $sortvar == "max_tmpf"
) {
    $sortdir = "DESC";
}
if ($single_station_mode) {
    $link = "obs.phtml?station=$station&network=$network&year={$year}&sortvar=";
    $stname = iem_pg_prepare(
        $access,
        <<<EOM
    SELECT s.*, t.id as station, t.name, t.county
    from cocorahs_$year s JOIN stations t
    ON (t.iemid = s.iemid) WHERE t.id = $1
    ORDER by $sortvar $sortdir
EOM
    );
    $rs = pg_execute($access, $stname, array($station));
} else {
    $year = $dt->format("Y");
    $link = "obs.phtml?network=$network&date={$datestr}&sortvar=";
    $table = sprintf("cocorahs_%s", $dt->format("Y"));
    $stname = iem_pg_prepare(
        $access,
        <<<EOM
        SELECT s.*, t.id as station, t.name, t.county
        from $table s JOIN stations t
        ON (t.iemid = s.iemid) WHERE day = $1 and
        network = $2 ORDER by $sortvar $sortdir
EOM
    );
    $rs = pg_execute($access, $stname, array($dt->format("Y-m-d"), $network));
}
$hirow = 1;
$table = "";

while ($row = pg_fetch_assoc($rs)) {
    $nwsli = $row["station"];

    $rain = precip2str($row["precip"]);
    $snow = snow2str($row["snow"]);
    $snowd = snow2str($row["snowd"]);

    $table .= sprintf(
        '<tr><td><a href="obs.phtml?station=%s&network=%s&year=%s">%s</a></td>'.
        '<td>%s</td><td>%s</td>'.
        '<td><a href="obs.phtml?date=%s&network=%s">%s</a></td>'.
        '<td>%s</td><td>%s</td><td>%s</td></tr>',
        $nwsli,
        $network,
        $year,
        $nwsli,
        $row["name"],
        $row["county"],
        $row["day"],
        $network,
        $row["day"],
        $rain,
        $snow,
        $snowd,
    );

}

$ss = networkSelect($network, $station);
$nselect = selectNetworkType("COCORAHS", $network);
$ys =  yearSelect(2000, $year, "year");

$t->content = <<<EOM
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="/cocorahs/">CoCoRaHS Mainpage</a></li>
        <li class="breadcrumb-item active" aria-current="page">CoCoRaHS Obs by Date or Station</li>
    </ol>
</nav>

<p>This page allows you to explore CoCoRaHS observations for a given
state by date or by single station for a given year.
You can then click on stations and dates to update
the data presentation.</p>

<div class="row mb-4">
    <div class="col-md-6">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">Option 1: Select State and Date</h5>
                <form method="GET" name="switchnet">
                    <div class="mb-3">
                        <label class="form-label">State:</label>
                        {$nselect}
                    </div>
                    <div class="mb-3">
                        <label for="date-input" class="form-label">Date:</label>
                        <input type="date" id="date-input" name="date" value="{$datestr}" class="form-control">
                    </div>
                    <input type="submit" value="Submit" class="btn btn-primary">
                </form>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">Option 2: Select Station and Year</h5>
                <form method="GET" name="switchnet2">
                    <div class="mb-3">
                        <label class="form-label">Station:</label>
                        {$ss}
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Year:</label>
                        {$ys}
                    </div>
                    <input type="submit" value="Submit" class="btn btn-primary">
                </form>
            </div>
        </div>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-striped table-bordered">
        <thead class="sticky">
        <tr>
          <th><a href="{$link}station">ID #:</a></th>
          <th>Site Name:</th>
          <th>County:</th>
          <th><a href="{$link}day">Date:</a></th>
          <th><a href="{$link}precip">Precip</a></th>
          <th><a href="{$link}snow">Snowfall</a></th>
          <th><a href="{$link}snowd">Snow Depth</a></th>
        </tr>
        </thead>
        <tbody>
        {$table}
        </tbody>
    </table>
</div>

<div class="alert alert-info mt-3">
    <p><strong>Usage Tips:</strong></p>
    <ul class="mb-0">
        <li>You can highlight the entire table with your cursor and copy-paste it into a spreadsheet program.</li>
        <li>Errors exist in this dataset and you should evaluate the observations before using.</li>
    </ul>
</div>
EOM;
$t->render('full.phtml');
