<?php
require_once('../classes/database.class.php');
include("../classes/saftModel.class.php");

date_default_timezone_set("Africa/Luanda");
$dom = new DOMDocument('1.0', 'utf-8');

$dataInicial = $_POST["dataInicial"];
$dataFinal = $_POST["dataFinal"];
$nomeFicheiro = $_POST["nomeFicheiro"];

$modelo = new SaftModel();
$empresa = $modelo->queryEmpresa();
$definicao = $modelo->queryDefinicao();
$entidade = $modelo->queryEntidade($dataInicial, $dataFinal);
$artigo = $modelo->queryArtigo($dataInicial, $dataFinal);
$tipoTaxa = $modelo->queryTipoTaxa();
$contagemDocumento = $modelo->countDocumento($dataInicial, $dataFinal);
$contagemRecibo = $modelo->countRecibo($dataInicial, $dataFinal);
$somaCredito = $modelo->sumCredito($dataInicial, $dataFinal);
$somaDebito = $modelo->sumDebito($dataInicial, $dataFinal);

$somaCreditoRecibo = $modelo->sumCreditoRecibo($dataInicial, $dataFinal);
$somaDebitoRecibo = $modelo->sumDebitoRecibo($dataInicial, $dataFinal);

$documento = $modelo->documento($dataInicial, $dataFinal);

$recibo = $modelo->recibo($dataInicial, $dataFinal);

$dom->preserveWhiteSpace = true;
$auditFile = $dom->createElement("AuditFile");
$auditFile->setAttribute("xmlns", "urn:OECD:StandardAuditFile-Tax:AO_1.01_01");
$auditFile->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");


$dom->appendChild($auditFile);
$header = $dom->createElement("Header");
$auditFile->appendChild($header);
$auditFileVersion = $dom->createElement("AuditFileVersion", "1.01_01");
$header->appendChild($auditFileVersion);
$companyID = $dom->createElement("CompanyID", $empresa[6]['valor'] == null ? "Desconhecido" : $empresa[6]['valor']);
$header->appendChild($companyID);
$taxRegistrationNumber = $dom->createElement("TaxRegistrationNumber", $empresa[6]['valor'] == null ? "Desconhecido" : $empresa[6]['valor']);
$header->appendChild($taxRegistrationNumber);
$taxAccountingBasis = $dom->createElement("TaxAccountingBasis", $definicao["tipoPrograma"]);
$header->appendChild($taxAccountingBasis);
$companyName = $dom->createElement("CompanyName", $empresa[1]['valor'] == null ? "Desconhecido" : $empresa[1]['valor']);
$header->appendChild($companyName);
$companyAddress = $dom->createElement("CompanyAddress");
$header->appendChild($companyAddress);
$addressDetail = $dom->createElement("AddressDetail", $empresa[3]['valor'] == null ? "Desconhecido" : $empresa[3]['valor']);
$companyAddress->appendChild($addressDetail);
$city = $dom->createElement("City", $empresa[10]['valor'] == null ? "Desconhecido" : $empresa[10]['valor']);
$companyAddress->appendChild($city);
$province = $dom->createElement("Province", $empresa[11]['valor'] == null ? "Desconhecido" : $empresa[11]['valor']);
$companyAddress->appendChild($province);
$country = $dom->createElement("Country", $definicao["pais"] == null ? $definicao["pais"] : $definicao["pais"]);
$companyAddress->appendChild($country);
$fiscalYear = $dom->createElement("FiscalYear", $definicao["serie"] == null ? "Desconhecido" : $definicao["serie"]);
$header->appendChild($fiscalYear);
$startDate = $dom->createElement("StartDate", $dataInicial == null ? "Desconhecido" : $dataInicial);
$header->appendChild($startDate);
$endDate = $dom->createElement("EndDate", $dataFinal == null ? "Desconhecido" : $dataFinal);
$header->appendChild($endDate);
$currencyCode = $dom->createElement("CurrencyCode", $definicao["moeda"] == null ? "Desconhecido" : $definicao["moeda"]);
$header->appendChild($currencyCode);
$dateCreated = $dom->createElement("DateCreated", date('Y-m-d') == null ? "Desconhecido" : date('Y-m-d'));
$header->appendChild($dateCreated);
$taxEntity = $dom->createElement("TaxEntity", "Global");
$header->appendChild($taxEntity);
$productCompanyTaxID = $dom->createElement("ProductCompanyTaxID", "AO5417432466");
$header->appendChild($productCompanyTaxID);
$softwareValidationNumber = $dom->createElement("SoftwareValidationNumber", "0/AGT/2021");
$header->appendChild($softwareValidationNumber);
$productID = $dom->createElement("ProductID", "BUESIMPLES/MAYONGI ANGOLA");
$header->appendChild($productID);
$productVersion = $dom->createElement("ProductVersion", "1");
$header->appendChild($productVersion);
$masterFiles = $dom->createElement("MasterFiles");
$auditFile->appendChild($masterFiles);

