<?php

session_start();

if(!isset($_SESSION['user_login_status']) && $_SESSION['user_login_status'] != 1)
   exit;

include("../../config/db.php");
include("../../config/conexion.php");
include("../../funciones.php");
require_once("../../modelos/factura.php");
require_once("../../modelos/factura_detalle.php");
require_once("../../classes/ZipHelper.php");
require_once(__DIR__.'/../../pdf/html2pdf.class.php');

$facturas = $_POST['facturas'];

//$arr_detalle = [];
$upload_directory = __DIR__.'/../../pdf/documentos/facturas_pdf/';

foreach($facturas as $id)
{
   // Obtener Factura Encabezado
   $factura = new factura();
   $data = $factura->ObtenerFactura($id);
   $data = $data[0];

   // Obtener Factura Detalles
   $facturadetalle = new factura_detalle();
   $datad = $facturadetalle->ObtenerFacturaDetalles($id);
   
   
   // guardando factura actual en pdf
   try{
      ob_start();
      include(__DIR__.'/../../pdf/documentos/res/plantilla_factura_html.php');
      $content = ob_get_contents();

      // init HTML2PDF
      $html2pdf = new HTML2PDF('P', 'LETTER', 'es', true, 'UTF-8', array(0, 0, 0, 0));
      // convert
      $html2pdf->writeHTML($content);
      // send the PDF
      $html2pdf->Output($upload_directory.'B'.($data->numero_factura).'.pdf','F');

         
}catch(HTML2PDF_exception $e){
   echo 'ERRRR :: '.$e->getMessage().''; die();
} 

$content .= ob_get_clean(); // add the content for the next document and now delete the output buffer 

sleep(1);
}


// Zipping Upload Files
$zipper = new ZipHelper();

$dirpath = '../../pdf/documentos/facturas_pdf';

$zippath = 'pdf/documentos/facturas_zip/facturas-'.time().'.zip';

$response = array("zippath" => $zippath, "opcion" => 2);

// Create zip archive
$zip = $zipper->zipDir($dirpath,'../../'.$zippath);

if($zip)
{
   echo json_encode($response);
}
else
{
   echo 0;
}





