<?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.) 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
*/

class AdminChatStyler  extends DbConectionMaker
{
    private string $style;
    private string $cssFile;
    private string $css;
    private array $variables = [];
    private array $categories = [];
    private string $message = '';

    public function __construct()
    {
		
		parent::__construct();
		
		// 🔐 Session sauber starten
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
		
        // CSRF
        if (empty($_SESSION['etchat_' . $this->_prefix . 'csrf_token'])) {
            $_SESSION['etchat_' . $this->_prefix . 'csrf_token'] = bin2hex(random_bytes(16));
        }
        $this->csrfToken = $_SESSION['etchat_' . $this->_prefix . 'csrf_token'];
		
        $this->checkAccess();
        $this->initPaths();
        $this->loadCss();
        $this->handlePost();
        $this->renderTemplate();
    }
	
	
	private array $labels = [
    '--Textfarbe' => 'User Schriftfarbe',
    '--Systemfarbe' => 'System Schriftfarbe',
    '--Botfarbe' => 'Bot Schriftfarbe',
	'--color-text-webfarbe' => 'Textfarbe Webseite',
    '--color-backround' => 'Hintergundfarbe',
    '--color-border' => 'Rahmenfarbe',
    '--color-box' => 'Boxenfarbe',
    '--color-link' => 'Links',
    '--color-link-hover' => 'Links (hover)',
    '--color-button-zeilen' => 'Button & Zeilen',
    '--color-button-hover' => 'Button (hover/aktive)',
    '--img' => 'Hintergrund Bild',
    '--font-family' => 'Schriftart',
    '--font-size-base' => 'Base',
    '--font-size-large' => 'Groß',
    '--font-size-small' => 'Klein',
    '--font-size-xlarge' => 'Extragroß',
	];

	private array $onOffVars = [
		'--banner_chat-on-off' => 'Banner Chat',
		'--banner_index-on-off' => 'Banner Index',
		'--uhrzeit-on-off' => 'Uhrzeit anzeigen',
		'--befehle-on-off' => 'Kurzbefehle anzeigen (Button)',
	];

    private function checkAccess(): void
    {
        $allowed = ['admin', 'grafik', 'co_admin'];

        if (!in_array($_SESSION['etchat_'.$this->_prefix.'user_priv'], $allowed, true)) {
            header("Location: ../");
            exit;
        }
    }

private function initPaths(): void
{
    $this->style = $_SESSION['etchat_'.$this->_prefix.'style'] ?? 'style_chat';
    $this->css = "styles/{$this->style}/style.css";
    $this->cssFile = "styles/{$this->style}/variables.css";
    
    // 🔥 NEU: Prüfen ob der Style-Ordner existiert
    if (!is_dir("styles/{$this->style}")) {
        $this->showStyleError();
        exit;
    }
    
    // Prüfen ob die variables.css existiert (deine vorhandene Prüfung)
    if (!file_exists($this->cssFile)) {
        $this->showStyleError();
        exit;
    }
}

// 🔥 NEUE METHODE: Fehler anzeigen
private function showStyleError(): void
{
	
ob_start();
	
    echo "<div>
            <h2>⚠️ Style nicht konfigurierbar</h2>
            <p>Das Design '<strong>" . htmlspecialchars($this->style) . "</strong>' ist nicht konfigurierbar.</p>
            <p>Bitte wähle einen anderes Design unter <a href='./?AdminPropertyIndex'>Design & Sprache</a>.</p>
        </div>";
		
$content = ob_get_clean();

$pageTitle  = 'Chat Styler';
$backLink   = './?AdminIndex';
$footerNote = '';

include dirname(__DIR__, 2) . '/styles/admin_tpl/admin_master_template.php';
		
}

    private function loadCss(): void
    {
        if (!file_exists($this->cssFile)) {
            $this->renderError();
            exit;
        }

        $cssContent = file_get_contents($this->cssFile);
        preg_match('/:root\s*{([^}]*)}/s', $cssContent, $matches);

        $currentCategory = 'Allgemein';

        if (!empty($matches[1])) {
            $lines = explode("\n", $matches[1]);

            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line)) continue;

                if (preg_match('/\/\*\s*(.+?)\s*\*\//', $line, $match)) {
                    $currentCategory = $match[1];
                    continue;
                }

