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

$trama = isset($_POST['t']) ? $_POST["t"]  : "";
//$page = $_SERVER['PHP_SELF'];
//$sec = "120";
//header("Refresh: $sec; url=$page");

$url = "http://10.0.65.11/event_cli.php";

$width = "85%";
$admin = false;
include 'traficoHeader.php'; 

function timezone_offset_string( $offset )
{
   return sprintf( "%s%02d:%02d", ( $offset >= 0 ) ? '+' : '-', abs( $offset / 3600 ), abs( $offset % 3600 ) );
}

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

tr:hover {
//   cursor:pointer;
}

.member-row {
   line-height:2.3em !important;
   font-size:10pt !important;
}

.open {
    min-height:2.3em !important;
    line-height:2.3em !important;
    background: url('images/details_open.png') no-repeat center center;
    cursor: pointer;
}
.close {
    line-height:2.3em !important;
    min-height:2.3em !important;
    background: url('images/details_close.png') no-repeat center center;
}


.not_recording {


}

</style>
<?php

//include "ejemplo.php";


   $ch = curl_init();
   curl_setopt($ch, CURLOPT_HEADER, 0);
   curl_setopt($ch, CURLOPT_URL,"http://10.0.65.11/event_cli.php");
   curl_setopt ($ch, CURLOPT_POST, TRUE);
   curl_setopt($ch, CURLOPT_POSTFIELDS, "option=conference");
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   $xmlString = curl_exec($ch);
   curl_close($ch);

    $xml = new SimpleXMLElement($xmlString);
//    print_r( $xmlString );


