<?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_services.php');
ini_set('max_execution_time', 240);

$trama = isset($_POST['t']) ? $_POST["t"]  : "6";

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

$admin = false;
$informes = $_SESSION["informes"];
$admin = $_SESSION["admin"];



$modo = isset($_POST['modo']) ? $_POST["modo"] : "1";
$equipo = isset($_POST['equipo']) ? $_POST["equipo"]  : "";
if( $equipo == "" ) {
   $equipo = isset($_SESSION['equipo']) ? $_SESSION["equipo"] : "";
}
$_SESSION['equipo'] = $equipo;

include 'traficoHeader.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;
}

.tfecha:hover, .tllamados:hover,
.tminutos:hover, .tpromedio:hover,
.tsep:hover, .timporte:hover, tsva:hover {
   cursor: pointer;
}

.myData {
   color: black !important;
}


</style>
<?php
   echo "<div class='card white' style='margin:0px;'>"; 
      echo "<div class='card-content black-text' style='border-top:none; !important'>"; 
            echo "<form id='ani_gw' action='traficoAni.php' method='post'>";
                echo "<div class='row' style='padding-left:20px; height:70px;'>";
                    echo "<div class='input-field col s3 m3'>";
                       echo "<select name='equipo'>";
//                       echo "<option value='' disabled></option>";        

                           $sql = sprintf( "select sql_no_cache * from ani_calls group by equipo" );
                           $result = $conn->query($sql);
                           if ($result->num_rows > 0) {
                              while($row = $result->fetch_assoc()) {
            
                                 $equipo_option = $row["equipo"];
                                 if( $equipo_option == $equipo ) $selected = "selected";  
                                 else $selected = "";     
                                 echo sprintf( "<option value= '%s' %s>%s</option>", $equipo_option, $selected, $equipo_option );
                              }
                           }
                       echo "</select>"; 
                       echo "<label>Equipo</label>";
                    echo "</div>"; 

                    echo "<div class='input-field col s3 m3'>";
                       echo "<select name='modo'>";
//                       echo "<option value='' disabled></option>";        
                         echo sprintf( "<option value= '0' %s>Todos</option>", $modo == "0" ? "selected" : "" );
                         echo sprintf( "<option value= '1' %s>Activos</option>", $modo == "1" ? "selected" : "" );
                         echo sprintf( "<option value= '2' %s>Inactivos</option>" , $modo == "2" ? "selected" : "" );
                       echo "</select>"; 
                       echo "<label>Modo</label>";
                    echo "</div>"; 

                    echo "<button class='btn waves-effect waves-light btn col' style='width:110px; margin-top:25px; margin-left:30px; height:35px;' type='submit' name='action' >Actualizar</button>";
                echo "</div>";
            echo "</form>";

            $sql = sprintf( "select sql_no_cache count(id) as cantidad, equipo from ani_calls where actual_call is not null and count > 0 group by equipo" );
            $result = $conn->query($sql);
            if( $result && $result->num_rows > 0) {

               echo "<table id='lines' class='highlight'>"; 
               echo "<tbody>"; 
               $i = 0;
               while($row = $result->fetch_assoc()) {
                  $cantidad[$i] = $row["cantidad"];
                  $equipos[$i] = $row["equipo"];
                  if( ++$i > 2 ) {
                     echo "<tr>";
                     for( $c = 0; $c < 3; $c++ ) {
                        echo "<td class='col' style='width:10%; font-size:10pt !important;'>$equipos[$c]:</td>";
                        echo "<td class='col right-align' style='width:10%; font-size:10pt !important;'>$cantidad[$c]</td>";
                        echo "<td class='col right-align' style='width:10%; font-size:10pt !important;'>&nbsp;</td>";
                     }
                     /*
                     echo "<td class='col' style='width:10%; font-size:10pt !important;'>$equipos[1]:</td>";
                     echo "<td class='col right-align' style='width:10%; font-size:10pt !important;'>$cantidad[1]</td>";
                     echo "<td class='col right-align' style='width:10%; font-size:10pt !important;'>&nbsp;</td>";
                     echo "<td class='col' style='width:10%; font-size:10pt !important;'>$equipos[2]:</td>";
                     echo "<td class='col right-align' style='width:10%; font-size:10pt !important;'>$cantidad[2]</td>";
                     echo "<td class='col right-align' style='width:10%; font-size:10pt !important;'>&nbsp;</td>";
                     */
                     echo "</tr>";
                     for( $i = 0; $i < 3; $i++ ) {
                        $cantidad[$i] = "";
                        $equipos[$i] = "";
                     }
                     $i = 0;
                  }
               }
               if( $i > 0 ) {
                  echo "<tr>";
                  for( $c = 0; $c < 3; $c++ ) {
                     echo "<td class='col' style='width:10%; font-size:10pt !important;'>$equipos[$c]:</td>";
                     echo "<td class='col right-align' style='width:10%; font-size:10pt !important;'>$cantidad[$c]</td>";
                     echo "<td class='col right-align' style='width:10%; font-size:10pt !important;'>&nbsp;</td>";
                  }
                  echo "</tr>";
               }
               echo "</tbody>";
               echo "</table>";
               echo "<div style='height:25px;'></div>";
            }
            if( is_resource( $result ) ) mysql_free_result( $result );


            echo "<table id='detail' class='highlight'>"; 
               echo "<thead>"; 
               echo "<tr style='border:none !important;'>"; 
