<?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 AdminCSSsIndex extends DbConectionMaker
{
    private string $fileContent = '';
    private string $fileName = '';
    private string $dataKey = '';

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

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

        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Content-Type: text/html; charset=utf-8');

        // -------------------------
        // Sprache
        // -------------------------
        $langObj = new LangXml();
        $langData = $langObj->getLang();
        $lang = $langData->admin[0]->admin_menus[0]
            ?? (object)['error' => [(object)['tagData' => 'Fehler: Sprachdatei unvollständig.']]];

        // -------------------------
        // Rechtecheck
        // -------------------------
        $userPriv = $_SESSION["etchat_{$this->_prefix}user_priv"] ?? '';
        if (!in_array($userPriv, ["admin", "grafik", "co_admin"], true)) {
            echo $lang->error[0]->tagData;
            return;
        }

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

        // -------------------------
        // Input
        // -------------------------
        $data = $_POST + $_GET;
        $this->dataKey = trim((string)($data['data3'] ?? ''));

        if ($this->dataKey === '') {
            echo "Keine Datei angegeben.";
            return;
        }

        // -------------------------
        // BASE PATH
        // -------------------------
        $basePath = realpath(__DIR__ . "/../../");

        if ($basePath === false) {
            echo "Base Path Fehler.";
            return;
        }

        $styleFolder = $_SESSION['etchat_'.$this->_prefix.'style'] ?? 'default';

        // -------------------------
        // STYLE FILE HANDLING
        // -------------------------
        if (str_starts_with($this->dataKey, 'styles/')) {

            $targetPath = realpath($basePath . "/" . $this->dataKey);

        } else {

            $targetPath = realpath($basePath . "/styles/{$styleFolder}/" . $this->dataKey);

        }

        // -------------------------
        // VALIDATION
        // -------------------------
        if ($targetPath === false) {
            echo "Datei nicht gefunden.";
            return;
        }

        $allowedDirs = [
            realpath($basePath . "/styles"),
            realpath($basePath . "/js"),
            realpath($basePath . "/class"),
            realpath($basePath . "/templates"),
			realpath($basePath . "/toolbox"),
        ];

        $allowed = false;

        foreach ($allowedDirs as $dir) {
            if ($dir && str_starts_with($targetPath, $dir)) {
                $allowed = true;
                break;
            }
        }

        if (!$allowed) {
            echo "Zugriff auf diese Datei ist nicht erlaubt.";
            return;
        }

        $this->fileName = $targetPath;
		
        if (!is_readable($this->fileName)) {
            echo "Datei nicht lesbar.";
            return;
        }

        // -------------------------
        // LOAD FILE
        // -------------------------
        $this->fileContent = file_get_contents($this->fileName) ?: '';

        // -------------------------
        // SAVE FILE
        // -------------------------
        if (isset($_POST['submit'], $_POST['text'])) {

            $tokenPost = $_POST['csrf_token'] ?? '';

            if (!hash_equals($_SESSION[$csrfKey], $tokenPost)) {
                echo "CSRF Fehler.";
                exit;
            }

            if (!is_writable($this->fileName)) {
                echo "Datei nicht schreibbar.";
                exit;
            }

            file_put_contents($this->fileName, $_POST['text'], LOCK_EX);

            $url = urlencode($this->dataKey);
            header("Location: ./?AdminCSSsIndex&data3={$url}&saved=1");
            exit;
        }

        $this->renderTemplate($lang, $_SESSION[$csrfKey]);
    }

    private function renderTemplate(object $lang, string $csrfToken): void
    {
        $file = htmlspecialchars($this->dataKey, ENT_QUOTES, 'UTF-8');
		
		$print_css_list3 = htmlspecialchars($this->dataKey, ENT_QUOTES, 'UTF-8');

        $print_css_list1 = '<form action="./?AdminCSSsIndex&data3='.$file.'" method="post">
                                <textarea id="b" name="text">';
        $print_css_list2 = '</textarea>
            <input type="hidden" name="csrf_token" value="'.htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8').'">
            <div class="codemirror-save" id="editor-save">
                <input type="submit" value="Speichern" name="submit">
            </div>
        </form>';

        $print_css_list = htmlspecialchars($this->fileContent, ENT_QUOTES, 'UTF-8');

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