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

if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
   $screen_width =  $_SESSION['screen_width'];
   $screen_height =  $_SESSION['screen_height']; 
} else if(isset($_REQUEST['width']) AND isset($_REQUEST['height'])) {
    $_SESSION['screen_width'] = $_REQUEST['width'];
    $_SESSION['screen_height'] = $_REQUEST['height'];
    header('Location: ' . $_SERVER['PHP_SELF']);
} else {
    echo '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
}

include_once('db_config_hosting.php');
include_once('db_system_status.php');
ini_set('max_execution_time', 240);

$page = $_SERVER['PHP_SELF'];
$sec = "120";
header("Refresh: $sec; url=$page");

$Fecha = isset($_POST['dia']) ? $_POST["dia"]  : "";
if( empty($Fecha) ) {        
   if( $_SESSION["fecha"] != "" ) $Fecha = $_SESSION["fecha"];
   else $Fecha = date("Y/m/d");
}
$_SESSION["fecha"] = $Fecha;
$Search = substr( $Fecha, 6, 4 ) . "-" . substr( $Fecha, 3, 2 ) . "-" . substr( $Fecha, 0, 2 );

$width = "85%";

/*
if( empty($Year) ) {        
   if( $_SESSION["year"] != "" ) $Year = $_SESSION["year"];
   else {
      $Year = date("Y");
   }
}

if( empty($Month) ) {       
   if( $_SESSION["month"] != "" ) $Month = $_SESSION["month"];
   else {
     $Month = date("n");
   }
}

if( empty($Day) ) {       
   if( $_SESSION["day"] != "" ) $Day = $_SESSION["day"];
   else {
     $Day = date("d");
   }
}

$_SESSION["Year"] = $Year;
$_SESSION["Month"] = $Month;
$_SESSION["Day"] = $Day;
*/

$informes = $_SESSION["informes"];

include 'traficoHeader.php'; 
include('fusion/fusioncharts.php');

function cnvSegundosHoras($tiempo_en_segundos) {
   $horas = floor($tiempo_en_segundos / 3600);
   $minutos = floor(($tiempo_en_segundos - ($horas * 3600)) / 60);
   $segundos = $tiempo_en_segundos - ($horas * 3600) - ($minutos * 60);
   if( $horas > 0 )
      return( sprintf("%d:%02d:%02d", $horas, $minutos, $segundos) ); 
   return( sprintf("%d:%02d", $minutos, $segundos) ); 
}
?>
<style>

.tabs {
  height: 40px !important;
}

.tabs.tabs-transparent {
  background-color: transparent;
}

.tabs.tabs-transparent .tab a,
.tabs.tabs-transparent .tab.disabled a,
.tabs.tabs-transparent .tab.disabled a:hover {
  color: rgba(255, 255, 255, 0.7);
}

.tabs.tabs-transparent .tab a:hover,
.tabs.tabs-transparent .tab a.active {
  color: #fff;
}

.tabs.tabs-transparent .indicator {
  background-color: #fff;
}

.tabs.tabs-fixed-width {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
}

.tabs.tabs-fixed-width .tab {
  -webkit-box-flex: 1;
  -webkit-flex-grow: 1;
      -ms-flex-positive: 1;
          flex-grow: 1;
}

.tabs .tab {
  line-height: 40px !important;
  height: 40px !important;
/*  text-transform: uppercase; */
  text-transform: none !important;
}

.tabs .tab a {
  color: #16a2d6 !important;
  -webkit-transition: color .28s ease, background-color .28s ease;
  transition: color .28s ease, background-color .28s ease;
}

.tabs .tab a:focus, .tabs .tab a:focus.active {
  background-color: rgba(22, 162, 214, 0.9) !important; 
  color: white !important;
  outline: none;
}

.tabs .tab a:hover, .tabs .tab a.active {
  color: #16a2d6 !important;
}

.tab a.active {
  color: white !important;
}

.tabs .tab.disabled a,
.tabs .tab.disabled a:hover {
  color: #16a2d6 !important;
}

.tabs .indicator {
  position: absolute;
  bottom: 0;
  height: 2px;
  background-color: #16a2d6;
  will-change: left, right;
}

.active {
   border: none !important;
}

.card {
-webkit-box-shadow: 0px 12px 15px -5px rgba(0,0,0,0.59); 
box-shadow: 0px 12px 15px -5px rgba(0,0,0,0.59);

}

th, td {
   padding: 0px;
}

.dropdown-content {
  overflow-x: hidden;
}

