<?php

/*
ET-Chat Copyright by SEDesign | ET-Chat v3.x.x Lizenz: CCPL | Autor: Evgeni Tcherkasski (info@s-e-d.de)
ET-Chat_T-FISH-MOD Weiterentwicklungen, Optimierungen und Ergänzungen am Code sind das geistige Eigentum von Tommy (Thomas Kuhn) und Harlekin (Bernd Witte).

Die darauf folgende Optimierungen und Ergänzungen am Code sind das Geistige Eigentum von Powermen (Christian K.) 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
*/

class LangXml extends EtChatConfig
{
    public $langXmlDoc;
    public $lastError = '';

    public function __construct($path = "./lang/", $xmlfile = "")
    {
        parent::__construct();

        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        $sessionFile = $_SESSION['etchat_'.$this->_prefix.'lang_xml_file'] ?? '';
        $xmlfile = !empty($xmlfile) ? $xmlfile : $sessionFile;

        if (empty($xmlfile)) {
            $xmlfile = "lang_de.xml";
        }

        $fullpath = rtrim($path, "/") . "/" . $xmlfile;

        if (!file_exists($fullpath)) {
            $this->lastError = "Language file not found: " . $fullpath;
            return;
        }

        libxml_use_internal_errors(true);

        $xml = simplexml_load_file($fullpath, 'SimpleXMLElement', LIBXML_NOCDATA);

        if ($xml === false) {
            $this->lastError = "Invalid language XML file.";
            return;
        }

        $this->langXmlDoc = $this->convertNode($xml);
    }

    public function getLang()
    {
        return $this->langXmlDoc;
    }

    public function getLastError(): string
    {
        return $this->lastError;
    }

    private function convertNode($node)
    {
        $obj = new stdClass();

        foreach ($node->children() as $name => $child) {

            if (!isset($obj->$name)) {
                $obj->$name = [];
            }

            $childObj = new stdClass();
            $childObj->tagData = trim((string)$child);

            // Attribute übernehmen
            $childObj->tagAttrs = [];
            foreach ($child->attributes() as $attrName => $attrValue) {
                $childObj->tagAttrs[$attrName] = (string)$attrValue;
            }

            // Rekursion für Kindelemente
            if ($child->count() > 0) {
                $childObj = $this->convertNode($child);
            }

            $obj->{$name}[] = $childObj;
        }

        return $obj;
    }
}