<?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);

    $idfactura = $json['prefijo'].$json['folio'];
    $hoy = getdate();
    $fechahoy = $hoy['year'].'-'.str_pad($hoy['mon'],2,'0',STR_PAD_LEFT).'-'.str_pad($hoy['mday'],2,'0',STR_PAD_LEFT);
    $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';
    $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'];

    $cliente = str_replace("&", "&amp;", $json['cliente']);
    $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'];
    $cufe = $json['CUFE'];

    $xmlfirmado = fopen('D:/ERP/Apache24/DATA/'.substr($json['codigoempresa'],0,5).'/TEMPORALES/face_'.$json['tipodoc'].$json['NITSDEMP'].'_'.strtolower($json['prefijo']).'_'.str_pad($json['folio'],9,'0',STR_PAD_LEFT).'.txt', 'r');
    $stringxmlfirmado = '';
    while(!feof($xmlfirmado)){
        $traer = fgets($xmlfirmado);
        $stringxmlfirmado = $stringxmlfirmado.$traer;
    }

    $respfirmada = fopen('D:/ERP/Apache24/DATA/'.substr($json['codigoempresa'],0,5).'/TEMPORALES/face_'.$json['tipodoc'].$json['NITSDEMP'].'_'.strtolower($json['prefijo']).'_'.str_pad($json['folio'],9,'0',STR_PAD_LEFT).'R.txt', 'r');
    $stringrespfirmada = '';
    while(!feof($respfirmada)){
        $traer = fgets($respfirmada);
        $stringrespfirmada = $stringrespfirmada.$traer;
    }

    $attach = <<<XML
    <?xml version="1.0" encoding="utf-8" standalone="no"?>
    <AttachedDocument xmlns="urn:oasis:names:specification:ubl:schema:xsd:AttachedDocument-2" 
    xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2" 
    xmlns:sts="dian:gov:co:facturaelectronica:Structures-2-1" 
    xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" 
    xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:AttachedDocument-2 http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-AttachedDocument-2.1.xsd">
    <cbc:UBLVersionID>UBL 2.1</cbc:UBLVersionID>
    <cbc:CustomizationID>Documentos adjuntos</cbc:CustomizationID>
    <cbc:ProfileID>DIAN 2.1</cbc:ProfileID>
    <cbc:ProfileExecutionID>2</cbc:ProfileExecutionID>
    <cbc:ID>$idfactura</cbc:ID>
    <cbc:IssueDate>$fechahoy</cbc:IssueDate>
    <cbc:IssueTime>$horafac</cbc:IssueTime>
    <cbc:DocumentType>Contenedor de Factura Electronica</cbc:DocumentType>
    <cbc:ParentDocumentID>$idfactura</cbc:ParentDocumentID>
    <cac:SenderParty>
    <cac:PartyTaxScheme>
    <cbc:RegistrationName>$razon</cbc:RegistrationName>
    <cbc:CompanyID schemeAgencyID="195"  schemeID="$dvemp"  schemeName="$tipdocemp">$nitsdemp</cbc:CompanyID>
    <cbc:TaxLevelCode>$resfiscalemp</cbc:TaxLevelCode>
    <cac:TaxScheme>
    <cbc:ID>01</cbc:ID>
    <cbc:Name>IVA</cbc:Name>
    </cac:TaxScheme>
    </cac:PartyTaxScheme>
    </cac:SenderParty>
    <cac:ReceiverParty>
    <cac:PartyTaxScheme>
    <cbc:RegistrationName>$cliente</cbc:RegistrationName>
    <cbc:CompanyID schemeAgencyID="195"  schemeID="$dv"  schemeName="$tipodoc">$nitsd</cbc:CompanyID>
    <cbc:TaxLevelCode>$resfiscal</cbc:TaxLevelCode>
    <cac:TaxScheme>
    <cbc:ID>01</cbc:ID>
    <cbc:Name>IVA</cbc:Name>
    </cac:TaxScheme>
    </cac:PartyTaxScheme>
    </cac:ReceiverParty>
    <cac:Attachment>
    <cac:ExternalReference>
    <cbc:MimeCode>text/xml</cbc:MimeCode>
    <cbc:EncodingCode>UTF-8</cbc:EncodingCode>
    <cbc:Description><![CDATA[$stringxmlfirmado]]></cbc:Description>
    </cac:ExternalReference>
    </cac:Attachment>
    <cac:ParentDocumentLineReference>
    <cbc:LineID>1</cbc:LineID>
    <cac:DocumentReference>
    <cbc:ID>$idfactura</cbc:ID>
    <cbc:UUID>$cufe</cbc:UUID>
    <cbc:IssueDate>$fechahoy</cbc:IssueDate>
    <cbc:DocumentType>ApplicationResponse</cbc:DocumentType>
    <cac:Attachment>
    <cac:ExternalReference>
    <cbc:MimeCode>text/xml</cbc:MimeCode>
    <cbc:EncodingCode>UTF-8</cbc:EncodingCode>
    <cbc:Description><![CDATA[$stringrespfirmada]]></cbc:Description>
    </cac:ExternalReference>
    </cac:Attachment>
    <cac:ResultOfVerification>
    <cbc:ValidatorID>Unidad Especial Direccion de Impuestos Y Aduanas Nacionales</cbc:ValidatorID>
    <cbc:ValidationResultCode>02</cbc:ValidationResultCode>
    <cbc:ValidationDate>$fechahoy</cbc:ValidationDate>
    <cbc:ValidationTime>$horafac</cbc:ValidationTime>
    </cac:ResultOfVerification>
    </cac:DocumentReference>
    </cac:ParentDocumentLineReference>
    </AttachedDocument>
    XML;

    file_put_contents('D:/ERP/Apache24/DATA/'.substr($json['codigoempresa'],0,5).'/ATT_DOC/face_'.$json['tipodoc'].$json['NITSDEMP'].'_'.strtolower($json['prefijo']).'_'.str_pad($json['folio'],9,'0',STR_PAD_LEFT).'.xml',$attach);

    echo json_encode('ATTCH Creado');
?>