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

$metar = get_str404("metar", "no");
$refresh = get_str404("refresh", "yes");
$sortcol = get_str404("sortcol", "ts");
$sortdir = get_str404("sortdir", "asc");
$expiry = 60 * 60 * 24 * 100; // 100 days

$t = new MyView();
// Clear duplicates from cookies
$stations = isset($_COOKIE["stations"]) ? array_unique(explode(",", $_COOKIE["stations"])) : array();
$st = isset($_GET["st"]) ? $_GET["st"] : "";
$str = isset($_GET["str"]) ? $_GET["str"] : "";

if ($st != "") {
    foreach ($st as $key => $value) {
        if (strlen($value) > 0 && !in_array($value, $stations)) {
            $stations[] = $value;
        }
    }
}
if ($str != "") {
    foreach ($str as $key => $value) {
        if (($key2 = array_search($value, $stations)) !== false) {
            unset($stations[$key2]);
        }
    }
}
setcookie("stations", implode(",", $stations), time() + $expiry, "/my/");

$t->title = "My IEM Current Conditions";
if ($refresh == 'yes') {
    $t->refresh = 60;
}
$t->current_network = "My Favorites";

$vals = array(
    "valid" => "Observation Time", "tmpf" => "Temperature",
    "dwpf" => "Dew Point", "pres" => "Altimeter", "relh" => "Relative Humidity",
    "sknt" => "Wind Speed", 12 => "20 min Gust",
    "gust" => "Peak Gust Today", "gtim" => "Time of Peak Gust",
    "pday" => "Today's Precipitation", "feel" => "Feels Like",
    "pmonth" => "Month's Precipitation", "phour" => "Hourly Precip",
    "tmpf0" => "Sensor 1 - Temp [F]",  "name" => "Station Name",
    "tmpf1" => "Sensor 2 - Temp [F]",
    "tmpf2" => "Sensor 3 - Temp [F]",
    "tmpf3" => "Sensor 4 - Temp [F]",
    "dry0" => "Sensor 1 - Cond [F]",
    "dry1" => "Sensor 2 - Cond [F]",
    "dry2" => "Sensor 3 - Cond [F]",
    "dry3" => "Sensor 4 - Cond [F]",
    "tsf0" => "Sensor 1 - Temp [F]",
    "tsf1" => "Sensor 2 - Temp [F]",
    "tsf2" => "Sensor 3 - Temp [F]",
    "tsf3" => "Sensor 4 - Temp [F]",
    "rwis_subf" => "Subsurface Temp [F]",
    "pave_avg" => "Average Surface Temp [F]",
    "ts" => "Observation Time", "min_tmpf" => "Low Air Temperature Today",
    "vsby" => "Visibility", "max_tmpf" => "High Air Temperature Today",
    "max_sknt_ts" => "Time of Peak Gust",
    "max_sknt" => "Wind Gust [knots]", "peak" => "Peak Wind Gust [kts]",
    "peak_ts" => "Time of Peak Wind Gust",
    "city" => "Site Name"
);

$allowedSortCols = array_filter(array_keys($vals), "is_string");
if (!in_array($sortcol, $allowedSortCols, true)) {
    $sortcol = "ts";
}
if ($sortdir !== "asc" && $sortdir !== "desc") {
    $sortdir = "asc";
}
$rsortdir = ($sortdir === "asc") ? "desc" : "asc";

$ar = array(
    "no" => "No",
    "yes" => "Yes"
);
$mselect = make_select("metar", $metar, $ar);
$ar = array(
    "no" => "No",
    "yes" => "Yes"
);
$refresh_select = make_select("refresh", $refresh, $ar);

// Build a listing of stations to get data for
$reqstations = Array();
$doSF = FALSE;
foreach ($stations as $key => $value) {
    if (strpos($value, '_SF') == 5) {
        $value = substr($value, 0, 5);
        $doSF = TRUE;
    }
    $reqstations[] = $value;
}

if (!empty($reqstations)) {
    $jobj = require_json_response("/api/1/currents.json", array("station" => implode(",", $reqstations)));
} else {
    $jobj = array("data" => array());
}

