<?php
session_start();
if( $_SESSION["user"] == "" || $_SESSION["passwd"] == "" ) {
  header("Location: index.php");
}

$_SESSION["module"] = "T&eacute;cnica";
$permisos = $_SESSION["permisos"];
$section = "online";

include_once('db_config.php');
ini_set('max_execution_time', 120);

$admin = false;
include 'header.php'; 


$Total_Pages = 0;
$TotalRecords = isset($_POST['total']) ? $_POST["total"]  : "0"; 
$items_per_page = 50;
$Offset = 0;
$Page = isset($_POST['page']) ? $_POST["page"]  : "1";
$Order = isset($_POST['order']) ? $_POST["order"]  : "No";
$Direction = isset($_POST['dir']) ? $_POST["dir"]  : "0";
$Last_Order = $_SESSION["lastorder"];
$q = isset($_POST['query']) ? $_POST["query"]  : "";

   if( $Direction == 1 ) {
      $dir_text = " DESC ";
      $order_arrow = "<span class='right'><i class='material-icons'>arrow_drop_down</i><span>";
   }
   else {
      $dir_text = " ASC ";
      $order_arrow = "<span class='right'><i class='material-icons'>arrow_drop_up</i></span>";
   }
   for( $i = 0 ; $i < 7; $i++ ) $o[i] = "";

//echo $Order . "<br/>";

   switch( $Order ) {
      case '3':
         $order_txt = "framedipaddress";
         $o[1] = $order_arrow;
         break;

      case '4':
         $order_txt = "acctstarttime";
         $o[2] = $order_arrow;
         break;

      case '5':
         $order_txt = "acctsessiontime";
         $o[3] = $order_arrow;
         break;

      case '6':
         $order_txt = "acctoutputoctets";
         $o[4] = $order_arrow;
         break;

      case '7':
         $order_txt = "acctinputoctets";
         $o[5] = $order_arrow;
         break;

      case '8':
         $order_txt = "shortname";
         $o[6] = $order_arrow;
         break;

      default:
         $order_txt = "ag_users.lastname,ag_users.firstname, acctstarttime";
         if( $Direction == 1 ) 
            $order_txt = "ag_users.lastname";
         $o[0] = $order_arrow;
         break;
   }

   $_SESSION["lastorder"] = $Order;
   $Last_Order = $Order;

//echo $Order . "<br/>";
//echo $Direction . "<br/>";
//echo $Last_Order . "<br/>";

?>
<style>
.dropdown-content {
  overflow-x: hidden;
}

#claim:hover {
   background-color: #cfd8dc; 
}

.data {
   margin-top: 10px; 
   margin-bottom: 0;                       
   padding-left: 5%;
}


.margin {
   margin-top: 0; 
   margin-bottom: 0; 
}

.margin-label {
   margin-top: 5px; 
}

.row {
   padding: 0;
   margin: 0;
}

input[type=select]:disabled + label,
input[type=select]:disabled,
input[type=textarea]:disabled,
input[type=textarea] + label,
textarea.materialize-textarea:disabled + label, 
input[type=text] + label,
input[type=text]:disabled + label {
   color: #009688;
   color: grey;
}

textarea.materialize-textarea:disabled,
input[type=text]:disabled {
   color: #303030;
}

</style>
   <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
   <div id="content">
   <div class="container"  style='width:75%;'>
    <div style="height: 15px;"></div>
    <div class="col l9 m12 s12">
      <div class="page-content">
        <div style="height:20px; style="color:#eceff1;""></div>
        </div>  
        <table id='tab_header'>
                <thead>
                  <tr class="blue-grey darken-1">
<style>
.order {
}

</style>
<?php
                    echo "<th id='1' class='col s1' style='font-weight:normal; color:#eceff1;'>#</th>";
                    echo "<th id='2' class='col s3' style='font-weight:normal; color:#eceff1; width:25%;'>Cliente" . $o[0] . "</th>";
                    echo "<th id='3' class='col s1' style='font-weight:normal; color:#eceff1;'>IP" . $o[1] . "</th>";  
                    echo "<th id='4' class='col s1 right-align' style='font-weight:normal; color:#eceff1; width:18%;'>Conexion" . $o[2] . "</th>"; 
                    echo "<th id='5' class='col s1 right-align' style='font-weight:normal; color:#eceff1;'>Tiempo" . $o[3] . "</th>"; 
                    echo "<th id='6' class='col s1 right-align' style='font-weight:normal; color:#eceff1;'>Bajada" . $o[4] . "</th>"; 
                    echo "<th id='7' class='col s1 right-align' style='font-weight:normal; color:#eceff1;'>Subida" . $o[5] . "</th>"; 
                    echo "<th id='8' class='col s2' style='font-weight:normal; color:#eceff1; width:10%;'>Nodo" . $o[6] . "</th>"; 
                  echo "</tr>"; 
                echo "</thead>"; 
                echo "<tbody>"; 