if ($entidade != null) {
    for ($i = 0; $i < count($entidade); $i++) {
        $customer = $dom->createElement("Customer");
        $masterFiles->appendChild($customer);
        $customerID = $dom->createElement("CustomerID", $entidade[$i]["idEntidade"]);
        $customer->appendChild($customerID);
        $accountID = $dom->createElement("AccountID", "Desconhecido");
        $customer->appendChild($accountID);
        $customerTaxID = $dom->createElement("CustomerTaxID", $entidade[$i]["nif"]);
        $customer->appendChild($customerTaxID);
        $companyName = $dom->createElement("CompanyName", $entidade[$i]["nome"]);
        $customer->appendChild($companyName);
        $billingAddress = $dom->createElement("BillingAddress");
        $customer->appendChild($billingAddress);
        $addressDetail = $dom->createElement("AddressDetail", $entidade[$i]["morada"] == null ? "Desconhecido" : $entidade[$i]["morada"]);
        $billingAddress->appendChild($addressDetail);
        $city = $dom->createElement("City", $entidade[$i]["cidade"] == null ? "Desconhecido" : $entidade[$i]["cidade"]);
        $billingAddress->appendChild($city);
        $province = $dom->createElement("Province", $entidade[$i]["provincia"] == null ? "Desconhecido" : $entidade[$i]["provincia"]);
        $billingAddress->appendChild($province);
        $country = $dom->createElement("Country", $entidade[$i]["pais"] == null ? "Desconhecido" : $entidade[$i]["pais"]);
        $billingAddress->appendChild($country);
        $selfBillingIndicator = $dom->createElement("SelfBillingIndicator", "0");
        $customer->appendChild($selfBillingIndicator);
    }
}

if ($artigo != null) {
    for ($i = 0; $i < count($artigo); $i++) {
        $product = $dom->createElement("Product");
        $masterFiles->appendChild($product);
        $productType = $dom->createElement("ProductType", $artigo[$i]["tipoArtigo"] == null ? "Desconhecido" : $artigo[$i]["tipoArtigo"]);
        $product->appendChild($productType);
        $productCode = $dom->createElement("ProductCode", $artigo[$i]["idArtigo"] == null ? "Desconhecido" : $artigo[$i]["idArtigo"]);
        $product->appendChild($productCode);
        $productDescription = $dom->createElement("ProductDescription", $artigo[$i]["nome"] == null ? "Desconhecido" : $artigo[$i]["nome"]);
        $product->appendChild($productDescription);
        $productNumberCode = $dom->createElement("ProductNumberCode", $artigo[$i]["idArtigo"] == null ? "Desconhecido" : $artigo[$i]["idArtigo"]);
        $product->appendChild($productNumberCode);
    }
}

$taxTable = $dom->createElement("TaxTable");
$masterFiles->appendChild($taxTable);

