<?php
include('firmadorV2.php');
//include 'facturapost.php'; 

if (isset($_REQUEST['proyecto'])){$proyecto=$_REQUEST['proyecto'];}else{$proyecto="";}
if (isset($_REQUEST['codemp'])){$codemp=$_REQUEST['codemp'];}else{$codemp="";}
if (isset($_REQUEST['modulo'])){$modulo=$_REQUEST['modulo'];}else{$modulo="";}
if (isset($_REQUEST['document'])){$document=$_REQUEST['document'];}else{$document="";}
if (isset($_REQUEST['atmosphere'])){$atmosphere=$_REQUEST['atmosphere'];}else{$atmosphere="";}
if (isset($_REQUEST['chkfte'])){$chkfte=$_REQUEST['chkfte'];}else{$chkfte="";}

$GLOBALS['Pdfdet'] = "";
$GLOBALS['factura'] = "";
$GLOBALS['Pdfsup'] = "";
$invoice = array();
index($codemp,$document,$atmosphere);


function index($codemp,$document,$atmosphere){
  //ob_start(); // Iniciar el almacenamiento en búfer de salida

  //echo $codemp;
  //echo '<br>'.$atmosphere.'<br>';
  //return;
	date_default_timezone_set('America/Bogota');//Zona horaria bogota

	$connge = mysqli_connect('69.197.152.107','usufe','Naty@2012*','dnd');
    $connge-> set_charset("utf8");
    if($result = $connge->query("select trim(licemp.nriper) as nitempresa,trim(licemp.nomper) as nomempresa,trim(licemp.dirper) as diremp,trim(licemp.codciu) as cciuemp,trim(actciu.nomciu) as nciuemp,trim(actciu.nomdpt) as ndptemp,trim(actciu.coddpt) as cdptemp,trim(licemp.regiva) as regemp,trim(licemp.resfis) as resfis,trim(licemp.resfis) as respemp,trim(licemp.email) as emlemp,licemp.passcerificado from licemp,actciu where licemp.codciu=actciu.codciu and licemp.conedb='".$codemp."'")) {
		$emp=mysqli_fetch_assoc($result);
    }else{
      echo "error consulta empresa que genera factura";
      return;
    }
	$passcerificado=$emp['passcerificado'];

  $conng = mysqli_connect('66.70.255.14','emempire_docto','eZ676BO}Q}sY','emempire_ahorrocos');
  if($result = $connge->query("select * from documentos where codemp='".$codemp."' and codigo='".$document."'")) {
      if ($result->num_rows > 0) {
          echo "Documento registrado anteriormente";
           $row=mysqli_fetch_assoc($result);
          $sql="update carcmp set estcst ='".$row['statedian']."',cufe='".$row['cufe']."',chkok=1,fchenvio='".$row['insfch']."' where nrocmp='".$document."'";
          if ($conng->query($sql) === TRUE) {
            // echo "Factura registrada";
           } else {
              echo "Error insertando el registro: " . $connge->error;
          }
          $connge->close();
          $conng->close();
          //$qrgenerete='https://catalogo-vpfe.dian.gov.co/Document/searchqr?documentKey='.$row['cufe'];
          $qrgenerete=$row['qr'];
          $data=htmlspecialchars($qrgenerete);
          echo $data.$row["statedian"];
              //set it to writable location, a place for temp generated PNG files
          $PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
          //html PNG location prefix
          $PNG_WEB_DIR = 'temp/';
          include "phpqrcode/qrlib.php";    
    //ofcourse we need rights to create temp dir
          if (!file_exists($PNG_TEMP_DIR))
            mkdir($PNG_TEMP_DIR);
            $filename = $PNG_TEMP_DIR.$document.'.png';
            //processing form input
            //remember to sanitize user input in real-life solution !!!
    $errorCorrectionLevel = 'L';
    if (isset($_REQUEST['level']) && in_array($_REQUEST['level'], array('L','M','Q','H')))
        $errorCorrectionLevel = $_REQUEST['level'];    
    $matrixPointSize = 4;
    if (isset($_REQUEST['size']))
        $matrixPointSize = min(max((int)$_REQUEST['size'], 1), 10);
    if (isset($data)) { 
        //it's very important!
        if (trim($data) == '')
          //  die('data cannot be empty! <a href="?">back</a>');
        // user data
        $filename = $PNG_TEMP_DIR.$document.'.png';
        QRcode::png($data, $filename, $errorCorrectionLevel, $matrixPointSize, 2);    
    } else {    
        //default data
       // echo 'You can provide data in GET parameter: <a href="?data=like_that">like that</a><hr/>';    
        QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2);    
    }
    

          return;
      }
  }else{
      echo "error verificando envio de factura";
      return;
  }
	
	
    $conng-> set_charset("utf8");
    //if($result = $conng->query("select '' as cufe,prefel as code,nrocmp,numfel as invoice_number,round(vlrcmp,2) as TaxableAmount,round(carcmp.vlriva,2) as iva,round(vlrcmp,2) as subtotal,round(vlrcmp,2) as taxable_base,0.00 as other_charges,round(totcmp,2) as total from carcmp where nrocmp='".$document."'")) {
    if($result = $conng->query("select nrocmp,cufe,nriper,nomper,fchcmp,dirter,emlper,prefel,resfel,regper,resfis,tidper,ciuper,sum(CASE WHEN chkexc=0 THEN round(vlrdcm*canart,2) ELSE 0.00 END) as taxable_base,sum(round(vlrdcm*canart,2)) as TaxableAmount,sum(round(vlrdcm*canart,2)) as subtotal, sum(round(vlrdcm*canart*poriva/100,2)) as iva,sum(round((vlrdcm*canart)+(vlrdcm*canart*poriva/100),2)) as total,0.00 as other_charges, sum(CASE WHEN poriva=0 and chkexc=0 THEN round(vlrdcm*canart,2) ELSE 0.00 END)  as baseiva0,sum(CASE WHEN poriva=5 THEN round(vlrdcm*canart,2) ELSE 0.00 END)  as baseiva5, sum(CASE WHEN poriva=19 THEN round(vlrdcm*canart,2) ELSE 0.00 END)  as baseiva19,sum(CASE WHEN poriva=5 THEN round(vlrdcm*canart*poriva/100,2) ELSE 0.00 END)  as iva5, sum(CASE WHEN poriva=19 THEN round(vlrdcm*canart*poriva/100,2) ELSE 0.00 END)  as iva19  from vistacmp where nrocmp='".$document."' group by nrocmp,cufe,nriper,nomper,fchcmp,dirter,emlper,prefel,resfel,regper,resfis,tidper,ciuper")) {
		  $row=mysqli_fetch_assoc($result);
    }else{
      echo "error consulta de factura";
      return;
    }
	$invoice = $row;
	 $invoice["emp"] = $emp;
   $fecha=date('Y-m-d');
   $hora=date('H:i:s');
   $invoice["created_at"]=(string)$fecha;
    $invoice["hora_at"]=(string)$hora;
	//print_r($invoice).'<br>';
	

	$invoicedet = array();
	$query="select round(canart,2) as qty,round(vlrdcm,2) as list_price,round(pordto,2) as discount,round((dtoart)*canart,2) as discount_total,
