<?php
//============================================================+
// File name   : example_011.php
// Begin       : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 011 for TCPDF class
//               Colored Table (very simple table)
//
// Author: Nicola Asuni
//
// (c) Copyright:
//               Nicola Asuni
//               Tecnick.com LTD
//               www.tecnick.com
//               info@tecnick.com
//============================================================+

/**
 * Creates an example PDF TEST document using TCPDF
 * @package com.tecnick.tcpdf
 * @abstract TCPDF - Example: Colored Table
 * @author Nicola Asuni
 * @since 2008-03-04
 */


//echo "<head>";
//echo "<title>Servicios de Internet</title>";
//echo "<link rel='shortcut icon' href='logo.ico'>"; 
//echo "</head>"; 

// Include the main TCPDF library (search for installation path).
//require_once('tcpdf_include.php');

$output = isset($_POST['output']) ? $_POST["output"]  : "browser";
$mode = isset($_POST['mode']) ? $_POST["mode"]  : "monthly";
$informe = isset($_POST['informe']) ? $_POST["informe"]  : "altas";

//$mode = "monthly";
$output = "browser";
$informe = "tickets";

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

define('K_PATH_IMAGES', '/var/www/html/trafico/'); 
require_once('tcpdf/tcpdf.php');

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

$total_general = 0;

// extend TCPF with custom functions
class MYPDF extends TCPDF {

    protected $title = "";
    

   //Page header
    public function Header() {
         // Logo
         $image_file = K_PATH_IMAGES . 'images/Logo.png';
         $this->Image($image_file, 10, 10, 10, '', 'PNG', '', 'T', false, 300, '', false, false, 0, false, false, false);
         //                        x    y   w   h   type          resize   DPI  align  imask imgmask border  fitbox, hidden fitonpage [alt alimgs]

         // Set font
         $this->SetFont('helvetica', 'B', 12);

         // Title
         $this->SetY(20);
         $this->Cell(0, 10, $this->title, 0, false, 'C', 0, '', 0, false, 'M', 'M');

         // Header
         $this->SetFillColor(255, 255, 255);
         $this->SetTextColor(0);
         $this->SetDrawColor(255,255,255);
         $this->SetLineWidth(0);
         $this->SetFont('Courier','B',8);
         $this->SetY(28);
         $header = array('Comienzo', 'Fin', 'Duracion', '', 'Origen', 'Destino', 'Bloque', 'Excedente');
         $w = array(38,38,15,1,24,24,17,20);
//         $a = array('L','L','R','L','L','R','R');
         $a = array('L','L','R','R','L','L','R','R');
         $num_headers = count($header);
         for($i = 0; $i < $num_headers; ++$i) {
           $this->Cell($w[$i], 7, $header[$i], 0, 0, $a[$i], 1);    // Width, Height, Text, Border, ??, Align. Fill
         }
         $this->Ln();

    }

    // Page footer
    public function Footer() {
        global $total_general;
        global $informe;
        global $start_fecha;
        global $end_fecha;

         $this->SetY(-30);
         switch( $informe ) {
         /*
            case "facturacion":
            
//               $this->Cell($w[1], 6, "", '', 0, 'L', 0, '', 0, false, 'T', 'M');

              $total = number_format ( $total_general, 2, ',' ,  '.' ); 
              $this->Cell(14, 6, "Total General", '', 0, 'L', 0, '', 0, false, 'T', 'M');
              $this->Cell(70, 6, '', '', 0, 'L', 0, '', 0, false, 'T', 'M');
              $this->Cell(70, 6, '', '', 0, 'L', 0, '', 0, false, 'T', 'M');
              $this->Cell(30, 6, $total, '', 0, 'R', 0, '', 0, false, 'T', 'M');

              $this->SetY(-15);
              $this->SetFont('helvetica', '', 8);
//              $this->Cell(0,10, 'Pagina '.$this->getAliasNumPage().'-'.$this->getAliasNbPages(), 0, false, 'R', 0, '', 0, false, 'T', 'M');
              $this->Cell(190,10, 'Pagina '.$this->getAliasNumPage(), 0, false, 'R', 0, '', 0, false, 'T', 'M');
              break;
              */

            default:
              // Position at 15 mm from bottom
              $this->SetY(-15);
              $this->SetFont('helvetica', '', 8);
              $this->Cell(0, -10, 'Pagina '.$this->getAliasNumPage().'-'.$this->getAliasNbPages(), 0, false, 'R', 0, '', 0, false, 'T', 'M');
              break;
         }

    }

   // Load table data from file
   public function LoadData($file) {
      // Read file lines
      $lines = file($file);
      $data = array();
      foreach($lines as $line) {
         $data[] = explode(';', chop($line));
      }
      return $data;
   }