if ($tipoTaxa != null) {
    for ($i = 0; $i < count($tipoTaxa); $i++) {
        $taxTableEntry = $dom->createElement("TaxTableEntry");
        $taxTable->appendChild($taxTableEntry);
        $taxType = $dom->createElement("TaxType", $tipoTaxa[$i]["codigoTipoTaxa"] == null ? "Desconhecido" : $tipoTaxa[$i]["codigoTipoTaxa"]);
        $taxTableEntry->appendChild($taxType);
        $taxCountryRegion = $dom->createElement("TaxCountryRegion", $tipoTaxa[$i]["designacaoPais"] == null ? $definicao["pais"] : $tipoTaxa[$i]["designacaoPais"]);
        $taxTableEntry->appendChild($taxCountryRegion);
        $taxCode = $dom->createElement("TaxCode", $tipoTaxa[$i]["codigoTaxaImposto"] == null ? "Desconhecido" : $tipoTaxa[$i]["codigoTaxaImposto"]);
        $taxTableEntry->appendChild($taxCode);
        $Description = $dom->createElement("Description", $tipoTaxa[$i]["nomeCodigoTaxa"] == null ? "Desconhecido" : $tipoTaxa[$i]["nomeCodigoTaxa"]);
        $taxTableEntry->appendChild($Description);
        $TaxPercentage = $dom->createElement("TaxPercentage", $tipoTaxa[$i]["taxaImposto"] == null ? "Desconhecido" : $tipoTaxa[$i]["taxaImposto"]);
        $taxTableEntry->appendChild($TaxPercentage);
    }
}

$sourceDocuments = $dom->createElement("SourceDocuments");
$auditFile->appendChild($sourceDocuments);
$salesInvoices = $dom->createElement("SalesInvoices");
$sourceDocuments->appendChild($salesInvoices);
$numberOfEntries = $dom->createElement("NumberOfEntries", $contagemDocumento[0]["contador"] == null ? 0 : $contagemDocumento[0]["contador"]);
$salesInvoices->appendChild($numberOfEntries);
$totalDebit = $dom->createElement("TotalDebit", $somaDebito[0]["soma"] == null ? 0 : $somaDebito[0]["soma"]);
$salesInvoices->appendChild($totalDebit);
$totalCredit = $dom->createElement("TotalCredit", $somaCredito[0]["soma"] == null ? 0 : $somaCredito[0]["soma"]);
$salesInvoices->appendChild($totalCredit);