round((vlrdcm*canart-((dtoart)*canart)),2) as net_price_total,round((vlrdcm*canart-((dtoart)*canart))*poriva/100,2) as iva_total,round(poriva,2) as iva,mid(dspdcm,1,200) as name,artcod as codproducto,chkexc from cardet where nrocmp='".$document."'";
	 if($result = $conng->query($query)) {
		 
		 if ($result->num_rows > 0) {
    		while ($row = $result->fetch_assoc()) {
        		$invoicedet[] = $row;
    		}
		}else{
      echo "Sin Items para enviar FE <br><bR>";
      return;
    }
	 }
	 $invoice["items"] = $invoicedet;
   //echo '<br>Producto:    -------------';
 //print_r($invoicedet);
 //echo '<br>Producto:    -------------';
   //select nrocmp,nriper,nomper,fchcmp,dirter,emlper,prefel,resfel,regper,resfis,tidper,ciuper,sum(round(vlrdcm*canart,2)) as vlrcmp,sum(round(vlrdcm*canart*poriva/100,2)) as iva,sum(round((vlrdcm*canart)+(vlrdcm*canart*poriva/100),2)) as totcmp from vistacmp where nrocmp='DFE11361' group by nrocmp,nriper,nomper,fchcmp,dirter,emlper,prefel,resfel,regper,resfis,tidper,ciuper
	 $query="select trim(carcmp.nriper) as personal_id,carcmp.digper,trim(carcmp.nomper) as name,trim(actciu.codciu) as codcity,trim(actciu.nomciu) as city,trim(actciu.nomdpt) as depto,trim(actciu.coddpt) as coddepto,trim(carcmp.dirter) as address,trim(carcmp.nriper) as nriper,trim(carcmp.emlper) as email,trim(carcmp.tidper) as type_of_id from carcmp,actciu where (carcmp.codciu=actciu.codciu or carcmp.ciuper=actciu.codciu) and carcmp.nrocmp='".$document."'";
	 if($result = $conng->query($query)) {
		 $row=mysqli_fetch_assoc($result);
	 }else{
      echo "error consulta cliente de factura";
      return;
    }
	 //$invoice = array();
   	 $invoice["user"] = $row;
     //echo '<br><br>';
	 //print_r($invoice["user"]);
	 //echo '<br><br>';
	 $query="select carcmp.resfel as invoice_resolution,actres.fchres,actres.venres,actres.preres as code,actres.inires as invoice_code_from,finres as invoice_code_to,keyres as technical_key  from carcmp,actres where carcmp.resfel=actres.nrores and carcmp.nrocmp='".$document."'";
	 if($result = $conng->query($query)) {
		 $row=mysqli_fetch_assoc($result);
	 }else{
      echo "error consulta resolucion";
      return;
    }