$mydata = array();
foreach ($jobj["data"] as $bogus => $iemob) {
    $value = $iemob["station"];
    $mydata[$value] = $iemob;
    $mydata[$value]["ts"] = strtotime($mydata[$value]["local_valid"]);
    $mydata[$value]["sped"] = $mydata[$value]["sknt"] * 1.15078;
    $mydata[$value]["relh"] = relh(
        f2c($mydata[$value]["tmpf"]),
        f2c($mydata[$value]["dwpf"])
    );

    $mydata[$value]["peak_ts"] = 0;
    $mydata[$value]["peak"] = 0;
    if ($mydata[$value]["max_gust"] > $mydata[$value]["max_sknt"]) {
        $mydata[$value]["peak"] = $mydata[$value]["max_gust"];
        if ($mydata[$value]["local_max_gust_ts"] > 0) {
            $mydata[$value]["peak_ts"] = strtotime($mydata[$value]["local_max_gust_ts"]);
        }
    } else {
        $mydata[$value]["peak"] = $mydata[$value]["max_sknt"];
        if ($mydata[$value]["local_max_sknt_ts"] > 0) {
            $mydata[$value]["peak_ts"] = strtotime($mydata[$value]["local_max_sknt_ts"]);
        }
    }
    if ($mydata[$value]["pday"] < 0) $mydata[$value]["pday"] = "";
    if ($mydata[$value]["phour"] < 0) $mydata[$value]["phour"] = "";
    if ($mydata[$value]["vsby"] < 0) $mydata[$value]["vsby"] = "";
}

if (sizeof($mydata) == 0) {
    $t->content = "<p>There are currently 0 sites in your selected list.  Please visit
    one of the data network pages listed above and add sites to your favorites
    list.</p>";
    $t->render('sortables.phtml');
    die();
}
$uri = "current.phtml?sortdir={$rsortdir}&amp;refresh=$refresh&amp;metar=$metar&amp;sortcol=";

$finalA = aSortBySecondIndex($mydata, $sortcol, $sortdir);
$now = time();
$cgiStr = "";
$i = 0;
$table = "";

foreach ($finalA as $key => $val) {
    $i++;
    $parts = $finalA[$key];
    $cgiStr .= "st[]=" . $key . "&";
    $tdiff = $now - $parts["ts"];
    $table .= "<tr";
    if ($i % 2 == 0)  $table .= " bgcolor='#eeeeee'";
    $table .= ">\n
    <td><input type=\"checkbox\" name=\"str[]\" value=\"" . $key . "\"></td>
    <th>" . $parts["name"] . " [" . $parts["network"] . "]</th>";
    $table .= "<td ";
    $format = "h:i A";
    if ($tdiff > 10000) {
        $table .= 'bgcolor="red"';
        $format = "M d h:i A";
    } else if ($tdiff > 3600) {
        $table .= 'bgcolor="green"';
    } else {
    }
    $table .= ">" . date($format, $parts["ts"]) . "</td>";
    $table .= sprintf("<td>%s</td>\n", $parts["wxcodes"]);

    $table .= "<td align='center'>" . myround($parts["tmpf"], 0) . "(<font color=\"#ff0000\">" . myround($parts["max_tmpf"], 0) . "</font>/<font color=\"#0000ff\">" . myround($parts["min_tmpf"], 0) . ")</td>
          <td align='center'>" . myround($parts["dwpf"], 0) . "</td>
          <td>" . myround($parts["feel"], 0) . "</td>
          <td>" . myround($parts["relh"], 0) . "</td>
          <td>" . $parts["alti"] . "</td>
          <td>" . $parts["vsby"] . "</td>
            <td>" . myround($parts["drct"], 0) . "</td>
            <td>" . myround($parts["sknt"], 0) . "</td><td>" . myround($parts["peak"], 0) . " @ ";
    $table .= date($format, $parts["peak_ts"]);
    $table .= "</td>
          <td>" . $parts["phour"] . "</td>
          <td>" . $parts["pday"] . "</td></tr>\n";
    if ($metar == "yes") {
        $table .= "<tr";
        if ($i % 2 == 0)  $table .= " bgcolor='#eeeeee'";
        $table .= ">";
        $table .= "<td colspan=15 align=\"CENTER\">
             <font color=\"brown\">" . $parts["raw"] . "</font></td>
             </tr>\n";
    }
}