th, td {
   font-size: 11pt;
   font-weight: normal;
}

td {
   line-height:2.5em;
}

thead {
   border-bottom: none !important;
}

th {
   margin-bottom: 20px !important;
   text-decoration: underline;
   color: blue;
/*
   padding-bottom: 10px !important;
   border-width: 1px !important;
   border-bottom: solid !important;
   border-color: red !important;
   */
}

.select-wrapper input.select-dropdown {
   color: black;
   font-size:11pt;
}

.select-dropdown.dropdown-content li.selected,
.select-dropdown.dropdown-content li.selected:hover {
    background-color: rgba(0, 0, 0, 0.03);
    color: #666666;
    padding: 10px 16px !important;
}

.select-dropdown.dropdown-content li:hover {
    background-color: #16a2d6 !important;
    color: white!important;
    line-height: 16px !important;
}

.dropdown-content li {
    padding: 10px 16px !important;
}

.dropdown-content li > a, .dropdown-content li > span {
    color: inherit;
}


.dropdown-content li:focus,
.dropdown-content li > a, .dropdown-content li > span {
  font-size: 14px;
 //  color: black !important;
  color: #444444;
  display: block;
  line-height: 16px !important;
  padding: 10px 16px;
  margin: 0 0;
}

   .butn {
      color:black;
   }

   .butn:hover {
     color: red;
   }


</style>
<?php

/*
      $t1 = "Tramas 1-6";
      $t2 = "Tramas 7-12";
      $t3 = "Ouichat Tramas 1-6";
      $t4 = "Tr&aacute;fico";
      $t5 = "Informes";
      if( $screen_width <= 600 ) {
         $c = 4;
         $t1 = "Tramas 1-4";
         $t2 = "Tramas 5-8";
         $t3 = "Ouichat Tramas 1-4";
         $index = 180;

      }
      else if( $screen_width <= 700 ) $c = 5;
           else $c = 6;

           */
      $Segundos = 0;            
      $sql = "select sql_no_cache fecha as dia, dnis, llamados, segundos, minutos, importe, duracion, billsec, aplicacion from diario where fecha = '$Search'";
      $result = $conn->query($sql);
      if ($result->num_rows > 0) {
         while( $row = $result->fetch_assoc() ) {
            $Segundos += $row["segundos"] + $row["billsec"];
         }

      }
      if( is_resource( $result ) ) mysql_free_result( $result );
      $Minutos = number_format( $Segundos / 60, 0, ",", "." );

      /*
      echo "<div class='container sticky' style='width: 90%;'>";
      echo "<div style='margin-top: 10px; margin-bottom: 10px;'></div>";
      echo "<div class='row'>";
         echo "<div class='col s12 m12 l12' style='padding-left:20px; padding-right:20px;'>";

         $wx = "width:170px;";
         echo "<div class='row'>";
             echo "<div class='col s8 m10 l12'>"; 
               echo "<ul id='tabs_menu' class='tabs'>"; 
                  echo "<li class='tab col s2' style='$wx'><a id='0' href='#' onclick='onClick(this);'>$t1</a></li>"; 
                  echo "<li class='tab col s2' style='$wx'><a id='1' href='#' onclick='onClick(this);'>$t2</a></li>"; 
                  echo "<li class='tab col s2' style='$wx'><a id='2' href='#' onclick='onClick(this);'>$t3</a></li>"; 
                  echo "<li class='tab col s2' style='$wx'><a id='3' href='#' onclick='onClick(this); 'class='active'>$t4</a></li>"; 
                  if( $informes ) 
                     echo "<li class='tab col s2' style='$wx'><a id='4' href='#' onclick='onClick(this);'>$t5</a></li>"; 
//                  echo "<li class='tab col s8'><img src='images/LogoOuiChat.png' style='height:35px; padding-top:3px; float:right; padding-right:10px;'></li>"; 
                echo "</ul>"; 
              echo "</div>"; 
         echo "</div>"; 
      */

         echo "<div class='card white' style='margin:0px;'>"; 
            echo "<div class='card-content black-text' style='border-top:none; !important'>"; 
               echo "<div style='height:30px;'></div>";

               echo "<div id='trafico'></div>";
               $xmlData = "<chart caption=\"Trafico en Minutos: $Minutos\' ($Fecha) \" theme=\"fusion\" showLabels=\"0\" use3DLighting=\"1\" pieSliceDepth=\"25\" ";
               $xmlData .= "showLegend=\"1\" manageLabelOverflow=\"1\" legendItemFontSize=\"12\" formatNumberScale=\"0\" numberSuffix=\"\'\">";