//    $conng->close();
	 //$invoice = array();
   	 $invoice["office"] = $row;
	// print_r($invoice["office"]);


  $consecutive =$document;
  $items = $invoice["items"];//$invoice->items;
  $user = $invoice["user"];//$invoice->user;
  $office = $invoice["office"];//$invoice->office;
  $InvoiceAuthorization = $office["invoice_resolution"];//$office->invoice_resolution;
  $StartDate = $office["fchres"];//'2020-01-06';//del invoice office fchres
  $EndDate = $office["venres"];//'2022-01-06';//del invoice office venres
  $Prefix = $office["code"];//$invoice->code;
  $From = $office["invoice_code_from"];//$office->invoice_code_from;
  $To = $office["invoice_code_to"];//$office->invoice_code_to;
  $companyNIT = '900609772';
  $companyNITDV = '8';
  $SoftwareID = '83ca74a5-f174-45dd-99d8-ea9b920f967e';//Software id fijoo por ahora, set de pruebas
  $ClTec = $office["technical_key"];//$office->technical_key;
  $technical_key= $office["technical_key"];
  //echo '<br>keyreso'.$technical_key.'keyreso<br>';
  $pin = '20409';//fijo por ahora, esta informacion sale en la dian en el set de ruebas
  $AuthorizationProviderID = '800197268';//nit de la dian

  $CustomizationID = '10';//tipo de documentos osea factura de venta
  $ProfileExecutionID ='1';// $atmosphere;//Prueba2 Produccion 1
  $ID = $invoice["nrocmp"];//$invoice->invoice_number;//nro de factura con prefijo incluido
  
  $SoftwareSecurityCode = hash('sha384',$SoftwareID.$pin.$ID);
 //date_format(new DateTime($invoice["created_at"]), 'h:s:i')."-05:00";//date_format(new DateTime($invoice["created_at"]), 'Y-m-d');//
  $IssueDate  = $invoice["created_at"];//fecha desde la bd en campo created_at tipo datetime
  $IssueTime = $invoice["hora_at"]."-05:00";//hora desde la bd en campo created_at
  
  $InvoiceTypeCode = "01";
  $fechaActual = new DateTime();
	$primerDia = $invoice["created_at"];//$fechaActual->format('Y-m-01');
	$ultimoDia = $fechaActual->format('Y-m-t');
  $InvoicePeriodStartDate =$primerDia;//$invoice->created_at->startOfMonth()->toDateString(); 
  $InvoicePeriodEndDate = $ultimoDia;// $invoice->created_at->endOfMonth()->toDateString();
  $IndustryClasificationCode = '6701'; //cod actividad economica
  //print_r($invoice);
  $CompanyName = htmlspecialchars($emp["nomempresa"]);//nomemp
  $CompanyAddress = htmlspecialchars($emp["diremp"]);//diremp
  $CompanyCity =  htmlspecialchars($emp["nciuemp"]);//nomciuemp
  $CompanyDepto =  htmlspecialchars($emp["ndptemp"]);//nomdptemp
  $CompanyDeptoCode =  htmlspecialchars($emp["cdptemp"]);//coddptemp
  $companyEmail =  htmlspecialchars($emp["emlemp"]);//emailemp
  $TaxLevelCode =  htmlspecialchars($emp["respemp"]);//responsabilidademp
  $TLClistName =  htmlspecialchars($emp["regemp"]);//regimenivaemp
  $cityCode =  htmlspecialchars($emp["cciuemp"]);//codciuemp
  $TaxSchemeId = 'ZZ';//tipo impuestoemp
  $TaxSchemeName = 'No aplica';//nom impuestoemp

  $CustomerName = htmlspecialchars($user["name"]);
  $CustomerCityCode = htmlspecialchars($user["codcity"]);
  $CustomerCity = htmlspecialchars($user["city"]);
  $CustomerDepto = htmlspecialchars($user["depto"]);
  $CustomerDeptoCode = htmlspecialchars($user["coddepto"]);
  $CustomerAddress = htmlspecialchars($user["address"]);
  $CustomerNit = $user["personal_id"];
  $CustomerEmail = htmlspecialchars($user["email"]);
  $CustomerIdCode = $user["type_of_id"];
  $AdditionalAccountID = '2';

  $CustomerDV =  htmlspecialchars($user["digper"]);
  if ($CustomerIdCode == '31') {
      $CustomerDV = getDV($CustomerNit);
      $AdditionalAccountID = '1';
  };

  $PaymentMeansID = '1';
  $PaymentMeansCode = '10';

	

  $TaxableAmount = $invoice["taxable_base"];
  $TaxAmount = $invoice["iva"];
  if($TaxAmount>0.00){
      $Percent = '19.00';//Poner porcentaje si amerita 
  }else{
      $Percent = '0.00';
  }
  
  $LineExtensionAmount = $invoice["subtotal"];
  $TaxExclusiveAmount = $invoice["taxable_base"];
  $TaxInclusiveAmount = $invoice["total"];
  $ChargeTotalAmount = $invoice["other_charges"];
  $PayableAmount = $invoice["total"];
  $baseiva5= $invoice["baseiva5"];
  $iva5= $invoice["iva5"];
  $baseiva0= $invoice["baseiva0"];
  $baseiva19= $invoice["baseiva19"];
  $iva19= $invoice["iva19"];
  $OtherTaxes = '0.00';
  $LineCountNumeric = count( $invoice["items"]);//$items->count();

  $ClTec = $technical_key;  

  //$UUID = $this->addCufe($invoice,$ClTec);
  $UUID = addCufe($invoice,$ClTec,$atmosphere);
  //$cufe = $ID.$IssueDate.$IssueTime.$LineExtensionAmount.$codImp1.$ValImp1.$codImp2.$ValImp2.$codImp3.$ValImp3.$PayableAmount.$companyNIT.$CustomerNit.$ClTec.$ProfileExecutionID;
  //$UUID = hash('sha384',$cufe);
  $QRCode = "NumFac:$ID FecFac:$IssueDate HorFac:$IssueTime NitFac:$companyNIT DocAdq:$CustomerNit ValFac:$LineExtensionAmount ValIva:$TaxAmount ValOtroIm:$OtherTaxes ValTolFac:$PayableAmount CUFE:$UUID https://catalogo-vpfe.dian.gov.co/Document/searchqr?documentKey=$UUID";
  
  $xmlHead = formHeadXMl();

  $xmlExtensions = formExtensionXMl($InvoiceAuthorization,$StartDate,$EndDate,$Prefix,$From,$To,$companyNIT,$SoftwareID,$AuthorizationProviderID,$QRCode,$companyNITDV,$SoftwareSecurityCode);

  $xmlVersion = formVersionXMl($CustomizationID,$ProfileExecutionID,$ID,$UUID,$IssueDate,$IssueTime,$InvoiceTypeCode,$LineCountNumeric,$InvoicePeriodStartDate,$InvoicePeriodEndDate);

  $xmlCompany = formCompanyXMl($CompanyName,$CompanyCity,$CompanyDepto,$CompanyDeptoCode,$CompanyAddress,$companyNIT,$TaxLevelCode,$cityCode,$TaxSchemeId,$TaxSchemeName,$companyNITDV,$TLClistName,$companyEmail,$Prefix);

  $xmlCustomer = formCustomerXMl($AdditionalAccountID,$CustomerName,$CustomerCityCode,$CustomerCity,$CustomerDepto,$CustomerDeptoCode,$CustomerAddress,$CustomerNit,$CustomerIdCode,$CustomerDV,$CustomerEmail);