//   $zonahoraria = date_default_timezone_get();
//   echo 'Zona horaria predeterminada: ' . $zonahoraria . "<br/>";
//   date_default_timezone_set('America/Argentina/Buenos_Aires');
//   $offset = timezone_offset_get( new DateTimeZone( 'America/Argentina/Buenos_Aires' ), new DateTime() );
//   echo "Offset en Argentina: " . $offset . "<br/>";
//   echo "Hora en Buenos Aires: " . timezone_offset_string( $offset ) . "\n";

            $count = 1;
            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 id='conferences' class='highlight'>"; 
                        echo "<thead>"; 
                        echo "<tr style='border:none !important;'>"; 
                          echo "<th class='col' style='width:30px; text-decoration: none;'>&nbsp;</th>"; 
                          echo "<th class='col' style='width:3%; text-decoration: none;'>&nbsp;</th>"; 
                          echo "<th class='col' style='width:20%;'>COMIENZO</th>"; 
                          echo "<th class='col' style='width:30%;'>NOMBRE CONFERENCIA</th>"; 
                          echo "<th class='col right-align' style='width:7%; text-decoration: none;'>&nbsp;</th>"; 
                          echo "<th class='col right-align' style='width:15%;'>PARTICIPANTES</th>"; 
                          echo "<th class='col right-align' style='width:15%;'>DURACION</th>"; 
                          echo "<th class='col right-align' style='width:5%; text-decoration: none;'>&nbsp;</th>"; 
                        echo "</tr>"; 
                        echo "</thead>"; 
                      echo "<tbody>"; 

                     // Conference attributes
                     $x = 0;
                     $childs = array();

                     if( $xml->count() > 0 ) {

                        foreach($xml as $child) { 
                           $childs[$x] = $child;
                           ++$x;
                        }  
                        
                        $bubble = array();

                        /* Bubble sort */
                        for( $outer = 0; $outer < $x-1; $outer++ ) {
                           for( $inner = $outer+1; $inner < $x; $inner++) {
//                              echo $childs[$outer]['name'] . "<->" . $childs[$inner]['name'] . "<br/>";
                             if( $childs[$outer]['name'] > $childs[$inner]['name'] )  {
                                  $temp = $childs[$outer];
                                  print_r( $temp );
                                  echo "<br/>";

                                  $childs[$outer] = childs[$inner];
                                  $childs[$inner] = $temp;
                              }
                           }
                        }

//                       foreach($xml as $child) { 

                        for( $y = 0; $y < $x; $y++ ) {
                           $child = $childs[$y];


                           echo "<tr><a href='#'>";

                              $runtime = $child['run_time']; 
                              $formatted = date( "d/m/Y H:i:s", time() - intval( $runtime ) );
                              $name = $child['name'];
                              $members = $child['member-count']; 

                              $img = "images/conferences/not_recording.png";
                              $class = "not_recording";
                              if( ( $linea = intval( $name ) -  3600 ) >= 0 ) {
                                 $q = sprintf( "select sql_no_cache record from chat_ivr_recordings where linea=%d and record=1", intval( $name ) -  3600 );
                                 $result = $conn->query($q);
                                 if ($result->num_rows > 0) {
                                    if($row = $result->fetch_assoc()) {
                                       $record = $row["record"];
                                       $img = "images/conferences/recording.png";
                                       $class = "recording";
                                    }
                                 }
                                 if( $result && is_resource( $result ) ) mysql_free_result( $result );
                              }

                              echo "<td class='col open' style='width:30px; line-height:2.3em !important;'></td>"; 
                              echo "<td class='col right-align' style='width:3%; line-height:2.3em !important;'>" . sprintf( "%d.", $count ) . " </td>"; 
                              echo "<td id='fecha' class='col' style='width:20%; font-size:10pt !important;'>" . $formatted . "</td>";
                              echo "<td id='name'  class='col' style='width:30%; font-size:10pt !important;'>" . $name . "</td>";
                              echo "<td id='space1' class='col right-align' style='width:7%; font-size:10pt !important;'>&nbsp;</td>";
                              echo "<td id='members' class='col right-align' style='width:15%; font-size:10pt !important;'>" . $members . "</td>";
                              echo "<td id='runtime' class='col right-align' style='width:15%; font-size:10pt !important;'>" . cnvSegundosHoras($runtime) . "</td>";
                              echo "<td id='record_button' class='col right-align record $class' style='width:5%; font-size:10pt !important;'><a id='record' name='$name' href='#' onclick='onClick(this);'><img id='record_img' src='$img' style='height:22px; padding-top:10px;'></a></td>";
                              $count++;                                 
   
   /*
                              foreach($child->attributes() as $a => $b) {
   //                              echo $a . ": " . $b[0] . "<br/>"; 
                                 $formatted = "&nbsp;";
                                 echo "<td id='fecha' class='col right-align tfecha' style='width:15%; font-size:10pt !important;'>" . $formatted . "</td>";
                                 switch( $a ) {
                                    case 'name':
                                       echo "<td class='col' style='width:35%; font-size:10pt !important;'>" . $b[0] . "</td>";
                                       break;
                                 }
                              }
                              */
                           echo "</a>";
                           echo "</tr>";

//                           print_r($xml->$conference);
//                                  echo "<br/>";

//                           foreach($xml->conference as $conf) { 
//                              foreach($conf->members->member as $child){ 
//                              foreach($child->conference->members->member as $child){ 
                              foreach($child->members->member as $child_member){ 

                                 if( $child_member->caller_id_number != "anonymous" )  {
                                    $q = sprintf( "select sql_no_cache ani, dnis, linea from chat_ivr_online where ani='%s'", $child_member->caller_id_number );
                                    $result = $conn->query($q);
                                    if ($result->num_rows > 0) {
                                       if($row = $result->fetch_assoc()) {
                                          $dnis = $row["dnis"];
                                          $linea = $row["linea"];
                                       }
                                    }
                                    if( $result && is_resource( $result ) ) mysql_free_result( $result );
                                 }
                                 else {
                                    $dnis  = "N/D";
                                    $linea = "N/D";
                                 }

                                 echo "<tr class='members hide' style='background-color:white;'>";
                                    echo "<td colspan='7' style='margin:0; padding:0;'>";
                                       echo "<table style='background-color:#CFDAE7; font-size:10pt;'>";
                                          echo "<tr style='background-color:#F3F7F8; border-style:none;'>";
                                             echo "<td class='member-row' style='width:30px;'>&nbsp;</td>";
                                             echo "<td class='member-row' style='width:5%;'>&nbsp;</td>";
                                             echo "<td class='member-row' style='width:15%;'>Dnis: $dnis</td>";
                                             echo "<td class='member-row' style='width:6%;'>Caller ID:&nbsp;</td>";
                                             echo "<td id='callerid' class='member-row' style='width:9%;'>$child_member->caller_id_number</td>";
                                             echo "<td class='member-row' style='width:20%;'>Caller ID Name: $child_member->caller_id_name</td>";
                                             echo "<td class='member-row right-align' style='width:20%; padding-right:10px;'>Tiempo de Conexi&oacute;n: " . cnvSegundosHoras($child_member->join_time) . "</td>";
                                             echo "<td class='member-row right-align' style='width:15%; padding-right:10px;'>Linea: $linea</td>";
                                             echo "<td class='member-row' style='width:10%; padding-right:10px;'>&nbsp;</td>";
                                          echo "</tr>"; 
                                       echo "</table>";
                                    echo "</td>"; 
                                 echo "</tr>"; 
                              }
                        //   }
                        }                           
                     }
                     else {
                        echo "<tr>";
                        echo "<td class='col' style='width:3%; line-height:2.3em !important;'></td>"; 
                        echo "<td class='col' style='width:97%;'>No hay conferencias activas</td>";
                        echo "</tr>";
                     }
                     echo "</tbody>";
                     echo "</table>";
                 echo "</div>";
               echo "</div>";
            echo "</div>";
         echo "</div>";
      echo "</div>";
   mysqli_close($conn);
