<?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'];

    $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'];

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

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

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

    $recargo = number_format($json['recargo'],2,'.','');
    $anticipo = number_format($json['anticipo'],2,'.','');

    $totalparcial = number_format($json['neto'],2,'.','');
    $totalbase = number_format($json['baseiva'],2,'.','');
    $totalfactura = number_format($json['total'],2,'.','');
    $redondeo = 0;
    $totalfacturaOR = $totalfactura;
    if ($trm == 0) {
        $totalfactura = round($totalfactura);
        $redondeo = floatval($totalfactura) - floatval($totalfacturaOR);
    }
    $redondeo = number_format(sprintf("%.2f", $redondeo),2,'.','');
    $totalfactura = number_format($totalfactura,2,'.','');

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

    $refetd = $json['refetd'];
    $refedoc = $json['refedoc'];
    $cufefac = $json['cufefac'];
    $codrefe = $json['codrefe'];
    $descodrefe = $json['descodrefe'];
    $fecrefedoc = $json['fecrefedoc'];
    $refid = $refetd . $refedoc;
    $customizationid = 32;

    if (strlen($cufefac) > 0) {
        $customizationid = 30;
    }

    $cabecera = <<<XML
    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <DebitNote 
        xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:DebitNote-2 http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-DebitNote-2.1.xsd" 
        xmlns="urn:oasis:names:specification:ubl:schema:xsd:DebitNote-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>
            <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>
        </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>$customizationid</cbc:CustomizationID>
            XML;
        }
    $cabecera = $cabecera.<<<XML
        <cbc:ProfileID>DIAN 2.1: Nota Débito de Factura Electrónica de Venta</cbc:ProfileID>
        <cbc:ProfileExecutionID>$ambiente</cbc:ProfileExecutionID>
        <cbc:ID>$idfactura</cbc:ID>
        <cbc:UUID schemeName="CUDE-SHA384" schemeID="$ambiente"></cbc:UUID>
        <cbc:IssueDate>$fechafac</cbc:IssueDate>
        <cbc:IssueTime>$horafac</cbc:IssueTime>
        <cbc:Note>$nota</cbc:Note>
        <cbc:DocumentCurrencyCode>$moneda</cbc:DocumentCurrencyCode>
        <cbc:LineCountNumeric>$totalitems</cbc:LineCountNumeric>
    XML;

    if(strlen($cufefac)==0){
        $cabecera = $cabecera.<<<XML
        <cac:InvoicePeriod>
            <cbc:StartDate>$fechadeinicio</cbc:StartDate>
            <cbc:EndDate>$fechafinal</cbc:EndDate>
        </cac:InvoicePeriod>
        XML;
    }

    $cabecera = $cabecera.<<<XML
        <cac:DiscrepancyResponse>
            <cbc:ReferenceID>$refid</cbc:ReferenceID>
            <cbc:ResponseCode>$codrefe</cbc:ResponseCode>
            <cbc:Description>$descodrefe</cbc:Description>
        </cac:DiscrepancyResponse>
    XML;

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

    if(strlen($cufefac)>0){
        $cabecera = $cabecera.<<<XML
            <cac:BillingReference>
                <cac:InvoiceDocumentReference>
                    <cbc:ID>$refid</cbc:ID>
                    <cbc:UUID schemeName="CUFE-SHA384">$cufefac</cbc:UUID>
                    <cbc:IssueDate>$fecrefedoc</cbc:IssueDate>
                </cac:InvoiceDocumentReference>
            </cac:BillingReference>
        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="$tipdocemp">$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>
            </cac:Party>
        </cac:AccountingCustomerParty>
    XML;

    if($anticipo > 0){
        $cabecera = $cabecera.<<<XML
            <cac:PrepaidPayment>
                <cbc:ID>1</cbc:ID>
                <cbc:PaidAmount currencyID="$moneda">$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);
    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;
    }

    $cabecera = $cabecera.<<<XML
        <cac:PaymentMeans>
            <cbc:ID>$codpago</cbc:ID>
            <cbc:PaymentMeansCode>$mediopago</cbc:PaymentMeansCode>
            <cbc:PaymentDueDate>$fechahoy</cbc:PaymentDueDate>
            <cbc:PaymentID>$formapago</cbc:PaymentID>
        </cac:PaymentMeans>
        <cac:PaymentExchangeRate>
            <cbc:SourceCurrencyCode>$moneda</cbc:SourceCurrencyCode>
            <cbc:SourceCurrencyBaseRate>1.00</cbc:SourceCurrencyBaseRate>
            <cbc:TargetCurrencyCode>COP</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="$moneda">$totalivas</cbc:TaxAmount>
        XML;
        if($totaliva19>0){
            $cabecera = $cabecera.<<<XML

                    <cac:TaxSubtotal>
                        <cbc:TaxableAmount currencyID="$moneda">$totalbase19</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="$moneda">$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="$moneda">$totalbase16</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="$moneda">$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="$moneda">$totalbase5</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="$moneda">$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="$moneda">$totalimpcs</cbc:TaxAmount>
        XML;
        if($totalimpo2>0){
            $cabecera = $cabecera.<<<XML

                    <cac:TaxSubtotal>
                        <cbc:TaxableAmount currencyID="$moneda">$totalbaseimpo2</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="$moneda">$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="$moneda">$totalbaseimpo4</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="$moneda">$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="$moneda">$totalbaseimpo8</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="$moneda">$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="$moneda">$totalbaseimpo16</cbc:TaxableAmount>
                        <cbc:TaxAmount currencyID="$moneda">$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']);
            } 

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

        if ($totalazu34) {
            $cabecera = $cabecera.<<<XML
                <cac:TaxTotal>
                    <cbc:TaxAmount currencyID="$moneda">$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'];
                    $totmlt = $json['impuestos'][$i]['totmlt'];
                    $taxazu = $json['impuestos'][$i]['taxazu'];
                    $cabecera = $cabecera.<<<XML
                        <cac:TaxSubtotal>
                            <cbc:TaxAmount currencyID="$moneda">$totvalazu</cbc:TaxAmount>
                            <cbc:BaseUnitMeasure unitCode="MLT">$totmlt</cbc:BaseUnitMeasure>
                            <cbc:PerUnitAmount currencyID="$moneda">$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="$moneda">$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'];
                    $totmlt = $json['impuestos'][$i]['totmlt'];
                    $totbase = $json['impuestos'][$i]['totbase'];
                    $taxazu = $json['impuestos'][$i]['taxazu'];
                    $cabecera = $cabecera.<<<XML
                        <cac:TaxSubtotal>
                            <cbc:TaxableAmount currencyID="$moneda">$totbase</cbc:TaxableAmount>
                            <cbc:TaxAmount currencyID="$moneda">$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 ($anticipo > 0) {
        $net = str_replace(',','',number_format(floatval((floatval($totalbase) + floatval($totalivas) + floatval($totalimpcs) + floatval($totazucares))), 2));
        $totalnet = $net > 0 ? $net : $totalfactura;
        $totalfac = str_replace(',','',number_format(floatval((floatval($totalnet) - floatval($anticipo))), 2));
        $cabecera = $cabecera.<<<XML
            <cac:RequestedMonetaryTotal>
                <cbc:LineExtensionAmount currencyID="$moneda">$totalparcial</cbc:LineExtensionAmount>
                <cbc:TaxExclusiveAmount currencyID="$moneda">$totalbase</cbc:TaxExclusiveAmount>
                <cbc:TaxInclusiveAmount currencyID="$moneda">$totalnet</cbc:TaxInclusiveAmount>
                <cbc:PrepaidAmount currencyID="$moneda">$anticipo</cbc:PrepaidAmount>
                <cbc:PayableAmount currencyID="$moneda">$totalfac</cbc:PayableAmount>
            </cac:RequestedMonetaryTotal>
        XML;
    } elseif ($recargo > 0) {
        $totalnet = str_replace(',','',number_format(floatval((floatval($totalbase) + floatval($totalivas) + floatval($totalimpcs) + floatval($totazucares))), 2));
        $cabecera = $cabecera.<<<XML

            <cac:RequestedMonetaryTotal>
                <cbc:LineExtensionAmount currencyID="$moneda">$totalparcial</cbc:LineExtensionAmount>
                <cbc:TaxExclusiveAmount currencyID="$moneda">$totalbase</cbc:TaxExclusiveAmount>
                <cbc:TaxInclusiveAmount currencyID="$moneda">$totalnet</cbc:TaxInclusiveAmount>
                <cbc:ChargeTotalAmount currencyID="$moneda">$recargo</cbc:ChargeTotalAmount>
                <cbc:PayableAmount currencyID="$moneda">$totalfactura</cbc:PayableAmount>
            </cac:RequestedMonetaryTotal>
        XML;
    } else {
        $cabecera = $cabecera.<<<XML

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

    $detalle = '';
    for($i=0;$i<count($json['detalle']);$i++){
        if(floatval($json['detalle'][$i]['valor'])>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'],2,'.','');
            $tasadesc = number_format($json['detalle'][$i]['tasadesc'],2,'.','');
            $valdesc = number_format($json['detalle'][$i]['valdesc'],2,'.','');
            $parcial = number_format($json['detalle'][$i]['parcial'],2,'.','');
            $basedesc = number_format($parcial + $valdesc,2,'.','');
            $iva = number_format($json['detalle'][$i]['tasaiva'],2,'.','');
            $valoriva = number_format($json['detalle'][$i]['valiva'],2,'.','');
            $impo = number_format($json['detalle'][$i]['tasaimp'],2,'.','');
            $valorimpo = number_format($json['detalle'][$i]['valimp'],2,'.','');
            $l_codazu = $json['detalle'][$i]['codazu'];
            $l_totvalazu = number_format($json['detalle'][$i]['totvalazu'],2,'.','');
            $l_totmlt = $json['detalle'][$i]['totmlt'];
            $l_taxazu = number_format($json['detalle'][$i]['taxazu'],2,'.','');
            $idnum = $i + 1;
            $detalle = $detalle.<<<XML

                <cac:DebitNoteLine>
                    <cbc:ID>$idnum</cbc:ID>
                    <cbc:DebitedQuantity unitCode="EA">$cantidad</cbc:DebitedQuantity>
                    <cbc:LineExtensionAmount currencyID="$moneda">$parcial</cbc:LineExtensionAmount>
            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="$moneda">$valoriva</cbc:TaxAmount>
                            <cbc:TaxEvidenceIndicator>false</cbc:TaxEvidenceIndicator>
                            <cac:TaxSubtotal>
                                <cbc:TaxableAmount currencyID="$moneda">$parcial</cbc:TaxableAmount>
                                <cbc:TaxAmount currencyID="$moneda">$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="$moneda">$valorimpo</cbc:TaxAmount>
                            <cbc:TaxEvidenceIndicator>false</cbc:TaxEvidenceIndicator>
                            <cac:TaxSubtotal>
                                <cbc:TaxableAmount currencyID="$moneda">$parcial</cbc:TaxableAmount>
                                <cbc:TaxAmount currencyID="$moneda">$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="$moneda">$l_totvalazu</cbc:TaxAmount>
                                <cac:TaxSubtotal>
                                    <cbc:TaxAmount currencyID="$moneda">$l_totvalazu</cbc:TaxAmount>
                                    <cbc:BaseUnitMeasure unitCode="MLT">$l_totmlt</cbc:BaseUnitMeasure>
                                    <cbc:PerUnitAmount currencyID="$moneda">$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="$moneda">$l_totvalazu</cbc:TaxAmount>
                                <cac:TaxSubtotal>
                                    <cbc:TaxableAmount currencyID="$moneda">$parcial</cbc:TaxableAmount>
                                    <cbc:TaxAmount currencyID="$moneda">$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;
                }
            }

            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="$moneda">$valdesc</cbc:Amount>
                            <cbc:BaseAmount currencyID="$moneda">$basedesc</cbc:BaseAmount>
                        </cac:AllowanceCharge>
                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="$moneda">$precio</cbc:PriceAmount>
                        <cbc:BaseQuantity unitCode="EA">$cantidad</cbc:BaseQuantity>
                    </cac:Price>
                </cac:DebitNoteLine>
            XML;
        }   
    }

    $finalxml = $cabecera.$detalle;
    $finalxml = $finalxml.<<<XML
    </DebitNote>
    XML;

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

    echo json_encode('XML Creado');
?>