//$invoice["taxable_base"]; reemplace //ESTO AQUI PUEDE LLEVAR VARIOS REGISTROS iva del 5 e iva del 19 y base del iva 0%
  $xmlTotal = formTotalsXMl($PaymentMeansID,$PaymentMeansCode,$invoice["taxable_base"],$Percent,$TaxAmount,$LineExtensionAmount,$TaxExclusiveAmount,$TaxInclusiveAmount,$PayableAmount,$ChargeTotalAmount,$IssueDate,$baseiva5,$iva5,$baseiva0,$baseiva19,$iva19);

  $xmlLines = formLinesXMl($items);

  $xml = $xmlHead.$xmlExtensions.$xmlVersion.$xmlCompany.$xmlCustomer.$xmlTotal.$xmlLines;
 // echo '<br>'.htmlentities($xml).'<br>sinfirma';
  //return;

  // locacion del certificado
      $certificadop12 = 'locacion/micertificado.p12';
      // clave certificado
      $clavecertificado = $passcerificado;

    $firmado = new FirmadorV2($certificadop12, $clavecertificado);

      

      // prefijo archivo xml en facturas
      $pf = 'fv';

      // firmar factura
      $signed = $firmado->firmar($xml, $UUID, $pf);

      // nombre de archivos
      $nit = '0'.$companyNIT;
      // 000 si es software propio
      $ppp = '000';
      // año en curso
      $aa = '20';
      $a = str_pad($consecutive, 8, '0', STR_PAD_LEFT);
      // nombre del xml
      $xml_name = $pf.$nit.$ppp.$aa.$a.'.xml';

      // prefijo zip
      $z = 'z';
      // nombre zip
      $fileName = $z.$nit.$ppp.$aa.$a.'.zip';
      // nombre final zip con locacion donde se va a guardar
      $zip_name = 'path/facturas/file/'.$fileName;
      // crear new zip
      $zip = new ZipArchive;
      $zip->open($zip_name, ZipArchive::CREATE);
      // agregar el xml filmado 
      $zip->addFromString($xml_name, $signed);
      $zip->close();

      // get the contents 
      $document = file_get_contents($zip_name);
      // codificar
      $contentFile =  base64_encode($document);
      //return;
      // $contentFile es uno de los parametros que se envia en el body del requesta al web service     
      // hasta aqui la creacion del XML 
      // siguiente paso es generar el envotorio SOAP
      //$to = 'https://vpfe.dian.gov.co/WcfDianCustomerServices.svc';//Para cuando sea produccion
      //$to = "https://vpfe-hab.dian.gov.co/WcfDianCustomerServices.svc";//Para cuando se Habilitacion
      $to = "https://vpfe.dian.gov.co/WcfDianCustomerServices.svc";
      $action = "http://wcf.dian.colombia/IWcfDianCustomerServices/SendBillSync";
      $xmlFile = $contentFile;
      //echo '<br>Nombre  ...'.$fileName.'<br>';
      //echo ' archivo *******************'.$xmlFile.'<br>**********************************';
      $soap = $firmado->signSoap($fileName,$xmlFile,$to,$action);
      //echo $soap;
      $endpoint=$to;
      //return;
      $respuesta= $firmado->sendCurl($endpoint, $action, $soap);
      //echo $respuesta;
      //echo '<br><br>';
      $response = new DOMDocument;
      $response->loadXML($respuesta);
      //print_r($response);//Para ver estructura de respuesta
      // echo '<br><br>';
    //print_r($response->getElementsByTagName('Body')[0]);

      $code = $response->getElementsByTagName('StatusCode');
      $errors = $response->getElementsByTagName('ErrorMessage')[0];
      //echo '<br>status';
      //print_r($code[0]->nodeValue);
      
      //echo .'-----------*****---'.$code[0]->nodeValue.'----*********---------------';
      $NZipKey=$response->getElementsByTagName('XmlBase64Bytes');
      $NomStateDian=$response->getElementsByTagName('StatusDescription');
      $XmlDian=$response->getElementsByTagName('xmlFileName');
      //echo '<br>ZipKey: ';
    //  print_r($NZipKey[0]->nodeValue);
      if ($atmosphere==1) {
        $nMode="Produccion";
      } else {
        $nMode="Habilitacion";
      }
      $serialized_factura = serialize($invoice);
      echo $code[0]->nodeValue;
      //return;
      $sql = "INSERT INTO documentos(codigo,cufe,codemp,chkfte,nombre,email,fecha,insfch,dianstatereason,mode,statedian,archivodian,datos,qr) VALUES ('".$invoice["nrocmp"]."','".$UUID."','".$codemp."',1,'".$invoice["nomper"]."','".$invoice["emlper"]."','".$IssueDate."','".$IssueDate."','".$NomStateDian[0]->nodeValue."','".$nMode."','".$code[0]->nodeValue."','".$NZipKey[0]->nodeValue."','".$serialized_factura."','".$QRCode."')";
    //$sql = "INSERT INTO resolutions(numres,prefijo,codemp) VALUES ('".$NumRes->nodeValue."')";
    if ($connge->query($sql) === TRUE) {
        //echo "Factura registrada doc";
     
        $sql="update carcmp set estcst ='".$code[0]->nodeValue."',cufe='".$UUID."',chkok=1,fchenvio='".$IssueDate."' where nrocmp='".$invoice["nrocmp"]."'";
        if ($conng->query($sql) === TRUE) {
       // echo "Factura registrada"; 
          echo $code[0]->nodeValue;
        } else {
          echo "98";
        }
    } else {
      echo '97';
       // echo "Error insertando el registro: " . $connge->error;
    }
    
    $connge->close();
    $conng->close();
    
    $contenido_decodificado = base64_decode($NZipKey[0]->nodeValue);
    $xml_name='path/facturas/file/'.'Dian'.$xml_name;
    // Guardar el contenido decodificado en un archivo
    file_put_contents($xml_name, $contenido_decodificado);  
    sleep(2);
    generaqr($QRCode);
    sleep(3);
    return ;

   // Crear la URL con los parámetros
  $url = 'imprimir.html?param1=' . urlencode($contenidofac) . '&factura=' . urlencode($invoice["nrocmp"]);

  // Redirigir a la página HTML con los parámetros
  header('Location: ' . $url);
    // echo '<br>'.htmlentities($contenidofac).'<br>sinfirma';
    //imprimir($GLOBALS['Pdfdet'].'</body></html>',$code[0]->nodeValue,$invoice["nrocmp"]);
    
    

}

function obtenerPrimerDiaDelMes() {
    $mes = date('m');
    $año = date('Y');
    return date('Y-m-01', mktime(0, 0, 0, $mes, 1, $año));
}

function obtenerUltimoDiaDelMes() {
    $mes = date('m');
    $año = date('Y');
    $ultimoDia = date('d', mktime(0, 0, 0, $mes + 1, 0, $año));
    return date('Y-m-' . $ultimoDia, mktime(0, 0, 0, $mes, 1, $año));
}

