<?php
session_start();
if( $_SESSION["user"] == "" || $_SESSION["passwd"] == "" ) {
//   header("Location: index.php");
}
include_once('db_confign.php');
ini_set('max_execution_time', 120);

$Desde  = isset($_POST['desde']) ? $_POST["desde"]  : "";
$Hasta  = isset($_POST['hasta']) ? $_POST["hasta"]  : "";

//$Fecha = "";
$YS2015 = "";
$YS2016 = "";
$YS2017 = "";
$first = false;

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

if( empty($Desde) ) {        
   if( $_SESSION["Desde"] != "" ) $Desde = $_SESSION["Desde"];
   else $Desde = date("d-m-Y");   
   $first = true;
}


if( empty($Hasta) ) {        
   if( $_SESSION["Hasta"] != "" ) $Hasta = $_SESSION["Hasta"];
   else $Hasta = date("d-m-Y");   
   $first = true;
}

$D = substr( $Desde, 6, 4 ) . "/" . substr( $Desde, 3, 2 ) . "/" . substr( $Desde, 0, 2 );
$H = substr( $Hasta, 6, 4 ) . "/" . substr( $Hasta, 3, 2 ) . "/" . substr( $Hasta, 0, 2 ); 

//echo $D . "<br/>";
//echo $H . "<br/>";

$admin = false;
include 'header.php'; 
?>
<style>
.dropdown-content {
  overflow-x: hidden;
}

</style>
  <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <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>');
      
      
	console.log("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();
   };
</script>

  <div id="content">
  <div class="container"  > 
    <div class="col l9 m12 s12">
      <div class="page-content">
 <?php
         echo "<div class='row'>";
         echo "<div class='input-field col s12 right-align  red-text text-darken-4' style='font-size:14pt; text-decoration: underline;'><b>" . $Descripcion . "</b></div>";;
         echo "</div>";
         echo "<div class='row'>";
         echo "<div class='input-field col s2'>";
         echo "<label for='desde'>Desde</label>";
         echo "<input id='desde' type='date' class='datepicker' data-value='" . $D . "' onChange='onChange(this);'>";
         echo "</div>";
         echo "<div class='input-field col s2'>";
         echo "<label for='hasta'>Hasta</label>";
         echo "<input id='hasta' type='date' class='datepicker' data-value='" . $H . "' onChange='onChange(this);'>";
         echo "</div>";
         echo "<div class='input-field col s3'>";
         echo "<button onclick='Go();' class='btn waves-effect waves-light btn col s3' style='margin-top:15px; margin-left: 30px; width:190px;'>Preparar</button>";
         echo "</div>";
         echo "</row>";
?>
      </div>
   </div>
  </div>

<?php

   if( $first == false ) {
      $sql = "select sql_no_cache fecha, case when cid <> 'anonymous' then cid else '' end as ani,  (case when dnis = '1151720084' then 'Movistar' when dnis = '1151720085' then 'Personal' when dnis = '1151720086' then 'Claro' when dnis = '1151720087' then 'Nextel' else '' end) as Operadora from tickets where fecha >='" . $D . "' and fecha <='" . $H . " 23:59:59'  and dnis >='1151720084' and dnis <= '1151720087' order by fecha";
      console.log( $sql );      
//   echo $sql . "<br/>";
      $result = $conn->query($sql);

      if ($result->num_rows > 0) {

       $filename = "llamados.txt";
       $myfile = fopen($filename, "w") or die("Error!");
       while($row = $result->fetch_assoc()) {
//        $date = date_create($row["fecha"]);
//        $formatted = date_format($date, 'd-m-Y H:i:s');
//        echo $row["fecha"] . ";" . $row["ani"] . ";" . $row["Operadora"] . "<br/>";
      
          $txt = "'" . $row["fecha"] . "';" . $row["ani"] . ";" . $row["Operadora"] . "\r\n"; 
          fwrite($myfile, $txt);
       }
       fclose($myfile);
       mysqli_close($conn);
       echo "<script>\n";
       echo "post('download.php', {filename: 'llamados.txt' });\n";
       echo "</script>\n";
                                                                                                                             
//       echo "<a href='http://trafico.interactivos.net.ar/llamados.txt'>Descargar Archivo</a>";
/*

       $file_url = 'http://trafico.interactivos.net.ar/' . $filename;
       header('Content-Description: File Transfer');
       header('Content-Type: application/octet-stream');
       header("Content-disposition: attachment; filename=\"" . $filename . "\""); 
       header("Content-Transfer-Encoding: Binary"); 
       header('Expires: 0');
       header('Pragma: no-cache');
       header("Content-Length: ".filesize($filename));
       readfile($file_url); // do the double-download-dance (dirty but worky)
       */
    }  
  }     

   mysqli_close($conn);
?>          
  </div>
<style>
.screenReaderText { 
  border: 0; 
  clip: rect(0 0 0 0); 
  height: 1px; 
  margin: -1px; 
  overflow: hidden; 
  padding: 0; 
  position: absolute; 
  width: 1px; 
}
</style>


<script>
  $(document).ready(function() {

    $('.datepicker').pickadate({
       selectMonths: true, // Creates a dropdown to control month
       selectYears: 15, // Creates a dropdown of 15 years to control year
       monthsFull: [ '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' ],
       weekdaysFull: [ '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',
       close: 'Cerrar',
       format: 'dd-mm-yyyy',
       formatSubmit: 'yyyy-mm-dd'
       /*
       format: dateFormat,
       /*
       min: new Date(1935,1,1),
       onOpen: Register.OnDateOut(),
       onClose: Register.OnDateOut(),
       max: new Date(new Date().setYear(new Date().getFullYear() + 2))
         */
    });

  });  


   function Go() {

      var desde = $("#desde").val();
      var hasta = $("#hasta").val();
      
      console.log( desde );
      console.log( hasta );

      post('moviclips.php', {desde: desde, hasta: hasta });
	
   }

   function onChange(element) {

      var inicio = <?php echo(json_encode($Inicio)); ?>;
      var fin = <?php echo(json_encode($Fin)); ?>;

      switch( element.id ) {
         case "desde":
            
         case "hasta":
            break;

         default:
            break;
      }
   }
   
</script>
</body>
</html>