//   if( $TotalRecords <= 0 ) {

      $sql = "select sql_no_cache count(radacctid) as total from radacct where acctstoptime is NULL or acctstoptime =''";
      $result = $conn->query($sql);
      if ($result->num_rows > 0) {
         if( $row = $result->fetch_assoc()) {
            $TotalRecords = $row["total"];
         }
      }
      mysql_free_result( $result );
//   }
//   $TotalPages = intval( $TotalRecords / $items_per_page );
   $Total_Pages = IntVal( ( $TotalRecords / $items_per_page ) + 1 );

//   if( ( $TotalRecords - ( $TotalPages * $items_per_page ) ) > 0 ) $TotalPages += 1;
   $Offset = ($Page - 1) * $items_per_page;
   if( $Page > 1 ) $Offset -= ( $Page - 1 );
   
   if( strlen( $q ) > 0 ) {
//       $sql = "select sql_no_cache username, lastname from ag_useres where lastname like '" . $q . "%' order by " . $order_txt. $dir_text . " limit " . $Offset . ", " . $items_per_page; ;

      $sql = "select sql_no_cache *, concat(ag_users.lastname,' ',ag_users.firstname) as nombre from radacct left join nas on nasname = nasipaddress left join rm_users on rm_users.username=radacct.username left join ag_users on ag_users.username=radacct.username where ( acctstoptime is NULL or acctstoptime ='' ) and ag_users.lastname is not null and ( ag_users.lastname like '%" . $q . "%' or  ag_users.firstname like '%" . $q . "%' )  group by radacctid order by " . $order_txt. $dir_text . " limit " . $Offset . ", " . $items_per_page; ;
//      echo $sql . "<br/>";
   }
   else {
       $sql = "select sql_no_cache *, concat(ag_users.lastname,' ',ag_users.firstname) as nombre from radacct left join nas on nasname = nasipaddress left join rm_users on rm_users.username=radacct.username left join ag_users on ag_users.username=radacct.username where acctstoptime is NULL or acctstoptime ='' and ag_users.lastname is not null group by radacctid order by " . $order_txt. $dir_text . " limit " . $Offset . ", " . $items_per_page;
   }
//   echo $sql . "<br/>";
   $result = $conn->query($sql);
   $xor = 0;
   $n = 0;
   if ($result->num_rows > 0) {
       while($row = $result->fetch_assoc()) {

           $date = date_create($row["acctstarttime"]);
           $formatted = date_format($date, 'd-m-Y H:i');

           $sessiontime = $row["acctsessiontime"];
           $duracion = Seconds_2_Time($sessiontime);

           $size = $row["acctoutputoctets"];
           if( $size >= (1024 * 1024 * 1024))
           {
               $size /= (1024 * 1024 * 1024);
               $bajada = sprintf( "%10.2lf GB", $size );
           }
           else 
           {
               $size /= (1024 * 1024);
               $bajada = sprintf( "%10.2lf MB", $size );
           }

           $subida = $row["acctinputoctets"];
           if( $subida >= (1024 * 1024 * 1024))
           {
               $subida /= (1024 * 1024 * 1024);
               $upload = sprintf( "%10.2lf GB", $subida );
           }
           else 
           {
               $subida /= (1024 * 1024);
               $upload = sprintf( "%10.2lf MB", $subida );
           }

//           $num = sprintf( " %3d", ($Offset + $n) );
           $num = ($Offset + $n + 1);

           $ip = $row["framedipaddress"];
           if( $xor ^= 1 ) echo "<tr>";  
           else echo "<tr class='blue-grey lighten-5'>";
           echo "<td class='col s1 right-align' >" . $num . "</td>";
//         echo "<td class='col s4' style='width:25%;'><a href='tecnica.php'>" . $row["nombre"] . "</a></td>";
           echo "<td class='col s4' style='width:25%;'>" . $row["nombre"] . "</td>";
           echo "<td class='col s1' ><a target='_blank' href='http://$ip'>" . $ip . "</a></td>";
           echo "<td class='col s1 right-align' style='width:18%;'>" . $formatted . "</td>";
           echo "<td class='col s1 right-align' >" . $duracion . "</td>";
           echo "<td class='col s1 right-align' >" . $bajada . "</td>";
           echo "<td class='col s1 right-align' >" . $upload . "</td>";
           echo "<td class='col s2' style='width:10%;'>" . $row["shortname"] . "</td>";
        echo "</tr>";
        ++$n;
    }
  }     
   mysqli_close($conn);
