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

$mesosite = iemdb('mesosite');
$t = new MyView();
$t->current_network = "RWIS Surface";
$network = get_str404("network", 'IA_RWIS');
$sortcol = get_str404("sortcol", 'ts');
if ($sortcol == "sname") $sortcol = "name";
$t->title = "RWIS Surface Currents";
$t->refresh = 600;

$vals = array(
    "tsf0" => "Sensor 1 - Temp [F]",
    "tmpf" => "Air Temp [F]",
    "dwpf" => "Dew Point [F]",
    "tsf1" => "Sensor 2 - Temp [F]",
    "tsf2" => "Sensor 3 - Temp [F]",
    "tsf3" => "Sensor 4 - Temp [F]",
    "pave_avg" => "Ave Surf Temp",
    "dry0" => "Sensor 1 - Cond [F]",
    "dry1" => "Sensor 2 - Cond [F]",
    "dry2" => "Sensor 3 - Cond [F]",
    "dry3" => "Sensor 4 - Cond [F]",
    "ts" => "Observation Time",
    "name" => "Site Name",
);
if (!array_key_exists($sortcol, $vals)) {
    die405();
}

$t->breadcrumbs = <<<EOM
<ol class="breadcrumb mb-0">
 <li class="breadcrumb-item"><a href="/RWIS/">RWIS</a></li>
 <li class="breadcrumb-item active" aria-current="page">Current Conditions</li>
</ol>
EOM;
$nselect = selectNetworkType("RWIS", $network);
$nselect = str_replace('class="iemselect2"', 'class="iemselect2 form-select"', $nselect);
$nselect = str_replace('<select ', '<select id="network-select" ', $nselect);


$mydata = array();
$arr = array(
    "network" => $network,
);
$jobj = iemws_json("currents.json", $arr);

foreach ($jobj["data"] as $bogus => $ob) {
    $key = $ob["station"];
    $mydata[$key] = $ob;
    $mydata[$key]["ts"] = strtotime($ob["local_valid"]);

    if ($mydata[$key]['tmpf'] < -60) {
        $mydata[$key]['tmpf'] = "M";
        $mydata[$key]['dwpf'] = "M";
    }

    $t2 = array(
        $mydata[$key]['tsf0'], $mydata[$key]['tsf1'],
        $mydata[$key]['tsf2'], $mydata[$key]['tsf3']
    );
    arsort($t2);

    while (min($t2) == -99) {
        $ba = array_pop($t2);
        if (sizeof($t2) == 0) break;
    }

    asort($t2);
    if (sizeof($t2) > 0) {
        while ((max($t2) - min($t2)) > 20) {
            $ba = array_pop($t2);
        }
        $mydata[$key]['pave_avg'] = array_sum($t2) / sizeof($t2);
    } else {
        $mydata[$key]['pave_avg'] = -99.99;
    }
}

$table = "";
$finalA = array();
$finalA = aSortBySecondIndex($mydata, $sortcol);
$i = 0;
$now = time();
foreach ($finalA as $key => $parts) {
    $i++;
    $tdiff = $now - $parts["ts"];
    $table .= "<tr>";
    $table .= "<td><input type=\"checkbox\" class=\"form-check-input\" name=\"st[]\"
            value=\"" . $key . "_SF\"></td>";
    $table .= "<td>" . $parts["name"] . "</td>";
    $table .= "<td class=\"text-nowrap";
    if ($tdiff > 11900) {
        $table .= ' table-danger fw-semibold">' . date("M-d-Y h:i A", $parts["ts"]) . '</td>';
    } else if ($tdiff > 7200) {
        $table .= ' table-warning fw-semibold">' . date("M-d h:i A", $parts["ts"]) . '</td>';
    } else if ($tdiff > 3600) {
        $table .= ' table-success">' . date("h:i A", $parts["ts"]) . '</td>';
    } else {
        $table .= '">' . date("h:i A", $parts["ts"]) . '</td>';
    }
    if ($parts["tsf0"] < -90) $tmpf0 = "M";
    else $tmpf0 = round($parts["tsf0"], 1);
    if ($parts["tsf1"] < -90) $tmpf1 = "M";
    else $tmpf1 = round($parts["tsf1"], 1);
    if ($parts["tsf2"] < -90) $tmpf2 = "M";
    else $tmpf2 = round($parts["tsf2"], 1);
    if ($parts["tsf3"] < -90) $tmpf3 = "M";
    else $tmpf3 = round($parts["tsf3"], 1);
    if ($parts["pave_avg"] < -90) $pave_avg = "M";
    else $pave_avg = round($parts["pave_avg"], 1);

    $table .= <<< EOM
<td>{$parts["tmpf"]}</td><td>{$parts["dwpf"]}</td>
<td>{$tmpf0} ({$parts["scond0"]})</td>
<td>{$tmpf1} ({$parts["scond1"]})</td>
<td>{$tmpf2} ({$parts["scond2"]})</td>
<td>{$tmpf3} ({$parts["scond3"]})</td>
<td>{$pave_avg}</td>
</tr>
EOM;
}