if ($documento != null) {
    for ($i = 0; $i < count($documento); $i++) {
        $invoice = $dom->createElement("Invoice");
        $salesInvoices->appendChild($invoice);
        $invoiceNo = $dom->createElement("InvoiceNo", $documento[$i]["codigoDocumento"] == null ? "Desconhecido" : $documento[$i]["codigoDocumento"]);
        $invoice->appendChild($invoiceNo);
        $documentStatus = $dom->createElement("DocumentStatus");
        $invoice->appendChild($documentStatus);
        $invoiceStatus = $dom->createElement("InvoiceStatus", $documento[$i]["estadoEmissao"] == 1 ? "N" : "A");
        $documentStatus->appendChild($invoiceStatus);
        $invoiceStatusDate = $dom->createElement("InvoiceStatusDate", date("Y-m-d", strtotime($documento[$i]["dataDoc"])) . "T" . date("H:i:s", strtotime($documento[$i]["dataDoc"])));
        $documentStatus->appendChild($invoiceStatusDate);
        $sourceID = $dom->createElement("SourceID", $documento[$i]["idUsuario"] == null ? "Desconhecido" : $documento[$i]["idUsuario"]);
        $documentStatus->appendChild($sourceID);
        $sourceBilling = $dom->createElement("SourceBilling", "P");
        $documentStatus->appendChild($sourceBilling);
        $hash = $dom->createElement("Hash", $documento[$i]["hashSaft"]);
        $invoice->appendChild($hash);
        $hashControl = $dom->createElement("HashControl", "1");
        $invoice->appendChild($hashControl);
        $period = $dom->createElement("Period", date("m", strtotime($documento[$i]["dataDoc"])));
        $invoice->appendChild($period);
        $invoiceDate = $dom->createElement("InvoiceDate", date("Y-m-d", strtotime($documento[$i]["dataDoc"])));
        $invoice->appendChild($invoiceDate);
        $invoiceType = $dom->createElement("InvoiceType", $documento[$i]["idTipoDoc"] == 1 ? "FT" : ($documento[$i]["idTipoDoc"] == 2 ? "FR" : ($documento[$i]["idTipoDoc"] == 7 ? "NC" : ($documento[$i]["idTipoDoc"] == 8 ? "ND": "Outro"))));
        $invoice->appendChild($invoiceType);
        $specialRegimes = $dom->createElement("SpecialRegimes");
        $invoice->appendChild($specialRegimes);
        $selfBillingIndicator = $dom->createElement("SelfBillingIndicator", "0");
        $specialRegimes->appendChild($selfBillingIndicator);
        $cashVATSchemeIndicator = $dom->createElement("CashVATSchemeIndicator", "0");
        $specialRegimes->appendChild($cashVATSchemeIndicator);
        $thirdPartiesBillingIndicator = $dom->createElement("ThirdPartiesBillingIndicator", "0");
        $specialRegimes->appendChild($thirdPartiesBillingIndicator);
        $sourceID = $dom->createElement("SourceID", "1");
        $invoice->appendChild($sourceID);
        $systemEntryDate = $dom->createElement("SystemEntryDate", date("Y-m-d", strtotime($documento[$i]["dataDoc"])) . "T" . date("H:i:s", strtotime($documento[$i]["dataDoc"])));
        $invoice->appendChild($systemEntryDate);
        $customerID = $dom->createElement("CustomerID", $documento[$i]["idEntidade"]);
        $invoice->appendChild($customerID);
        $shipTo = $dom->createElement("ShipTo");
        $invoice->appendChild($shipTo);
        $address = $dom->createElement("Address");
        $shipTo->appendChild($address);
        $addressDetail = $dom->createElement("AddressDetail",  $documento[$i]["moradaE"] == null ? "Desconhecido" : $documento[$i]["moradaE"]);
        $address->appendChild($addressDetail);
        $city = $dom->createElement("City",  $documento[$i]["cidadeE"] == null ? "Desconhecido" : $documento[$i]["cidadeE"]);
        $address->appendChild($city);
        $province = $dom->createElement("Province",  $documento[$i]["provinciaE"] == null ? "Desconhecido" : $documento[$i]["provinciaE"]);
        $address->appendChild($province);
        $country = $dom->createElement("Country",  $documento[$i]["paisE"] == null ? $definicao["pais"] : $documento[$i]["paisE"]);
        $address->appendChild($country);
        $shipFrom = $dom->createElement("ShipFrom");
        $invoice->appendChild($shipFrom);
        $address = $dom->createElement("Address");
        $shipFrom->appendChild($address);
        $addressDetail = $dom->createElement("AddressDetail",  $empresa[3]['valor'] == null ? "Desconhecido" : $empresa[3]['valor']);
        $address->appendChild($addressDetail);
        $city = $dom->createElement("City",  $empresa[10]['valor'] == null ? "Desconhecido" : $empresa[10]['valor']);
        $address->appendChild($city);
        $province = $dom->createElement("Province",  $empresa[11]['valor'] == null ? "Desconhecido" : $empresa[11]['valor']);
        $address->appendChild($province);
        $country = $dom->createElement("Country",  $definicao["pais"] == null ? $definicao["pais"] : $definicao["pais"]);
        $address->appendChild($country);
        $movementEndTime = $dom->createElement("MovementEndTime", date("Y-m-d", strtotime($documento[$i]["dataDoc"])) . "T" . date("H:i:s", strtotime($documento[$i]["dataDoc"])));
        $invoice->appendChild($movementEndTime);
        $movementStartTime = $dom->createElement("MovementStartTime", date("Y-m-d", strtotime($documento[$i]["dataDoc"])) . "T" . date("H:i:s", strtotime($documento[$i]["dataDoc"])));
        $invoice->appendChild($movementStartTime);
        $linha = $modelo->linhaDocumento($documento[$i]["idDocumento"]);
        for ($j = 0; $j < count($linha); $j++) {
            $line = $dom->createElement("Line");
            $invoice->appendChild($line);
            $lineNumber = $dom->createElement("LineNumber", $j + 1);
            $line->appendChild($lineNumber);
            $productCode = $dom->createElement("ProductCode", $linha[$j]["idArtigo"]);
            $line->appendChild($productCode);
            $productDescription = $dom->createElement("ProductDescription", $linha[$j]["descricaoAd"]);
            $line->appendChild($productDescription);
            $quantity = $dom->createElement("Quantity", $linha[$j]["qtd"]);
            $line->appendChild($quantity);
            $unitOfMeasure = $dom->createElement("UnitOfMeasure", $linha[$j]["nomeUm"]);
            $line->appendChild($unitOfMeasure);
            $unitPrice = $dom->createElement("UnitPrice", $linha[$j]["preco"]);
            $line->appendChild($unitPrice);
            $taxPointDate = $dom->createElement("TaxPointDate", $linha[$j]["dataDocumentoAd"]);
            $line->appendChild($taxPointDate);
            if ($documento[$i]["idTipoDoc"] == 7) {
                $references = $dom->createElement("References");
                $line->appendChild($references);
                $queryDocumento = $modelo->queryDoc($documento[$i]["codigoDocumento"]);
                for($k = 0; $k < count($queryDocumento); $k++){
                    //$reference = $dom->createElement("Reference", $queryDocumento[$k]["codigoDocumento"]);
                    //$line->appendChild($reference);
                    //$reason = $dom->createElement("Reason", $referencia);
                    //$line->appendChild($reason);
                }
            }
            $description = $dom->createElement("Description", $linha[$j]["descricaoAd"]);
            $line->appendChild($description);
            if ($documento[$i]["idTipoDoc"] == 7) {
                $debitAmount = $dom->createElement("DebitAmount", $linha[$j]["total"]);
                $line->appendChild($debitAmount);
            } else {
                $creditAmount = $dom->createElement("CreditAmount", $linha[$j]["total"]);
                $line->appendChild($creditAmount);
            }
            $tax = $dom->createElement("Tax");
            $line->appendChild($tax);
            $taxType = $dom->createElement("TaxType", $linha[$j]["tipoTaxatt"]);
            $tax->appendChild($taxType);
            $taxCountryRegion = $dom->createElement("TaxCountryRegion", $linha[$j]["codigo"]);
            $tax->appendChild($taxCountryRegion);
            $taxCode = $dom->createElement("TaxCode", $linha[$j]["codigoTaxa"]);
            $tax->appendChild($taxCode);
            $taxPercentage = $dom->createElement("TaxPercentage", $linha[$j]["taxa"]);
            $tax->appendChild($taxPercentage);
            if($linha[$j]["taxa"] == 0){
                $taxExemptionReason = $dom->createElement("TaxExemptionReason", $linha[$j]["motivoIsencao"]);
                $line->appendChild($taxExemptionReason);
                $taxExemptionCode = $dom->createElement("TaxExemptionCode", $linha[$j]["tipoTaxatt"] == 'NS' ? "M02" : 'M10');
                $line->appendChild($taxExemptionCode);
            }
            $settlementAmount = $dom->createElement("SettlementAmount", $linha[$j]["imposto"]);
            $line->appendChild($settlementAmount);
        }


        $documentTotals = $dom->createElement("DocumentTotals");
        $invoice->appendChild($documentTotals);
        $taxPayable = $dom->createElement("TaxPayable", $documento[$i]["imposto"] == null ? "Desconhecido" : $documento[$i]["imposto"]);
        $documentTotals->appendChild($taxPayable);
        $netTotal = $dom->createElement("NetTotal", $documento[$i]["totalLiquido"] == null ? "Desconhecido" : $documento[$i]["totalLiquido"]);
        $documentTotals->appendChild($netTotal);
        if ($documento[$i]["idTipoDoc"] != 7) {
            $grossTotal = $dom->createElement("GrossTotal", $documento[$i]["total"] == null ? "Desconhecido" : $documento[$i]["total"]);
            $documentTotals->appendChild($grossTotal);
        } else {
            $grossTotal = $dom->createElement("GrossTotal", $documento[$i]["total"]);
            $documentTotals->appendChild($grossTotal);
        }
        $modoPagamento = $modelo->modoPagamento($documento[$i]["idDocumento"]);
        if ($modoPagamento != null) {
            for ($j = 0; $j < count($modoPagamento); $j++) {
                $payment = $dom->createElement("Payment");
                $documentTotals->appendChild($payment);
                $paymentMechanism = $dom->createElement("PaymentMechanism", $modoPagamento[$j]["mecanismoPagamento"]);
                $payment->appendChild($paymentMechanism);
                $paymentAmount = $dom->createElement("PaymentAmount", $modoPagamento[$j]["valor"]);
                $payment->appendChild($paymentAmount);
                $paymentDate = $dom->createElement("PaymentDate", date("Y-m-d", strtotime($documento[$i]["dataDoc"])));
                $payment->appendChild($paymentDate);
            }
        }
    }
}