?>          
              </tbody>
            </table>
          </div>
    <div style="height:20px;"></div>
    <div class='container' >
    <div class="col l9 m12 s12">
    <div class="page-content center-align">
<?php

   if( $offset == 0 ) $first_page="disabled";
   else $first_page = "waves-effect";

   echo "<div style='margin:15px; margin-top: 0;'>P&aacute;gina " . $Page . " de " . $Total_Pages . "</div>"; 
   echo "<ul class='pagination'>";
       echo "<li class='" . $first_page . "' onclick='clickFirst(this)'><i class='material-icons'>first_page</i></li>"; 
       echo "<li class='waves-effect' onclick='clickLeft(this)'><i class='material-icons'>chevron_left</i></li>"; 
       echo "<li class='waves-effect' onclick='clickRight(this)'><i class='material-icons'>chevron_right</i></li>"; 
       echo "<li class='waves-effect' onclick='clickLast(this)'><i class='material-icons'>last_page</i></li>"; 
  echo "</ul>"; 
  echo "</div>"; 
  echo "</div>"; 
  echo "</div>"; 

   function Seconds_2_Time($seg) {
      $d = floor($seg / 86400);
      $h = floor(($seg - ($d * 86400)) / 3600);
      $m = floor(($seg - ($d * 86400) - ($h * 3600)) / 60);
      $s = $seg % 60;
      $dh = sprintf( "%dd:%02dh:%02d", $d, $h, $m );
      return $dh;
   }      
?>
  </div>
  </div>
  <script type="text/javascript" src="js/jquery.min.js"></script>
      <script type="text/javascript" src="js/jquery.form.js"></script> 
  <script type="text/javascript" src="js/materialize.min.js"></script>
<script>

   // Post to the provided URL with the specified parameters.
   function post(path, parameters) {
      var form = $('<form></form>');

       form.attr("method", "post");
       form.attr("action", path);

       $.each(parameters, function(key, value) {
           var field = $('<input></input>');
           field.attr("type", "hidden");
           field.attr("name", key);
           field.attr("value", value);
           form.append(field);
       });

       // The form needs to be a part of the document in
       // order for us to be able to submit it.
       $(document.body).append(form);
      form.submit();
   };

/*
   function goClient(e) {
//       post("tecnica.php", {cliente: e.currentTarget.cells[0].innerHTML }); 
   };
   */

   function OnClick(e) {
//       post("dnis.php", {dia: e.currentTarget.cells[2].innerHTML, dnis: e.currentTarget.cells[2].innerHTML }); 
   };

   function clickFirst(e) {
      var pagina = 1;
      post("online.php", {page: pagina });
   }

   function clickLast(e) {
      var total = <?php echo json_encode($TotalRecords); ?>;
      var pagina = Number(total);
      post("online.php", {page: pagina, total: total });
   }

   function clickLeft(e) {

      var page = <?php echo json_encode($Page); ?>;
      var total = <?php echo json_encode($TotalRecords); ?>;
      pagina = Number(page) - 1;
      if( pagina >= 1 ) {
         post("online.php", {page: pagina, total: total });
      }
   };

   function clickRight(e) {
      var page = <?php echo json_encode($Page); ?>;
      var total = <?php echo json_encode($TotalRecords); ?>;
      pagina = Number(page) + 1;
      if( pagina <= Number(total) ) {
         post("online.php", {page: pagina, total: total });
      }
   };

  $(document).ready(function() {

    $( "#tab_header tr th" ).click(function(e) {

//       var order = e.target.innerHTML;
         var order = e.target.id;
         console.log( order );
         var direction = <?php echo json_encode($Direction); ?>;
         var last_order = <?php echo json_encode($Last_Order); ?>;
         if( last_order == order ) {
            direction ^= 1;
         }
         else {
            direction = 0; 
         }

//         console.dir( e );
//         console.dir( e.target.innerHTML );
//         console.dir( e.target.innerText );
         var page = <?php echo json_encode($Page); ?>;
         var total = <?php echo json_encode($TotalRecords); ?>;
         pagina = Number(page);
//         post("online.php", {page: pagina, total: total, order: e.target.innerHTML, dir: direction });
         post("online.php", {page: pagina, total: total, order: e.target.id, dir: direction });
     });


    $('#tab_header').on('click', 'tr', function(e) {
//         alert( "Ordenar" );
    });

  });   
</script>
</body>
</html>