$content = <<<EOM
<form name="opts" method="GET" action="current.phtml">
<input type="hidden" name="sortcol" value="{$sortcol}">
<input type="hidden" name="refresh" value="{$refresh}">
<p>
<table class="table table-sm">
<tr>
  <th>View Options:</th>
  <td>Include METARS (ASOS): {$mselect}</td>
  <th>Automatically Refresh?</th>
  <td>{$refresh_select}</td>
  <td><input type="submit" value="Update Settings"></td>
</tr></table><p>
</form>


<h3></h3>

<br>Sorted by: <b>({$vals[$sortcol]})</b>  &nbsp; &nbsp;
Click on a column to sort it.<br>

<form method="GET" action="current.phtml">

<table class="table table-striped table-sm table-bordered">
<thead>
<tr>

  <th rowspan="2">DEL</th>
  <th rowspan="2"><a href="{$uri}name">Station:</a></th>
  <th rowspan="2"><a href="{$uri}ts">Valid</a></th>
  <th rowspan="2">Present Wx</th>
  <th colspan=6></td>
  <th colspan="3" bgcolor="#EEEEEE">Wind (knots)</th>
  <th colspan="2" bgcolor="#e6e6fa">Precipitation (inch)</th>
</tr>
<tr>
  <th><a href="{$uri}tmpf">Temp</a> (<a href="{$uri}max_tmpf">Hi</a>/<a href="{$uri}min_tmpf">Lo</a>)</th>
  <th><a href="{$uri}dwpf">DewP</a></th>
  <th><a href="{$uri}feel">Feels</a></th>
  <th><a href="{$uri}relh">RH%</a></th>
  <th><a href="{$uri}pres">Pres</a></th>
  <th><a href="{$uri}vsby">Vsby</a></th>
  <th>Dir</th>
  <th><a href="{$uri}sknt">Speed</a></th>
  <th><a href="{$uri}peak">Today Gust</a>
    <a href="{$uri}peak_ts">@time</a></th>
  <th><a href="{$uri}phour">Hour</a></th>
  <th><a href="{$uri}pday">Today</a></th>
</tr>
 </thead>
<tbody>
{$table}
</tbody>
</table>