function addCufe($invoice,$ClTec,$atmosphere){
	//$invoice["total"]
  //date_format(new DateTime($invoice["created_at"]), 'Y-m-d');
  //date_format(new DateTime($invoice["created_at"]), 'h:s:i')."-05:00";
  //$ID = $invoice["nrocmp"].$invoice["invoice_number"];//$invoice->code.$invoice->invoice_number;
  $ID = trim($invoice["nrocmp"]);
  $IssueDate  = $invoice["created_at"];
  $IssueTime = $invoice["hora_at"]."-05:00";
  $codImp1 = '01';
  $ValImp1 =  $invoice["iva"];//$invoice->iva;
  $codImp2 = '04';
  $ValImp2 =  '0.00';
  $codImp3 = '03';
  $ValImp3 =  '0.00';
  $LineExtensionAmount = $invoice["subtotal"];//$invoice->subtotal;
  $PayableAmount = $invoice["total"];//$invoice->total;
  $companyNIT =  $invoice["emp"]["nitempresa"];
  $CustomerNit = $invoice["user"]["personal_id"];//$invoice->user->personal_id;
  $ProfileExecutionID = '1';//2 prueba 1 Produccion
  //echo "<br>".$ID.'-'.$IssueDate.'-'.$IssueTime.'-'.$LineExtensionAmount.'-'.$codImp1.'-'.$ValImp1.'-'.$codImp2.'-'.$ValImp2.'-'.$codImp3.'-'.$ValImp3.'-'.$PayableAmount.$companyNIT.'-'.$CustomerNit.'-'.$ClTec.'modo:'.$ProfileExecutionID;
  $cufe = $ID.$IssueDate.$IssueTime.$LineExtensionAmount.$codImp1.$ValImp1.$codImp2.$ValImp2.$codImp3.$ValImp3.$PayableAmount.$companyNIT.$CustomerNit.$ClTec.$ProfileExecutionID;
  //echo '<br>cufe:...'.$cufe.'<br>';
  $cufe = hash('sha384',$cufe);        
  
  if ($cufe != $invoice["cufe"]) {
	  $invoice["cufe"] = $cufe;
	//  $invoice->save();
  
  }
   
  return $cufe;

}

function getDV($nit){
    $b = 11;
    $nit = strrev($nit); 
    $vpri = [3,7,13,17,19,23,29,37,41,43,47,53,59,67,71];
    $z = strlen($nit) ;
    $x = 0 ;
    for ($i=0; $i < $z; $i++) { 
      $y =  substr($nit, $i, 1);
      $n =  $vpri[$i];
      $x += ( $y * $n) ;
    }     
    $r = $x % $b;
    $dv = ( $r > 1 ) ? $b - $r : $r; 
    return $dv;
}

function formLinesXMl($items){
	
  $string = "";
  
  foreach ($items as $key => $value) {

    $LineID = $key+1;
    $LineQty = $value["qty"];//$value->qty;
    $AllowanceChargeID = 1;
    $LineBaseAmount = $value["list_price"];//$value->list_price;
    $AllowancePercentage = $value["discount"];//$value->discount;
    $LineAllowanceAmount = $value["discount_total"];//$value->discount_total;
    $LineTotal = $value["net_price_total"];//$value->net_price_total;
    $LineTax = $value["iva_total"];//$value->iva_total;
    $LineTaxPercentage = $value["iva"];//$value->iva;
    //echo $LineTaxPercentage;
    $LineItemName = htmlspecialchars( $value["name"]);//htmlspecialchars($value->name);
    $LineItemCodigo= htmlspecialchars( $value["codproducto"]);
    $vChkExcluido=$value["chkexc"];
    //if ($LineTax > 0.00) {
      $TaxableAmount = $LineTotal;
    //}else{
    //  $TaxableAmount = 0.00;
    //}
      $GLOBALS['Pdfdet'].='<tr style="font-size:8px">
              <td style="width:20%">'.$LineItemCodigo.'</td>
              <td style="width:35%">'.$LineItemName.'</td>
              <td style="width:10%">'.$LineQty .'</td>
              <td style="width:10%">NIU</td>
              <td style="width:30%">'.$LineTotal.'</td>
            </tr>';

    $string .= 
    "<cac:InvoiceLine> 
      <cbc:ID>$LineID</cbc:ID> 
      <cbc:InvoicedQuantity unitCode='EA'>$LineQty</cbc:InvoicedQuantity> 
      <cbc:LineExtensionAmount currencyID='COP'>$LineTotal</cbc:LineExtensionAmount>"; 
    
    if ($LineTotal == 0) {
      
      $total_list_price = $LineBaseAmount*$LineQty;
      if ($total_list_price == 0) {
        $total_list_price = 1;
      }
      $string .=  
      "<cac:PricingReference>
        <cac:AlternativeConditionPrice>
          <cbc:PriceAmount currencyID='COP'>$total_list_price</cbc:PriceAmount>
          <cbc:PriceTypeCode>01</cbc:PriceTypeCode>
        </cac:AlternativeConditionPrice>
      </cac:PricingReference>";
    }    
    if($AllowancePercentage<=0.00){

    }else{
        $string .=  
          "<cac:AllowanceCharge> 
          <cbc:ID>$AllowanceChargeID</cbc:ID> 
          <cbc:ChargeIndicator>false</cbc:ChargeIndicator> 
          <cbc:MultiplierFactorNumeric>$AllowancePercentage</cbc:MultiplierFactorNumeric> 
          <cbc:Amount currencyID='COP'>$LineAllowanceAmount</cbc:Amount> 
          <cbc:BaseAmount currencyID='COP'>$LineBaseAmount</cbc:BaseAmount> 
        </cac:AllowanceCharge>";
    }
    if($vChkExcluido==1){

    }else{
         $string .=  
            "<cac:TaxTotal> 
                <cbc:TaxAmount currencyID='COP'>$LineTax</cbc:TaxAmount> 
                <cac:TaxSubtotal> 
                  <cbc:TaxableAmount currencyID='COP'>$TaxableAmount</cbc:TaxableAmount> 
                  <cbc:TaxAmount currencyID='COP'>$LineTax</cbc:TaxAmount> 
                  <cac:TaxCategory> 
                    <cbc:Percent>$LineTaxPercentage</cbc:Percent> 
                    <cac:TaxScheme> 
                      <cbc:ID>01</cbc:ID> 
                      <cbc:Name>IVA</cbc:Name> 
                    </cac:TaxScheme> 
                  </cac:TaxCategory> 
                </cac:TaxSubtotal> 
            </cac:TaxTotal>";
    }
    $string .=  
    "<cac:Item> 
          <cbc:Description>$LineItemName</cbc:Description> 
          <cac:StandardItemIdentification>
           <cbc:ID schemeID='001' schemeName='UNSPSC' schemeAgencyID='10'>$LineItemCodigo</cbc:ID>
          </cac:StandardItemIdentification>
        </cac:Item> 
        <cac:Price> 
          <cbc:PriceAmount currencyID='COP'>$LineTotal</cbc:PriceAmount> 
          <cbc:BaseQuantity unitCode='EA'>$LineQty</cbc:BaseQuantity> 
        </cac:Price> 
      </cac:InvoiceLine>";

  
  }

  return $string."</Invoice>";

}

