<?php
 include('firmadorV2.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="";}


index($codemp,$document,$atmosphere);
$invoice = array();

function index($codemp,$document,$atmosphere){
  echo $codemp;
  //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,licemp.digper,licemp.idsw 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'];
	
	$companyNIT = $emp['passcerificado'];
  $companyNITDV = $emp['digper'];
  $SoftwareID = $emp['idsw'];//Software id fijoo por ahora, set de pruebas
  $AuthorizationProviderID = '800197268';//nit de la dian

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

  $firmado = new FirmadorV2($certificadop12, $clavecertificado);
  $to = "https://vpfe.dian.gov.co/WcfDianCustomerServices.svc";
  $action = "http://wcf.dian.colombia/IWcfDianCustomerServices/GetNumberingRange";
  $xmlFile = "";
  $fileName="";
  $soap = $firmado->signSoapNum($fileName,$xmlFile,$to,$action);
  echo $soap;
  $endpoint=$to;
  $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
  $code = $response->getElementsByTagName('StatusCode');
  $errors = $response->getElementsByTagName('ErrorMessage')[0];
  echo '<br><br>';
  print_r($response->getElementsByTagName('Body')[0]);
  //echo .'-----------*****---'.$code[0]->nodeValue.'----*********---------------';

$NumberRangeResponse = $response->getElementsByTagName('NumberRangeResponse');

// Cuenta el número de nodos
$NumberRangeResponseCount = $NumberRangeResponse->length;
echo "Número de nodos que contienen 'TechnicalKey': " . $NumberRangeResponseCount;
$num = 0;
while ($num < $NumberRangeResponseCount) {
    echo "<br>Resolucion N: ";
    $NumRes=$response->getElementsByTagName('ResolutionNumber')->item($num);
    $PreRes=$response->getElementsByTagName('Prefix')->item($num);
    $NumFrom=$response->getElementsByTagName('FromNumber')->item($num);
    $NumTo=$response->getElementsByTagName('ToNumber')->item($num);
    $KeyReso=$response->getElementsByTagName('TechnicalKey')->item($num);
    $FchRes=$response->getElementsByTagName('ValidDateFrom')->item($num);
    $VenRes=$response->getElementsByTagName('ValidDateTo')->item($num);
    echo 'Resolucion N: '.$NumRes->nodeValue.' Prefijo: '.$PreRes->nodeValue.' Desde: '.$NumFrom->nodeValue.' Hasta: '.$NumTo->nodeValue.' Key: '.$KeyReso->nodeValue.'<br>';
    $sql = "INSERT INTO resolutions(numres,prefijo,codemp,inires,finres,fchres,venres,keyres) VALUES ('".$NumRes->nodeValue."','".$PreRes->nodeValue."','".$codemp."','".$NumFrom->nodeValue."','".$NumTo->nodeValue."','".$FchRes->nodeValue."','".$VenRes->nodeValue."','".$KeyReso->nodeValue."')";
    //$sql = "INSERT INTO resolutions(numres,prefijo,codemp) VALUES ('".$NumRes->nodeValue."')";
    if ($connge->query($sql) === TRUE) {
        echo "Nuevo registro creado exitosamente";
    } else {
        echo "Error insertando el registro: " . $connge->error;
    }

    $num += 1;
}
$connge->close();
return;
$technicalKeyNode = $response->getElementsByTagName('TechnicalKey')->item(1);

// Obtén el valor del nodo
$technicalKey = $technicalKeyNode->nodeValue;
echo '<br><br>';
echo $technicalKey;

return;
$xml=$respuesta;
// Define los namespaces para poder acceder a los elementos correctamente
$namespaces = $xml->getNamespaces(true);

// Navega por el XML usando los namespaces
$body = $xml->children($namespaces['s'])->Body;
$response = $body->children($namespaces[''])->GetNumberingRangeResponse;
$result = $response->children($namespaces[''])->GetNumberingRangeResult;
$responseList = $result->children($namespaces['b'])->ResponseList;
$numberRangeResponse = $responseList->children($namespaces['c'])->NumberRangeResponse;

// Obtén el valor de TechnicalKey
$technicalKey = (string) $numberRangeResponse->TechnicalKey;

echo $technicalKey;
         

}

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["code"].$invoice["invoice_number"];//$invoice->code.$invoice->invoice_number;
  $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 = $atmosphere;//2 prueba 1 Produccion
  echo "<br>".$ID.$IssueDate.$IssueTime.'-'.$LineExtensionAmount.$codImp1.'-'.$ValImp1.$codImp2.'-'.$ValImp2.$codImp3.'-'.$ValImp3.'-'.$PayableAmount.$companyNIT.$CustomerNit.$ClTec.$ProfileExecutionID;
  $cufe = $ID.$IssueDate.$IssueTime.$LineExtensionAmount.$codImp1.$ValImp1.$codImp2.$ValImp2.$codImp3.$ValImp3.$PayableAmount.$companyNIT.$CustomerNit.$ClTec.$ProfileExecutionID;
  echo $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);
    if ($LineTax > 0) {
      $TaxableAmount = $LineTotal;
    }else{
      $TaxableAmount = 0;
    }


    $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>";
    }    

    $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>
        <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> 
        <cac:Item> 
          <cbc:Description>$LineItemName</cbc:Description> 
          <cac:StandardItemIdentification>
           <cbc:ID schemeID='001' schemeName='UNSPSC' schemeAgencyID='10'>44120000</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){

  // $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>";
  }

  $string .=
      "<cac:TaxTotal> 
        <cbc:TaxAmount currencyID='COP'>$TaxAmount</cbc:TaxAmount> 
        <cac:TaxSubtotal> 
          <cbc:TaxableAmount currencyID='COP'>$TaxableAmount</cbc:TaxableAmount> 
          <cbc:TaxAmount currencyID='COP'>$TaxAmount</cbc:TaxAmount> 
          <cac:TaxCategory> 
            <cbc:Percent>$Percent</cbc:Percent> 
            <cac:TaxScheme> 
              <cbc:ID>01</cbc:ID> 
              <cbc:Name>IVA</cbc:Name> 
            </cac:TaxScheme> 
          </cac:TaxCategory> 
        </cac:TaxSubtotal> 
      </cac:TaxTotal> 
      <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;
} 