<input type="submit" value="Remove Stations">
</form>
EOM;
if ($doSF) {
    $sfstations = array();
    foreach ($stations as $key => $value) {
        if (strpos($value, '_SF') == 5) {
            $value = substr($value, 0, 5);
            if (!array_key_exists($value, $mydata)) {
                continue;
            }
            $sfstations[] = $value;

            $t2 = array(
                $mydata[$value]['tsf0'], $mydata[$value]['tsf1'],
                $mydata[$value]['tsf2'], $mydata[$value]['tsf3']
            );
            arsort($t2);
            while (min($t2) == -99.99) {
                $ba = array_pop($t2);
                if (sizeof($t2) == 0) break;
            }
            if (sizeof($t2) > 0) {
                while ((max($t2) - min($t2)) > 20) {
                    $ba = array_pop($t2);
                }
                $mydata[$value]['pave_avg'] = array_sum($t2) / sizeof($t2);
            } else {
                $mydata[$value]['pave_avg'] = -99.99;
            }
        }
    }
    $table = "";
    reset($mydata);
    $finalA = aSortBySecondIndex($mydata, $sortcol);
    $i = 0;
    $now = time();
    foreach ($finalA as $key => $val) {
        if (!in_array($key, $sfstations)) continue;
        $parts = $finalA[$key];
        $i++;
        $tdiff = $now - $parts["ts"];
        if ($tdiff > 86400 * 5) {
            continue;
        }
        $table .= "<tr";
        if ($i % 2 == 0)  $table .= " bgcolor='#eeeeee'";

        $table .= ">";
        $table .= "<td><input type=\"checkbox\" name=\"str[]\"
            value=\"" . $key . "_SF\"></td>";
        $table .= "<th>" . $parts["name"] . "</th>";
        $table .= "<td";
        if ($tdiff > 11900) {
            $table .= ' bgcolor="red">' . date("M-d-Y h:i A", $parts["ts"]) . '</td>';
        } else if ($tdiff > 7200) {
            $table .= ' bgcolor="orange">' . date("M-d-Y h:i A", $parts["ts"]) . '</td>';
        } else if ($tdiff > 3600) {
            $table .= ' bgcolor="green">' . date("h:i A", $parts["ts"]) . '</td>';
        } else {
            $table .= '>' . date("h:i A", $parts["ts"]) . '</td>';
        }
        if ($parts["tsf0"] < -90) $tmpf0 = "M";
        else $tmpf0 = myround($parts["tsf0"], 1);
        if ($parts["tsf1"] < -90) $tmpf1 = "M";
        else $tmpf1 = myround($parts["tsf1"], 1);
        if ($parts["tsf2"] < -90) $tmpf2 = "M";
        else $tmpf2 = myround($parts["tsf2"], 1);
        if ($parts["tsf3"] < -90) $tmpf3 = "M";
        else $tmpf3 = myround($parts["tsf3"], 1);
        if ($parts["rwis_subf"] < -90) $subt = "M";
        else $subt = myround($parts["rwis_subf"], 1);
        if ($parts["pave_avg"] < -90) $pave_avg = "M";
        else $pave_avg = myround($parts["pave_avg"], 1);

        $table .= "<td align='center'>{$parts['tmpf']}</td>
            <td align='center'>{$parts['dwpf']}</td>
            <td align='center'>{$tmpf0}</td>
            <td align='center'>{$tmpf1}</td>
            <td align='center'>{$tmpf2}</td>
            <td align='center'>{$tmpf3}</td>
            <td align='center'>{$subt}</td>
            <td align='center'>{$pave_avg}</td>
            </tr>\n";
    }

    $content .= <<<EOM
<h3>RWIS Pavement Conditions</h3>
<form method="GET" action="current.phtml" name="opts2">
<input type="hidden" name="sortcol" value="{$sortcol}">
<input type="hidden" name="refresh" value="{$refresh}">
<table class="table table-striped table-sm table-bordered">
<tr>
  <td rowspan="2">DEL:</td>
  <th rowspan="2"><a href="{$uri}name">Station:</a></th>
  <th rowspan="2"><a href="{$uri}ts">Ob Time</a></th>
  <th colspan="2" bgcolor="#acdcda">Air:</th>
  <th bgcolor="#acdcda">Sensor 1</th>
  <th bgcolor="#acdcda">Sensor 2</th>
  <th bgcolor="#acdcda">Sensor 3</th>
  <th bgcolor="#acdcda">Sensor 4</th>
  <td></td>
  <td></td>
<tr>

  <th><a href="{$uri}tmpf">Temp</a></th>
  <th><a href="{$uri}dwpf">Dew P</a></th>
  <th><a href="{$uri}tsf0">Temp</a></th>
  <th><a href="{$uri}tsf1">Temp</a></th>
  <th><a href="{$uri}tsf2">Temp</a></th>
  <th><a href="{$uri}tsf3">Temp</a></th>
  <th><a href="{$uri}rwis_subf">Sub T</a></th>
  <th><a href="{$uri}pave_avg">Ave Surface Temp</a> [<b>2</b>]
</th>
{$table}
</table>
<input type="submit" value="Remove Stations">
</form>
EOM;
}

$content .= <<<EOM
<br><br>

<b>Notes:</b><br>
        <ol>
<li>The average surface temperature is calculated by the IEM using some
logic to account for sites without 4 sensors or broken sensors.</li>
        </ol>

EOM;
$t->content = $content;
$t->render('sortables.phtml');
