<?php
    header('Access-Control-Allow-Origin: *'); 
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

    date_default_timezone_set("America/Bogota");
    
    $json = json_decode($_POST['data'],true);

    $resolucion = $json['J_RESOLUCI'];

    $fresi = explode('/',$json['J_FECVIINI']);
    $fechainicioresolucion = $fresi[2].'-'.$fresi[1].'-'.$fresi[0];

    $fresf = explode('/',$json['J_FECVIFIN']);
    $fechafinresolucion = $fresf[2].'-'.$fresf[1].'-'.$fresf[0];
    
    $tipoinvoice = $json['invoicetype'];
    $idsoftware = $json['IDSOFTWARE'];
    $prefijo = $json['prefijo'];
    $folioinicial = $json['J_FOLINI'];
    $foliofinal = $json['J_FOLFIN'];
    $idfactura = $json['prefijo'].$json['folio'];
    $fechafac = $json['fecha'];
    $nota = str_replace("&", "&amp;", $json['observacion']);

    $hoy = getdate();
    $horafac = str_pad($hoy['hours'],2,'0',STR_PAD_LEFT).':'.str_pad($hoy['minutes'],2,'0',STR_PAD_LEFT).':'.str_pad($hoy['seconds'],2,'0',STR_PAD_LEFT).'-05:00';

    $vencimientofac = $json['vencimiento'];
    $fechahoy = $hoy['year'].'-'.str_pad($hoy['mon'],2,'0',STR_PAD_LEFT).'-'.str_pad($hoy['mday'],2,'0',STR_PAD_LEFT);
    $moneda = $json['moneda'];
    $trm = $json['trm'];
    $totalitems = $json['NumeroItems'];

    if ($trm > 0) {
        $totalparcialUsd = number_format($json['neto'],2,'.','');
        $descgeneralUsd =  number_format($json['descuentogral'],2,'.','');
        $anticipoUsd = number_format($json['anticipo'],2,'.','');
        $recargoUsd = number_format($json['recargo'],2,'.','');
        $totalbaseUsd = number_format($json['baseiva'],2,'.','');
        $totalivasUsd = number_format(str_replace(',','',number_format((floatval($json['iva19']) + floatval($json['iva16']) + floatval($json['iva5'])),2)),2,'.','');
        $totalimpcsUsd = number_format(str_replace(',','',number_format((floatval($json['valimpo2']) + floatval($json['valimpo4']) + floatval($json['valimpo8']) + floatval($json['baseimpo16'])),2)),2,'.','');
        $totalimpuestosUsd = number_format($totalivasUsd + $totalimpcsUsd,2,'.','');
        $totalfacturaUsd = number_format($json['total'],2,'.','');
    }

    $diasmesactual = date( 't', strtotime($fechahoy));
    $fechadeinicio = $hoy['year'].'-'.str_pad($hoy['mon'],2,'0',STR_PAD_LEFT).'-01';
    $fechafinal = $hoy['year'].'-'.str_pad($hoy['mon'],2,'0',STR_PAD_LEFT).'-'.$diasmesactual;

    $actividad = $json['ACTIVIDAD'];
    $razon = str_replace("&", "&amp;", $json['RAZON']);
    $codmuniemp = $json['CODMUNIEMP'];
    $municiemp = $json['MUNICIEMP'];
    $departaemp = $json['DEPARTAEMP'];
    $coddepartaemp = substr($json['CODMUNIEMP'],0,2);
    $diremp = $json['DIREMP'];
    $nitsdemp = $json['NITSDEMP'];
    $dvemp = $json['DVEMP'];
    $tipdocemp = $json['TIPDOCEMP'];
    $resfiscalemp = $json['E_OFICINA'];
    $telemp = $json['TELEMP'];
    $emailemp = $json['EMAILEMP'];

    //datos de factura
    $cliente = str_replace("&", "&amp;", $json['cliente']);
    $codmuni = $json['codmuni'];
    $munici = $json['municipio'];
    $departa = $json['departamento'];
    $coddeparta = substr($json['codmuni'],0,2);
    $dir = $json['dir'];
    $codpais = $json['codpais'];
    $pais = $json['pais'];
    
    $nitsd = $json['nit'];
    $dv = 0;
    if($json['tipocli'] == "13" or $json['tipocli'] == "31") {
        $arrnit = explode('-',$json['nit']);
        if(count($arrnit)==1){
            $nitsd = $arrnit[0];
            $dv = 0;
        } else {
            $nitsd = $arrnit[0];
            $dv = $arrnit[1];
        }
    }
    $tipodoc = $json['tipocli'];
    $resfiscal = $json['resfiscal'];
    $tel = $json['tel'];
    $correo = $json['correo1'];
    $taxschemecliente = $json['TAXSCHEMECLIENTE'];

    $idtaxschemecli = "01";
    $nametaxschemecli = "IVA";
    if ($taxschemecliente == 1) {
        $idtaxschemecli = "ZZ";
        $nametaxschemecli = "No aplica";
    }

    $formapago = $json['fpago'];
    $codpago = $json['CCODPAGO'];
    $mediopago = $json['CMEDIOPAGO'];

    $trm2 = ($trm == 0) ? 1: $trm;

    $totaliva5 =  number_format($json['iva5'] * $trm2,2,'.','');
    $totalbase5 =  number_format($json['baseiva5'] * $trm2,2,'.','');
    $totaliva16 =  number_format($json['iva16'] * $trm2,2,'.','');
    $totalbase16 =  number_format($json['baseiva16'] * $trm2,2,'.','');
    $totaliva19 =  number_format($json['iva19'] * $trm2,2,'.','');
    $totalbase19 =  number_format($json['baseiva19'] * $trm2,2,'.','');

    $totalimpo2 =  number_format($json['valimpo2'] * $trm2,2,'.','');
    $totalbaseimpo2 =  number_format($json['baseimpo2'] * $trm2,2,'.','');
    $totalimpo4 =  number_format($json['valimpo4'] * $trm2,2,'.','');
    $totalbaseimpo4 =  number_format($json['baseimpo4'] * $trm2,2,'.','');
    $totalimpo8 =  number_format($json['valimpo8'] * $trm2,2,'.','');
    $totalbaseimpo8 =  number_format($json['baseimpo8'] * $trm2,2,'.','');
    $totalimpo16 =  number_format($json['valimpo16'] * $trm2,2,'.','');
    $totalbaseimpo16 =  number_format($json['baseimpo16'] * $trm2,2,'.','');

    $totazucares =  number_format($json['valazucares'] * $trm2,2,'.','');

    $tasaretefuente = number_format($json['tasaretefuente'] * $trm2,2,'.','');
    $retefuente = number_format($json['retefuente'] * $trm2,2,'.','');
    $tasareteiva = number_format($json['tasareteiva'] * $trm2,2,'.','');
    $reteiva = number_format($json['reteiva'] * $trm2,2,'.','');
    $tasareteica = number_format($json['tasareteica'] * $trm2,2,'.','');
    $reteica = number_format($json['reteica'] * $trm2,2,'.','');
    
    $recargo = number_format($json['recargo'] * $trm2,2,'.','');
    $anticipo = number_format($json['anticipo'] * $trm2,2,'.','');
    $descgeneral = number_format($json['descuentogral'] * $trm2,2,'.','');

    $totalparcial = number_format($json['neto'] * $trm2,2,'.','');
    $totalbase = number_format($json['baseiva'] * $trm2,2,'.','');
    $totalfactura = number_format($json['total'] * $trm2,2,'.','');
    $redondeo = 0;
    $totalfacturaOR = $totalfactura;
    if ($trm == 0) {
        $totalfactura = round($totalfactura);
        $redondeo = floatval($totalfactura) - floatval($totalfacturaOR);
    } else {
        $totaliva5 = number_format($totalbase5 * 5/100,2,'.','');
        $totaliva16 = number_format($totalbase16 * 16/100,2,'.','');
        $totaliva19 = number_format($totalbase19 * 19/100,2,'.','');

        $totalimpo2 = number_format($totalbaseimpo2 * 2/100,2,'.','');
        $totalimpo4 = number_format($totalbaseimpo4 * 4/100,2,'.','');
        $totalimpo8 = number_format($totalbaseimpo8 * 8/100,2,'.','');
        $totalimpo16 = number_format($totalbaseimpo16 * 16/100,2,'.','');
        $totimpuestos = $totaliva5 + $totaliva16 + $totaliva19 + $totalimpo2 + $totalimpo4 + $totalimpo8 + $totalimpo16;
        if ($totimpuestos > 0) {
            $totalfactura = number_format($totalbase5 + $totalbase16 + $totalbase19 + $totalbaseimpo2 + $totalbaseimpo4 + $totalbaseimpo8 + $totalbaseimpo16 + $totimpuestos,2,'.','');
            $totalfacturaOR = $totalfactura;
        }
    }
    $redondeo = number_format(sprintf("%.2f", $redondeo),2,'.','');
    $totalfactura = number_format($totalfactura,2,'.','');

    $ordencompra = $json['ordencompra'];
    $remision = $json['remision'];
    $contrato = $json['codcontrato'];

    $codigo_prestador  = "";
    $cod_mod_pago = "";
    $modalidad_pago = "";
    $cod_plan_beneficios = "";
    $plan_beneficios = "";
    $num_contrato ="";
    $trabajador_cedula = "";
    $trabajador_nombres = "";
    $trabajdor_apellidos = "";

    // if (property_exists($json,'codigop')){
    //     $codigo_prestador = $json['codigop'];
    //     if ($json['modpago'] == "---------") {
    //         $modpago = explode("-",$json['modpago']);
    //         $cod_mod_pago = $modpago[0];
    //         $modalidad_pago = $modpago[1];
    //     }
    //     if ($json['beneficios'] == "---------") {
    //         $beneficios = explode("-",$json['beneficios']);
    //         $cod_plan_beneficios = $beneficios[0];
    //         $plan_beneficios = $beneficios[1];
    //     }
    //     $num_contrato = $json['codigop'];
    //     $trabajador_cedula = $json['docpaciente'];
    //     $trabajador_nombres = $json['nom1']." ".$json['nom2'];
    //     $trabajdor_apellidos = $json['ape1']." ".$json['ape2'];
    // }

    if (array_key_exists('codigop', $json)){
        $codigo_prestador = $json['codigop'];
        if ($json['modpago'] == "---------") {
            $modpago = explode("-",$json['modpago']);
            $cod_mod_pago = $modpago[0];
            $modalidad_pago = $modpago[1];
        }
        if ($json['beneficios'] == "---------") {
            $beneficios = explode("-",$json['beneficios']);
            $cod_plan_beneficios = $beneficios[0];
            $plan_beneficios = $beneficios[1];
        }
        $num_contrato = $json['codigop'];
        $trabajador_cedula = $json['docpaciente'];
        $trabajador_nombres = $json['nom1']." ".$json['nom2'];
        $trabajdor_apellidos = $json['ape1']." ".$json['ape2'];
    }


    if($json['AMBIENTE']==0){
        $ambiente = 2;
    } else {
        $ambiente = 1;
    }

    $cabecera = <<<XML
    <?xml version="1.0" encoding="utf-8" standalone="no"?>
    <Invoice 
        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" 
        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:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2" 
        xmlns:sts="dian:gov:co:facturaelectronica:Structures-2-1" 
        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" 
        xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ext:UBLExtensions>
    XML;
    $cabecera = $cabecera.<<<XML
            <ext:UBLExtension>
                <ext:ExtensionContent>
                    <sts:DianExtensions>
                        <sts:InvoiceControl>
                            <sts:InvoiceAuthorization>$resolucion</sts:InvoiceAuthorization>
                            <sts:AuthorizationPeriod>
                                <cbc:StartDate>$fechainicioresolucion</cbc:StartDate>
                                <cbc:EndDate>$fechafinresolucion</cbc:EndDate>
                            </sts:AuthorizationPeriod>
                            <sts:AuthorizedInvoices>
                                <sts:Prefix>$prefijo</sts:Prefix>
                                <sts:From>$folioinicial</sts:From>
                                <sts:To>$foliofinal</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 schemeName="31" schemeID="1" schemeAgencyName="CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)" schemeAgencyID="195">901034990</sts:ProviderID>
                            <sts:SoftwareID schemeAgencyID="195" schemeAgencyName="CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)">$idsoftware</sts:SoftwareID>
                        </sts:SoftwareProvider>
                        <sts:SoftwareSecurityCode schemeAgencyName="CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)" schemeAgencyID="195"></sts:SoftwareSecurityCode>
                        <sts:AuthorizationProvider>
                            <sts:AuthorizationProviderID schemeID="4" schemeName="31" schemeAgencyID="195" schemeAgencyName="CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)">800197268</sts:AuthorizationProviderID>
                        </sts:AuthorizationProvider>
                        <sts:QRCode></sts:QRCode>
                    </sts:DianExtensions>
                </ext:ExtensionContent>
            </ext:UBLExtension>
            <ext:UBLExtension>
                <ext:ExtensionContent>
                </ext:ExtensionContent>
            </ext:UBLExtension>
    XML;
    if (strlen($codigo_prestador) > 0) {
        $cabecera = $cabecera.<<<XML
            <ext:UBLExtension>
                <ext:ExtensionContent>
                    <CustomTagGeneral>
                        <Name>Responsable</Name>
                        <Value>url www.minsalud.gov.co</Value>
                        <Name>Tipo, identificador:2022</Name>
                        <Value>Resolución 0510:2022</Value>
                        <Interoperabilidad>
                            <Group schemeName="Sector Salud">
                                <Collection schemeName="Usuario">
                                    <AdditionalInformation>
                                        <Name>CODIGO_PRESTADOR</Name>
                                        <Value>$codigo_prestador</Value>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <Name>MODALIDAD_PAGO</Name>
                                        <Value schemeName="salud_modalidad_pago.gc" schemeID="$cod_mod_pago">$modalidad_pago</Value>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <Name>COBERTURA_PLAN_BENEFICIOS</Name>
                                        <Value schemeName="salud_cobertura.gc" schemeID="$cod_plan_beneficios">$plan_beneficios</Value>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <Name>NUMERO_CONTRATO</Name>
                                        <Value>$num_contrato</Value>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <Name>NUMERO_POLIZA</Name>
                                        <Value>$num_poliza</Value>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <Name>Fecha de inicio del periodo de facturacion</Name>
                                        <Value>$fechadeinicio</Value>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <Name>Fecha de finalizacion del periodo de facturacion</Name>
                                        <Value>$fechafinal</Value>
                                    </AdditionalInformation>
                                </Collection>
                            </Group>
                        </Interoperabilidad>
                    </CustomTagGeneral>
                </ext:ExtensionContent>
            </ext:UBLExtension>
        XML;
    }
    if ($trm > 0){
        $cabecera = $cabecera.<<<XML
            <ext:UBLExtension>
                <ext:ExtensionContent>
                    <CustomTagGeneral>
                        <Interoperabilidad>
                            <Group schemeName="Exportación">
                                <Collection schemeName="DATOS ADICIONALES">
                                    <AdditionalInformation>
                                        <name>Responsable/Encargado</name>
                                        <value/>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <name>Lugar de Salida</name>
                                        <value/>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <name>Medio de transporte</name>
                                        <value/>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <name>Tipo de Doc.de transporte</name>
                                        <value/>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <name>N° de Doc. de transporte</name>
                                        <value/>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <name>Transportadora o Tramitadora</name>
                                        <value/>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <name>País de Origen de la M/cia</name>
                                        <value/>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <name>Destino</name>
                                        <value/>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <name>Términos de pago</name>
                                        <value/>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <name>Seguro</name>
                                        <value/>
                                    </AdditionalInformation>
                                    <AdditionalInformation>
                                        <name>Observaciones</name>
                                        <value/>
                                    </AdditionalInformation>
                                </Collection>
                            </Group>
                        </Interoperabilidad>
                        <TotalesCop>
                            <FctConvCop>$trm</FctConvCop>
                            <MonedaCop>$moneda</MonedaCop>
                            <SubTotalCop>$totalparcialUsd</SubTotalCop>
                            <DescuentoDetalleCop>$descgeneralUsd</DescuentoDetalleCop>
                            <RecargoDetalleCop>$recargoUsd</RecargoDetalleCop>
                            <TotalBrutoFacturaCop>$totalbaseUsd</TotalBrutoFacturaCop>
                            <TotIvaCop>$totalivasUsd</TotIvaCop>
                            <TotIncCop>$totalimpcsUsd</TotIncCop>
                            <TotBolCop>0.00</TotBolCop>
                            <ImpOtroCop>0.00</ImpOtroCop>
                            <MntImpCop>$totalimpuestosUsd</MntImpCop>
                            <TotalNetoFacturaCop>$totalfacturaUsd</TotalNetoFacturaCop>
                            <MntDctoCop>$descgeneral</MntDctoCop>
                            <MntRcgoCop>$recargo</MntRcgoCop>
                            <VlrPagarCop>$totalfactura</VlrPagarCop>
                            <ReteFueCop>$retefuente</ReteFueCop>
                            <ReteIvaCop>$reteiva</ReteIvaCop>
                            <ReteIcaCop>$reteica</ReteIcaCop>
                            <TotAnticiposCop>$anticipoUsd</TotAnticiposCop>
                        </TotalesCop>
                    </CustomTagGeneral>
                </ext:ExtensionContent>
            </ext:UBLExtension>
    XML;
    }
    $cabecera = $cabecera.<<<XML
        </ext:UBLExtensions>        
        <cbc:UBLVersionID>UBL 2.1</cbc:UBLVersionID>
    XML;
    
        if($anticipo > 0){
            $cabecera = $cabecera.<<<XML
                <cbc:CustomizationID schemeID="SS-SinAporte" schemeAgencyName="www.minsalud.gov.co 'mantenimiento'" schemeDataURI="TipoOperacionF-2.1_SSalud.gc">SS-CUFE</cbc:CustomizationID>
            XML;
        } else {
            $cabecera = $cabecera.<<<XML
                <cbc:CustomizationID>10</cbc:CustomizationID>
            XML;
        }
        
    $cabecera = $cabecera.<<<XML

        <cbc:ProfileID>DIAN 2.1: Factura Electrónica de Venta</cbc:ProfileID>
        <cbc:ProfileExecutionID>$ambiente</cbc:ProfileExecutionID>
        <cbc:ID>$idfactura</cbc:ID>
        <cbc:UUID schemeName="CUFE-SHA384" schemeID="$ambiente"></cbc:UUID>
        <cbc:IssueDate>$fechafac</cbc:IssueDate>
        <cbc:IssueTime>$horafac</cbc:IssueTime>
        <cbc:DueDate>$vencimientofac</cbc:DueDate>
        <cbc:InvoiceTypeCode>$tipoinvoice</cbc:InvoiceTypeCode>
        <cbc:Note>$nota</cbc:Note>
        <cbc:TaxPointDate>$fechahoy</cbc:TaxPointDate>
        <cbc:DocumentCurrencyCode>COP</cbc:DocumentCurrencyCode>
        <cbc:LineCountNumeric>$totalitems</cbc:LineCountNumeric>
        <cac:InvoicePeriod>
            <cbc:StartDate>$fechadeinicio</cbc:StartDate>
            <cbc:EndDate>$fechafinal</cbc:EndDate>
        </cac:InvoicePeriod>
    XML;

    if(strlen($ordencompra)>0){
        $cabecera = $cabecera.<<<XML
            <cac:OrderReference>
                <cbc:ID>$ordencompra</cbc:ID>
            </cac:OrderReference>
        XML;
    }

    if(strlen($remision)>0){
        $cabecera = $cabecera.<<<XML
            <cac:ReceiptDocumentReference>
                <cbc:ID>$remision</cbc:ID>
            </cac:ReceiptDocumentReference>
        XML;
    }

    if(strlen($contrato)>0){
        $cabecera = $cabecera.<<<XML
            <cac:ContractDocumentReference>
                <cbc:ID>$contrato</cbc:ID>
            </cac:ContractDocumentReference>
        XML;
    }

    $tipoorgemp = 1;
    if ($tipdocemp == "13") {
        $tipoorgemp = 2;
    }

    $tipoorgcli = 1;
    if ($tipodoc == "13") {
        $tipoorgcli = 2;
    }

    $cabecera = $cabecera.<<<XML
        <cac:AccountingSupplierParty>
            <cbc:AdditionalAccountID schemeAgencyID="195">$tipoorgemp</cbc:AdditionalAccountID>
            <cac:Party>
                <cbc:IndustryClassificationCode>$actividad</cbc:IndustryClassificationCode>
                <cac:PartyName>
                    <cbc:Name>$razon</cbc:Name>
                </cac:PartyName>
                <cac:PhysicalLocation>
                    <cac:Address>
                        <cbc:ID>$codmuniemp</cbc:ID>
                        <cbc:CityName>$municiemp</cbc:CityName>
                        <cbc:CountrySubentity>$departaemp</cbc:CountrySubentity>
                        <cbc:CountrySubentityCode>$coddepartaemp</cbc:CountrySubentityCode>
                        <cac:AddressLine>
                            <cbc:Line>$diremp</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>$razon</cbc:RegistrationName>
                    <cbc:CompanyID schemeAgencyID="195" schemeAgencyName="CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)" schemeID="$dvemp" schemeName="$tipdocemp">$nitsdemp</cbc:CompanyID>
                    <cbc:TaxLevelCode listName="05">$resfiscalemp</cbc:TaxLevelCode>
                    <cac:RegistrationAddress>
                        <cbc:ID>$codmuniemp</cbc:ID>
                        <cbc:CityName>$municiemp</cbc:CityName>
                        <cbc:CountrySubentity>$departaemp</cbc:CountrySubentity>
                        <cbc:CountrySubentityCode>$coddepartaemp</cbc:CountrySubentityCode>
                        <cac:AddressLine>
                            <cbc:Line>$diremp</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>01</cbc:ID>
                        <cbc:Name>IVA</cbc:Name>
                    </cac:TaxScheme>
                </cac:PartyTaxScheme>
                <cac:PartyLegalEntity>
                    <cbc:RegistrationName>$razon</cbc:RegistrationName>
                    <cbc:CompanyID schemeAgencyID="195" schemeAgencyName="CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)" schemeID="$dvemp" schemeName="31">$nitsdemp</cbc:CompanyID>
                    <cac:CorporateRegistrationScheme>
                        <cbc:ID>$prefijo</cbc:ID>
                        <cbc:Name>$razon</cbc:Name>
                    </cac:CorporateRegistrationScheme>
                </cac:PartyLegalEntity>
                <cac:Contact>
                    <cbc:Name>$razon</cbc:Name>
                    <cbc:Telephone>$telemp</cbc:Telephone>
                    <cbc:ElectronicMail>$emailemp</cbc:ElectronicMail>
                </cac:Contact>
            </cac:Party>
        </cac:AccountingSupplierParty>
        <cac:AccountingCustomerParty>
            <cbc:AdditionalAccountID>$tipoorgcli</cbc:AdditionalAccountID>
            <cac:Party>
                <cac:PartyIdentification>
                    <cbc:ID schemeID="$dv" schemeName="$tipodoc">$nitsd</cbc:ID>
                </cac:PartyIdentification>
                <cac:PartyName>
                    <cbc:Name>$cliente</cbc:Name>
                </cac:PartyName>
                <cac:PhysicalLocation>
                    <cac:Address>
                        <cbc:ID>$codmuni</cbc:ID>
                        <cbc:CityName>$munici</cbc:CityName>
                        <cbc:CountrySubentity>$departa</cbc:CountrySubentity>
                        <cbc:CountrySubentityCode>$coddeparta</cbc:CountrySubentityCode>
                        <cac:AddressLine>
                            <cbc:Line>$dir</cbc:Line>
                        </cac:AddressLine>
                        <cac:Country>
                            <cbc:IdentificationCode>$codpais</cbc:IdentificationCode>
                            <cbc:Name languageID="es">$pais</cbc:Name>
                        </cac:Country>
                    </cac:Address>
                </cac:PhysicalLocation>
                <cac:PartyTaxScheme>
                    <cbc:RegistrationName>$cliente</cbc:RegistrationName>
                    <cbc:CompanyID schemeAgencyID="195" schemeAgencyName="CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)" schemeID="$dv" schemeName="$tipodoc">$nitsd</cbc:CompanyID>
                    <cbc:TaxLevelCode listName="48">$resfiscal</cbc:TaxLevelCode>
                    <cac:RegistrationAddress>
                        <cbc:ID>$codmuni</cbc:ID>
                        <cbc:CityName>$munici</cbc:CityName>
                        <cbc:CountrySubentity>$departa</cbc:CountrySubentity>
                        <cbc:CountrySubentityCode>$coddeparta</cbc:CountrySubentityCode>
                        <cac:AddressLine>
                            <cbc:Line>$dir</cbc:Line>
                        </cac:AddressLine>
                        <cac:Country>
                            <cbc:IdentificationCode>$codpais</cbc:IdentificationCode>
                            <cbc:Name languageID="es">$pais</cbc:Name>
                        </cac:Country>
                    </cac:RegistrationAddress>
                    <cac:TaxScheme>
                        <cbc:ID>$idtaxschemecli</cbc:ID>
                        <cbc:Name>$nametaxschemecli</cbc:Name>
                    </cac:TaxScheme>
                </cac:PartyTaxScheme>
                <cac:PartyLegalEntity>
                    <cbc:RegistrationName>$cliente</cbc:RegistrationName>
                    <cbc:CompanyID schemeAgencyID="195" schemeAgencyName="CO, DIAN (Dirección de Impuestos y Aduanas Nacionales)" schemeID="$dv" schemeName="$tipodoc">$nitsd</cbc:CompanyID>
                    <cac:CorporateRegistrationScheme>
                        <cbc:Name>$cliente</cbc:Name>
                    </cac:CorporateRegistrationScheme>
                </cac:PartyLegalEntity>
                <cac:Contact>
                    <cbc:Name>$cliente</cbc:Name>
                    <cbc:Telephone>$tel</cbc:Telephone>
                    <cbc:ElectronicMail>$correo</cbc:ElectronicMail>
                </cac:Contact>
    XML;
                if (strlen($trabajador_cedula) > 0){
                $cabecera = $cabecera.<<<XML

                <cac:Person>
                    <cbc:FirstName>$trabajador_nombres</cbc:FirstName>
                    <cbc:FamilyName>$trabajdor_apellidos</cbc:FamilyName>
                </cac:Person>
                XML;
                }
    $cabecera = $cabecera.<<<XML
            </cac:Party>
        </cac:AccountingCustomerParty>
        <cac:PaymentMeans>
            <cbc:ID>$codpago</cbc:ID>
            <cbc:PaymentMeansCode>$mediopago</cbc:PaymentMeansCode>
            <cbc:PaymentDueDate>$fechahoy</cbc:PaymentDueDate>
            <cbc:PaymentID>$formapago</cbc:PaymentID>
        </cac:PaymentMeans>
    XML;

    if($anticipo > 0){
        $cabecera = $cabecera.<<<XML
            <cac:PrepaidPayment>
                <cbc:ID>1</cbc:ID>
                <cbc:PaidAmount currencyID="COP">$anticipo</cbc:PaidAmount>
                <cbc:ReceivedDate>$fechahoy</cbc:ReceivedDate>
                <cbc:InstructionID>Cuota Moderadora o Copago</cbc:InstructionID>
            </cac:PrepaidPayment>
        XML;
    }

    $tasarecargo = number_format(floatval((floatval($recargo) / floatval($totalparcial)) * 100), 2);
    $idallowance = 1;
    if ($recargo > 0 and $descgeneral > 0) {
        $idallowance = 2;
    } 
    if($recargo > 0){
        $cabecera = $cabecera.<<<XML

            <cac:AllowanceCharge>
                <cbc:ID>1</cbc:ID>
                <cbc:ChargeIndicator>true</cbc:ChargeIndicator>
                <cbc:AllowanceChargeReason>Recargo</cbc:AllowanceChargeReason>
                <cbc:MultiplierFactorNumeric>$tasarecargo</cbc:MultiplierFactorNumeric>
                <cbc:Amount currencyID="COP">$recargo</cbc:Amount>
                <cbc:BaseAmount currencyID="COP">$totalparcial</cbc:BaseAmount>
            </cac:AllowanceCharge>
        XML;
    }

    $totalbase2 = str_replace(',','',number_format(floatval((floatval($totalfactura) + floatval($descgeneral))), 2));
    $tasadescuentogral = number_format(floatval((floatval($descgeneral) / floatval($totalbase2)) * 100), 2);
    if($descgeneral > 0){
        $cabecera = $cabecera.<<<XML
            <cac:AllowanceCharge>
                <cbc:ID>$idallowance</cbc:ID>
                <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
                <cbc:AllowanceChargeReasonCode>01</cbc:AllowanceChargeReasonCode>
                <cbc:AllowanceChargeReason>Descuento general</cbc:AllowanceChargeReason>
                <cbc:MultiplierFactorNumeric>$tasadescuentogral</cbc:MultiplierFactorNumeric>
                <cbc:Amount currencyID="COP">$descgeneral</cbc:Amount>
                <cbc:BaseAmount currencyID="COP">$totalbase2</cbc:BaseAmount>
            </cac:AllowanceCharge>
        XML;
    }

    if ($trm>0) {
        $cabecera = $cabecera.<<<XML
            <cac:PaymentExchangeRate>
                <cbc:SourceCurrencyCode>COP</cbc:SourceCurrencyCode>
                <cbc:SourceCurrencyBaseRate>$trm</cbc:SourceCurrencyBaseRate>
                <cbc:TargetCurrencyCode>$moneda</cbc:TargetCurrencyCode>
                <cbc:TargetCurrencyBaseRate>1.00</cbc:TargetCurrencyBaseRate>
                <cbc:CalculationRate>$trm</cbc:CalculationRate>
                <cbc:Date>$fechafac</cbc:Date>
            </cac:PaymentExchangeRate>
        XML;
    }    
    
    $totalivas = str_replace(',','',number_format(floatval($totaliva19) + floatval($totaliva16) + floatval($totaliva5),2));
    if($totalivas>0){
        $cabecera = $cabecera.<<<XML

            <cac:TaxTotal>
                <cbc:TaxAmount currencyID="COP">$totalivas</cbc:TaxAmount>
        XML;
        if($totaliva19>0){
            $cabecera = $cabecera.<<<XML

                    <cac:TaxSubtotal>
                        <cbc:TaxableAmount currencyID="COP">$totalbase19</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="COP">$totaliva19</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>
            XML;
        }
        if($totaliva16>0){
            $cabecera = $cabecera.<<<XML

                    <cac:TaxSubtotal>
                        <cbc:TaxableAmount currencyID="COP">$totalbase16</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="COP">$totaliva16</cbc:TaxAmount>
                        <cac:TaxCategory>
                            <cbc:Percent>16.00</cbc:Percent>
                            <cac:TaxScheme>
                                <cbc:ID>01</cbc:ID>
                                <cbc:Name>IVA</cbc:Name>
                            </cac:TaxScheme>
                        </cac:TaxCategory>
                    </cac:TaxSubtotal>
            XML;
        }
        if($totaliva5>0){
            $cabecera = $cabecera.<<<XML

                    <cac:TaxSubtotal>
                        <cbc:TaxableAmount currencyID="COP">$totalbase5</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="COP">$totaliva5</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>
            XML;
        }
        $cabecera = $cabecera.<<<XML

            </cac:TaxTotal>
        XML;
    }

    $totalimpcs = str_replace(',','',number_format(floatval($totalimpo2) + floatval($totalimpo4) + floatval($totalimpo8) + floatval($totalimpo16),2));
    if($totalimpcs>0){
        $cabecera = $cabecera.<<<XML

            <cac:TaxTotal>
                <cbc:TaxAmount currencyID="COP">$totalimpcs</cbc:TaxAmount>
        XML;
        if($totalimpo2>0){
            $cabecera = $cabecera.<<<XML

                    <cac:TaxSubtotal>
                        <cbc:TaxableAmount currencyID="COP">$totalbaseimpo2</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="COP">$totalimpo2</cbc:TaxAmount>
                        <cac:TaxCategory>
                            <cbc:Percent>2.00</cbc:Percent>
                            <cac:TaxScheme>
                                <cbc:ID>04</cbc:ID>
                                <cbc:Name>INC</cbc:Name>
                            </cac:TaxScheme>
                        </cac:TaxCategory>
                    </cac:TaxSubtotal>
            XML;
        }
        if($totalimpo4>0){
            $cabecera = $cabecera.<<<XML

                    <cac:TaxSubtotal>
                        <cbc:TaxableAmount currencyID="COP">$totalbaseimpo4</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="COP">$totalimpo4</cbc:TaxAmount>
                        <cac:TaxCategory>
                            <cbc:Percent>4.00</cbc:Percent>
                            <cac:TaxScheme>
                                <cbc:ID>04</cbc:ID>
                                <cbc:Name>INC</cbc:Name>
                            </cac:TaxScheme>
                        </cac:TaxCategory>
                    </cac:TaxSubtotal>
            XML;
        }
        if($totalimpo8>0){
            $cabecera = $cabecera.<<<XML

                    <cac:TaxSubtotal>
                        <cbc:TaxableAmount currencyID="COP">$totalbaseimpo8</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="COP">$totalimpo8</cbc:TaxAmount>
                        <cac:TaxCategory>
                            <cbc:Percent>8.00</cbc:Percent>
                            <cac:TaxScheme>
                                <cbc:ID>04</cbc:ID>
                                <cbc:Name>INC</cbc:Name>
                            </cac:TaxScheme>
                        </cac:TaxCategory>
                    </cac:TaxSubtotal>
            XML;
        }
        if($totalimpo16>0){
            $cabecera = $cabecera.<<<XML

                    <cac:TaxSubtotal>
                        <cbc:TaxableAmount currencyID="COP">$totalbaseimpo16</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="COP">$totalimpo16</cbc:TaxAmount>
                        <cac:TaxCategory>
                            <cbc:Percent>16.00</cbc:Percent>
                            <cac:TaxScheme>
                                <cbc:ID>04</cbc:ID>
                                <cbc:Name>INC</cbc:Name>
                            </cac:TaxScheme>
                        </cac:TaxCategory>
                    </cac:TaxSubtotal>
            XML;
        }
        $cabecera = $cabecera.<<<XML

            </cac:TaxTotal>
        XML;
    }
    
    if (floatval($totazucares) > 0) {
        $totalazu34 = 0;
        $totalazu35 = 0;
        
        for($i=0;$i<count($json['detalle']);$i++){
            if ($json['detalle'][$i]['codazu'] == "34"){
                $totalazu34 += floatval($json['detalle'][$i]['totvalazu'] * $trm2);
            } 

            if ($json['detalle'][$i]['codazu'] == "35"){
                $totalazu35 += floatval($json['detalle'][$i]['totvalazu'] * $trm2);
            } 
        }

        if ($totalazu34) {
            $cabecera = $cabecera.<<<XML
                <cac:TaxTotal>
                    <cbc:TaxAmount currencyID="COP">$totalazu34</cbc:TaxAmount>
            XML;
            for($i=0;$i<count($json['impuestos']);$i++){
                if ($json['impuestos'][$i]['codazu'] == "34"){
                    $codazu = $json['impuestos'][$i]['codazu'];
                    $totvalazu = $json['impuestos'][$i]['totvalazu'] * $trm2;
                    $totmlt = $json['impuestos'][$i]['totmlt'];
                    $taxazu = $json['impuestos'][$i]['taxazu'];
                    $cabecera = $cabecera.<<<XML
                        <cac:TaxSubtotal>
                            <cbc:TaxAmount currencyID="COP">$totvalazu</cbc:TaxAmount>
                            <cbc:BaseUnitMeasure unitCode="MLT">$totmlt</cbc:BaseUnitMeasure>
                            <cbc:PerUnitAmount currencyID="COP">$taxazu</cbc:PerUnitAmount>
                            <cac:TaxCategory>
                                <cac:TaxScheme>
                                    <cbc:ID>$codazu</cbc:ID>
                                    <cbc:Name>IBUA</cbc:Name>
                                </cac:TaxScheme>
                            </cac:TaxCategory>
                        </cac:TaxSubtotal>
                    XML;
                } 
            }
            $cabecera = $cabecera.<<<XML
                </cac:TaxTotal>
            XML;
        }

        if ($totalazu35) {
            $cabecera = $cabecera.<<<XML
                <cac:TaxTotal>
                    <cbc:TaxAmount currencyID="COP">$totalazu35</cbc:TaxAmount>
            XML;
            for($i=0;$i<count($json['impuestos']);$i++){
                if ($json['impuestos'][$i]['codazu'] == "35"){
                    $codazu = $json['impuestos'][$i]['codazu'];
                    $totvalazu = $json['impuestos'][$i]['totvalazu'] * $trm2;
                    $totmlt = $json['impuestos'][$i]['totmlt'];
                    $totbase = $json['impuestos'][$i]['totbase'] * $trm2;
                    $taxazu = $json['impuestos'][$i]['taxazu'];
                    $cabecera = $cabecera.<<<XML
                        <cac:TaxSubtotal>
                            <cbc:TaxableAmount currencyID="COP">$totbase</cbc:TaxableAmount>
                            <cbc:TaxAmount currencyID="COP">$totvalazu</cbc:TaxAmount>
                            <cac:TaxCategory>
                                <cbc:Percent>$taxazu</cbc:Percent>
                                <cac:TaxScheme>
                                    <cbc:ID>$codazu</cbc:ID>
                                    <cbc:Name>ICUI</cbc:Name>
                                </cac:TaxScheme>
                            </cac:TaxCategory>
                        </cac:TaxSubtotal>
                    XML;
                } 
            }
            $cabecera = $cabecera.<<<XML
                </cac:TaxTotal>
            XML;
        }
    }

    if ($tasaretefuente > 0) {
        $cabecera = $cabecera.<<<XML
        <cac:WithholdingTaxTotal>
            <cbc:TaxAmount currencyID="COP">$retefuente</cbc:TaxAmount>
            <cac:TaxSubtotal>
                <cbc:TaxableAmount currencyID="COP">$totalparcial</cbc:TaxableAmount>
                <cbc:TaxAmount currencyID="COP">$retefuente</cbc:TaxAmount>
                <cac:TaxCategory>
                    <cbc:Percent>$tasaretefuente</cbc:Percent>
                    <cac:TaxScheme>
                        <cbc:ID>06</cbc:ID>
                        <cbc:Name>ReteRenta</cbc:Name>
                    </cac:TaxScheme>
                </cac:TaxCategory>
            </cac:TaxSubtotal>
        </cac:WithholdingTaxTotal>
    XML;
    }

    if ($tasareteiva > 0) {
        $cabecera = $cabecera.<<<XML
        <cac:WithholdingTaxTotal>
            <cbc:TaxAmount currencyID="COP">$reteiva</cbc:TaxAmount>
            <cac:TaxSubtotal>
                <cbc:TaxableAmount currencyID="COP">$totalivas</cbc:TaxableAmount>
                <cbc:TaxAmount currencyID="COP">$reteiva</cbc:TaxAmount>
                <cac:TaxCategory>
                    <cbc:Percent>$tasareteiva</cbc:Percent>
                    <cac:TaxScheme>
                        <cbc:ID>05</cbc:ID>
                        <cbc:Name>ReteIVA</cbc:Name>
                    </cac:TaxScheme>
                </cac:TaxCategory>
            </cac:TaxSubtotal>
        </cac:WithholdingTaxTotal>
    XML;
    }
    
    if ($tasareteica > 0) {
        $cabecera = $cabecera.<<<XML
        <cac:WithholdingTaxTotal>
            <cbc:TaxAmount currencyID="COP">$reteica</cbc:TaxAmount>
            <cac:TaxSubtotal>
                <cbc:TaxableAmount currencyID="COP">$totalparcial</cbc:TaxableAmount>
                <cbc:TaxAmount currencyID="COP">$reteica</cbc:TaxAmount>
                <cac:TaxCategory>
                    <cbc:Percent>$tasareteica</cbc:Percent>
                    <cac:TaxScheme>
                        <cbc:ID>07</cbc:ID>
                        <cbc:Name>ReteICA</cbc:Name>
                    </cac:TaxScheme>
                </cac:TaxCategory>
            </cac:TaxSubtotal>
        </cac:WithholdingTaxTotal>
    XML;
    }

    if ($anticipo > 0) {
        $net = str_replace(',','',number_format(floatval((floatval($totalbase) + floatval($totalivas) + floatval($totazucares))), 2));
        $totalnet = $net > 0 ? $net : $totalfactura;
        $totalfac = str_replace(',','',number_format(floatval((floatval($totalnet) - floatval($anticipo))), 2));
        $cabecera = $cabecera.<<<XML
            <cac:LegalMonetaryTotal>
                <cbc:LineExtensionAmount currencyID="COP">$totalparcial</cbc:LineExtensionAmount>
                <cbc:TaxExclusiveAmount currencyID="COP">$totalbase</cbc:TaxExclusiveAmount>
                <cbc:TaxInclusiveAmount currencyID="COP">$totalnet</cbc:TaxInclusiveAmount>
                <cbc:PrepaidAmount currencyID="COP">$anticipo</cbc:PrepaidAmount>
                <cbc:PayableAmount currencyID="COP">$totalfac</cbc:PayableAmount>
            </cac:LegalMonetaryTotal>
        XML;
    } elseif ($recargo > 0) {
        $totalnet = str_replace(',','',number_format(floatval((floatval($totalbase) + floatval($totalivas) + floatval($totazucares))), 2));
        $cabecera = $cabecera.<<<XML

            <cac:LegalMonetaryTotal>
                <cbc:LineExtensionAmount currencyID="COP">$totalparcial</cbc:LineExtensionAmount>
                <cbc:TaxExclusiveAmount currencyID="COP">$totalbase</cbc:TaxExclusiveAmount>
                <cbc:TaxInclusiveAmount currencyID="COP">$totalnet</cbc:TaxInclusiveAmount>
                <cbc:ChargeTotalAmount currencyID="COP">$recargo</cbc:ChargeTotalAmount>
                <cbc:PayableAmount currencyID="COP">$totalfactura</cbc:PayableAmount>
            </cac:LegalMonetaryTotal>
        XML;
    } elseif ($descgeneral > 0) {
        $totalnet = str_replace(',','',number_format(floatval((floatval($totalbase) + floatval($totalivas) + floatval($totazucares))), 2));
        $totalnet = $totalnet > 0 ? $totalnet : $totalparcial;
        $cabecera = $cabecera.<<<XML
            <cac:LegalMonetaryTotal>
                <cbc:LineExtensionAmount currencyID="COP">$totalparcial</cbc:LineExtensionAmount>
                <cbc:TaxExclusiveAmount currencyID="COP">$totalbase</cbc:TaxExclusiveAmount>
                <cbc:TaxInclusiveAmount currencyID="COP">$totalnet</cbc:TaxInclusiveAmount>
                <cbc:AllowanceTotalAmount currencyID="COP">$descgeneral</cbc:AllowanceTotalAmount>
        XML;
            if ($redondeo != 0) {
                $cabecera = $cabecera.<<<XML
                <cbc:PayableRoundingAmount currencyID="COP">$redondeo</cbc:PayableRoundingAmount>
                XML;
            }
        $cabecera = $cabecera.<<<XML
                <cbc:PayableAmount currencyID="COP">$totalfactura</cbc:PayableAmount>
            </cac:LegalMonetaryTotal>
        XML;
    } else {
        $cabecera = $cabecera.<<<XML

            <cac:LegalMonetaryTotal>
                <cbc:LineExtensionAmount currencyID="COP">$totalparcial</cbc:LineExtensionAmount>
                <cbc:TaxExclusiveAmount currencyID="COP">$totalbase</cbc:TaxExclusiveAmount>
                <cbc:TaxInclusiveAmount currencyID="COP">$totalfacturaOR</cbc:TaxInclusiveAmount>
        XML;
            if ($redondeo != 0) {
                $cabecera = $cabecera.<<<XML
                <cbc:PayableRoundingAmount currencyID="COP">$redondeo</cbc:PayableRoundingAmount>
                XML;
            }
        $cabecera = $cabecera.<<<XML
                <cbc:PayableAmount currencyID="COP">$totalfactura</cbc:PayableAmount>
            </cac:LegalMonetaryTotal>
        XML;
    }

    $detalle = '';
    for($i=0;$i<count($json['detalle']);$i++){
        $regalia = 0;
        $parcial2 = 0;
        if (array_key_exists('regalia', $json['detalle'][$i])){
            $regalia = $json['detalle'][$i]['regalia'];
            $parcial2 = number_format($json['detalle'][$i]['parcial2'] * $trm2,2,'.','');
        }
        if(floatval($json['detalle'][$i]['valor'])>0 or floatval($parcial2)>0){
            $codigo = $json['detalle'][$i]['codprod'];
            $descripcion = str_replace("&", "&amp;", $json['detalle'][$i]['descripcion']);
            $cantidad = $json['detalle'][$i]['cantidad'];
            $precio = number_format($json['detalle'][$i]['valor'] * $trm2,2,'.','');
            $tasadesc = number_format($json['detalle'][$i]['tasadesc'],2,'.','');
            $valdesc = number_format($json['detalle'][$i]['valdesc'] * $trm2,2,'.','');
            $parcial = number_format($json['detalle'][$i]['parcial'] * $trm2,2,'.','');
            $tasadesc2 = number_format($json['detalle'][$i]['tasadesc2'],2,'.','');
            $valdesc2 = number_format($json['detalle'][$i]['valdesc2'] * $trm2,2,'.','');
            $basedesc = number_format($parcial + $valdesc  + $valdesc2,2,'.','');
            $basedesc2 = number_format($parcial + $valdesc2,2,'.','');
            $iva = number_format($json['detalle'][$i]['tasaiva'],2,'.','');
            $valoriva = number_format($json['detalle'][$i]['valiva'] * $trm2,2,'.','');
            $impo = number_format($json['detalle'][$i]['tasaimp'],2,'.','');
            $valorimpo = number_format($json['detalle'][$i]['valimp'] * $trm2,2,'.','');
            $l_codazu = $json['detalle'][$i]['codazu'];
            $l_totvalazu = number_format($json['detalle'][$i]['totvalazu'] * $trm2,2,'.','');
            $l_totmlt = $json['detalle'][$i]['totmlt'];
            $l_taxazu = number_format($json['detalle'][$i]['taxazu'],2,'.','');
            if ($trm>0) {
                $valoriva = number_format($parcial * $iva / 100,2,'.','');
                $valorimpo  = number_format($parcial * $valorimpo / 100,2,'.','');
            }
            
            $idnum = $i + 1;
            $detalle = $detalle.<<<XML
                <cac:InvoiceLine>
                    <cbc:ID>$idnum</cbc:ID>
                    <cbc:Note>$codigo</cbc:Note>
                    <cbc:Note>nota</cbc:Note>
                    <cbc:InvoicedQuantity unitCode="EA">$cantidad</cbc:InvoicedQuantity>
                    <cbc:LineExtensionAmount currencyID="COP">$parcial</cbc:LineExtensionAmount>
            XML;

            if ($regalia>0){
                $parcial = $parcial2;
                $precio2 = number_format($parcial / $cantidad,2,'.','');
                $detalle = $detalle.<<<XML
                    <cbc:FreeOfChargeIndicator>true</cbc:FreeOfChargeIndicator>
                    <cac:PricingReference>
                        <cac:AlternativeConditionPrice>
                            <cbc:PriceAmount currencyID="COP">$precio2</cbc:PriceAmount>
                            <cbc:BaseQuantity unitCode="94">$cantidad</cbc:BaseQuantity>
                            <cbc:PriceTypeCode>03</cbc:PriceTypeCode>
                            <cbc:PriceType>Otro</cbc:PriceType>
                        </cac:AlternativeConditionPrice>
                    </cac:PricingReference>
                XML;
            } else{
                $detalle = $detalle.<<<XML
                    <cbc:FreeOfChargeIndicator>false</cbc:FreeOfChargeIndicator>
                XML;
            }
    
            if($tasadesc>0){
                $detalle = $detalle.<<<XML
                        <cac:AllowanceCharge>
                            <cbc:ID>1</cbc:ID>
                            <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
                            <cbc:AllowanceChargeReason>Descuento</cbc:AllowanceChargeReason>
                            <cbc:MultiplierFactorNumeric>$tasadesc</cbc:MultiplierFactorNumeric>
                            <cbc:Amount currencyID="COP">$valdesc</cbc:Amount>
                            <cbc:BaseAmount currencyID="COP">$basedesc</cbc:BaseAmount>
                        </cac:AllowanceCharge>
                XML;
            }

            if($tasadesc2>0){
                $detalle = $detalle.<<<XML
                        <cac:AllowanceCharge>
                            <cbc:ID>2</cbc:ID>
                            <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
                            <cbc:AllowanceChargeReason>Descuento</cbc:AllowanceChargeReason>
                            <cbc:MultiplierFactorNumeric>$tasadesc2</cbc:MultiplierFactorNumeric>
                            <cbc:Amount currencyID="COP">$valdesc2</cbc:Amount>
                            <cbc:BaseAmount currencyID="COP">$basedesc2</cbc:BaseAmount>
                        </cac:AllowanceCharge>
                XML;
            }

            if (intval(floatval($parcial))==0 and intval(floatval($valoriva+$valorimpo+$l_totvalazu)) > 0 and intval(floatval($tasadesc)) == 100) {
                $parcial = $basedesc;
            }
    
            if($valoriva>0){
                $detalle = $detalle.<<<XML
                        <cac:TaxTotal>
                            <cbc:TaxAmount currencyID="COP">$valoriva</cbc:TaxAmount>
                            <cbc:TaxEvidenceIndicator>false</cbc:TaxEvidenceIndicator>
                            <cac:TaxSubtotal>
                                <cbc:TaxableAmount currencyID="COP">$parcial</cbc:TaxableAmount>
                                <cbc:TaxAmount currencyID="COP">$valoriva</cbc:TaxAmount>
                                <cac:TaxCategory>
                                    <cbc:Percent>$iva</cbc:Percent>
                                    <cac:TaxScheme>
                                        <cbc:ID>01</cbc:ID>
                                        <cbc:Name>IVA</cbc:Name>
                                    </cac:TaxScheme>
                                </cac:TaxCategory>
                            </cac:TaxSubtotal>
                        </cac:TaxTotal>
                XML;
            }

            if($valorimpo>0){
                $detalle = $detalle.<<<XML
    
                        <cac:TaxTotal>
                            <cbc:TaxAmount currencyID="COP">$valorimpo</cbc:TaxAmount>
                            <cbc:TaxEvidenceIndicator>false</cbc:TaxEvidenceIndicator>
                            <cac:TaxSubtotal>
                                <cbc:TaxableAmount currencyID="COP">$parcial</cbc:TaxableAmount>
                                <cbc:TaxAmount currencyID="COP">$valorimpo</cbc:TaxAmount>
                                <cac:TaxCategory>
                                    <cbc:Percent>$impo</cbc:Percent>
                                    <cac:TaxScheme>
                                        <cbc:ID>04</cbc:ID>
                                        <cbc:Name>INC</cbc:Name>
                                    </cac:TaxScheme>
                                </cac:TaxCategory>
                            </cac:TaxSubtotal>
                        </cac:TaxTotal>
                XML;
            }

            if ($l_totvalazu>0) {
                if ($l_codazu == "34") {
                    $detalle = $detalle.<<<XML
                        <cac:TaxTotal>
                            <cbc:TaxAmount currencyID="COP">$l_totvalazu</cbc:TaxAmount>
                                <cac:TaxSubtotal>
                                    <cbc:TaxAmount currencyID="COP">$l_totvalazu</cbc:TaxAmount>
                                    <cbc:BaseUnitMeasure unitCode="MLT">$l_totmlt</cbc:BaseUnitMeasure>
                                    <cbc:PerUnitAmount currencyID="COP">$l_taxazu</cbc:PerUnitAmount>
                                    <cac:TaxCategory>
                                        <cac:TaxScheme>
                                            <cbc:ID>$l_codazu</cbc:ID>
                                            <cbc:Name>IBUA</cbc:Name>
                                        </cac:TaxScheme>
                                    </cac:TaxCategory>
                                </cac:TaxSubtotal>
                        </cac:TaxTotal>
                    XML;
                }

                if ($l_codazu == "35") {
                    $detalle = $detalle.<<<XML
                        <cac:TaxTotal>
                            <cbc:TaxAmount currencyID="COP">$l_totvalazu</cbc:TaxAmount>
                                <cac:TaxSubtotal>
                                    <cbc:TaxableAmount currencyID="COP">$parcial</cbc:TaxableAmount>
                                    <cbc:TaxAmount currencyID="COP">$l_totvalazu</cbc:TaxAmount>
                                    <cac:TaxCategory>
                                        <cbc:Percent>$l_taxazu</cbc:Percent>
                                        <cac:TaxScheme>
                                            <cbc:ID>$l_codazu</cbc:ID>
                                            <cbc:Name>ICUI</cbc:Name>
                                        </cac:TaxScheme>
                                    </cac:TaxCategory>
                                </cac:TaxSubtotal>
                        </cac:TaxTotal>
                    XML;
                }
            }
    
            $detalle = $detalle.<<<XML
                    
                    <cac:Item>
                        <cbc:Description>$descripcion</cbc:Description>
                        <cac:SellersItemIdentification>
                            <cbc:ID>$codigo</cbc:ID>
                        </cac:SellersItemIdentification>
                        <cac:StandardItemIdentification>
                            <cbc:ID schemeID="999" schemeName="Estándar de adopción del contribuyente">$codigo</cbc:ID>
                        </cac:StandardItemIdentification>
                    </cac:Item>
                    <cac:Price>
                        <cbc:PriceAmount currencyID="COP">$precio</cbc:PriceAmount>
                        <cbc:BaseQuantity unitCode="EA">$cantidad</cbc:BaseQuantity>
                    </cac:Price>
                </cac:InvoiceLine>
            XML;
        }
    }

    $finalxml = $cabecera.$detalle;
    $finalxml = $finalxml.<<<XML

    </Invoice>
    XML;

    file_put_contents('D:/ERP/Apache24/DATA/'.substr($json['codigoempresa'],0,5).'/TEMPORALES/'.$json['ARCHIVO'].'.xml',$finalxml);

    echo json_encode('XML Creado');
?>