$content = <<<EOM
<div class="card shadow-sm mb-3">
    <div class="card-body">
        <form method="GET" action="currentSF.phtml" class="row g-3 align-items-end">
            <div class="col-12 col-lg-8">
                <label for="network-select" class="form-label mb-1">Select RWIS Network</label>
                {$nselect}
            </div>
            <div class="col-12 col-md-4 col-lg-4">
                <button type="submit" class="btn btn-primary w-100">Show Network</button>
            </div>
        </form>
    </div>
</div>

<div class="mb-3">
    <h2 class="h4 mb-2">Current RWIS Surface Conditions</h2>
    <p class="text-body-secondary mb-1">This page refreshes every 10 minutes. Click a column heading to change the sort.</p>
    <p class="mb-0">Sorted by: <span class="badge text-bg-light">{$vals[$sortcol]}</span></p>
</div>

<form method="GET" action="/my/current.phtml">
<div class="table-responsive">
<table class="table table-striped table-bordered table-sm table-hover align-middle mb-0">
<caption class="caption-top">RWIS surface conditions for the selected network. Timestamp colors indicate older observations.</caption>
<thead class="table-light">
<tr>
  <th rowspan="2">ADD:</th>
  <th rowspan="2"><a href="currentSF.phtml?network={$network}&sortcol=name">Station:</a></th>
  <th rowspan="2"><a href="currentSF.phtml?network={$network}&sortcol=ts">Ob Time</a></th>
  <th colspan="2">Air:</th>
  <th>Sensor 1</th>
  <th>Sensor 2</th>
  <th>Sensor 3</th>
  <th>Sensor 4</th>
  <th>&nbsp;</th>
</tr>
<tr>
  <th><a href="currentSF.phtml?network={$network}&sortcol=tmpf">Temp</a></th>
  <th><a href="currentSF.phtml?network={$network}&sortcol=dwpf">Dew P</a></th>
  <th><a href="currentSF.phtml?network={$network}&sortcol=tsf0">Temp</a></th>
  <th><a href="currentSF.phtml?network={$network}&sortcol=tsf1">Temp</a></th>
  <th><a href="currentSF.phtml?network={$network}&sortcol=tsf2">Temp</a></th>
  <th><a href="currentSF.phtml?network={$network}&sortcol=tsf3">Temp</a></th>
  <th><a href="currentSF.phtml?network={$network}&sortcol=pave_avg">Ave Surface Temp</a> [<b>1</b>]</th>
</tr></thead>
<tbody>
{$table}
</tbody>
</table>
</div>

<div class="d-flex flex-column flex-sm-row gap-2 mt-3">
        <button type="submit" class="btn btn-primary">Add to Favorites</button>
        <button type="reset" class="btn btn-outline-secondary">Reset</button>
</div>

</form>


<div class="alert alert-light border mt-4 mb-0" role="note">
        <p class="fw-semibold mb-1">Notes</p>
        <p class="mb-0"><strong>1</strong> The average surface temperature is calculated by the IEM using logic to account for sites without four sensors or with broken sensors.</p>
</div>
EOM;
$t->content = $content;
$t->render('sortables.phtml');
