<?php
session_start();
if( $_SESSION["user"] == "" || $_SESSION["passwd"] == "" || $_SESSION["admin"] == false ) {
   mysqli_close($conn);
   header("Location: index.php");
}


include_once('db_config.php');

ini_set('max_execution_time', 240);

$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 = "";

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;


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

if( $Year == "2015")  $YS2015 = "selected";
if( $Year == "2016")  $YS2016 = "selected";
$admin = false;
$Movistar = 0.9225;
$Personal = 1.476;
$Claro =  0.738;
$Nextel = 1.107;
include 'header.php'; 
?>
<style>
.dropdown-content {
  overflow-x: hidden;
}
</style>
  <div id="content">
  <div class="container" >
    <div style="height: 15px;"></div>
    <div class="col l9 m12 s12">
      <div class="page-content">
        <div style="height:20px;"></div>
        <form id="asterisco" action="llamados.php" method="post"> 
        <div class="row">
        <div class="input-field col m3">
            <select name="month">
 <?php
            echo "<option value='' disabled>Seleccione el Mes</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>";
?>                
              </select>
          <label>Mes</label>
          </div>      
          <div class="input-field col  m3">
              <select  name="year">
              <option value="" disabled selected>Seleccione el A&ntilde;o</option>
<?php

                echo "<option value='2015' " . $YS2015 . ">2015</option>";
                echo "<option value='2016' " . $YS2016 . ">2016</option>";
?>              
              </select>
          <label>A&ntilde;o</label>
          </div>    
          <button class="btn waves-effect waves-light btn col s1" style="margin-top:25px; margin-left: 30px;" type="submit" name="action" >Go!</button>
          </row>  
          </form>
           <div style="height:70px;"></div>
        </div>  
        <table id="detail" class="highlight">
                <thead>
                  <tr class="red lighten-3">
                    <th class="col s1" data-field="id">Fecha</th>
                    <th class="col s1 right-align" data-field="calls" class="col s1 right-align">Llamados</th>
                    <th class="col s1 right-align" data-field="minutes" class="col s2 right-align">Minutos</th>
                    <th class="col s1 right-align" data-field="promedio" class="col s2 right-align">Promedio</th>
                    <th class="col s1 right-align" data-field="price" class="col s2 right-align">Terminacion</th>
                    <th class="col s1 right-align" data-field="price_sva" class="col s2 right-align">Importe SVA</th>
                    <th class="col s1 right-align" data-field="price_total" class="col s2 right-align">Importe Total</th>
                  </tr>
                </thead>
                <tbody>

<script type="text/javascript" charset="utf-8">
  var Month = "";
  var Year = "";
  function btnClick() {

  } 
</script>
<?php
//$sql = "select  sql_no_cache dnis, date(fecha) as dia, dnis, aplicacion, count(id) as llamados, sum(duracion) as segundos, sum(duracion_facturada) as minutos, sum( duracion_facturada ) * Tarifa as importe from tickets where year(fecha) ='" . $Year . "' and Month(fecha)='" . $Month . "'  group by date(fecha)";
//$sql = "select sql_no_cache fecha as dia, dnis, llamados, ( minutos * 60 ) as segundos, minutos, importe from diario where Importe > 0 and year(fecha)='"  . $Year . "' and Month(fecha)='" . $Month . "' group by fecha, dnis";

  $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, ( minutos * 60 ) as segundos, minutos, importe from diario where Importe > 0 and fecha='"  . $Year . "-" . $Month . "-" . $i . "'";

     $result = $conn->query($sql);

     if ($result->num_rows > 0) {
        // output data of each row
       $Fecha = "";
       $Total_Llamados = 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 "1140008966":  $Valor = 0.92225;  break;
               case "1140008967":  $Valor = 1.476;    break;
               case "1140008969":  $Valor = 0.738;    break;
               case "1140008970":  $Valor = 1.107;    break;
               default:            $Valor = 0;        break;
            }
            $Importe = $row["minutos"] * 0.00974 * 0.80;
            $Importe_SVA = $row["minutos"] * $Valor;

            $Total_Llamados += $row["llamados"];
            $Total_Minutos += $row["minutos"];
            $Total_SVA += $Importe_SVA;
            $Importe_Total += $Importe;

            $General_Total_Llamados += $row["llamados"];
            $General_Total_Minutos += $row["minutos"];
            $General_Importe_Total += $Importe;
            $General_Total_SVA += $Importe_SVA;

       }

       if( $Total_Llamados == 0 ) $Promedio = 0;  
       else $Promedio = $Total_Minutos / $Total_Llamados;
       $Horas = intval($Promedio / 60);
       $Promedio_Min = intval($Promedio - $Horas);
       $Promedio_Sec = ($Promedio - $Horas - $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;

       echo "<tr>";
       echo "<td class='col s1' >" . $formatted . "</td>";
       echo "<td class='col s1 right-align'>" . number_format ( $Total_Llamados, 0, ',' ,  '.' ) . "</td>";
       echo "<td class='col s1 right-align'>" . number_format ( $Total_Minutos, 0, ',' ,  '.' ) . "</td>";
       echo "<td class='col s1 right-align'>" .  $Sec . " </td>";
       echo "<td class='col s1 right-align'>" . number_format ( $Importe_Total , 2, ',' ,  '.' ) . "</td>";
       echo "<td class='col s1 right-align'>" . number_format ( $Total_SVA , 2, ',' ,  '.' ) . "</td>";
       echo "<td class='col s1 right-align'>" . number_format ( $Importe_Total + $Total_SVA , 2, ',' ,  '.' ) . "</td>";
       echo "</tr>";

      } 
      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 "<tfoot>";
    echo "<tr style='color:white; font-weight: 500;'>";
    echo "<td class='col s1'></td>";
    echo "<td class='col s1 right-align red darken-4'>" . number_format ( $General_Total_Llamados, 0, ',' ,  '.' ) . "</td>";
    echo "<td class='col s1 right-align red darken-4'>" . number_format ( $General_Total_Minutos, 0, ',' ,  '.' ) . "</td>";
    echo "<td class='col s1 right-align red darken-4'>" . $Sec . "</td>";
    echo "<td class='col s1 right-align red darken-4'>" . number_format ( $General_Importe_Total, 2, ',' ,  '.' ) . "</td>";
    echo "<td class='col s1 right-align red darken-4'>" . number_format ( $General_Total_SVA, 2, ',' ,  '.' ) . "</td>";
    echo "<td class='col s1 right-align red darken-4'>" . number_format ( $General_Importe_Total + $General_Total_SVA, 2, ',' ,  '.' ) . "</td>";
    echo "</tr>";
    echo "</tfoot>";
?>        
    </tbody>
    </table>
    </div>
    <div style="height:100px;"></div>
  </div>
  </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="js/materialize.min.js"></script>
<script>
   // Post to the provided URL with the specified parameters.
   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() {
              // bind 'myForm' and provide a simple callback function 
              /*
              $('#asterisco').ajaxForm(function() { 
                    alert("Thank you for your comment!"; 
              }); */ 

    $('select').material_select();

    $('#month').on('change', function() {
        Month = this.value;
        console.log( this.value )
    });   
    $('#year').on('change', function() {
        Year = this.value;
        console.log( this.value )
    });   

//  $('#detail tr').click(function() {

    $('#detail').on('click', 'tr', function(e) {
         post("detalle.php", {dia: e.currentTarget.cells[0].innerHTML }); 
    });
  });   
</script>
</body>
</html>