                if (strpos($line, '--') !== false && strpos($line, ':') !== false) {
                    [$key, $value] = explode(":", $line);

                    $key = trim($key);
                    $value = trim($value, " ;");

                    if ($key === '--img' && preg_match('/^url\((["\']?)(.*?)\1\)$/', $value, $m)) {
                        $value = $m[2];
                    }

                    $this->variables[$key] = $value;
                    $this->categories[$key] = $currentCategory;
                }
            }
        }
    }
	
	private function normalizeChatColor(string $value): string
	{
		$value = trim($value);

		// #F3F3F3 → F3F3F3
		if (str_starts_with($value, '#')) {
			return strtoupper(substr($value, 1));
		}

		// rgb(...) → HEX OHNE #
		if (preg_match('/rgba?\((.*?)\)/i', $value, $m)) {
			$parts = explode(',', $m[1]);
			$r = (int)$parts[0];
			$g = (int)$parts[1];
			$b = (int)$parts[2];
			return sprintf("%02X%02X%02X", $r, $g, $b);
		}

		return $value;
	}
	

	private function handlePost(): void
	{
		// ✅ ERST prüfen: ist überhaupt ein POST?
		if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
			return;
		}

		// 🔐 Dann erst CSRF prüfen
		if (!isset($_POST['csrf_token']) || 
			!hash_equals($_SESSION['etchat_'.$this->_prefix.'csrf_token'], $_POST['csrf_token'])) {
			$this->message = "<div class='message error'>Ungültiger CSRF Token!</div>";
			return;
		}

		foreach ($_POST as $key => $value) {
			if (!isset($this->variables[$key])) continue;

			if ($key === '--img') {
				$filename = trim($value, " '\"");
				$value = $filename === '' ? "none" : "url('hintergrund/$filename')";
			}

			if (in_array($key, ['--Textfarbe', '--Systemfarbe'], true)) {
				$this->variables[$key] = $this->normalizeChatColor($value);
			} else {
				$this->variables[$key] = $value;
			}
		}

		$this->saveCss();

		$this->message = '<div class="success-banner">    
							<span>Gespeichert erfolgreich!</span>
							<span class="close-btn" onclick="closeSuccessBanner()">✖</span>
						</div>';
	}

    private function saveCss(): void
    {
        $newContent = ":root {\n";
        $lastCategory = '';

        foreach ($this->variables as $key => $value) {
            $categoryName = $this->categories[$key] ?? 'Allgemein';

            if ($categoryName !== $lastCategory) {
                $newContent .= "  /* $categoryName */\n";
                $lastCategory = $categoryName;
            }

            $newContent .= "  $key: $value;\n";
        }

        $newContent .= "}\n";

        file_put_contents($this->cssFile, $newContent);
    }

    private function isColor(string $value): bool
    {
        return preg_match('/^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$/', $value)
            || preg_match('/^rgba?\(/', $value)
            || preg_match('/^hsl\(/', $value);
    }

	private function toRGBA(string $value): string
	{
		$value = trim($value);

		if (preg_match('/^#([a-f0-9]{3})$/i', $value, $m)) {
			$r = hexdec(str_repeat($m[1][0], 2));
			$g = hexdec(str_repeat($m[1][1], 2));
			$b = hexdec(str_repeat($m[1][2], 2));
			return "rgba($r,$g,$b,1)";
		}

		if (preg_match('/^#([a-f0-9]{6})$/i', $value, $m)) {
			$r = hexdec(substr($m[1], 0, 2));
			$g = hexdec(substr($m[1], 2, 2));
			$b = hexdec(substr($m[1], 4, 2));
			return "rgba($r,$g,$b,1)";
		}

		if (preg_match('/^rgba?\(/i', $value)) {
			return preg_replace('/\s+/', '', $value);
		}

		return $value;
	}

    private function renderError(): void
    {
        echo "<div class='error-box'>CSS Datei nicht gefunden: {$this->cssFile}</div>";
    }

private function renderTemplate(): void
{
    $csrfToken = $this->csrfToken;
    $labels = $this->labels;
    $onOffVars = $this->onOffVars;
    $variables = $this->variables;
    $categories = $this->categories;
    $message = $this->message;
    $css = $this->css;
    $style = $this->style;

    // 🔥 NEU: Gruppierung
    $groupedVariables = [];

    foreach ($this->variables as $key => $value) {
        $category = $this->categories[$key] ?? 'Allgemein';

        $groupedVariables[$category][] = [
            'key'   => $key,
            'value' => $value,
            'label' => $this->labels[$key] ?? $this->onOffVars[$key] ?? $key
        ];
    }

    // Background Bilder
    $backgroundDir = "styles/{$this->style}/hintergrund/";
    $backgroundFiles = is_dir($backgroundDir)
        ? array_filter(scandir($backgroundDir), fn($f) => preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $f))
        : [];

    $isColor = fn($value) => $this->isColor($value);

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