//             $date = $Year . "/" . $Month . "/" . $Day;
               $sql = "select sql_no_cache fecha as dia, dnis, llamados, segundos, minutos, importe, duracion, billsec, aplicacion from diario where Importe > 0 and fecha = '$Search'";

               $result = $conn->query($sql);
               $first = 0;
               $otros = 0;
               $discador = 0;
               $conferencia = 0;
               if ($result->num_rows > 0) {
                  while( $row = $result->fetch_assoc() ) {

                     $llamados = $row["llamados"];
                     $segundos = ( $row["segundos"] + $row["billsec"] ) / 60;
                     $aplicacion = $row["aplicacion"];
                     $dnis = $row["dnis"];

                     if( $aplicacion == "Discador" || $aplicacion == "Conferencia" ) {
                        if( $aplicacion == "Discador" ) {
                           $discador += $segundos;
//                           echo "Discador: $segundos => $discador<br/>";
                        }
                        if( $aplicacion == "Conferencia" ) {
                           $conferencia += $segundos;
//                           echo "Conferencia: $segundos => $conferencia<br/>";
                        }

                     }

                     if( $aplicacion != "Discador" && $aplicacion != "Conferencia" ) {

                        if( $segundos < 2000 && $dnis != "1155000045" && $dnis != "1151720074" && $dnis != "2215150018" ) {
                           $otros += $segundos; 
//                           echo "Otros: $segundos => $otros<br/>";
                        }
                        else {
                           if( $dnis == "2215150018" ) $xmlData .= "<set label=\"" . $aplicacion . "\" value=\"" . $segundos . "\" isSliced=\"1\" />"; 
                           else $xmlData .= "<set label=\"" . $aplicacion . "\" value=\"" . $segundos . "\" />";  
                        }
                     }
                  }

//                  echo $discador . "<br/>";
//                  echo $conferencia . "<br/>";

                  $xmlData .= "<set label=\"Otros\" value=\"" . $otros . "\" />";  
                  $xmlData .= "<set label=\"Discador\" value=\"" . $discador . "\" />";  
                  $xmlData .= "<set label=\"Conferencia\" value=\"" . $conferencia . "\" />";  
               }
               $xmlData .= "</chart>";
               if( is_resource( $result ) ) mysql_free_result( $result );
               $Chart = new FusionCharts("doughnut3d", "mytrafico" , "100%", "350", "trafico", "xml", $xmlData);
               $Chart->render();

               echo "</div>";

         echo "</div>";

         echo "<div class='card white' style='margin:0px;'>"; 
            echo "<div class='card-content black-text' style='border-top:none; !important'>"; 
               echo "<div style='height:30px;'></div>";

               echo "<table style='width:100%;'>";
                  echo "<tr style='border-style:none !important;'>";
                     echo "<td style='width:100%; padding:0; margin:0; padding-right:3px; padding-bottom:3px;'>";
                        echo "<div style=' height:500px;' id='chart-container'></div>";
                     echo "</td>";
                 echo "</tr>";
               echo "</table>";
               echo "<div style='height:5px;'></div>";