if ($recibo != null) {
        $payments = $dom->createElement("Payments");
        $sourceDocuments->appendChild($payments);
        $numberOfEntries = $dom->createElement("NumberOfEntries", $contagemRecibo[0]["contador"] == null ? 0 : $contagemRecibo[0]["contador"]);
        $payments->appendChild($numberOfEntries);
        $totalDebit = $dom->createElement("TotalDebit", $somaDebitoRecibo[0]["soma"] == null ? 0 : $somaDebitoRecibo[0]["soma"]);
        $payments->appendChild($totalDebit);
        $totalCredit = $dom->createElement("TotalCredit", $somaCreditoRecibo[0]["soma"] == null ? 0 : $somaCreditoRecibo[0]["soma"]);
        $payments->appendChild($totalCredit);
    for ($i = 0; $i < count($recibo); $i++) {

        $payment = $dom->createElement("Payment");
        $payments->appendChild($payment);
        $paymentRefNo = $dom->createElement("PaymentRefNo", $recibo[$i]["codigoDocumento"]);
        $payment->appendChild($paymentRefNo);
        $period = $dom->createElement("Period", date("m", strtotime($recibo[$i]["dataDoc"])));
        $payment->appendChild($period);
        $transactionDate = $dom->createElement("TransactionDate", date("Y-m-d", strtotime($recibo[$i]["dataDoc"])));
        $payment->appendChild($transactionDate);
        $paymentType = $dom->createElement("PaymentType", "RC");
        $payment->appendChild($paymentType);
        $documentStatus = $dom->createElement("DocumentStatus");
        $payment->appendChild($documentStatus);
        $paymentStatus = $dom->createElement("PaymentStatus", $recibo[$i]["estadoEmissao"] == 1 ? "N" : "A");
        $documentStatus->appendChild($paymentStatus);
        $PaymentStatusDate = $dom->createElement("PaymentStatusDate", date("Y-m-d", strtotime($recibo[$i]["dataDoc"])) . "T" . date("H:i:s", strtotime($recibo[$i]["dataDoc"])));
        $documentStatus->appendChild($PaymentStatusDate);
        $sourceID = $dom->createElement("SourceID", $recibo[$i]["idUsuario"] == null ? "Desconhecido" : $recibo[$i]["idUsuario"]);
        $documentStatus->appendChild($sourceID);
        $sourcePayment = $dom->createElement("SourcePayment", "P");
        $documentStatus->appendChild($sourcePayment);

        $modoPagamentoRecibo = $modelo->modoPagamento($recibo[$i]["idDocumento"]);
        if (count($modoPagamentoRecibo) > 0) {
            for ($j = 0; $j < count($modoPagamentoRecibo); $j++) {
                $paymentMethod = $dom->createElement("PaymentMethod");
                $payment->appendChild($paymentMethod);
                $paymentMechanism = $dom->createElement("PaymentMechanism", $modoPagamentoRecibo[$j]["mecanismoPagamento"]);
                $paymentMethod->appendChild($paymentMechanism);
                $paymentAmount = $dom->createElement("PaymentAmount", $modoPagamentoRecibo[$j]["valor"]);
                $paymentMethod->appendChild($paymentAmount);
                $paymentDate = $dom->createElement("PaymentDate", date("Y-m-d", strtotime($recibo[$i]["dataDoc"])));
                $paymentMethod->appendChild($paymentDate);
            }
        }

        $sourceID = $dom->createElement("SourceID", $recibo[$i]["idUsuario"] == null ? "Desconhecido" : $recibo[$i]["idUsuario"]);
        $payment->appendChild($sourceID);
        $systemEntryDate = $dom->createElement("SystemEntryDate", date("Y-m-d", strtotime($recibo[$i]["dataDoc"])) . "T" . date("H:i:s", strtotime($recibo[$i]["dataDoc"])));
        $payment->appendChild($systemEntryDate);
        $customerID = $dom->createElement("CustomerID", $recibo[$i]["idEntidade"]);
        $payment->appendChild($customerID);
        $queryFactura = $modelo->queryDocumentoFac($recibo[$i]["idDocumento"], 1);
        for ($j = 0; $j < count($queryFactura); $j++) {
            $line = $dom->createElement("Line");
            $payment->appendChild($line);
            $lineNumber = $dom->createElement("LineNumber", $j + 1);
            $line->appendChild($lineNumber);
            $sourceDocumentID = $dom->createElement("SourceDocumentID");
            $line->appendChild($sourceDocumentID);
            $originatingON = $dom->createElement("OriginatingON", $queryFactura[$j]["codigoDocumento"]);
            $sourceDocumentID->appendChild($originatingON);
            $invoiceDate = $dom->createElement("InvoiceDate", date("Y-m-d", strtotime($queryFactura[$j]["dataDoc"])));
            $sourceDocumentID->appendChild($invoiceDate);
            $creditAmount = $dom->createElement("CreditAmount", $queryFactura[$j]["entregueDocRelac"]);
            $line->appendChild($creditAmount);
        }

        $documentTotals = $dom->createElement("DocumentTotals");
        $payment->appendChild($documentTotals);
        $taxPayable = $dom->createElement("TaxPayable", $recibo[$i]["imposto"] == null ? "Desconhecido" : $recibo[$i]["imposto"]);
        $documentTotals->appendChild($taxPayable);
        $netTotal = $dom->createElement("NetTotal", $recibo[$i]["totalLiquido"] == null ? "Desconhecido" : $recibo[$i]["totalLiquido"]);
        $documentTotals->appendChild($netTotal);
        $grossTotal = $dom->createElement("GrossTotal", $recibo[$i]["total"] == null ? "Desconhecido" : $recibo[$i]["total"]);
        $documentTotals->appendChild($grossTotal);
    }
}

$dom->save("./ficheiro/" . $nomeFicheiro . ".xml");
$xmlString = $dom->saveXML();
if ($xmlString != null) {
    echo json_encode(["filename" => $nomeFicheiro, "xmlString" => $xmlString]);
} else {
    echo json_encode("Sem dados");
}


