<?php
session_start();
if( $_SESSION["user"] == "" || $_SESSION["passwd"] == "" ) {
   mysqli_close($conn);
   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.php');
ini_set('max_execution_time', 240);

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

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

// $informes = $_SESSION["informes"];

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

$width = "90%";

$dolar_oficial = 140;
$dolar_blue = 292;

if( empty($Year) ) {        
   if (isset($_SESSION['Year']) ) $Year = $_SESSION["Year"]; 
   else {
      $Year = date("Y");
   }
}

if( empty($Month) ) {       
   if (isset($_SESSION['Month']) ) $Month = $_SESSION["Month"]; 
   else {
     $Month = date("n");
   }
}

$_SESSION["Year"] = $Year;
$_SESSION["Month"] = $Month;
$user_id = $_SESSION["user_id"];
$admin = $_SESSION["admin"];
$readonly = $_SESSION["readonly"];


include 'dialerHeader.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;
}
.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
   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='dialerLlamados.php' method='post'>";
                         echo "<div class='row' style='padding-left:0px; padding-top:20px;'>";

                             echo "<div class='input-field col s2 m2'>";
                                echo "<select id='month' name='month' style='width:250px;'>";
//                                echo "<option value='' disabled></option>";        
                                echo "<option value= '1'>Enero</option>";
                                echo "<option value= '2'>Febrero</option>";
                                echo "<option value= '3'>Marzo</option>";
                                echo "<option value= '4'>Abril</option>";
                                echo "<option value= '5'>Mayo</option>";
                                echo "<option value= '6'>Junio</option>";
                                echo "<option value= '7'>Julio</option>";
                                echo "<option value= '8'>Agosto</option>";
                                echo "<option value= '9'>Septiembre</option>";
                                echo "<option value='10'>Octubre</option>";
                                echo "<option value='11'>Noviembre</option>";
                                echo "<option value='12'>Diciembre</option>";
                                echo "</select>"; 
                               echo "<label>Mes</label>";
                            echo "</div>"; 
                            echo "<div class='input-field col s2 m2'>"; 
                               echo "<select id='year' name=y'year' >"; 
//                               echo "<option value='' disabled selected>Seleccione el A&ntilde;o</option>"; 
                               echo "<option value='2023'>2023</option>";
                               echo "<option value='2022'>2022</option>";
                               echo "</select>"; 
                               echo "<label>A&ntilde;o</label>";
                            echo "</div>";

                            echo "<div class='input-field col s4 m4'>"; 
                               echo "<select id='campaign_list' name='campaign_list' class ='test'>"; 
                               echo "<option value='all'>Todas</option>";
                               echo "</select>"; 
                               echo "<label>Campa&ntilde;a</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:15px;'></div>";
                     echo "</form>";

                     echo "<table id='detail' class='highlight'>"; 
                        echo "<thead>"; 
                        echo "<tr style='border:none !important;'>"; 