/*

               echo "<div id='hours'></div>";
               $xmlData = "<chart caption=\"Sesiones Diarias\" yaxisname=\"Llamados\" theme=\"fusion\" canvasBgColor=\"#ffffff\" ";
               $xmlData .= "xAxisNameFontSize=\"15\" yAxisNameFontSize=\"15\" divlineisdashed=\"1\" divlinedashlen=\"1\" divlinegaplen=\"1\" ";
               $xmlData .= "showLabels=\"1\" captionFont=\"Roboto\" captionFontSize=\"16\" captionFontBold=\"0\" ";
               $xmlData .= "showValues=\"0\" placeValuesInside=\"0\" labelDisplay=\"AUTO\"";
               $xmlData .= ">";

               $sql = "select sql_no_cache * from ( select * from system_status where date(fecha)= '$Search' order by fecha desc limit 36 ) sub order by fecha asc";
               $result = $conn1->query($sql);
               $first = 0;
               $otros = 0;

               if ($result->num_rows > 0) {
                  while( $row = $result->fetch_assoc() ) {

                     $fecha = $row["fecha"];
                     $label = substr( $fecha, 11, 5 );
              
                     $active = $row["sessionsActive"];
                     $peak = $row["sessionsPeak"];

                     $seriesActivas .= "<set label=\"$label\" value=\"$active\" />";
//                    $seriesPico .= "<set value=\"$peak\" />";
                  }
               }
//               else echo mysqli_error( $conn1 ) . "<br/>";

//               $seriesActivas .= "</dataset>";
//               $seriesPico .= "</dataset>";

//               $xmlData .= $categories;
               $xmlData .= $seriesActivas;
//               $xmlData .= $Pico;
               $xmlData .= "</chart>";

               if( is_resource( $result ) ) mysql_free_result( $result );
//               $Chart = new FusionCharts("mscolumn3d", "myhours" , "100%", "350", "hours", "xml", $xmlData);
               $Chart = new FusionCharts("column3d", "myhours" , "100%", "350", "hours", "xml", $xmlData);
               $Chart->render();

            echo "</div>";
            */
            echo "<div class='row'>";
            echo "<div class='col s8 m10 l12'>"; 
            echo "<div>";
            echo "<a id='back' class='butn' style='float:right; padding-right:40px;' href='#' onClick='onClick(this);'>VOLVER</a>";
            echo "<img src='images/goback-min.png' style='height:30px; float:right; padding-bottom:5px; padding-right:10px;'>";
            echo "</div>";
            echo "<div style='height:20px; margin-top: 10px; margin-bottom: 10px;'></div>";
            echo "</div>";
            echo "</div>";
         echo "</div>";
      echo "</div>";

      echo "</div>";

      echo "</div>";
      echo "</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="materialize/1.0.0/js/materialize.js"></script>
   <script type="text/javascript">

   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();
   };

   $(document).ready(function() {
         console.log( "READY!" );

         $('select').formSelect();

         $('.tabs').tabs();
         $('#tabs_menu').tabs();
         $('ul.tabs').tabs();
    });

   function onClick(e) {

      switch( e.id ) {
         case "0":
            post("traficoPanel.php", {t:0});
            break;

         case "1":
            post("traficoPanel.php", {t:1});
            break;

         case "2":
            post("traficoPanel.php", {t:2});
            break;

         case "3":
            post("traficoLlamados.php", {t:3});
            break;


         case "4":
            post("traficoConference.php", {t:4});


         case "5":
            post("traficoOpciones.php", {t:5});
            break;

         case "back":
            post("traficoLlamados.php", {t:3});
            break;
      }
   }


   FusionCharts.ready(function(){
      Bandwidth();

   });


   function fetchCheckStatus(response) {
      if (response.status >= 200 && response.status < 300) {
         return response;
      }
      const error = new Error(response.statusText);
      error.response = response;
      throw error;
   }

   function loadData(url) {
      const option = {
         method: 'GET',
         headers: new Headers(),
         mode: 'cors',
         cache: 'default',
      };

      return fetch(url, option)
       .then(fetchCheckStatus)
         .then(resp => {
            const contentType = resp.headers.get('Content-Type');
            if (contentType && contentType.indexOf('application/json') !== -1) {
//               console.log( "1.1" );
               return resp.json();
            }
//               console.log( "1.2" );
            console.log( resp.text() );
            return resp.text();
         })
         .then(data => data)
         .catch(() => {
            console.log('Something went wrong! Please check data/schema files');
         });
   }


   function loadSql(url) {
      var progress = $.Deferred();
      $.post(url,{}, 
          function (data) { 
            return progress.resolve(data);
         }
      );
      return progress.promise();
   }

   /*

[{
    "name": "Llamadas",
    "type": "string"
}, {
    "name": "Time",
    "type": "date",
    "format": "%d-%m-%Y %H:%M"
}, {
    "name": "Cantidad",
    "type": "number"
}]

*/

   function Bandwidth() {

      Promise.all([
            loadSql("traficoSesionesData.php"),
            loadData("sessionData.json")
      ]).then(res => {
         const [data, schema] = res; 
      
         console.dir( data );
         console.dir( schema );
         const dataStore = new FusionCharts.DataStore();
         const dataSource = {
            "caption": {
                "text": "Sesiones"
            },
            "subcaption": {
               "text": ""
            },
            yAxis: [{
               "plot": {
                  "value": "Cantidad",
                  "type": "line"
               }
            }],
            "series": "Llamadas",
            "chart": {
               "decimals": 0
            }
         };
         
         dataSource.data = dataStore.createDataTable(data, schema);
      
         new FusionCharts({
            type: "timeseries",
            renderAt: "chart-container",
            width: "100%",
            height: "500",
            dataSource
         }).render();
      
      });
   }

</script>
</body>
</html>

