<?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', 240);

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

$Year     = isset($_POST['year']) ? $_POST["year"]  : "";
$Month  = isset($_POST['month']) ? $_POST['month'] : "";
$Fecha = "";
$Total_Llamados = 0;
$Total_Minutos = 0;
$Importe_Total = 0;
$Total_Dia_Llamados = 0;
$Total_Dia_Minutos = 0;
$Importe_Dia_Total = 0;

$YS2015 = "";
$YS2016 = "";
$YS2017 = "";
$YS2018 = "";
$YS2019 = "";
$YS2020 = "";
$YS2021 = "";
$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");
   }
}

$_SESSION["Year"] = $Year;
$_SESSION["Month"] = $Month;

$informes = $_SESSION["informes"];


$sm = array("", "", "", "", "", "", "", "", "", "", "", "");
$sm[$Month-1] = "selected";

if( $Year == "2015")  $YS2015 = "selected";
if( $Year == "2016")  $YS2016 = "selected";
if( $Year == "2017")  $YS2017 = "selected";
if( $Year == "2018")  $YS2018 = "selected";
if( $Year == "2019")  $YS2019 = "selected";
if( $Year == "2020")  $YS2020 = "selected";
if( $Year == "2021")  $YS2021 = "selected";
$admin = false;
$Movistar = 0.9225;
$Movistar = 1.476; 
$Personal = 1.476;
$Personal_New = 1.575;
$Claro =  0.738;
$Nextel = 1.107;
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;
}



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

      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);'>$t4</a></li>"; 
                  if( $informes ) 
                     echo "<li class='tab col s2' style='$wx'><a id='4' href='#' class='active'>$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 class='row' style='padding-left:20px;'>";
                      echo "<div class='input-field col s3 m3'>";
                         echo "<select id='informes' name='informe'  onchange='onChange(this)'>";
                         echo "<option value= '1'>Detalle de Llamados</option>";
                         echo "<option value= '2'>Detalle de Mierda</option>";
                         echo "</select>"; 
                        echo "<label>Informe</label>";
                     echo "</div>"; 

                     echo "<div id='field_desde' class='input-field col s2'>";
                     echo "<label for='desde'>Desde</label>";
                     echo "<input id='desde' type='text' class='datepicker' value='" . $D1 . "' onChange='onChange(this);'>";
                     echo "</div>";

                     echo "<div id='field_hasta' class='input-field col s2'>";
                     echo "<label for='hasta'>Hasta</label>";
                     echo "<input id='hasta' type='text' class='datepicker' value='" . $H1 . "' onChange='onChange(this);'>";
                     echo "</div>";
                     echo "<div class='input-field col s3'>";
                     echo "<button onclick='Submit();' class='btn waves-effect waves-light btn col s3' style='margin-top:15px; width:120px; height:33px; line-height:33px; padding-bottom:10px; text-transform:none;'>Visualizar</button>";
                     echo "</div>";
                  echo "</div>"; 

               /*
                     echo "<form id='asterisco' action='traficoLlamados.php' method='post'>";
                         echo "<div class='row' style='padding-left:20px;'>";
                             echo "<div class='input-field col s3 m3'>";
                                echo "<select name='month'>";
//                                echo "<option value='' disabled></option>";        
                                echo "<option value= '1' " . $sm[0] .  ">Enero</option>";
                                echo "<option value= '2' " . $sm[1] .  ">Febrero</option>";
                                echo "<option value= '3' " . $sm[2] .  ">Marzo</option>";
                                echo "<option value= '4' " . $sm[3] .  ">Abril</option>";
                                echo "<option value= '5' " . $sm[4] .  ">Mayo</option>";
                                echo "<option value= '6' " . $sm[5] .  ">Junio</option>";
                                echo "<option value= '7' " . $sm[6] .  ">Julio</option>";
                                echo "<option value= '8' " . $sm[7] .  ">Agosto</option>";
                                echo "<option value= '9' " . $sm[8] .  ">Septiembre</option>";
                                echo "<option value='10' " . $sm[9] .  ">Octubre</option>";
                                echo "<option value='11' " . $sm[10] . ">Noviembre</option>";
                                echo "<option value='12' " . $sm[11] . ">Diciembre</option>";
                                echo "</select>"; 
                               echo "<label>Mes</label>";
                            echo "</div>"; 
                            echo "<div class='input-field col s2 m2'>"; 
                               echo "<select  name='year'>"; 
//                               echo "<option value='' disabled selected>Seleccione el A&ntilde;o</option>"; 
                               echo "<option value='2020' " . $YS2020 . ">2020</option>";
                               echo "<option value='2019' " . $YS2019 . ">2019</option>";
                               echo "<option value='2018' " . $YS2018 . ">2018</option>";
                               echo "<option value='2017' " . $YS2017 . ">2017</option>";
                               echo "<option value='2016' " . $YS2016 . ">2016</option>";
                               echo "<option value='2015' " . $YS2015 . ">2015</option>";
                               echo "</select>"; 
                               echo "<label>A&ntilde;o</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 "<div style='height:25px;'></div>";
                     echo "</form>";

                     echo "<table id='detail' class='highlight'>"; 
                        echo "<thead>"; 
                        echo "<tr style='border:none !important;'>"; 
//                        echo "<tr>"; 
                          echo "<th class='col s1 right-align' style='width:15%;'>FECHA</th>"; 
                          echo "<th class='col s1 right-align' style='width:12%;'>LLAMADOS</th>"; 
                          echo "<th class='col s1 right-align' style='width:12%;'>MINUTOS</th>"; 
                          echo "<th class='col s1 right-align' style='width:12%;'>PROMEDIO</th>"; 
                          echo "<th class='col s2 right-align' style='width:16%;'>&nbsp;</th>"; 
                          echo "<th class='col s2 right-align' style='width:15%;'>TERMINACION USD</th>"; 
                          echo "<th class='col s2 right-align' style='width:15%;'>IMPORTE SVA $</th>"; 
                          echo "<th class='col s2 right-align' style='width:3%; text-decoration:none;'>&nbsp;</th>"; 
                        echo "</tr>"; 
                        echo "</thead>"; 
                      echo "<tbody>"; 

                      $General_Total_Llamados = 0;
                      $General_Total_Minutos = 0;
                      $General_Importe_Total = 0;
                
                      for( $i = 31; $i > 0; $i-- ) {
                         $sql = "select sql_no_cache fecha as dia, dnis, llamados, segundos, minutos, importe from diario where fecha='"  . $Year . "-" . $Month . "-" . $i . "'";
                         $result = $conn->query($sql);
                      
                         if ($result->num_rows > 0) {
                           $Fecha = "";
                           $Total_Llamados = 0;
                           $Total_Segundos = 0;
                           $Total_Minutos = 0;
                           $Importe_Total = 0;
                           $Total_SVA = 0;
                           $segundos = 0;
                      
                           while($row = $result->fetch_assoc()) {
                      
                                $date = date_create($row["dia"]);
                                $formatted = date_format($date, 'd-m-Y');
                      
                                switch( $row["dnis"] ) {
                                   case "1151720091":  $Valor = $Movistar / 60;  break;
                                   case "1151720096":  $Valor = $Claro    / 60;  break;
                                   default:            $Valor = 0;        break;
                                }
             //                   $Importe = $row["segundos"] / 60 * 0.00974;
                                $Importe = $row["segundos"] * 0.0045;
                                if( $date >= "2019-09-01 00:00:00" )
                                   $Importe = $row["minutos"] * 0.0045 * 0.65;
                      
                                $segundos = $row["segundos"];
                                $minutos = $row["minutos"];
                                
                                if( $segundos < 30 ) $segundos = 30;
                                else if( $segundos < 60 ) $segundos = 60;
                                $Importe_SVA = $segundos * $Valor;
                      
                                $Total_Segundos += $row["segundos"];
                                $Total_Llamados += $row["llamados"];
                                $Total_Minutos += $minutos;
                                $Total_SVA += $Importe_SVA;
                                $Importe_Total += $Importe;
                      
                                $General_Total_Llamados += $row["llamados"];
                                $General_Total_Minutos += $minutos;
                                $General_Importe_Total += $Importe;
                                $General_Total_SVA += $Importe_SVA;
                      
                      
             //              if( $Total_Llamados == 0 ) $Promedio = 0;  
             //              else $Promedio = $Total_Minutos / $Total_Llamados;
                      
                               if( $Total_Llamados == 0 ) $Promedio = 0;  
                               else $Promedio = $Total_Segundos / $Total_Llamados;
                      
                               $Sec = cnvSegundosHoras($Promedio);
                               $Valor = 0;
                            }
                      
                            echo "<tr><a href='#'>";
                               echo "<td id='nfecha' class='col right-align tfecha' style='width:15%; font-size:10pt !important;'>" . $formatted . "</td>";
                               echo "<td class='col right-align tllamados' style='width:12%; font-size:10pt !important;'>" . number_format ( $Total_Llamados, 0, ',' ,  '.' ) . "</td>";
                               echo "<td class='col right-align tminutos' style='width:12%; font-size:10pt !important;'>" . number_format ( $Total_Segundos / 60, 0, ',' ,  '.' ) . "</td>";
                               echo "<td class='col right-align tpromedio' style='width:12%; font-size:10pt !important;'>" .  $Sec . " </td>";
                               echo "<td class='col right-align tsep' style='width:16%; font-size:10pt !important;'>&nbsp;</td>";
                               echo "<td class='col right-align timporte' style='width:15%; font-size:10pt !important;'>" . number_format ( $Importe_Total , 2, ',' ,  '.' ) . "</td>";
                               echo "<td class='col right-align tsva' style='width:15%; font-size:10pt !important;'>" . number_format ( $Total_SVA , 2, ',' ,  '.' ) . "</td>";
                               echo "<td class='col tgraph' style='width:3%; font-size:10pt !important;'><a id='i_$formatted' href='#' onclick='onClick(this);'><img src='images/pie3d-min.png' style='height:25px; padding-top:5px;'></a></td>";
                            echo "</a>";
                            echo "</tr>";

                         } 
                      }
                      if( is_resource( $result ) ) mysql_free_result( $result );
                      mysqli_close($conn);
             
                      if( $General_Total_Llamados == 0 ) $Promedio = 0;
                      else $Promedio = $General_Total_Minutos / $General_Total_Llamados;

                      $Horas = intval($Promedio / 60);
                      $Promedio_Min = intval( $Promedio - $Horas );
                      $Promedio_Sec = ($Promedio - $Horas - $Promedio_Min ) * 60;
                      $Sec = sprintf("%d:%02d", $Promedio_Min, $Promedio_Sec);
             
                      echo "</tbody>";

                      echo "<tfoot>";
                      echo "<tr style='color:white; background-color:#16a2d6;'>";
                      echo "<td class='col s1'             style='width:15%; font-size:11pt !important;'>&nbsp;</td>";
                      echo "<td class='col s1 right-align' style='width:12%; font-size:11pt !important;'>" . number_format ( $General_Total_Llamados, 0, ',' ,  '.' ) . "</td>";
                      echo "<td class='col s1 right-align' style='width:12%; font-size:11pt !important;'>" . number_format ( $General_Total_Minutos, 0, ',' ,  '.' ) . "</td>";
                      echo "<td class='col s1 right-align' style='width:12%; font-size:11pt !important;'>" . $Sec . "</td>";
                      echo "<td class='col s1 right-align' style='width:16%; font-size:11pt !important;'>&nbsp;</td>";
                      echo "<td class='col s1 right-align' style='width:15%; font-size:11pt !important;'>" . number_format ( $General_Importe_Total, 2, ',' ,  '.' ) . "</td>";
                      echo "<td class='col s1 right-align' style='width:15%; font-size:11pt !important;'>" . number_format ( $General_Total_SVA, 2, ',' ,  '.' ) . "</td>";
                      echo "<td class='col s1 right-align' style='width:3%; font-size:11pt !important;'>&nbsp;</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 }); 
   }

   $(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();
      $('.datepicker').datepicker({
         selectMonths: true, // Creates a dropdown to control month
         selectYears: 15, // Creates a dropdown of 15 years to control year
         months: [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ],
         monthsShort: [ 'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic' ],
         weekdays: [ 'Domingo', 'Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado' ],
         weekdaysShort: [ 'Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab' ],
         weekdaysLetter: [ 'D', 'L', 'M', 'M', 'J', 'V', 'S' ],
         today: 'Hoy',
         clear: 'Borrar',
         cancel: 'Cerrar',
         format: 'dd-mm-yyyy',
         formatSubmit: 'yyyy-mm-dd'
      });


//  $('#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 }); 
      });



      /*
      $('#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) {

/*      
      if( e && e.id != "" && e.id.substr(0,2) == "i_" ) {
         console.log( "icon" );
         var name = e.id;
         console.log( "2. " + name.substr(2,10) );
         post("traficoDiario.php", {dia: name.substr(2,10) }); 
      }
      */

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

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

   function onChange(e) {

      console.dir( e );
      console.log( e.id );
      switch( e.id ) {

         case "informes":
            var tipo = $("#informes").val();

            if( tipo == "1" ) {
               $("#field_desde").css( 'display', '' ); 
               $("#field_hasta").css( 'display', '' ); 
            }
            else {
               $("#field_desde").css( 'display', 'none' ); 
               $("#field_hasta").css( 'display', 'none' ); 
            }
            break;
      }
   }

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

