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

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

    $formapago = $json['fpago'];

    $totaliva5 = $json['iva5'];
    $totalbase5 = $json['baseiva5'];
    $totaliva16 = $json['iva16'];
    $totalbase16 = $json['baseiva16'];
    $totaliva19 = $json['iva19'];
    $totalbase19 = $json['baseiva19'];

    $totalparcial = $json['neto'];
    $totalbase = $json['baseiva'];
    $totalfactura = number_format($json['total'],2,'.','');

    $ordencompra = $json['ordencompra'];
    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>
            <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>
        <cbc:CustomizationID>10</cbc:CustomizationID> 
        <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></cbc:Note>
        <cbc:TaxPointDate>$fechahoy</cbc:TaxPointDate>
        <cbc:DocumentCurrencyCode>$moneda</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;
    }

    $cabecera = $cabecera.<<<XML
        <cac:AccountingSupplierParty>
            <cbc:AdditionalAccountID schemeAgencyID="195">1</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>$codpais</cbc:IdentificationCode>
                            <cbc:Name languageID="es">$pais</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>$codpais</cbc:IdentificationCode>
                            <cbc:Name languageID="es">$pais</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>1</cbc:AdditionalAccountID>
            <cac:Party>
                <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>CO</cbc:IdentificationCode>
                            <cbc:Name languageID="es">COLOMBIA</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>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>$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>
        <cac:PaymentMeans>
            <cbc:ID>1</cbc:ID>
            <cbc:PaymentMeansCode>1</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;
    }

    $cabecera = $cabecera.<<<XML

        <cac:LegalMonetaryTotal>
            <cbc:LineExtensionAmount currencyID="$moneda">$totalparcial</cbc:LineExtensionAmount>
            <cbc:TaxExclusiveAmount currencyID="$moneda">$totalbase</cbc:TaxExclusiveAmount>
            <cbc:TaxInclusiveAmount currencyID="$moneda">$totalfactura</cbc:TaxInclusiveAmount>
            <cbc:PayableAmount currencyID="$moneda">$totalfactura</cbc:PayableAmount>
        </cac:LegalMonetaryTotal>
    XML;

    $detalle = '';
    for($i=0;$i<count($json['detalle']);$i++){
        if(intval($json['detalle'][$i]['valor'])>0){
            $codigo = $json['detalle'][$i]['codprod'];
            $descripcion = $json['detalle'][$i]['descripcion'];
            $cantidad = $json['detalle'][$i]['cantidad'];
            $precio = $json['detalle'][$i]['valor'];
            $tasadesc = $json['detalle'][$i]['tasadesc'];
            $valdesc = $json['detalle'][$i]['valdesc'];
            $parcial = $json['detalle'][$i]['parcial'];
            $basedesc = $parcial + $valdesc;
            $iva = number_format($json['detalle'][$i]['tasaiva'],2,'.','');
            $valoriva = $json['detalle'][$i]['valiva'];
            $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="$moneda">$parcial</cbc:LineExtensionAmount>
                    <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="$moneda">$valdesc</cbc:Amount>
                            <cbc:BaseAmount currencyID="$moneda">$basedesc</cbc:BaseAmount>
                        </cac:AllowanceCharge>
                XML;
            }
    
            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;
            }
    
            $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: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');
?>