//               echo "<tr>"; 
                 echo "<th class='col s1' style='width:5%;'>#</th>"; 
                 echo "<th class='col s1' style='width:10%;'>DDE</th>"; 
                 echo "<th class='col s1' style='width:10%;'>CID</th>"; 
                 echo "<th class='col s1' style='width:10%;'>COMIENZO</th>"; 
                 echo "<th class='col s1' style='width:10%;'>ACTUAL</th>"; 
                 echo "<th class='col s1' style='width:10%;'>ULTIMO</th>"; 
                 echo "<th class='col s1 style='width:35%;'>EQUIPO</th>"; 
                 echo "<th class='col s2 right-align' style='width:8%;'>LINEAS</th>"; 
               echo "</tr>"; 
               echo "</thead>"; 
             echo "<tbody>"; 

             echo "<div style='height:25px;'></div>";

             switch( $modo ) {
               default:
               case "0":
                  $filter = "";
                  break;

               case "1":
                  $filter = " and actual_call is not null";
                  break;

               case "2":
                  $filter = " and actual_call is null";
                  break;
             }

             $sql = sprintf( "select sql_no_cache * from ani_calls where equipo = '%s' %s and (last_call is null or last_call >= date_sub(date(now()),interval 5 day)) and count > 0 order by cid, first_call", $equipo, $filter );
             $result = $conn->query($sql);
      
             $number = 0;
             $total_lines = 0;
             
             if ($result->num_rows > 0) {
               while($row = $result->fetch_assoc()) {
             
                  ++$number;
                  $dde = $row["dnis"];
                  $cid = $row["cid"];
                  $lines_count = $row["count"] + $row["count_conference"];
                  $first_call = $row["first_call"];
                  $actual_call = $row["actual_call"];
                  $last_call = $row["last_call"];
                  $equipo = $row["equipo"];

                  $start_formatted = date_format(date_create($first_call), 'd-m-Y H:m:s');


                  if( $actual_call == "" ) {
                     $actual_formatted = "&nbsp;";

                     if( $last_call == "" ) $last_formatted = "&nbsp;"; 
                     else $last_formatted = date_format(date_create($last_call), 'd-m-Y H:m:s');
                  }

                  else {
                     $actual_formatted = date_format(date_create($actual_call), 'd-m-Y H:m:s');
                     $last_formatted = "&nbsp;";
                  }   


                  $total_lines += $lines_count;

                  echo "<tr><a href='#'>";
                  echo "<td id='number' class='col tfecha' style='width:5%; font-size:10pt !important;'>" . $number . "</td>";
                  echo "<td id='cid' class='col tfecha' style='width:10%; font-size:10pt !important;'>" . $dde . "</td>";
                  echo "<td id='cid' class='col tfecha' style='width:10%; font-size:10pt !important;'>" . $cid. "</td>";
                  echo "<td id='start' class='col tfecha' style='width:10%; font-size:10pt !important;'>" . $start_formatted . "</td>";
                  echo "<td id='actual' class='col tfecha' style='width:10%; font-size:10pt !important;'>" . $actual_formatted . "</td>";
                  echo "<td id='last' class='col tfecha' style='width:10%; font-size:10pt !important;'>" . $last_formatted . "</td>";
                  echo "<td id='last' class='col tfecha' style='width:35%; font-size:10pt !important;'>" . $equipo . "</td>";
                  echo "<td id='count' class='col right-align tfecha' style='width:8%; font-size:10pt !important;'>" . $lines_count . "</td>";
                  echo "</a>";
                  echo "</tr>";
               } // while
             } // if
             if( $result && is_resource( $result ) ) mysql_free_result( $result );
             mysqli_close($conn);
    
             echo "</tbody>";
             echo "<tfoot>";
             echo "<tr style='color:white; background-color:#16a2d6;'>";
             echo "<td class='col s1'             style='width:2%; font-size:11pt !important;'>&nbsp;</td>";
             echo "<td class='col s1'             style='width:8%; font-size:11pt !important;'>&nbsp;</td>";
             echo "<td class='col s1'             style='width:8%; font-size:11pt !important;'>&nbsp;</td>";
             echo "<td class='col s1'             style='width:15%; font-size:11pt !important;'>&nbsp;</td>";
             echo "<td class='col s1'             style='width:15%; font-size:11pt !important;'>&nbsp;</td>";
             echo "<td class='col s1'             style='width:15%; font-size:11pt !important;'>&nbsp;</td>";
             echo "<td class='col s1'             style='width:15%; font-size:11pt !important;'>&nbsp;</td>";
             echo "<td class='col s1 right-align' style='width:8%; font-size:11pt !important;'>" . number_format ( $total_lines, 0, ',' ,  '.' ) . "</td>";
             echo "</tr>";
             echo "</tfoot>";
             echo "</table>";
        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();
   };

   function linkDetalle( tr ) {
      var fecha = tr.find('#nfecha')[0].innerHTML;
//     console.log( fecha[0].innerHTML );
      console.log( fecha );
      post("traficoDetalle.php", {dia: fecha, t:3 }); 
   }

   $(document).ready(function() {

      console.log( "READY!" );
      $('#month').on('change', function() {
         Month = this.value;
         console.log( this.value )
      });   
      $('#year').on('change', function() {
         Year = this.value;
         console.log( this.value )
      });   

      $('select').formSelect();

//  $('#detail tr').click(function() {

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

       $('#detail tbody').on('click', 'td.tfecha', function () { linkDetalle( $(this).closest('tr') ) });
       $('#detail tbody').on('click', 'td.tllamados', function () { linkDetalle( $(this).closest('tr') ) });
       $('#detail tbody').on('click', 'td.tminutos', function () { linkDetalle( $(this).closest('tr') ) });
       $('#detail tbody').on('click', 'td.tpromedio', function () { linkDetalle( $(this).closest('tr') ) });
       $('#detail tbody').on('click', 'td.tsep', function () { linkDetalle( $(this).closest('tr') ) });
       $('#detail tbody').on('click', 'td.timporte', function () { linkDetalle( $(this).closest('tr') ) });
       $('#detail tbody').on('click', 'td.sva', function () { linkDetalle( $(this).closest('tr') ) });

      $('#detail tbody').on('click', 'td.tgraph', function () {
         var tr = $(this).closest('tr');
         var fecha = tr.find('#nfecha')[0].innerHTML ;
         post("traficoDiario.php", {dia: fecha, t:3 }); 
      });



      /*
      $('#detail tbody').on('click', 'tr', function () {
            console.log( "click tr" );
            var tr = $(this).closest('tr');
            console.dir( tr );

            var fecha = tr.find('#tfecha').val();
            console.log( fecha );
             post("traficoDetalle.php", {fecha: fecha }); 
//            post("traficoDetalle.php", {dia: name.substr(2,10) }); 
      });

//      $('#detail').on('click', 'tr', function(e) {
//          post("traficoDetalle.php", {dia: e.currentTarget.cells[0].innerHTML }); 
//      });
*/
  });   

   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});
//            post("traficoGateways.php", {t:2});
            break;

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

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


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

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

         case "7":
            post("traficoAni.php", {t:7});
            break;

      }
   }

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