//                        echo "<tr>"; 
                          echo "<th class='col' style='width:30px;'>FECHA</th>"; 
                          echo "<th class='col s4' width:35%;'>DISCADOR</th>"; 
                          echo "<th class='col s1 right-align' style='width:10%;'>LLAMADOS</th>"; 
                          echo "<th class='col s1 right-align' style='width:10%;'>MINUTOS</th>"; 
                          echo "<th class='col s1 right-align' style='width:10%;'>COSTO USD</th>"; 
                          echo "<th class='col s2 right-align' style='width:20%;'>VENTA USD</th>"; 
                        echo "</tr>"; 
                        echo "</thead>"; 
                      echo "<tbody>"; 

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

                     if( $campaign_id == 0 ) $filter = "";
                     else $filter = sprintf( " and campaign=%d", $campaign_id );
                     if( $admin == true )   
                        $sql = "select date(inbound_cdr.start_time) as Fecha, count(inbound_cdr.id) as Llamados, sum(billsec) as Segundos, campaign.descripcion as description from inbound_cdr left join campaign on campaign.id=inbound_cdr.campaign where inbound_cdr.start_time >='2022-02-22 00:00:00' and Month(inbound_cdr.start_time) = $Month and Year(inbound_cdr.start_time)=$Year $filter GROUP BY date(inbound_cdr.start_time)";
                     else $sql = "select date(inbound_cdr.start_time) as Fecha, count(inbound_cdr.id) as Llamados, sum(billsec) as Segundos, campaign.descripcion as description from inbound_cdr left join campaign on campaign.id=inbound_cdr.campaign where inbound_cdr.start_time >='2022-02-22 00:00:00' and Month(inbound_cdr.start_time) = $Month and Year(inbound_cdr.start_time)=$Year and user_id=$user_id $filter GROUP BY date(inbound_cdr.start_time)";

                     $result = $conn->query($sql);
                     $count = 0;
                     $data = false;
                     if ($result && $result->num_rows > 0) {
                        while( $row = $result->fetch_assoc() ) {
         
                           $campaign = "Lumen";
                           $campaign = $row["description"];
                           $fecha = $row["Fecha"];
                           $llamados = $row["Llamados"];
                           $segundos = $row["Segundos"];
         
                           $costo = 0.15018;
                           $venta = 0.1239;
         
                           $minutos = number_format( $segundos/60, 0, ',', '.' );
                           $llamados = number_format( $llamados, 0, ',', '.' );
                           $costos = $costo * $segundos /60;
                           $ventas = $venta * $segundos /60;
         
                           $total_c = $costos * $dolar_oficial / $dolar_blue;
                           $total_costo = number_format ( $costos, 2, ',' ,  '.' ); 
                           $total_venta = number_format ( $ventas, 2, ',' ,  '.' ); 
         //                  $total_general += ($ventas - $total_c);
                           $total_general += ($ventas);
                           $total = number_format($total_general, 2, ',' ,  '.' );  
               
//                               $Sec = cnvSegundosHoras($Promedio);
                
                           $date = date_create($fecha);
                           $formatted = date_format($date, 'd-m-Y');

                           $total_general_llamados += $row["Llamados"];
                           $total_general_minutos  += ($segundos/60);
                           $total_general_costos   += $costos;
                           $total_general_ventas   += $ventas;
                      
                           echo "<tr><a href='#'>";
                              echo "<td id='nfecha' class='col list_field' style='width:30px; font-size:10pt !important;'>" . $formatted . "</td>";
                              echo "<td class='col list_field' style='width:35%; font-size:10pt !important;'>$campaign</td>";
                              echo "<td class='col right-align list_field' style='width:12%; font-size:10pt !important;'>$llamados</td>";
                              echo "<td class='col right-align list_field' style='width:12%; font-size:10pt !important;'>$minutos</td>";
                              echo "<td class='col right-align list_field' style='width:15%; font-size:10pt !important;'>$total_costo</td>";
                              echo "<td class='col right-align list_field' style='width:20%; font-size:10pt !important;'>$total_venta</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>";
                           $data = true;
                         } 
                      }
                      else {
                           echo "<tr>";
                              echo "<td id='nfecha' class='col' style='width:30px; padding-top:10px; font-weight:bold; font-size:11pt !important; color:red; '>SIN DATOS</td>";
                              echo "<td class='col' style='width:35%; font-size:10pt !important;'>&nbsp;</td>";
                              echo "<td class='col right-align' style='width:12%; font-size:10pt !important;'>&nbsp;</td>";
                              echo "<td class='col right-align' style='width:12%; font-size:10pt !important;'>&nbsp;</td>";
                              echo "<td class='col right-align' style='width:15%; font-size:10pt !important;'>&nbsp;</td>";
                              echo "<td class='col right-align' style='width:20%; font-size:10pt !important;'>&nbsp;</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 "</tr>";
                           $data = false;

                      }
                      if( $result && is_resource( $result ) ) mysql_free_result( $result );
                      mysqli_close($conn);
                      echo "</tbody>";

                      if( $data == true ) {
                         $total_general_llamados = number_format($total_general_llamados, 0, ',' , '.' );  
                         $total_general_minutos = number_format($total_general_minutos, 0, ',' , '.' );  
                         $total_general_costos = number_format($total_general_costos, 2, ',' , '.' );  
                         $total_general_ventas = number_format($total_general_ventas, 2, ',' , '.' );  

                         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;'>&nbsp;</td>";
                         echo "<td class='col s1 right-align' style='width:12%; font-size:11pt !important;'>$total_general_llamados</td>";
                         echo "<td class='col s1 right-align' style='width:12%; font-size:11pt !important;'>$total_general_minutos</td>";
                         echo "<td class='col s1 right-align' style='width:15%; font-size:11pt !important;'>$total_general_costos</td>";
                         echo "<td class='col s1 right-align' style='width:15%; font-size:11pt !important;'>$total_general_ventas</td>";
                         echo "</tr>";
                         echo "</tfoot>";
                      }
                      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 campaign_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() {

      var Month = <?php echo json_encode($Month); ?>;
      var Year = <?php echo json_encode($Year); ?>;


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

      $('#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.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$='month'] option[value='" + Month + "']").attr("selected", true); 
       $("select[id$='year'] option[value='" + Year + "']").attr("selected", true); 
       $("#month").formSelect();
       $("#year").formSelect();

       populateCampaigns();

//       $('#campaign_id').siblings('input').css("width", "300px");
       $('#campaign_list').siblings('input').css("width", "300px");
  });   



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

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

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

         });
      });
   }



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

