<?php

namespace Helpers\Outil;

use Helpers\Log\LogSysteme;

class Document
{
    
    // public static function getUrlDocument(string $urlDoc)
    // {
    //     if (substr($urlDoc, 0, 1) == '%') {
    //         $positionDuDeuxieme = strpos(substr($urlDoc, 1), '%');
    //         if ($positionDuDeuxieme === false) {
    //             throw new \Exception('Invalid "'.$urlDoc.'"');
    //         }
    //         $clef = substr($urlDoc, 1, $positionDuDeuxieme);
    //         $urlDoc = str_replace('%'.$clef.'%', $_SESSION['base1'][$clef], $urlDoc);
    //     }
    // }
   
    public static function removeAllNamespaces(\DOMDocument $domSource): \DOMDocument
    {
        $dom = new \DOMDocument();
        $dom->formatOutput = true;
       
        $domSource = clone $domSource;
        $domSource->formatOutput = true;

        $dom->loadXML((string) preg_replace('/\sxmlns="(.*?)"/', '', XmlHelper::saveXML($domSource)));
        $xpath = new \DOMXPath($dom);

        $elements = $xpath->query('//namespace::*');
        if ($elements === false) {
            $elements = [];
        }
        foreach ($elements as $namespaceNode) {
            $prefix = str_replace('xmlns:', '', (string) $namespaceNode->nodeName);
            $nodes = $xpath->query("//*[namespace::{$prefix}]");
            if ($nodes === false) {
                LogSysteme::prefixErrorLog(new \Exception('Invalid xpath "//*[namespace::'.$prefix.']"'));
                continue;
            }

            /** @var \DOMElement $node */
            foreach ($nodes as $node) {
                $namespaceUri = $node->lookupNamespaceURI($prefix);
                $node->removeAttributeNS($namespaceUri, $prefix);
            }
        }

        // TODO : why do that ?
        $dom->loadXML(XmlHelper::saveXML($dom));

        return $dom;
    }
}
