<?php
session_start();
if( !isset($_SESSION["user"]) || !isset($_SESSION["passwd"]) || $_SESSION["user"] == "" || $_SESSION["passwd"] == "" ) {
   header("Location: index.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 = "20";
//header("Refresh: $sec; url=$page");

//$Year     = isset($_POST['year']) ? $_POST["year"]  : "";
//$Month  = isset($_POST['month']) ? $_POST['month'] : "";
$equipo_id  = isset($_POST['equipo_id']) ? $_POST['equipo_id'] : "";
$Fecha = "";
$enddate = "";                             

$width = "90%";


if( empty($equipo_id) ) {        
   if (isset($_SESSION['equipo_id']) ) $equipo_id = $_SESSION["equipo_id"]; 
   else {
      $equipo_id = 0;
   }
}

$_SESSION["equipo_id"] = $equipo_id;
$user_id = isset($_SESSION['user_id']) ? $_SESSION["user_id"]  : ""; 
$admin = isset($_SESSION['admin']) ? $_SESSION["admin"]  : "0"; 
$readonly = isset($_SESSION['readonly']) ? $_SESSION["readonly"]  : "1"; 

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>
body, #content, #nav, .page-content {
  background-color: #222222 !important;
}
.page-content, .pagination {
   color: e0e0e0;
}
#blink {
  transition: 0.1s;
}

.blink {
  animation: blink 1s steps(1, end) infinite;
}

@keyframes blink {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.openRow {
    background: url('images/plus15.png') no-repeat center center;
    background-color: rgb(57, 64, 68) !important;
    cursor: pointer;
    padding-left: 30px !important;
}
.close {
    background: url('images/details_close.png') no-repeat center center;
}

.base {
    cursor: pointer;
    color: black;
    background-color: rgb(57, 64, 68) !important;
    color: e1e1e1;
}

.working {
    cursor: pointer;
}

.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;
   */
}


.list_field:hover {
   cursor: pointer;
}

.select-dropdown.dropdown-content li.selected:hover {
    background-color: rgba(0, 0, 0, 0.03);
    color: black;
}

.select-dropdown.dropdown-content li:hover {
    background-color: rgba(0, 0, 0, 0.08);
    background-color: #16a2d6;
    color: white;
}
.dropdown-content li > a, .dropdown-content li > span {
    color: inherit;
}

#contextMenu li:hover, #contextMenu li.active {
    background-color: #16a2d6 !important;
    color: white;
    font-size: 14px !important;
}
.dropdown-content li > a, .dropdown-content li > span {
//   width:200px !important;
   font-size: 14px !important;
}
.activetr {
   background-color: rgb( 0, 0, 0, 0.2 ) !important;
}
ul.dropdown-client li:hover {
 background-color:#90a4ae;
}
.dropdown-client {
   background-color: white;
   opacity: 1;
   overflow-y: auto;
   border-bottom: 1px solid #d0d0d0;
   box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
}
ul.dropdown-client li {
   line-height:3em;
   height:3em;
   vertical-align: middle;
   color: #009688;
   min-height: 3em;
   text-align: left;
   padding: 0px 16px;
}
ul.dropdown-client li:hover {
 background-color:#90a4ae;
}

//

.test ul.dropdown-content { 
 width: 300px;!important;
}

