<?php 
@ini_set("display_errors","1");
@ini_set("display_startup_errors","1");

require_once __DIR__ . '/MyCode/docx_merge_1.2.0/autoload.php';
use DocxMerge\DocxMerge;

require_once("include/dbcommon.php");
require_once __DIR__ ."/MyCode/FacturaWord.php"; 

custom_error(2,"Iniciación Print múltiple"); // To debug 

$id_arr = $_SESSION['ID_SELECT'];

custom_error(3,"ID's seleccionados: ".implode(",", $id_arr)); // To debug

$file_arr = array();
 
foreach ($id_arr as &$id) {
    $_SESSION['idfactura'] = $id;
		$temp_file = create_factura();
		$file_arr[] = $temp_file;
} 
custom_error(4,"files creados : ".implode(",", $file_arr)); // To debug

$result_file = tempnam(sys_get_temp_dir(), 'WOR');
unlink($result_file);
$result_file = str_replace('.','_',$result_file).'.docx';

custom_error(5,"files result : ".$result_file); // To debug

$dm = new DocxMerge();
$dm->merge($file_arr,
	  $result_file,
	  true
 );

foreach ($file_arr as &$file_temp) {  // Delete temporal file
    unlink($file_temp);
}

$documento = file_get_contents($result_file);

custom_error(6,"files result : ".$result_file.' Contenido: '.strlen($documento)); // To debug

unlink($result_file);  // delete file tmp

header("Content-Disposition: attachment; filename= factura.docx");
header('Content-Type: application/docx');
echo $documento;

    