<?php
require_once "../../config/settings.inc.php";
require_once "../../include/database.inc.php";
require_once "../../include/sites.php";
require_once "../../include/myview.php";

$ctx = get_sites_context();
$station = $ctx->station;
$network = $ctx->network;
$metadata = $ctx->metadata;
$t = new MyView();
$t->iemselect2 = true;
$t->title = "Site Calibration";
$t->sites_current = "cal";

$xref = array(
    "IA_ASOS" => "iaawos",
    "IA_RWIS" => "iarwis",
    "ISUAG" => "isuag",
    "ISUSM" => "isusm"
);

$portfolio = array_key_exists($network, $xref) ? $xref[$network] : null;

$varDict = array(
    "tmpf" => "Air Temperature [F]",
    "dwpf" => "Dew Point [F]"
);
$table = "";
if ($portfolio != null) {
    $conn = iemdb("portfolio");
    $stname = iem_pg_prepare(
        $conn,
        "SELECT * from iem_calibration WHERE portfolio = $1 and " .
            "station = $2 ORDER by valid DESC"
    );
    $rs = pg_execute($conn, $stname, array($portfolio, $station));

    if (pg_num_rows($rs) == 0) {
        $table .= "<tr><th colspan=6>No events found in database.</th></tr>";
    }

    $rowDict = array("tmpf" => "", "dwpf" => "");
    while ($row = pg_fetch_assoc($rs)) {
        $param = $row["parameter"];
        $color = "#00f";
        $ts = strtotime(substr($row["valid"], 0, 16));
        $ds = date("d M Y, h:i A", $ts);
        if (floatval($row["adjustment"]) > 0) {
            $color = "#f00";
        }
        $rowDict[$param] .= sprintf("<tr style=\"color: $color;\"><th>%s</th><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>", $row["id"], $row["station"], $ds, $row["parameter"], $row["final"], $row["adjustment"]);
        if (strlen($row["comments"]) > 0) {
            $rowDict[$param] .= "<tr><td></td><td colspan=5>Comments: " . $row["comments"] . "</td></tr>";
        }
    }

    foreach ($rowDict as $param => $tbl) {
        $table .= "<tr><th colspan=\"6\" align=\"left\" style=\"background: #eee; border-bottom: 1px solid #000\">" . $varDict[$param] . "</th></tr>";
        $table .= $tbl;
    }
} else {
    $table .= "<tr><td colspan=\"6\">Sorry no calibration information is collected for $network network</td></tr>";
}

$t->content = <<<EOM
<table class="table table-striped">
<thead><tr>
 <th>ID#:</th>
 <th>Station ID:</th>
 <th>Valid:</th>
 <th>Variable:</th>
 <th>Final Value:</th>
 <th>Adjustment:</th>
</tr></thead>
{$table}
</table>
EOM;
$t->render('sites.phtml');
