<?php
// Load the PHPWord library classes
require_once __DIR__ . '/phpword_1.0.0/autoload.php'; 
use PhpOffice\PhpWord\Element\TextRun;

// Load the QR library classes
require_once __DIR__ . '/qr-code_4.4.9/autoload.php'; 

use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;

function create_factura() 
{
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

$idfactura= $_SESSION['idfactura'] ; // identificación de factura a obtener

$decimal = new \NumberFormatter("es-ES", \NumberFormatter::DECIMAL); 
$decimal->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 2);
$decimal->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 2); // by default some locales got max 2 fraction digits
$entero = new \NumberFormatter("es-ES", \NumberFormatter::DECIMAL);
$entero->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
$entero->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 0); 

// Template processor instance creation
$template_word = __DIR__.'/PlantillaFactura.docx';
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($template_word);

// -------------------- ^ cabecera necesaria para las plantillas de Word ------------------
$sql="SELECT Nif, NombreRazonSocial, Domicilio, RestoDomicilio, FechaFactura, TotalFactura FROM factura where idfactura = $idfactura";
$resql=db_query($sql,$conn);
$data=db_fetch_array($resql);

$nif = new TextRun();
$nif_arr = array ($data['Nif'],'dos');

for($i = 0; $i < count($nif_arr); ++$i) {
	$nif->addText($nif_arr[$i]);
	if ( $i+1 <> count($nif_arr)) { 
		$nif->addTextBreak(1);
  }
}

// Variables on different parts of document
$templateProcessor->setComplexValue('NIF', $nif);
// $templateProcessor->setValue('NIF', $data['Nif']); 
$templateProcessor->setValue('Nombre', $data['NombreRazonSocial']);  
$templateProcessor->setValue('Direccion1', $data['Domicilio']);
$templateProcessor->setValue('Direccion2', $data['RestoDomicilio']);
$templateProcessor->setValue('Total', $decimal->format($data['TotalFactura']));
$FechaFactura=$data['FechaFactura'];

// Set Image - Create QR
// Load the QR library classes

$writer = new PngWriter();

// Create QR code
$txt = "Factura: $idfactura";
$qrCode = QrCode::create($txt)
    ->setEncoding(new Encoding('UTF-8'))
    ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())
    ->setSize(200)
    ->setMargin(10)
    ->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())
    ->setForegroundColor(new Color(0, 0, 0))
    ->setBackgroundColor(new Color(255, 255, 255));

// Create generic logo

$logo = Logo::create(__DIR__.'/fernando.png')
    ->setResizeToWidth(50);

// Create generic label

$label = Label::create('fhumanes')
    ->setTextColor(new Color(255, 0, 0));

$result = $writer->write($qrCode, $logo, $label);


// Create name file
$file = tempnam(sys_get_temp_dir(), 'PNG');
unlink($file);
$file = str_replace('.','_',$file).'.png';

// Save it to a file
$result->saveToFile($file);

$image = $file;
$templateProcessor->setImageValue('foto', array('path' => $image, 'width' => 100, 'height' => 100, 'ratio' => true));
unlink($file);

$sql="SELECT count(*) Lineas FROM linea_factura where factura_idfactura= $idfactura";
$resql=db_query($sql,$conn);
$data=db_fetch_array($resql);
$NumeroLineas= $data['Lineas']; // número de líneaas de factura
// Simple table
$templateProcessor->cloneRow('rowArticulo', $NumeroLineas);

$sql="SELECT Nombre, Precio, Cantidad, Valor  FROM linea_factura where factura_idfactura= $idfactura ";
$rsSql=db_query($sql,$conn);
$countLines=0;
while ($data2 = db_fetch_array($rsSql)){
		$countLines=$countLines+1;
		$templateProcessor->setValue('rowArticulo#'.$countLines, $data2['Nombre']);
		$templateProcessor->setValue('rowPrecio#'.$countLines, $decimal->format($data2['Precio']));
		$templateProcessor->setValue('rowCantidad#'.$countLines, $entero->format($data2['Cantidad']));
		$templateProcessor->setValue('rowValor#'.$countLines, $decimal->format($data2['Valor']));
		// $templateProcessor->setImageValue('rowFoto#'.$countLines, array('path' => $image, 'width' => 50, 'height' => 50, 'ratio' => true));
	}

// Date Local completed

$date = DateTime::createFromFormat('Y-m-d', $FechaFactura);
$formatter = new IntlDateFormatter('es_ES', IntlDateFormatter::LONG, IntlDateFormatter::LONG);
$formatter->setPattern("d 'de' MMMM 'de' yyyy");
$mydate = $formatter->format($date);
$templateProcessor->setValue('FechaDeHoyCompleta', $mydate);

// $templateProcessor->setValue('FechaDeHoyCompleta', $FechaFactura);

// -------------------- v pie para salvar el nuevo documento Word ------------------
$temp_file = tempnam(sys_get_temp_dir(), 'Word');
$templateProcessor->saveAS($temp_file);

// Saving the document as PDF file...
/*
$phpWord = \PhpOffice\PhpWord\IOFactory::load($temp_file);

$domPdfPath = realpath(__DIR__ . '/../../ComponentCode/PHPWord_1.0.0/dompdf/dompdf');
\PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
\PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'PDF');
$objWriter->save($temp_file);
*/
return $temp_file;
}
/*
// ------------------ Operation with file result -------------------------------------------
$documento = file_get_contents($temp_file);
unlink($temp_file);  // delete file tmp
header("Content-Disposition: attachment; filename= factura.docx");
header('Content-Type: application/docx');
echo $documento;
*/
?>
