<?php
require_once "../../config/settings.inc.php";
define("IEM_APPID", 75);
require_once "../../include/myview.php";
$t = new MyView();
require_once "../../include/database.inc.php";
require_once "../../include/forms.php";
require_once "../../include/mlib.php";
$pgconn = iemdb('iem');

$sortcol = get_str404("sortcol", "valid");
$network = get_str404("network", 'IA_DCP', 9);
$shef = get_str404("shef", "no") === 'yes';

$t->title = "DCP/GOES Current Conditions";
$t->refresh = 600;

$t->breadcrumbs = <<<EOM
<ol class="breadcrumb mb-0">
<li class="breadcrumb-item"><a href="/DCP/">DCP Network</a></li>
<li class="breadcrumb-item active" aria-current="page">Sortable Currents</li>
</ol>
EOM;
$cols = array(
    "valid" => "Timestamp",
    'station' => "Station ID",
    'name' => 'Station Name',
    'HGIZ' => 'Water Stage Height',
    'TAIZ' => 'Air Temperature',
    'PPHZ' => '1 Hour Precip',
    'PPDZ' => 'Today Precip',
    'VBIZ' => 'Battery Voltage',
    'TWIZ' => 'Water Temperature',
);
if (!array_key_exists($sortcol, $cols)) {
    die405();
}

$stname = iem_pg_prepare(
    $pgconn,
    "select c.*, s.name, " .
        "c.valid at time zone s.tzname as localvalid " .
        "from current_shef c JOIN stations s " .
        "on (c.station = s.id) where s.network = $1 and c.value > -1000 ".
        "order by valid desc"
);
$rs = pg_execute($pgconn, $stname, array($network));

$obs = array();
while ($row = pg_fetch_assoc($rs)) {
    $datakey = sprintf(
        "%s%s%s",
        $row["physical_code"],
        $row["duration"],
        $row["extremum"]
    );
    $lvalid = strtotime($row["localvalid"]);
    if (!array_key_exists($row['station'], $obs)) {
        $obs[$row['station']] = array("valid" => $lvalid);
    }
    if ($lvalid != $obs[$row['station']]['valid']) {
        continue;
    }
    $obs[$row['station']][$datakey] = $row["value"];
    $obs[$row['station']]['name'] = $row["name"];
}
$final = aSortBySecondIndex($obs, $sortcol, "desc");

$nselect = selectNetworkType("DCP", $network);
$nselect = str_replace('class="iemselect2"', 'class="iemselect2 form-select"', $nselect);
$nselect = str_replace('<select ', '<select id="network-select" ', $nselect);

$ar = array("no" => "No", "yes" => "Yes");
$sselect = make_select(
    "shef",
    $shef ? "yes" : "no",
    $ar,
    "",
    "form-select",
    FALSE,
    FALSE,
    TRUE,
    array("id" => "shef-select")
);

$t->current_network = "DCP";
$shefqs = $shef ? "&shef=yes" : "";
$baseurl2 = "current.phtml?network=$network{$shefqs}&sortcol=";

$content = <<<EOM
<div class="card shadow-sm mb-3">
    <div class="card-body">
        <form method="GET" action="current.phtml" name="myselector" class="row g-3 align-items-end">
            <input type="hidden" name="sortcol" value="{$sortcol}">
            <div class="col-12 col-lg-6">
                <label for="network-select" class="form-label mb-1">Select Network</label>
                {$nselect}
            </div>
            <div class="col-12 col-md-4 col-lg-3">
                <label for="shef-select" class="form-label mb-1">Show SHEF Codes</label>
                {$sselect}
            </div>
            <div class="col-12 col-md-4 col-lg-3">
                <button type="submit" class="btn btn-primary w-100">Update View</button>
            </div>
        </form>
    </div>
</div>

<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-2 mb-2">
    <p class="mb-0">Sorted by: <span class="badge text-bg-light">{$cols[$sortcol]}</span></p>
    <p class="text-body-secondary small mb-0">Rows with stale observations are highlighted.</p>
</div>

<div class="table-responsive">
<table class="table table-sm table-striped table-bordered table-hover align-middle mb-0">
<caption class="caption-top">Latest DCP/GOES observations for selected state.</caption>
<thead class="table-light">
<tr>
  <th><a href="{$baseurl2}station">SiteID:</a></th>
  <th><a href="{$baseurl2}name">Station Name:</a></th>
  <th><a href="{$baseurl2}valid">Valid:</a></th>
  <th><a href="{$baseurl2}HGIZ">Stage</a> [ft]</th>
  <th><a href="{$baseurl2}TAIZ">Temp</a> [F]</th>
  <th><a href="{$baseurl2}TWIZ">Water Temp</a> [F]</th>
  <th><a href="{$baseurl2}PPHZ">1h Rain</a> [in]</th>
  <th><a href="{$baseurl2}PPDZ">Today Rain</a> [in]</th>
  <th><a href="{$baseurl2}VBIZ">Battery</a> [V]</th>
  </tr></thead>
<tbody>
EOM;
$now = time();
foreach ($final as $site => $value) {
    $url = sprintf("/sites/site.php?station=%s&network=%s", $site, $network);
    $content .= "<tr><td><a href=\"$url\">$site</a></td>
    <td>" . $value["name"] . "</td>";
    $content .= "<td class=\"text-nowrap";
    $tdiff = $now - $value["valid"];
    $dtfmt = "d M h:i A";
    if ($tdiff > (6 * 3600)) {
        $dtfmt = "d M Y h:i A";
        $content .= ' table-danger fw-semibold';
    }
    $content .= "\">" . date($dtfmt, $value["valid"]) . "</td>";

    if (array_key_exists('HGIZ', $value)) {
        $content .= sprintf("<td>%s</td>", $value["HGIZ"]);
    } else {
        $content .= "<td></td>";
    }

    if (array_key_exists('TAIZ', $value)) {
        $content .= sprintf("<td>%s</td>", $value["TAIZ"]);
    } else {
        $content .= "<td></td>";
    }

    if (array_key_exists('TWIZ', $value)) {
        $content .= sprintf("<td>%s</td>", $value["TWIZ"]);
    } else {
        $content .= "<td></td>";
    }

    if (array_key_exists('PPHZ', $value)) {
        $content .= sprintf("<td>%s</td>", $value["PPHZ"]);
    } else {
        $content .= "<td></td>";
    }

    if (array_key_exists('PPDZ', $value)) {
        $content .= sprintf("<td>%s</td>", $value["PPDZ"]);
    } else {
        $content .= "<td></td>";
    }

    if (array_key_exists('VBIZ', $value)) {
        $content .= sprintf("<td>%s</td>", $value["VBIZ"]);
    } else {
        $content .= "<td></td>";
    }


    $content .= "</tr>";
    if ($shef) {
        $content .= "<tr class=\"table-secondary\"><td colspan=\"9\" class=\"small font-monospace\">";
        foreach ($value as $k => $v) {
            if ($k == 'name' || $k == 'valid') continue;
            $content .= sprintf("/%s %s ", $k, $v);
        }
        $content .= "</td></tr>";
    }
}
$content .= <<<EOM
</tbody><tfoot>
<tr><td colspan="9">&nbsp;</td></tr>
</tfoot></table>
</div>
EOM;
$t->content = $content;
$t->render('sortables.phtml');
