<?php
/**
 * Products, Quotations & Invoices modules.
 * Extensions to SugarCRM
 * @package Advanced OpenSales for SugarCRM
 * @subpackage Products
 * @copyright SalesAgility Ltd http://www.salesagility.com
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with this program; if not, see http://www.gnu.org/licenses
 * or write to the Free Software Foundation,Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301  USA
 *
 * @author Salesagility Ltd <support@salesagility.com>
 */

	require_once('modules/AOS_PDF_Templates/PDF_Lib/mpdf.php');
	require_once('modules/AOS_PDF_Templates/templateParser.php');
	require_once('modules/AOS_PDF_Templates/sendEmail.php');
	require_once('modules/AOS_PDF_Templates/AOS_PDF_Templates.php');
	global $mod_strings;


	/*
	* 15-Marzo-2014: Inicio
	* @liablegeeks hora y fecha en los archivos
	*/
	date_default_timezone_set('UTC');
	$fecha = date("Y-m-d_H:i:s");
	$file_name = $mod_strings['LBL_PDF_NAME']."_".str_replace(" ","_","massiveOuput").$fecha.".pdf";
	/*
	* 15-Marzo-2014: Fin
	* @liablegeeks hora y fecha en los archivos
	*/	ob_clean();
	try{
		//Crear pdf
		$pdf=new mPDF('en','letter','','DejaVuSans',15,15,16,16,8,8);
		$pdf->setAutoFont();

		//Agregar paginas
		foreach($facturasArray as &$idFactura){

			//Verificar estado si es impresa o pendiente
			/*
			 * Inicio modificaci¨®n
			 * @liablegeks 12 de Febrero
			 * Pasar de estado pendiente a impresa
			 */
			$sql = "SELECT status FROM aos_invoices WHERE id = '".$idFactura."' AND deleted = 0";
			//??porque se borro esta linea??$res = $GLOBALS['db']->query($sql);
			
			$estadoFactura = $GLOBALS['db']->getOne($sql);	
					
			/*
			 * Fin modificaci¨®n
			 * @liablegeks 12 de Febrero
			 * Pasar de estado pendiente a impresa
			 */		
			
			/*
			 * *****************************************************************************************************
			 * /
			 	
			/*
			 * Inicio modificaci¨®n
			 * @liablegeks 12 de Febrero
			 * S¨®lo generar factura si y s¨®lo si es estado impresa o por imprimir o en Cartera
			 */
			 
			if( strtolower($estadoFactura) == 'cartera' || strtolower($estadoFactura) == 'pendiente' || strtolower($estadoFactura) == 'impreso'){
				
				/*
				 * Inicio modificaci¨®n
				 * @liablegeks 12 de Febrero
				 * Pasar de estado pendiente a impreso
				 */
				if( strtolower($estadoFactura) == 'pendiente')
				{
					$sql = "UPDATE aos_invoices SET status = 'Impreso' WHERE id = '".$idFactura."' AND deleted = 0";
					$res = $GLOBALS['db']->query($sql);
				}
				/*
				 * Fin modificaci¨®n
				 * @liablegeks 12 de Febrero
				 * Pasar de estado pendiente a impreso
				 */			
				
				$lineItems = array();
				$sql = "SELECT id, product_id FROM aos_products_quotes WHERE parent_id = '".$idFactura."' AND deleted = 0";
				$res = $GLOBALS['db']->query($sql);
				while($row = $GLOBALS['db']->fetchByAssoc($res)){
					$lineItems[$row['id']] = $row['product_id'];
				}
				
				$serviceLineItems = array();
				$sql = "SELECT id, product_id FROM aos_products_quotes WHERE parent_id = '".$idFactura."' AND deleted = 0";
				$res = $GLOBALS['db']->query($sql);
				while($row = $GLOBALS['db']->fetchByAssoc($res)){
					$serviceLineItems[$row['id']] = $row['product_id'];
				}
				
				//Template
				$sql = "select template_ddown_c from aos_invoices where id='".$idFactura."'";
				$template_ddown_c =  $GLOBALS['db']->getOne($sql);	
				$template_ddown_c = str_replace('^',"",$template_ddown_c);
				
				
				$sql = "select pdffooter from aos_pdf_templates where id='".$template_ddown_c."'";
				$pdffooter = $GLOBALS['db']->getOne($sql);

				$sql = "select pdfheader from aos_pdf_templates where id='".$template_ddown_c."'";
				$pdfheader = $GLOBALS['db']->getOne($sql);	
				

				$sql = "select description from aos_pdf_templates where id='".$template_ddown_c."'";
				$description = $GLOBALS['db']->getOne($sql);	

				//Traer datos
				$sql = "select billing_account_id from aos_invoices where id='".$idFactura."'";
				$billing_account_id =  $GLOBALS['db']->getOne($sql);	
				
				$sql = "select billing_contact_id from aos_invoices where id='".$idFactura."'";
				$billing_contact_id =  $GLOBALS['db']->getOne($sql);		
				
				$sql = "select assigned_user_id from aos_invoices where id='".$idFactura."'";
				$assigned_user_id =  $GLOBALS['db']->getOne($sql);		

				$object_arr = array();
				$object_arr['AOS_Invoices'] = $idFactura;
				
				$object_arr['Accounts'] = $billing_account_id;
				$object_arr['Contacts'] = $billing_contact_id;
				$object_arr['Users'] = $assigned_user_id;

				
				$search = array ('@<script[^>]*?>.*?</script>@si', 		// Strip out javascript
								'@<[\/\!]*?[^<>]*?>@si',		// Strip out HTML tags
								'@([\r\n])[\s]+@',			// Strip out white space
								'@&(quot|#34);@i',			// Replace HTML entities
								'@&(amp|#38);@i',
								'@&(lt|#60);@i',
								'@&(gt|#62);@i',
								'@&(nbsp|#160);@i',
								'@&(iexcl|#161);@i',
								'@&#(\d+);@e',
								'@<address[^>]*?>@si'
				);

				$replace = array ('',
								 '',
								 '\1',
								 '"',
								 '&',
								 '<',
								 '>',
								 ' ',
								 chr(161),
								 'chr(\1)',
								 '<br>'
				);
				
				$header = preg_replace($search, $replace, $pdfheader);
				$footer = preg_replace($search, $replace, $pdffooter);
				$text = preg_replace($search, $replace, $description);
				$text = preg_replace('/\{DATE\s+(.*?)\}/e',"date('\\1')",$text );
				$module_type_low = 'aos_invoices';

				$text = str_replace("\$aos_quotes","\$".$module_type_low,$text);
				$text = str_replace("\$aos_invoices","\$".$module_type_low,$text);
				$text = str_replace("\$total_amt","\$".$module_type_low."_total_amt",$text);
				$text = str_replace("\$discount_amount","\$".$module_type_low."_discount_amount",$text);
				$text = str_replace("\$subtotal_amount","\$".$module_type_low."_subtotal_amount",$text);
				$text = str_replace("\$tax_amount","\$".$module_type_low."_tax_amount",$text);
				$text = str_replace("\$shipping_amount","\$".$module_type_low."_shipping_amount",$text);
				$text = str_replace("\$total_amount","\$".$module_type_low."_total_amount",$text);
				
				
				$codeBar = 0;
				$sql = "select code_bar_c from aos_invoices_cstm where id_c='".$idFactura."'";
				$res = $GLOBALS['db']->query($sql);
				while($row = $GLOBALS['db']->fetchByAssoc($res)){
					$codeBar = $row['code_bar_c'];
				}
				
				//$imagenPng = "<IMG width='120' height='60' SRC=\"custom/include/ImgBarcode/image.php?code=".$codebar."&type=EAN13\"><br/><center>".$codeBar."</center>";
                                $imagenPng= "<img src=\"custom/include/ImgBarcode/generatorEAN13/generador.php?code=".$codeBar."\"   />";


                                //Cambia el barrio con base al contacto - Diego Alcides
                                $sql = "SELECT name FROM  contacts INNER JOIN  contacts_cstm ON contacts_cstm.id_c=contacts.id  INNER JOIN gea_barrios ON  contacts_cstm.barrios_c= gea_barrios.id WHERE  id_c= '".$billing_contact_id."' AND gea_barrios.deleted = 0 AND contacts.deleted = 0";
                                $nameNeighborhood = $GLOBALS['db']->getOne($sql);
                                $text = str_replace("\$contacts_barrios_c",$nameNeighborhood,$text);


				$text = str_replace("\$aos_invoices_code_bar_c",$imagenPng,$text);
				

				$firstValue = '';
				$firstNum = 0;
				
				$lastValue = '';
				$lastNum = 0;
                /*
				 * @liablegeeks: 12 de Feb 2014
				 * Calculo de pagos de acuerdo al pago seleccionado
				 * Caso 1 pago vacio
				 * Caso 2 pago 2
				 * Caso 4 pago 4
				 * Caso 8 pago 8
				 * Inicio de modificacion
				 */

				$sql = "SELECT fechas_sugeridas_c FROM aos_invoices_cstm  join aos_invoices where id_c=id and id_c = '".$idFactura."' AND deleted = 0";
				$fechas_sugeridas = (integer)$GLOBALS['db']->getOne($sql);			
				
				 $sql = "select sum(product_total_price) from aos_products_quotes where parent_id='".$idFactura."' AND deleted = 0";
				$total = (float)$GLOBALS['db']->getOne($sql);
				
				$divisor = 1;
				
				switch ($fechas_sugeridas){
					case 2:
						$divisor = 2;
						$text = str_replace("\$compromisoPago3","",$text);
						$text = str_replace("\$compromisoPago4","",$text);
						$text = str_replace("\$compromisoPago5","",$text);
						$text = str_replace("\$compromisoPago6","",$text);
						$text = str_replace("\$compromisoPago7","",$text);
						$text = str_replace("\$compromisoPago8","",$text);

						$text = str_replace("\$aos_invoices_fecha_sugerida3_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida4_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida5_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida6_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida7_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida8_c","",$text);			

						$total = $total / $divisor;			
						
						$text = str_replace("\$compromisoPago1",$total,$text);
						$text = str_replace("\$compromisoPago2",$total,$text);	
						
						
						break;
					case 3:
						$divisor = 3;
						$text = str_replace("\$compromisoPago4","",$text);
						$text = str_replace("\$compromisoPago5","",$text);
						$text = str_replace("\$compromisoPago6","",$text);
						$text = str_replace("\$compromisoPago7","",$text);
						$text = str_replace("\$compromisoPago8","",$text);

						$text = str_replace("\$aos_invoices_fecha_sugerida4_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida5_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida6_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida7_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida8_c","",$text);			

						$total = $total / $divisor;			
						
						$text = str_replace("\$compromisoPago1",$total,$text);
						$text = str_replace("\$compromisoPago2",$total,$text);	
						$text = str_replace("\$compromisoPago3",$total,$text);	
						
						
						break;
					case 4:
						$divisor = 4;
						$text = str_replace("\$compromisoPago5","",$text);
						$text = str_replace("\$compromisoPago6","",$text);
						$text = str_replace("\$compromisoPago7","",$text);
						$text = str_replace("\$compromisoPago8","",$text);

						$text = str_replace("\$aos_invoices_fecha_sugerida5_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida6_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida7_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida8_c","",$text);	
						
						$total = $total / $divisor;
						
						$text = str_replace("\$compromisoPago1",$total,$text);
						$text = str_replace("\$compromisoPago2",$total,$text);			
						$text = str_replace("\$compromisoPago3",$total,$text);
						$text = str_replace("\$compromisoPago4",$total,$text);
						
						break;
					case 8:
						$divisor = 8;
						
						$total = $total / $divisor;
						
						$text = str_replace("\$compromisoPago1",$total,$text);
						$text = str_replace("\$compromisoPago2",$total,$text);			
						$text = str_replace("\$compromisoPago3",$total,$text);
						$text = str_replace("\$compromisoPago4",$total,$text);
						$text = str_replace("\$compromisoPago5",$total,$text);
						$text = str_replace("\$compromisoPago6",$total,$text);
						$text = str_replace("\$compromisoPago7",$total,$text);
						$text = str_replace("\$compromisoPago8",$total,$text);
						break;
					default:
						//pregunta si es contado o si es contra entrega
						if($fechas_sugeridas==9){
							$text = str_replace("\$compromisoPago1","Contado",$text);
						}elseif($fechas_sugeridas==10){
							$text = str_replace("\$compromisoPago1","C. Entrega",$text);
						}else{
							$text = str_replace("\$compromisoPago1","",$text);
						}
						$text = str_replace("\$compromisoPago2","",$text);			
						$text = str_replace("\$compromisoPago3","",$text);
						$text = str_replace("\$compromisoPago4","",$text);
						$text = str_replace("\$compromisoPago5","",$text);
						$text = str_replace("\$compromisoPago6","",$text);
						$text = str_replace("\$compromisoPago7","",$text);
						$text = str_replace("\$compromisoPago8","",$text);

						$text = str_replace("\$aos_invoices_fecha_sugerida2_c","",$text);			
						$text = str_replace("\$aos_invoices_fecha_sugerida3_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida4_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida5_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida6_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida7_c","",$text);
						$text = str_replace("\$aos_invoices_fecha_sugerida8_c","",$text);	
						break;
				}
				
				
				/*
				 * @liablegeeks: 12 de Feb 2014
				 * Calculo de pagos de acuerdo al pago seleccionado
				 * Caso 1 pago vacio
				 * Caso 2 pago 2
				 * Caso 4 pago 4
				 * Caso 8 pago 8
				 * Fin de modificaci¨®n
				 */					
				//Find first and last valid line values
				$product_quote = new AOS_Products_Quotes();
					foreach($product_quote->field_defs as $name => $arr){
						if(!((isset($arr['dbType']) && strtolower($arr['dbType']) == 'id') || $arr['type'] == 'id' || $arr['type'] == 'link')){
						
							$curNum = strpos($text,'$aos_products_quotes_'.$name);
							if($curNum)
							{
								if($curNum < $firstNum || $firstNum == 0)
								{
									$firstValue = '$aos_products_quotes_'.$name;
									$firstNum = $curNum;
								}
								else if($curNum > $lastNum)
								{
									$lastValue = '$aos_products_quotes_'.$name;
									$lastNum = $curNum;
								}
							}
						}
					}

				$product = new AOS_Products();
					foreach($product->field_defs as $name => $arr){
						if(!((isset($arr['dbType']) && strtolower($arr['dbType']) == 'id') || $arr['type'] == 'id' || $arr['type'] == 'link')){
						
							$curNum = strpos($text,'$aos_products_'.$name);
							if($curNum)
							{
								if($curNum < $firstNum || $firstNum == 0)
								{
									$firstValue = '$aos_products_'.$name;
									$firstNum = $curNum;
								}
								else if($curNum > $lastNum)
								{
									$lastValue = '$aos_products_'.$name;
									$lastNum = $curNum;
								}
							}
						}
					}

				if($firstValue !== '' && $lastvalue !== ''){
					//Converting Text
					$parts = explode($firstValue,$text);
					$text = $parts[0];
					$parts = explode($lastValue,$parts[1]);
					$linePart = $firstValue . $parts[0] . $lastValue;

					if(count($lineItems) != 0){
						//Read line start <tr> value
						$tcount = strrpos($text,"<tr");
						$lsValue = substr($text,$tcount);
						$tcount=strpos($lsValue,">")+1;
						$lsValue = substr($lsValue,0,$tcount);
					
						//Read line end values
						$tcount=strpos($parts[1],"</tr>")+5;
						$leValue = substr($parts[1],0,$tcount);
						
						//Converting Line Items
						$obb = array();
						$sep = '';
						$tdTemp = explode($lsValue,$text);
				
						foreach($lineItems as $idD => $productId){
							$obb['AOS_Products_Quotes'] = $idD;
							$obb['AOS_Products'] = $productId;
							$text .= $sep . templateParser::parse_template($linePart, $obb);
							$sep = $leValue. $lsValue . $tdTemp[count($tdTemp)-1];
						}
					}
					else{
						$tcount = strrpos($text,"<tr");
						$text = substr($text,0,$tcount);
						
						$tcount=strpos($parts[1],"</tr>")+5;
						$parts[1]= substr($parts[1],$tcount);
					}
				
					$text .= $parts[1];
				}
				$firstValue = '';
				$firstNum = 0;
				
				$lastValue = '';
				$lastNum = 0;
				
				$text = str_replace("\$aos_services_quotes_service","\$aos_services_quotes_product",$text);

				/*
				 * @liablegeeks: Begin
				 * Se copia la primera funci¨®n y se hace el reemplazo para que el parser la tome
				 */
				$firstValue = '';
				$firstNum = 0;
				
				$lastValue = '';
				$lastNum = 0;
				
				//Find first and last valid line values
				$product_quote = new AOS_Products_Quotes();
					foreach($product_quote->field_defs as $name => $arr){
						if(!((isset($arr['dbType']) && strtolower($arr['dbType']) == 'id') || $arr['type'] == 'id' || $arr['type'] == 'link')){
						
							$curNum = strpos($text,'$aos_dproducts_quotes_'.$name);
							if($curNum)
							{
								if($curNum < $firstNum || $firstNum == 0)
								{
									$firstValue = '$aos_dproducts_quotes_'.$name;
									$firstNum = $curNum;
								}
								else if($curNum > $lastNum)
								{
									$lastValue = '$aos_dproducts_quotes_'.$name;
									$lastNum = $curNum;
								}
							}
						}
					}

				if($firstValue !== '' && $lastvalue !== ''){
					//Converting Text
					$parts = explode($firstValue,$text);
					$text = $parts[0];
					$parts = explode($lastValue,$parts[1]);
					$linePart = $firstValue . $parts[0] . $lastValue;
					
					$linePart= str_replace("aos_dproducts_quotes_name","aos_products_quotes_name",$linePart);
					$linePart= str_replace("aos_dproducts_quotes_product_list_price","aos_products_quotes_product_list_price",$linePart);
					$linePart= str_replace("aos_dproducts_quotes_product_qty","aos_products_quotes_product_qty",$linePart);
					$linePart= str_replace("aos_dproducts_quotes_product_discount","aos_products_quotes_product_discount",$linePart);
					//@liablegeeks: 15-Marzo-2014 Inicio: Agrego esta linea 
					$linePart= str_replace("aos_dproducts_quotes_product_total_price","aos_products_quotes_product_total_price",$linePart);
					//@liablegeeks: 15-Marzo-2014 Fin: Agrego esta linea 
					$linePart= str_replace("aos_dproducts_quotes_product_unit_price","aos_products_quotes_product_unit_price",$linePart);
					
					/*@liablegeeks debug de variables consultar http://virtualhostlatino.com/gea/datos.txt
								$ar=fopen(getcwd()."/datos.txt","w") or
						die("Problemas en la creacion");
						fputs($ar,$linePart);
						fclose($ar);	
						*/	
					if(count($lineItems) != 0){
						//Read line start <tr> value
						$tcount = strrpos($text,"<tr");
						$lsValue = substr($text,$tcount);
						$tcount=strpos($lsValue,">")+1;
						$lsValue = substr($lsValue,0,$tcount);
					
						//Read line end values
						$tcount=strpos($parts[1],"</tr>")+5;
						$leValue = substr($parts[1],0,$tcount);
						
						//Converting Line Items
						$obb = array();
						$sep = '';
						$tdTemp = explode($lsValue,$text);
						

						
						foreach($lineItems as $id => $productId){
							$obb['AOS_Products_Quotes'] = $id;
							$obb['AOS_Products'] = $productId;
							$text .= $sep . templateParser::parse_template($linePart, $obb);
							$sep = $leValue. $lsValue . $tdTemp[count($tdTemp)-1];
						}
					}
					else{
						$tcount = strrpos($text,"<tr");
						$text = substr($text,0,$tcount);
						
						$tcount=strpos($parts[1],"</tr>")+5;
						$parts[1]= substr($parts[1],$tcount);
					}
				
					$text .= $parts[1];
				}
				$firstValue = '';
				$firstNum = 0;
				
				$lastValue = '';
				$lastNum = 0;
				
				$text = str_replace("\$aos_services_quotes_service","\$aos_services_quotes_product",$text);
					
				/*
				 * @liablegeeks: End
				 */	
				 
				 
				//Find first and last valid line values
				$product_quote = new AOS_Products_Quotes();
					foreach($product_quote->field_defs as $name => $arr){
						if(!((isset($arr['dbType']) && strtolower($arr['dbType']) == 'id') || $arr['type'] == 'id' || $arr['type'] == 'link')){
						
							$curNum = strpos($text,'$aos_services_quotes_'.$name);
							if($curNum)
							{
								if($curNum < $firstNum || $firstNum == 0)
								{
									$firstValue = '$aos_products_quotes_'.$name;
									$firstNum = $curNum;
								}
								else if($curNum > $lastNum)
								{
									$lastValue = '$aos_products_quotes_'.$name;
									$lastNum = $curNum;
								}
							}
						}
					}
				if($firstValue !== '' && $lastvalue !== '')
				{
					$text = str_replace("\$aos_products","\$aos_null",$text);
					$text = str_replace("\$aos_services","\$aos_products",$text);
				
					$parts = explode($firstValue,$text);
					$text = $parts[0];
					$parts = explode($lastValue,$parts[1]);
					$linePart = $firstValue . $parts[0] . $lastValue;

					if(count($serviceLineItems) != 0){
						//Read line start <tr> value
						$tcount = strrpos($text,"<tr");
						$lsValue = substr($text,$tcount);
						$tcount=strpos($lsValue,">")+1;
						$lsValue = substr($lsValue,0,$tcount);
					
						//Read line end values
						$tcount=strpos($parts[1],"</tr>")+5;
						$leValue = substr($parts[1],0,$tcount);
						
						//Converting ServiceLine Items
						$obb = array();
						$sep = '';
						$tdTemp = explode($lsValue,$text);
				
				
						foreach($serviceLineItems as $id => $productId){
							$obb['AOS_Products_Quotes'] = $id;
							$obb['AOS_Products'] = $productId;
							$text .= $sep . templateParser::parse_template($linePart, $obb);
							$sep = $leValue. $lsValue . $tdTemp[count($tdTemp)-1];
						}
					}
					else{
						//Remove Line if no values
						$tcount = strrpos($text,"<tr");
						$text = substr($text,0,$tcount);
						
						$tcount=strpos($parts[1],"</tr>")+5;
						$parts[1]= substr($parts[1],$tcount);
					}
				
					$text .= $parts[1];
				}

			/*
			 * @liablegeeks: Start pdf creation
			 */

			$converted = templateParser::parse_template($text, $object_arr);
			$header = templateParser::parse_template($header, $object_arr);
			$footer = templateParser::parse_template($footer, $object_arr);

			$printable = str_replace("\n","<br />",$converted);
			$pdf->SetHTMLHeader($header);
			$pdf->SetHTMLFooter($footer);
			
			//Agregar p¨¢gina en horizontal
			$pdf->AddPage('L', // L - landscape, P - portrait
				'', '', '', '',
				10, // margin_left
				10, // margin right
				10, // margin top
				10, // margin bottom
				8, // margin header
				2); // margin footer	
			$pdf->writeHTML($converted);	

			}			
			/*
			 * Fin modificaci¨®n
			 * @liablegeks 12 de Febrero
			 * S¨®lo generar factura si y s¨®lo si es estado impresa o por imprimir
			 */		

		}		
		$pdf->Output($file_name, "D");

	}catch(mPDF_exception $e){
		echo $e;
	}


?>
