<?php

$informe = isset($_POST['informe']) ? $_POST["informe"]  : "tickets";

$start_fecha = "2019-11-01";
$end_fecha = "2019-12-01";

include_once('db_config_hosting.php');
ini_set('max_execution_time', 120);

define('K_PATH_CSV', '/var/www/html/trafico/pdf'); 

   switch ($informe ) {
      case "tickets":
         if( ( $cfile = fopen( K_PATH_CSV . "/tickets.csv", "w" ) ) ) {

            fwrite( $cfile, "Inicio;Fin;Duracion;Origen;Destino;Bloque;Excedente\n" );
            $sql = "select sql_no_cache fecha, DATE_ADD(fecha, INTERVAL duracion SECOND) as end_date, dnis, cid, duracion from tickets where date(fecha) >= '$start_fecha' and date(fecha) < '$end_fecha' and dnis='1151720091' order by fecha";
            $result = $conn->query($sql);
            if ($result->num_rows > 0) {
               while( $row = $result->fetch_assoc() ) {
         
                  $fecha = $row["fecha"];
                  $dnis = $row["dnis"];
                  $cid = $row["cid"];
                  $duracion = $row["duracion"];
                  $end_date = $row["end_date"];

                  if( $cid == "anonymous" ) $cid = "";         
                  $bloque = 1;
                  $excedente = 0;
                  if( $duracion > 30 ) {
                     $excedente = $duracion - 30;
                  }
         
                  $start_date = date("d-m-Y G:i:s", strtotime( $fecha ) );  
                  $start_time = date("d-m-Y G:i:s", strtotime( $end_date ) );  
                  fwrite( $cfile, "$start_date;$start_time;" . number_format( $duracion, 0, '' ,  '' ) . ";$cid;$dnis;" . number_format( $bloque, 0, '' ,  '' ) . ";" . number_format( $excedente, 0, '' ,  '' ) . "\n" );
               } 
            }
            if( $result && is_resource( $result ) ) mysql_free_result( $result );
            fclose( $cfile );
         }
         break;

      default:
         break;
   }
   mysqli_close($conn);
?>