function formTotalsXMl($PaymentMeansID,$PaymentMeansCode,$TaxableAmount,$Percent,$TaxAmount,$LineExtensionAmount,$TaxExclusiveAmount,$TaxInclusiveAmount,$PayableAmount,$ChargeTotalAmount,$IssueDate,$baseiva5,$iva5,$baseiva0,$baseiva19,$iva19){

  // $Percent = ($TaxAmount*100)/$TaxableAmount;
  $string = 
    "<cac:PaymentMeans> 
      <cbc:ID>$PaymentMeansID</cbc:ID> 
        <cbc:PaymentMeansCode>$PaymentMeansCode</cbc:PaymentMeansCode> 
        <cbc:PaymentDueDate>$IssueDate</cbc:PaymentDueDate> 
      </cac:PaymentMeans>"; 
  
  if ($ChargeTotalAmount > 0 ){
   $string .=   
      "<cac:AllowanceCharge>
        <cbc:ID>1</cbc:ID>
        <cbc:ChargeIndicator>true</cbc:ChargeIndicator>  
        <cbc:AllowanceChargeReason>ENVIO - PROCESAMIENTO</cbc:AllowanceChargeReason>  
        <cbc:Amount currencyID='COP'>$ChargeTotalAmount</cbc:Amount> 
      </cac:AllowanceCharge>";
  }
if($baseiva0>0.00 or $baseiva5>0.00 or $baseiva19>0.00){
  $string .=
      "<cac:TaxTotal> 
        <cbc:TaxAmount currencyID='COP'>$TaxAmount</cbc:TaxAmount> ";

if($baseiva0>0.00){
  $string .=
      "<cac:TaxSubtotal> 
          <cbc:TaxableAmount currencyID='COP'>$baseiva0</cbc:TaxableAmount> 
          <cbc:TaxAmount currencyID='COP'>0.00</cbc:TaxAmount> 
          <cac:TaxCategory> 
            <cbc:Percent>0.00</cbc:Percent> 
            <cac:TaxScheme> 
              <cbc:ID>01</cbc:ID> 
              <cbc:Name>IVA</cbc:Name> 
            </cac:TaxScheme> 
          </cac:TaxCategory> 
        </cac:TaxSubtotal> ";
}
if($baseiva5>0.00){
  $string .=
      "<cac:TaxSubtotal> 
          <cbc:TaxableAmount currencyID='COP'>$baseiva5</cbc:TaxableAmount> 
          <cbc:TaxAmount currencyID='COP'>$iva5</cbc:TaxAmount> 
          <cac:TaxCategory> 
            <cbc:Percent>5.00</cbc:Percent> 
            <cac:TaxScheme> 
              <cbc:ID>01</cbc:ID> 
              <cbc:Name>IVA</cbc:Name> 
            </cac:TaxScheme> 
          </cac:TaxCategory> 
        </cac:TaxSubtotal> ";
}
if($baseiva19>0.00){
  $string .=
      "<cac:TaxSubtotal> 
          <cbc:TaxableAmount currencyID='COP'>$baseiva19</cbc:TaxableAmount> 
          <cbc:TaxAmount currencyID='COP'>$iva19</cbc:TaxAmount> 
          <cac:TaxCategory> 
            <cbc:Percent>19.00</cbc:Percent> 
            <cac:TaxScheme> 
              <cbc:ID>01</cbc:ID> 
              <cbc:Name>IVA</cbc:Name> 
            </cac:TaxScheme> 
          </cac:TaxCategory> 
        </cac:TaxSubtotal> ";
}
$string .=
      "</cac:TaxTotal>";
}
$string .=
      "<cac:LegalMonetaryTotal> 
        <cbc:LineExtensionAmount currencyID='COP'>$LineExtensionAmount</cbc:LineExtensionAmount> 
        <cbc:TaxExclusiveAmount currencyID='COP'>$TaxExclusiveAmount</cbc:TaxExclusiveAmount> 
        <cbc:TaxInclusiveAmount currencyID='COP'>$TaxInclusiveAmount</cbc:TaxInclusiveAmount>
        <cbc:AllowanceTotalAmount currencyID='COP'>0.00</cbc:AllowanceTotalAmount> 
        <cbc:ChargeTotalAmount currencyID='COP'>$ChargeTotalAmount</cbc:ChargeTotalAmount>
        <cbc:PrepaidAmount currencyID='COP'>0.00</cbc:PrepaidAmount>
        <cbc:PayableRoundingAmount currencyID='COP'>0.00</cbc:PayableRoundingAmount> 
        <cbc:PayableAmount currencyID='COP'>$PayableAmount</cbc:PayableAmount> 
      </cac:LegalMonetaryTotal>";

  return $string;
}

