<?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');
ini_set('max_execution_time', 120);

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

$informes = $_SESSION["informes"];

$Page = isset($_POST['page']) ? $_POST["page"]  : "1";
$Fecha = isset($_POST['dia']) ? $_POST["dia"]  : "";
$Dnis = isset($_POST['dnis']) ? $_POST["dnis"]  : "1155000045";

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


$Total_Llamados = 0;
$Total_Minutos = 0;
$Importe_Total = 0;

$width = "85%";
$Movistar = 1.476; 
$Claro =  0.738;
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) ); 
}
?>
  <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<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
      $Movistar = 1.476; 
      $Personal = 1.575;
      $Claro    =  0.738;

/*
      $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;
               $font = "9pt";
            }
            else {
               $c = 6;
               $font = "10pt";
            }

      */

      $Total_Pages = 0;
      $items_per_page = 25; 

      $Fecha_End = $Search . " " . "23:59:59";
      $sql = "select count(id) as TotalRecords from tickets where fecha >='" . $Search . "' and fecha <= '$Fecha_End' and dnis = '" . $Dnis . "'";

      $result = $conn->query($sql);
      if ($result->num_rows > 0) {
         if( $row = $result->fetch_assoc()) {
            $TotalRecords = $row["TotalRecords"];
         }
      }
      $Total_Pages = intval( $TotalRecords / $items_per_page );
      if( ( $TotalRecords - ( $Total_Pages * $items_per_page ) ) > 0 ) $Total_Pages += 1;
      if( $result && is_resource( $result ) ) mysql_free_result( $result );
      $offset = ($Page - 1) * $items_per_page;

      /*
      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='#' class='active' onclick='onClick(this);'>$t4</a></li>"; 
                  if( $informes ) 
                     echo "<li class='tab col s2' style='$wx'><a id='4' href='#' onclick='onClick(this);'>$t5</a></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:10px;'></div>";
                     if( $offset == 0 ) $first_page="disabled";
                     else $first_page = "waves-effect";

                     echo "<div class='row right-align' style='padding-right:40px;'>";
                     echo "<div style='margin:5px; margin-top: 0; padding-right:10px;'>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 style='height:50px;'></div>";
                     echo "<table id='detail' class='highlight'>"; 
                        echo "<thead>"; 
                        echo "<tr style='border:none !important;'>"; 
                          echo "<th class='col' style='width:10%;'>DNIS</th>"; 
                          echo "<th class='col' style='width:20%;'>APLICACION</th>"; 
                          echo "<th class='col' style='width:15%;'>FECHA</th>"; 
                          echo "<th class='col' style='width:10%;'>CID</th>"; 
                          echo "<th class='col right-align' style='width:10%;'>DURACION</th>"; 
                          echo "<th class='col' style='width:35%;'>OPERADOR</th>"; 
                        echo "</tr>"; 
                        echo "</thead>"; 
                      echo "<tbody>"; 

                     $sql = "select sql_no_cache dnis, aplicacion, fecha, date(fecha) as dia, cid, duracion, tarifa, importe, operador from tickets where fecha >='" . $Search . "'  and fecha <= '$Fecha_End' and dnis='" . $Dnis . "' order by fecha desc LIMIT " . $offset . ", " . $items_per_page;
//         sprintf( query, "select sql_no_cache indicativo, bloque, servicio, modalidad from numeracion_cnc where concat(indicativo,bloque) = SUBSTRING('%s',1, LENGTH(concat(indicativo,bloque)))", ANI ); 

                     $result = $conn->query($sql);
                     $first = true;
                     if ($result->num_rows > 0) {
                        while($row = $result->fetch_assoc()) {
  
                           $date = date_create($row["fecha"]);
                           $formatted = date_format($date, 'd-m-Y H:i:s');

                           switch( $row["dnis"] ) {
                              case "1151720091": 
                                 if( ( $segundos = $row["duracion"] ) < 30 ) $segundos = 30;
                                 else if( ( $segundos = $row["duracion"] ) < 60 ) $segundos = 60;
                                 break;

                              default:            
                                 $segundos = $row["duracion"];
                                 break;
                           }
   
                           $Promedio = $segundos / 60;
                           $Horas = intval($Promedio / 60);
                           $Promedio_Min = intval($Promedio - ($Horas * 60 ));
                           $Promedio_Sec = ($Promedio - ( $Horas * 60 ) - $Promedio_Min ) * 60;

                           if( $Horas > 0 )
                              $Sec = sprintf("%d:%02d:%02d", $Horas, $Promedio_Min, $Promedio_Sec);
                              else $Sec = sprintf("%d:%02d",$Promedio_Min, $Promedio_Sec);
                           $Valor = 0;

                           $Importe = $segundos / 60 * 0.0045;

                           $Importe_SVA = $segundos / 60 * $Valor;
                           $Importe_SVA_General += $Importe_SVA;
//                           $operador = substr( $row["operador"],0, 45 );
                           $aplicacion = substr( $row["aplicacion"],0, 45 );

                           if( $aplicacion == "" ) $aplicacion = "&nbsp;";
     
                           echo "<tr>";
                           if( $first == true ) {
                              $text = $row["dnis"];
                           }
                           else {
                              $text = "&nbsp;";
                              $aplicacion = "&nbsp;";
                           }
                           
                           $operador = "";
                           if( ( $cid = $row["cid"] ) == "anonymous" ) $cid = "&nbsp;";
                           else {
                              $q = sprintf( "select sql_no_cache indicativo, bloque, servicio, modalidad, operador from numeracion_enacom where concat(indicativo,bloque) = SUBSTRING('%s',1, LENGTH(concat(indicativo,bloque)))", $cid ); 
//                              echo $q;
                              $resultq = $conn->query($q);
                              if ($resultq->num_rows > 0) {
                                 if($rowq = $resultq->fetch_assoc()) {
                                    $operador = substr( $rowq["operador"],0, 45 );
                                    $operador = str_replace(" Y ", " y ", ucwords( strtolower ( utf8_decode( $operador ) ) ) );
                                 }
                              }
                              if( $resultq && is_resource( $resultq ) ) free( $resultq );
                           }

                           if( $operador == "" ) $operador = "&nbsp;";


                           echo "<tr><a href='#'>";
                           echo "<td class='col' style='width:10%; font-size:$font !important;'>" . $text . "</td>";
                           echo "<td class='col' style='width:20%; font-size:$font !important;'>" .  $aplicacion . " </td>";
                           echo "<td class='col' style='width:15%; font-size:$font !important;'>" . $formatted . "</td>";
                           echo "<td class='col' style='width:10%; font-size:$font !important;'>" . $cid . "</td>";
                           echo "<td class='col right-align' style='width:10%; font-size:$font !important;'>" .  $Sec . " </td>";
//                           echo "<td class='col' style='width:35%; font-size:$font !important;'>" . ucwords( strtolower ( $operador ) ) . " </td>";
                           echo "<td class='col' style='width:35%; font-size:$font !important;'>" . $operador . " </td>";
                           echo "</a>";
                           echo "</tr>";

                           $Total_Minutos += $segundos;
                           $Importe_Total += $Importe;
                           $first = false;
                        }
                     } 
                     if( 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 right-align' style='width:12%; font-size:10pt !important;'>&nbsp;</td>";
                        echo "<td class='col s1' style='width:10%; font-size:10pt !important;'>&nbsp;</td>";
                        echo "<td class='col s1' style='width:22%; font-size:10pt !important;'>&nbsp;</td>";
                        echo "<td class='col s1 right-align' style='width:10%; font-size:10pt !important;'>" . number_format ( $Total_Llamados, 0, ',' ,  '.' ) . "</td>";
                        echo "<td class='col s1 right-align' style='width:10%; font-size:10pt !important;'>" . number_format ( $Total_Minutos / 60, 0, ',' ,  '.' ) . "</td>";
                        echo "<td class='col s1 right-align' style='width:10%; font-size:10pt !important;'>" .  $Sec . " </td>";
                        echo "<td class='col s1 right-align' style='width:12%; font-size:10pt !important;'>" . number_format ( $Importe_Total , 2, ',' ,  '.' ) . "</td>";
                        echo "<td class='col s1 right-align' style='width:12%; font-size:10pt !important;'>" . number_format ( $Importe_Total_SVA , 2, ',' ,  '.' ) . "</td>";
                     echo "</tr>";
                     echo "</tfoot>";
                     */
                     echo "</table>";

                     echo "<div style='height:15px; margin-top: 10px; margin-bottom: 10px;'></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:10px;' href='#' onClick='onClick(this);'>VOLVER</a>";
                              echo "<img src='images/goback-min.png' style='height:30px; float:right; padding-bottom:5px; padding-right:5px;'>";
                           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!" );
      $('#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();

  });   

   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;

      }
   }

   function clickFirst(e) {
      var fecha = <?php echo json_encode($Fecha_Actual); ?>;
      var dnis = <?php echo json_encode($Dnis); ?>;
      var pagina = 1;

      post("traficoDnis.php", {dia: fecha, dnis: dnis, page: pagina });
   }

   function clickLast(e) {
      var fecha = <?php echo json_encode($Fecha_Actual); ?>;
      var dnis = <?php echo json_encode($Dnis); ?>;
      var total = <?php echo json_encode($Total_Pages); ?>;
      var pagina = Number(total);
      post("traficoDnis.php", {dia: fecha, dnis: dnis, page: pagina });
   }

   function clickLeft(e) {

      var fecha = <?php echo json_encode($Fecha_Actual); ?>;
      var dnis = <?php echo json_encode($Dnis); ?>;
      var page = <?php echo json_encode($Page); ?>;
      var total = <?php echo json_encode($Total_Pages); ?>;

      pagina = Number(page) - 1;
      if( pagina >= 1 ) {
         post("traficoDnis.php", {dia: fecha, dnis: dnis, page: pagina });
      }
   };

   function clickRight(e) {

      var fecha = <?php echo json_encode($Fecha_Actual); ?>;
      var dnis = <?php echo json_encode($Dnis); ?>;
      var page = <?php echo json_encode($Page); ?>;
      var total = <?php echo json_encode($Total_Pages); ?>;

      pagina = Number(page) + 1;
      if( pagina <= Number(total) ) {
         console.log( pagina + "  "  + total );
         post("traficoDnis.php", {dia: fecha, dnis: dnis, page: pagina });
      }
   };

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