</style>
<?php
   $width = "100%";
   echo "<div id='content'>";
   echo "<div class='container' style='width:" . $width . ";' >";
   echo "<div style='height: 5px;'></div>";
   echo "<div class='col l9 m12 s12'>"; 
      echo "<div class='page-content' style='padding-left:0 !important; padding-right:0 !important;'>"; 

            echo "<div class='card white' style='margin:0px;'>"; 
               echo "<div class='card-content black-text' style='border-top:none; !important'>"; 
                     echo "<form id='periodo' action='dialerActivos.php' method='post'>";
                         echo "<div class='row' style='padding-left:0px; padding-top:20px;'>";
                            echo "<div class='input-field col s4 m4'>"; 
                               echo "<select id='equipo_id' name='equipo_id' class ='test'>"; 
                               echo "<option value='0'>Todas</option>";
                               echo "</select>"; 
                               echo "<label>Gateway</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>";

                     echo "<table id='detail' class='highlight'>"; 
                        echo "<thead>"; 
                        echo "<tr style='border:none !important;'>"; 
                          echo "<th class='col right-align' style='width:5%;'>#&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</th>"; 
                          echo "<th class='col' style='width:10%;'>CID</th>"; 
                          echo "<th class='col s4' style='width:15%;'>COMIENZO</th>"; 
                          echo "<th class='col s1' style='width:15%;'>FIN</th>"; 
                          echo "<th class='col s1 right-align' style='width:8%;'>DURACION</th>"; 
                          echo "<th class='col s1 right-align' style='width:50%;'>&nbsp;</th>"; 
                        echo "</tr>"; 
                        echo "</thead>"; 
                      echo "<tbody>"; 

                     $total_general_llamados = 
                     $total_general_minutos  = 
                     $total_general_costos   = 
                     $total_general_ventas   = 0;

                     $equipo = "Synway-1";
                     $fecha = "2023-02-01";
                     /*
                     $sql = sprintf( "select equipo, cid, min(start_time) as start, max(start_time) as endtime, cast(sum(duracion)/60 as int ) as duration from tickets left join aplicaciones on aplicaciones.dnis=tickets.dnis where equipo = '%s' and start_time >= '%s' group by cid order by endtime", $equipo, $fecha);
                     $result = $conn->query($sql);
                     $count = 0;
                     $data = false;
                     $line = 1;
                     if( $result && $result->num_rows > 0) {                                                            
                        while( $row = $result->fetch_assoc() ) {
                           $start = $row["start"];
                           $enddate = $row["endtime"]; 
                           $duration = $row["duration"];

                           $name = $row["equipo"];
                           $cid = $row["cid"];
                     
                           $date = date_create($start);
                           $formatted1 = date_format($date, 'd-m-Y H:i:s');

                           $date = date_create($enddate);
                           $formatted2 = date_format($date, 'd-m-Y H:i:s');

                           echo "<tr><a href='#'>";
                              echo "<td id='line' class='col right-align list_field' style='width:5%; font-size:10pt !important;'>$line.&nbsp;&nbsp;&nbsp;</td>";
                              echo "<td id='nfecha' class='col list_field' style='width:10%; font-size:10pt !important;'>" . $cid . "</td>";
                              echo "<td class='col list_field' style='width:15%; font-size:10pt !important;'>$formatted1</td>";
                              echo "<td class='col list_field' style='width:15%; font-size:10pt !important;'>$formatted2</td>";
                              echo "<td class='col right-align list_field' style='width:8%; font-size:10pt !important;'>$duration</td>";
                             echo "<th class='col s1 right-align' style='width:50%;'>&nbsp;</th>"; 
                           echo "</a>";
                           echo "</tr>";
                           $data = true;
                           $line++;
                        } 
                      }
                      else {
                           echo "<tr>";
                              echo "<td id='line' class='col' style='width:10% !important; padding-top:10px; font-weight:bold; font-size:11pt !important; color:red; '>SIN DATOS</td>";
                              echo "<td id='nfecha' class='col list_field' style='width:10%; font-size:10pt !important;'>&nbsp;</td>";
                              echo "<td class='col list_field' style='width:20%; font-size:10pt !important;'>&nbsp;</td>";
                              echo "<td class='col list_field' style='width:10%; font-size:10pt !important;'>&nbsp;</td>";
                              echo "<td class='col list_field' style='width:10%; font-size:10pt !important;'>&nbsp;</td>";
                              echo "<td class='col right-align list_field' style='width:5%; font-size:10pt !important;'>&nbsp;</td>";
                              echo "<td class='col right-align list_field' style='width:5%; font-size:10pt !important;'>&nbsp;</td>";
                              echo "<td class='col list_field' style='width:10%; font-size:10pt !important;'>&nbsp;</td>";
                              echo "<td class='col right-align list_field' style='width:20%; font-size:10pt !important;'>&nbsp;</td>";
                           echo "</tr>";
                           $data = false;
                     
                      }
                      if( $result && is_resource( $result ) ) mysql_free_result( $result );
                      mysqli_close($conn);
                      */
                      echo "</tbody>";
                     echo "</table>";
                 echo "</div>";
               echo "</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">

   var equipo_id = 0;

   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 );
      post("dialerDetalle.php", {dia: fecha, t:3 }); 
   }

   $(document).ready(function() {


      equipo_id = <?php echo json_encode($equipo_id); ?>;
      console.log( equipo_id );

      $('select').formSelect();

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

       $('#detail tbody').on('click', 'td.list_field', 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 }); 
      });

      $('.dropdown-trigger').dropdown({
         "hover": true,
         "constrainWidth": false,
         "coverTrigger": false
      });
      $('.modal-trigger').modal({
          dismissible: false,
          preventScrolling: true,
          opacity: .7, // Opacity of modal background
          in_duration: 300, // Transition in duration
          out_duration: 200, // Transition out duration
          starting_top: '40%'
       });         

       $('.modal-trigger').modal({
          dismissible: false,
          opacity: .7, // Opacity of modal background
          in_duration: 300, // Transition in duration
          out_duration: 200, // Transition out duration
          starting_top: '40%'
       });     


       $("select[id$='equipo_id'] option[value='" + equipo_id + "']").attr("selected", true); 
       $("#equipo_id").formSelect();