function formCustomerXMl($AdditionalAccountID,$CustomerName,$CustomerCityCode,$CustomerCity,$CustomerDepto,$CustomerDeptoCode,$CustomerAddress,$CustomerNit,$customerIdCode,$CustomerDV,$CustomerEmail){
    return   
    "<cac:AccountingCustomerParty>
      <cbc:AdditionalAccountID>$AdditionalAccountID</cbc:AdditionalAccountID>
          <cac:Party> 
              <cac:PartyIdentification>
                <cbc:ID schemeID='' schemeName='$customerIdCode' schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)'>$CustomerNit</cbc:ID>
              </cac:PartyIdentification>
              <cac:PartyName> 
                  <cbc:Name>$CustomerName</cbc:Name>
              </cac:PartyName> 
              <cac:PhysicalLocation> 
                  <cac:Address> 
                      <cbc:ID>$CustomerCityCode</cbc:ID> 
                      <cbc:CityName>$CustomerCity</cbc:CityName> 
                      <cbc:CountrySubentity>$CustomerDepto</cbc:CountrySubentity> 
                      <cbc:CountrySubentityCode>$CustomerDeptoCode</cbc:CountrySubentityCode> 
                      <cac:AddressLine> 
                          <cbc:Line>$CustomerAddress</cbc:Line> 
                      </cac:AddressLine> 
                      <cac:Country> 
                          <cbc:IdentificationCode>CO</cbc:IdentificationCode> 
                          <cbc:Name languageID='es'>Colombia</cbc:Name> 
                      </cac:Country> 
                  </cac:Address> 
              </cac:PhysicalLocation> 
              <cac:PartyTaxScheme> 
                  <cbc:RegistrationName>$CustomerName</cbc:RegistrationName> 
                  <cbc:CompanyID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)' schemeName='$customerIdCode' schemeID='$CustomerDV'>$CustomerNit</cbc:CompanyID>
                  <cbc:TaxLevelCode>R-99-PN</cbc:TaxLevelCode> 
                  <cac:RegistrationAddress>
                      <cbc:ID>$CustomerCityCode</cbc:ID>
                      <cbc:CityName>$CustomerCity</cbc:CityName>
                      <cbc:PostalZone>000000</cbc:PostalZone>
                      <cbc:CountrySubentity>$CustomerDepto</cbc:CountrySubentity>
                      <cbc:CountrySubentityCode>$CustomerDeptoCode</cbc:CountrySubentityCode>
                      <cac:AddressLine>
                        <cbc:Line>$CustomerAddress</cbc:Line>
                      </cac:AddressLine>
                      <cac:Country>
                        <cbc:IdentificationCode>CO</cbc:IdentificationCode>
                        <cbc:Name languageID='es'>COLOMBIA</cbc:Name>
                      </cac:Country>
                  </cac:RegistrationAddress>
                  <cac:TaxScheme> 
                      <cbc:ID>ZZ</cbc:ID> 
                      <cbc:Name>No aplica</cbc:Name> 
                  </cac:TaxScheme> 
              </cac:PartyTaxScheme> 
              <cac:PartyLegalEntity> 
                  <cbc:RegistrationName>$CustomerName</cbc:RegistrationName> 
                  <cbc:CompanyID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)' schemeID='$CustomerDV' schemeName='$customerIdCode'>$CustomerNit</cbc:CompanyID>
              </cac:PartyLegalEntity> 
              <cac:Contact>
                  <cbc:ElectronicMail>$CustomerEmail</cbc:ElectronicMail>
              </cac:Contact>
              <cac:Person>
                  <cbc:FirstName>$CustomerName</cbc:FirstName>
                  <cbc:FamilyName></cbc:FamilyName>
              </cac:Person>
          </cac:Party> 
      </cac:AccountingCustomerParty>
      <cac:TaxRepresentativeParty>
          <cac:PartyIdentification>
             <cbc:ID schemeID='' schemeName='13' schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)'>$CustomerNit</cbc:ID>
          </cac:PartyIdentification>
          <cac:PartyName>
             <cbc:Name>$CustomerName</cbc:Name>
          </cac:PartyName>
      </cac:TaxRepresentativeParty>";

}
function formCompanyXMl($CompanyName,$CompanyCity,$CompanyDepto,$CompanyDeptoCode,$CompanyAddress,$companyNIT,$TaxLevelCode,$cityCode,$TaxSchemeId,$TaxSchemeName,$companyNITDV,$TLClistName,$companyEmail,$Prefix){

   $string = 
   "<cac:AccountingSupplierParty> 
      <cbc:AdditionalAccountID schemeAgencyID='195'>1</cbc:AdditionalAccountID> 
      <cac:Party>
          <cbc:IndustryClassificationCode/>
          <cac:PartyIdentification>
              <cbc:ID schemeID='8' schemeName='31' schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)'>$companyNIT</cbc:ID>
          </cac:PartyIdentification> 
          <cac:PartyName> 
              <cbc:Name>$CompanyName</cbc:Name> 
          </cac:PartyName>
          <cac:PhysicalLocation>
              <cac:Address>
                  <cbc:ID>$cityCode</cbc:ID>
                  <cbc:CityName>$CompanyCity</cbc:CityName>
                  <cbc:PostalZone>000000</cbc:PostalZone>
                  <cbc:CountrySubentity>$CompanyDepto</cbc:CountrySubentity>
                  <cbc:CountrySubentityCode>$CompanyDeptoCode</cbc:CountrySubentityCode>
                  <cac:AddressLine>
                      <cbc:Line>$CompanyAddress</cbc:Line>
                  </cac:AddressLine>
                  <cac:Country>
                      <cbc:IdentificationCode>CO</cbc:IdentificationCode>
                      <cbc:Name languageID='es'>Colombia</cbc:Name>
                  </cac:Country>
              </cac:Address>
          </cac:PhysicalLocation> 
          <cac:PartyTaxScheme> 
              <cbc:RegistrationName>$CompanyName</cbc:RegistrationName> 
              <cbc:CompanyID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)' schemeID='$companyNITDV' schemeName='31'>$companyNIT</cbc:CompanyID> 
              <cbc:TaxLevelCode listName='$TLClistName'>$TaxLevelCode</cbc:TaxLevelCode> 
              <cac:RegistrationAddress> 
                  <cbc:ID>$cityCode</cbc:ID> 
                  <cbc:CityName>$CompanyCity</cbc:CityName>
                  <cbc:PostalZone>000000</cbc:PostalZone> 
                  <cbc:CountrySubentity>$CompanyDepto</cbc:CountrySubentity> 
                  <cbc:CountrySubentityCode>$CompanyDeptoCode</cbc:CountrySubentityCode> 
                  <cac:AddressLine> 
                      <cbc:Line>$CompanyAddress</cbc:Line> 
                  </cac:AddressLine> 
                  <cac:Country> 
                      <cbc:IdentificationCode>CO</cbc:IdentificationCode> 
                      <cbc:Name languageID='es'>Colombia</cbc:Name> 
                  </cac:Country> 
              </cac:RegistrationAddress> 
              <cac:TaxScheme> 
                  <cbc:ID>$TaxSchemeId</cbc:ID> 
                  <cbc:Name>$TaxSchemeName</cbc:Name> 
              </cac:TaxScheme> 
          </cac:PartyTaxScheme> 
          <cac:PartyLegalEntity> 
              <cbc:RegistrationName>$CompanyName</cbc:RegistrationName> 
              <cbc:CompanyID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)' schemeID='$companyNITDV' schemeName='31'>$companyNIT</cbc:CompanyID>
              <cac:CorporateRegistrationScheme>
                <cbc:ID>$Prefix</cbc:ID>
              </cac:CorporateRegistrationScheme> 
          </cac:PartyLegalEntity> 
          <cac:Contact>
              <cbc:ElectronicMail>$companyEmail</cbc:ElectronicMail>
          </cac:Contact>
      </cac:Party> 
  </cac:AccountingSupplierParty>";
   return $string;
}