?>    
   <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();


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

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

       $('#conferences tbody').on('click', 'td.open', function () {

            var tr = $(this).closest('tr');
            var next_tr = tr.next('tr');

            $(this).removeClass('open' );
            $(this).addClass('close' );
//            next_tr.removeClass('hide');

            while( next_tr.hasClass( "members" ) ) {
               next_tr.removeClass('hide');
               next_tr = next_tr.next('tr');
            } 

       });        


       $('#conferences tbody').on('click', 'td.close', function () {

           var tr = $(this).closest('tr');
           var next_tr = tr.next('tr');

           $(this).removeClass('close' );
           $(this).addClass('open' );

            while( next_tr.hasClass( "members" ) ) {
               next_tr.addClass('hide');
               next_tr = next_tr.next('tr');
            } 
       });        

       $('#conferences tbody').on('click', 'td.record', function () {

           var not_rec = 'images/conferences/not_recording.png';
           var rec = 'images/conferences/recording.png';
           var tr = $(this).closest('tr');
           var img = tr.find('#record_img')[0];
           var name = tr.find('#record')[0].name;
           var mode = "2";

          console.log( "Hola" );
           if( $(this).hasClass('recording' ) ) {
               $(this).removeClass('recording' );
               $(this).addClass('not_recording' );
               img.src = not_rec;
               mode = "2";
           }
           else {
               $(this).removeClass('not_recording' );
               $(this).addClass('recording' );
               img.src = rec;
               mode = "1";
            }

            var next_tr = tr.next('tr');
            var i = 0;
            var cid = new Array(5);
            cid[0] = cid[1] = "";
            while( next_tr.hasClass( "members" ) ) {
               var caller_id = next_tr.find('#callerid')[0].innerText;
               next_tr = next_tr.next('tr');
               cid[i] = caller_id;
               if( i++ >= 2 ) break;
            } 
            /*
            console.dir( name );
            for( x = 0; x < i; x++ )
               console.log( cid[x] );
              */
            Record_Conference(name,cid[0],cid[1],mode);


       });        




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

      }
   }

   function Record_Conference(name,origen,destino,mode) {
      var url = <?php echo json_encode($url); ?>;

      var linea = parseInt( name ) - 3600;
      console.log( name );
      console.log( origen );
      console.log( destino );
      console.log( linea );

      $.ajax({
       type: "POST",
       url: url,
          data: { 'option': "conference_record", 'conference_name': name, 'origen': origen, 'destino': destino, 'mode': mode, 'linea': linea },
            success: function(data){
               console.log( data );
//               var msg = JSON.parse(data);
            }
      });
   }


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