//       populateCampaigns();
       populateEquipos();

       $('#equipo_id').siblings('input').css("width", "300px");

/*
        var blink = document.getElementById('blink');
        setInterval(function() {
            blink.style.opacity = (blink.style.opacity == 0 ? 1 : 0);
        }, 1500);
        */
  });   



   function populateEquipos() {
      
      promisePopulateEquipos().then(function(info) {


      }).catch(function(err) {
         resolve("Ok");
      });
   }


   function promisePopulateEquipos() {

//      $("#modal_wait").css( 'display', 'block' );
      return new Promise(function(resolve, reject) {
               
         $.ajax({ type: "POST", url: "traficoGetEquipos.php",
            data: {},
               success: function(data){

                     $( "#equipo_id" ).empty();
                     var msg = JSON.parse(data);
                     console.log( msg );
                    $("y#equipo_id").append($("<option selected></option>").val('0').html('Todas'));
                     for( i = 0; i < msg.length; i++ ) {
                        $("#equipo_id").append($("<option></option>").val(msg[i].option).html(msg[i].nombre));
                     };

                     $("select[id$='equipo_id'] option[value='" + equipo_id + "']").attr("selected", true); 
                     $("#equipo_id").formSelect();
                     resolve(1);
                 },
                 complete: function(){
//                     $("#modal_wait").css( 'display', 'none' ); 
                 },
                 error:
                    function(err) {
                     console.log( "ERROR" );
                      reject(0);
                   }

         });
      });
   }



   /*
   function populateCampaigns() {
      
      promisePopulateCampaigns().then(function(info) {


      }).catch(function(err) {
         resolve("Ok");
      });
   }


   function promisePopulateCampaigns() {

//      $("#modal_wait").css( 'display', 'block' );
      return new Promise(function(resolve, reject) {
               
         $.ajax({ type: "POST", url: "dialerGetCampaigns.php",
            data: {},
               success: function(data){

                     $( "#equipo_id" ).empty();
                     var msg = JSON.parse(data);
                     console.log( msg );
                    $("#campaign_id").append($("<option selected></option>").val('0').html('Todas'));
                     for( i = 0; i < msg.length; i++ ) {
                        $("#campaign_id").append($("<option></option>").val(msg[i].option).html(msg[i].descripcion));
                     };

                     $("select[id$='campaign_id'] option[value='" + campaign_id + "']").attr("selected", true); 
                     $("#campaign_id").formSelect();
                     resolve(1);
                 },
                 complete: function(){
//                     $("#modal_wait").css( 'display', 'none' ); 
                 },
                 error:
                    function(err) {
                     console.log( "ERROR" );
                      reject(0);
                   }

         });
      });
   }
   */



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

