<?php
require_once "../../config/settings.inc.php";
require_once "../../include/myview.php";
require_once "../../include/forms.php";
$t = new MyView();
$t->current_network = "RWIS Traffic";
require_once "../../include/database.inc.php";
$dbconn = iemdb("iem");
$sortcol = isset($_GET['sortcol']) ? xssafe($_GET['sortcol']): 'valid';

/* Query out the data */
$stname = iem_pg_prepare($dbconn, <<<EOM
    WITH data as (
        SELECT t.location_id, avg_speed, normal_vol, long_vol, occupancy,
        valid, s.name from
        rwis_traffic t JOIN rwis_traffic_sensors s on (t.id = s.id)
    )
    select d.*, t.name as station_name from data d JOIN stations t ON
    (d.location_id = t.remote_id) WHERE t.network = 'IA_RWIS'
EOM
);
$rs = pg_execute($dbconn, $stname, Array() );

 $t->title = "RWIS Current Traffic Data";
 $t->refresh = 600;

 function fancytime($strtime){
    if (is_null($strtime)) return "";
     $now = time();
     $ts = strtotime($strtime);
     if (($now - $ts) < 600){ return date("h:i A", $ts); }
     else { return date("M d h:i A", $ts); }
 }
 $vals = Array(
         "name" => "Station Name",
         "valid" => "Observation Time",
         "avg_speed" => "Average Speed [mph]",
         "normal_vol" => "2 Axel Volume",
         "long_vol" => "3+ Axel Volume",
         "occupancy" => "Occupancy",
 );

 $table = "";
 for($i=0;$row=pg_fetch_assoc($rs);$i++){
     $table .= sprintf("<tr><th>%s</th><th>%s</th><td>%s</td><td>%.1f</td><td>%s</td><td>%s</td><td>%s</td></tr>\n",
             $row["station_name"], $row["name"], fancytime($row["valid"]), $row["avg_speed"],
             $row["normal_vol"], $row["long_vol"], $row["occupancy"]);
 }

$t->content = <<<EOM
<h3>Iowa RWIS Traffic Data</h3>

<p>** This page will automatically refresh every 10 minutes.
<br>Click on a column to sort it.</p>

<p>Sorted by: <b>{$vals[$sortcol]}</b><br>
<table style="width: 100%; font-size: 10pt;" cellspacing="0" cellpadding="1" border="1">
<thead>
<tr>
  <th><a href="traffic.phtml?sortcol=name">Station:</a></th>
  <th>Lane ID:</th>
  <th><a href="traffic.phtml?sortcol=valid">Ob Time</a></th>
  <th><a href="traffic.phtml?sortcol=avg_speed">Average Speed</a></th>
  <th><a href="traffic.phtml?sortcol=normal_vol">2 axel volume</a></th>
  <th><a href="traffic.phtml?sortcol=long_vol">3+ axel volume</a></th>
  <th><a href="traffic.phtml?sortcol=occupancy">Occupancy</a></th>
</tr>
</thead>
<tbody>
{$table}
</tbody>
</table>

</form>

<br><br>
EOM;
$t->render("sortables.phtml");