function formVersionXMl($CustomizationID,$ProfileExecutionID,$ID,$UUID,$IssueDate,$IssueTime,$InvoiceTypeCode,$LineCountNumeric,$InvoicePeriodStartDate,$InvoicePeriodEndDate){
  $string = "<cbc:UBLVersionID>UBL 2.1</cbc:UBLVersionID> <cbc:CustomizationID>$CustomizationID</cbc:CustomizationID> <cbc:ProfileID>DIAN 2.1: Factura Electrónica de Venta</cbc:ProfileID> <cbc:ProfileExecutionID>$ProfileExecutionID</cbc:ProfileExecutionID> <cbc:ID>$ID</cbc:ID> <cbc:UUID schemeID='$ProfileExecutionID' schemeName='CUFE-SHA384'>$UUID</cbc:UUID> <cbc:IssueDate>$IssueDate</cbc:IssueDate> <cbc:IssueTime>$IssueTime</cbc:IssueTime> <cbc:DueDate>$IssueDate</cbc:DueDate> <cbc:InvoiceTypeCode>$InvoiceTypeCode</cbc:InvoiceTypeCode> <cbc:Note/> <cbc:TaxPointDate>$IssueDate</cbc:TaxPointDate> <cbc:DocumentCurrencyCode>COP</cbc:DocumentCurrencyCode> <cbc:LineCountNumeric>$LineCountNumeric</cbc:LineCountNumeric> <cac:InvoicePeriod> <cbc:StartDate>$InvoicePeriodStartDate</cbc:StartDate> <cbc:EndDate>$InvoicePeriodEndDate</cbc:EndDate> </cac:InvoicePeriod> <cac:OrderReference> <cbc:ID>$ID</cbc:ID> </cac:OrderReference>";
  return $string;
}

function formExtensionXMl($InvoiceAuthorization,$StartDate,$EndDate,$Prefix,$From,$To,$companyNIT,$SoftwareID,$AuthorizationProviderID,$QRCode,$companyNITDV,$SoftwareSecurityCode){
  return 
  "<ext:UBLExtensions> 
      <ext:UBLExtension> 
          <ext:ExtensionContent> 
              <sts:DianExtensions> 
                  <sts:InvoiceControl> 
                      <sts:InvoiceAuthorization>$InvoiceAuthorization</sts:InvoiceAuthorization> 
                      <sts:AuthorizationPeriod> 
                          <cbc:StartDate>$StartDate</cbc:StartDate> 
                          <cbc:EndDate>$EndDate</cbc:EndDate> 
                      </sts:AuthorizationPeriod> 
                      <sts:AuthorizedInvoices> 
                          <sts:Prefix>$Prefix</sts:Prefix> 
                          <sts:From>$From</sts:From> 
                          <sts:To>$To</sts:To> 
                      </sts:AuthorizedInvoices> 
                  </sts:InvoiceControl> 
                  <sts:InvoiceSource> 
                      <cbc:IdentificationCode listAgencyID='6' listAgencyName='United Nations Economic Commission for Europe' listSchemeURI='urn:oasis:names:specification:ubl:codelist:gc:CountryIdentificationCode-2.1'>CO</cbc:IdentificationCode> 
                  </sts:InvoiceSource> 
                  <sts:SoftwareProvider> 
                      <sts:ProviderID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)' schemeID='$companyNITDV' schemeName='31'>$companyNIT</sts:ProviderID> 
                      <sts:SoftwareID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)'>$SoftwareID</sts:SoftwareID> 
                  </sts:SoftwareProvider> 
                  <sts:SoftwareSecurityCode schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)'>$SoftwareSecurityCode</sts:SoftwareSecurityCode> 
                  <sts:AuthorizationProvider> 
                      <sts:AuthorizationProviderID schemeAgencyID='195' schemeAgencyName='CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)' schemeID='4' schemeName='31'>$AuthorizationProviderID</sts:AuthorizationProviderID> 
                      </sts:AuthorizationProvider> 
                      <sts:QRCode> $QRCode </sts:QRCode> 
              </sts:DianExtensions> 
          </ext:ExtensionContent> 
      </ext:UBLExtension> 
      <ext:UBLExtension> <ext:ExtensionContent></ext:ExtensionContent> </ext:UBLExtension> </ext:UBLExtensions>";
}

function formHeadXMl(){
  $string = "<?xml version='1.0' encoding='UTF-8' standalone='no'?><Invoice xmlns='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2' xmlns:cac='urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2' xmlns:cbc='urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2' xmlns:ds='http://www.w3.org/2000/09/xmldsig#' xmlns:ext='urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2' xmlns:sts='http://www.dian.gov.co/contratos/facturaelectronica/v1/Structures' xmlns:xades='http://uri.etsi.org/01903/v1.3.2#' xmlns:xades141='http://uri.etsi.org/01903/v1.4.1#' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-Invoice-2.1.xsd'>";
  return $string;
} 

function generaqr($qrgenerete){
  return;
    $data=htmlspecialchars($qrgenerete);
    //echo $data;
    //set it to writable location, a place for temp generated PNG files
    $PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
    //html PNG location prefix
    $PNG_WEB_DIR = '../temp/';
    include "../phpqrcode/qrlib.php";    
    //ofcourse we need rights to create temp dir
    if (!file_exists($PNG_TEMP_DIR))
        mkdir($PNG_TEMP_DIR);
         $filename = $PNG_TEMP_DIR.$document.'.png';
            //processing form input
            //remember to sanitize user input in real-life solution !!!
    $errorCorrectionLevel = 'L';
    if (isset($_REQUEST['level']) && in_array($_REQUEST['level'], array('L','M','Q','H')))
        $errorCorrectionLevel = $_REQUEST['level'];    
    $matrixPointSize = 4;
    if (isset($_REQUEST['size']))
        $matrixPointSize = min(max((int)$_REQUEST['size'], 1), 10);
    if (isset($data)) { 
        //it's very important!
        if (trim($data) == '')
          //  die('data cannot be empty! <a href="?">back</a>');
        // user data
        $filename = $PNG_TEMP_DIR.$document.'.png';
        QRcode::png($data, $filename, $errorCorrectionLevel, $matrixPointSize, 2);    
    } else {    
        //default data
       // echo 'You can provide data in GET parameter: <a href="?data=like_that">like that</a><hr/>';    
        QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, $matrixPointSize, 2);    
    }
}
