<?php
declare(strict_types=1);

/**
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.)
und wird unter der Namenserweiterung M.C.v.x.x.x. geführt. 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
 */

class AdminSpracheBearbeiten extends DbConectionMaker
{
    private string $csrfToken = '';

    public function __construct()
    {
        parent::__construct();

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

        // 🔐 Zugriff prüfen
        if (
            empty($_SESSION["etchat_" . $this->_prefix . "user_priv"]) ||
            $_SESSION["etchat_" . $this->_prefix . "user_priv"] !== "admin"
        ) {
            $this->fail("Zugriff verweigert.");
        }

        // 🔐 CSRF
        $csrfKey = 'etchat_' . $this->_prefix . 'csrf_token';
        if (empty($_SESSION[$csrfKey])) {
            $_SESSION[$csrfKey] = bin2hex(random_bytes(16));
        }
        $this->csrfToken = $_SESSION[$csrfKey];

        $config = $this->dbObj->sqlGet(
            "SELECT etchat_config_id, etchat_config_style, etchat_config_lang
             FROM {$this->_prefix}etchat_config
             WHERE etchat_config_id = :id",
            [':id' => 1]
        );

        $this->showEditor($config);
    }

    private function showEditor(array $config): void
    {
        $langFile = 'lang_de.xml';
        $styles = [];

        $langBase = realpath(__DIR__ . '/../../lang/');

        foreach ($config as $data) {

            if (!empty($data['etchat_config_lang'])) {
                $safeFile = basename($data['etchat_config_lang']);
                $fullPath = realpath(__DIR__ . '/../../lang/' . $safeFile);

                if ($fullPath && $langBase && str_starts_with($fullPath, $langBase)) {
                    $langFile = $safeFile;
                }
            }

            if (!empty($data['etchat_config_style'])) {
                $styles[] = $data['etchat_config_style'];
            }
        }

        $styles = array_values(array_unique($styles));

        $langPath = __DIR__ . '/../../lang/' . $langFile;

        if (!file_exists($langPath)) {
            $this->fail("XML nicht gefunden.");
        }

        libxml_use_internal_errors(true);
        $xml = simplexml_load_file($langPath);

        if (!$xml instanceof SimpleXMLElement) {
            $this->fail("XML Fehler.");
        }

        // Backup löschen
        if (
            $_SERVER['REQUEST_METHOD'] === 'POST' &&
            isset($_POST['delete_backups']) &&
            isset($_POST['csrf']) &&
            hash_equals($this->csrfToken, $_POST['csrf'])
        ) {
            $this->deleteBackups($langFile);
            header("Location: ./?AdminSpracheBearbeiten");
            exit;
        }

        $backupCount = $this->countBackups($langFile);

        $bereichsArray = iterator_to_array($xml);

        $bereich = $_GET['bereich'] ?? array_key_first($bereichsArray);

        if (!isset($bereichsArray[$bereich])) {
            $bereich = array_key_first($bereichsArray);
        }

        $this->dbObj->close();

        // 👉 Template Variablen
        $csrfToken = $this->csrfToken;

        include "styles/admin_tpl/indexSpracheBearbeiten.tpl.html";
    }

    private function deleteBackups(string $langFile): void
    {
        $backupDir = __DIR__ . '/../../lang/old/';

        if (!is_dir($backupDir)) return;

        $files = glob($backupDir . basename($langFile) . '.bak.*');

        if ($files === false) return;

        usort($files, fn($a, $b) => filemtime($b) <=> filemtime($a));

        $toDelete = array_slice($files, 3);

        foreach ($toDelete as $f) {
            if (is_file($f)) unlink($f);
        }
    }

    private function countBackups(string $langFile): int
    {
        $backupDir = __DIR__ . '/../../lang/old/';

        $files = is_dir($backupDir)
            ? glob($backupDir . basename($langFile) . '.bak.*')
            : [];

        return $files !== false ? count($files) : 0;
    }

    public function renderNodes($node, string $prefix = ''): void
    {
        $counts = [];

        foreach ($node as $k => $v) {
            $counts[$k] = ($counts[$k] ?? 0) + 1;
        }

        $indexCounter = [];

        foreach ($node as $key => $value) {

            $idx = $indexCounter[$key] ?? 0;
            $indexCounter[$key] = $idx + 1;

            $hasMultiple = ($counts[$key] ?? 0) > 1;

            $pfad = $prefix . $key . ($hasMultiple ? '_' . $idx : '');

            if ($value->children()->count() > 0) {

                echo "<fieldset><legend>" . htmlspecialchars($key) . "</legend>";

                $this->renderNodes($value, $pfad . '/');

                echo "</fieldset>";

            } else {

                $val = (string)$value;
                $safeVal = htmlspecialchars($val);

                echo "<label>" . htmlspecialchars($key) . "</label><br>";

                if (mb_strlen($val) > 60) {
                    echo "<textarea class='admin-textarea-medium' name='eintraege[" . htmlspecialchars($pfad) . "]'>$safeVal</textarea>";
                } else {
                    echo "<input type='text' name='eintraege[" . htmlspecialchars($pfad) . "]' value='$safeVal'>";
                }

                echo "<br><br>";
            }
        }
    }

    private function fail(string $msg): void
    {
        echo htmlspecialchars($msg);
        exit;
    }
}