   // Colored table
   public function ColoredTable($header,$data,$conn,$mode,$informe) {

      global $total_general;
      global $start_fecha;
      global $end_fecha;

      $count = 0;

      // Colors, line width and bold font
      /*
      $this->SetFillColor(255, 0, 0);
      $this->SetTextColor(255);
      $this->SetDrawColor(128, 0, 0);
      $this->SetLineWidth(0.3);
//      $this->SetFont('', 'B');
*/

      $this->SetY(34);

      $this->SetFillColor(255, 255, 255);
      $this->SetTextColor(0);
      $this->SetDrawColor(255,255,255);
      $this->SetLineWidth(0);
      $this->SetFont('Courier','B',8);

      switch( $informe ) {

         case "tickets":

            // Header
//            $header = array('Comienzo', 'Fin', 'Duracion', 'Origen', 'Destino', 'Bloque', 'Excedente');
            $w = array(38,38,15,1,24,24,17,20);
//            $a = array('L','L','R','L','L','R','R');
//            $num_headers = count($header);
//            for($i = 0; $i < $num_headers; ++$i) {
//               $this->Cell($w[$i], 7, $header[$i], 0, 0, $a[$i], 1);    // Width, Height, Text, Border, ??, Align. Fill
//            }
//            $this->Ln();
      
            // Data
            $this->SetFont('Courier','',8);
            $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' order by fecha limit 100";
            $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' order by fecha limit 100";
            $result = $conn->query($sql);
            $count = 0;
            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"];

                  $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 ) );  
      
//                  $nombre = utf8_encode( $nombre );
//                  $nombre = ucwords( strtolower ( $nombre ) );
//                  $direccion = utf8_encode( $direccion );
      
                  $fill = 0;
      
                  // Celdas
                  $this->Cell($w[0], 6, $start_date, 'LR', 0, 'L', $fill);
                  $this->Cell($w[1], 6, $start_time, 'LR', 0, 'L', $fill);
                  $this->Cell($w[2], 6, number_format( $duracion, 0, '.' ,  ',' ), 'LR', 0, 'R', $fill );
                  $this->Cell($w[3], 6, "", 'LR', 0, 'L', $fill);
                  $this->Cell($w[4], 6, $cid, 'LR', 0, 'L', $fill);
                  $this->Cell($w[5], 6, $dnis, 'LR', 0, 'L', $fill);
                  $this->Cell($w[6], 6, number_format( $bloque, 0, '.' ,  ',' ), 'LR', 0, 'R', $fill );
                  $this->Cell($w[7], 6, number_format( $excedente, 0, '.' ,  ',' ), 'LR', 0, 'R', $fill );
                  $this->Ln();
                  $fill=!$fill;
               } 
            }
            if( $result && is_resource( $result ) ) mysql_free_result( $result );
            break;

      }
      return $count;
   }
}

// create new PDF document

$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//                      P                 mm          A$


// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Servicios Interactivos');
$pdf->SetSubject('Informes');
$pdf->SetKeywords('informes, tickets');

// set default header data
//$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 011', PDF_HEADER_STRING);
//$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 011', PDF_HEADER_STRING);

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP + 8, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER + 5);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// print colored table
switch( $informe ) {
   case "tickets":
      $title = 'Detalle de Llamados';
      $filename = "tickets.pdf";
//      $pdf->SetAutoPageBreak(TRUE, 40);
      break;
}

// set image scale factor
$pdf->SetTitle($title);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/tcpdf/lang/spa.php')) {
   require_once(dirname(__FILE__).'/tcpdf/lang/spa.php');
   $pdf->setLanguageArray($l);
}

// ---------------------------------------------------------

// set font
$pdf->SetFont('helvetica', '', 12);

// add a page
$pdf->AddPage();

// column titles
$header = array('Cliente', 'Nombre', 'Servicio Instalado', 'Fecha');

// data loading
//$data = $pdf->LoadData('tcpdf/data/table_data_demo.txt');


$n = $pdf->ColoredTable($header, $data, $conn, $mode, $informe );

// ---------------------------------------------------------

// close and output PDF document
   switch( $output ) {
      case 'browser':
         $pdf->Output($filename, 'I');
         break;

      case 'email':
         if( intval( $n ) > 0 ) {
//            $pdf->Output('/var/www/html/trafico/pdf/'. $filename, 'F');
            $pdf->writeHTML('/var/www/html/trafico/pdf/'. $filename, 'F');
            $errorText = "{ \"errno\": 0, \"count\": \"" . $n . "\" }";
         }
         echo $errorText;
         break;
   }

mysqli_close($conn);


//============================================================+
// END OF FILE
//============================================================+
