<?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 AdminAnkuendigung extends ConnectDB
{
    private string $cacheFile;
    private array $data = [];

    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');

        $this->initSecurity();

        $this->cacheFile = __DIR__ . '/../../cache/Ankuendigung.cache.php';

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->handlePost();
        }

        $this->data = $this->loadData();
        $this->render();
    }

    private function initSecurity(): void
    {
        $allowedRoles = ["admin", "co_admin", "chatwache"];
        $role = $_SESSION["etchat_" . $this->_prefix . "user_priv"] ?? "";

        if (!in_array($role, $allowedRoles, true)) {
            header("Location: ./");
            exit();
        }

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

    private function handlePost(): void
    {
        if (
            !isset($_POST['csrf_token'], $_SESSION['etchat_' . $this->_prefix . 'csrf_token']) ||
            !hash_equals($_SESSION['etchat_' . $this->_prefix . 'csrf_token'], (string)$_POST['csrf_token'])
        ) {
            die("Ungültiger CSRF-Token");
        }

        $speed = max(3, min(50, (int)($_POST["speed"] ?? 10)));

        $text1 = trim($_POST["text1"] ?? "");
        $text2 = trim($_POST["text2"] ?? "");
        $text3 = trim($_POST["text3"] ?? "");
		$text4 = trim($_POST["text4"] ?? "");

        $parts = array_filter([$text1, $text2, $text3, $text4]);
        $text = implode(" ✦ ✦ ✦ ", $parts);
        $text = $text !== "" ? "✦ ✦ ✦ " . $text . " ✦ ✦ ✦" : "";
        $text = mb_substr($text, 0, 255);

        $bgSelect = $_POST["bgcolor_select"] ?? "";
        $colorSelect = $_POST["color_select"] ?? "";

        // BG
        $bgcolor = ($bgSelect === "custom")
            ? $this->validateColor($_POST["bgcolor"] ?? "")
            : "";

        // COLOR
        if ($colorSelect === "custom") {
            $color = $this->validateColor($_POST["color"] ?? "");
            $mode = "custom";
        } elseif ($colorSelect === "rainbow") {
            $color = "rainbow";
            $mode = "rainbow";
        } else {
            $color = $this->validateColor($colorSelect);
            $mode = $colorSelect;
        }

        $html = $this->buildHtml($text, $bgcolor, $color, $mode, $speed);

        file_put_contents($this->cacheFile, $html, LOCK_EX);

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

    private function loadData(): array
    {
        $data = [
            'text1' => '',
            'text2' => '',
            'text3' => '',
			'text4' => '',
            'bgcolor' => '',
            'color' => 'white',
            'bgmode' => '',
            'colormode' => 'white',
            'speed' => 10
        ];

        if (!is_readable($this->cacheFile)) {
            return $data;
        }

        $content = file_get_contents($this->cacheFile);

        if (!$content) return $data;

        if (preg_match('/marqueeAnim\s+([0-9]{1,2})s/', $content, $m)) {
            $data['speed'] = (int)$m[1];
        }

        if (preg_match("/<b[^>]*>(.*?)<\/b>/", $content, $m)) {
            $txt = html_entity_decode($m[1], ENT_QUOTES);
            $txt = trim($txt, " ✦");
            $parts = explode(" ✦ ✦ ✦ ", $txt);

            $data['text1'] = $parts[0] ?? '';
            $data['text2'] = $parts[1] ?? '';
            $data['text3'] = $parts[2] ?? '';
			$data['text4'] = $parts[3] ?? '';
        }

        if (preg_match('/background:\s*(#[0-9a-fA-F]{3,6})/', $content, $m)) {
            $data['bgcolor'] = $m[1];
            $data['bgmode'] = 'custom';
        }

        if (strpos($content, 'class="rnb"') !== false) {
            $data['color'] = 'rainbow';
            $data['colormode'] = 'rainbow';
        } elseif (preg_match('/color:\s*(#[0-9a-fA-F]{3,6})/', $content, $m)) {
            $data['color'] = $m[1];
            $data['colormode'] = 'custom';
        } elseif (preg_match('/color:\s*([a-zA-Z]+)/', $content, $m)) {
            $data['color'] = strtolower($m[1]);
            $data['colormode'] = strtolower($m[1]);
        }

        return $data;
    }

    private function buildHtml(string $text, string $bg, string $color, string $mode, int $speed): string
    {
        $bgStyle = $bg ? 'background:' . htmlspecialchars($bg, ENT_QUOTES) . ';' : '';

        $base = '
<style>
.marquee-wrap{overflow:hidden;width:100%;border-radius:10px;margin:2px 0;}
.marquee{display:inline-block;white-space:nowrap;padding-left:100%;animation:marqueeAnim ' . $speed . 's linear infinite;}
@keyframes marqueeAnim{0%{transform:translateX(0);}100%{transform:translateX(-100%);}}
.marquee:hover{animation-play-state:paused;}
</style>';

        if ($mode === "rainbow") {
            return $base . '
<div class="marquee-wrap" style="' . $bgStyle . '">
<div class="marquee">
<b class="rnb">' . htmlspecialchars($text, ENT_QUOTES) . '</b>
</div></div>
<style>
.rnb{background:linear-gradient(90deg, red, orange, yellow, green, cyan, blue, purple);
background-size:200% 100%;
-webkit-background-clip:text;
color:transparent;
animation:rainbowAnim 7s linear infinite;}
@keyframes rainbowAnim{0%{background-position:0%}50%{background-position:100%}100%{background-position:0%}}
</style>';
        }

        return $base . '
<div class="marquee-wrap" style="' . $bgStyle . '">
<div class="marquee" style="color:' . htmlspecialchars($color, ENT_QUOTES) . ';">
<b>' . htmlspecialchars($text, ENT_QUOTES) . '</b>
</div></div>';
    }

    private function render(): void
    {
        $data = $this->data;

        $msg = $_SESSION['msg'] ?? '';
        unset($_SESSION['msg']);

        $colors = ["red","orange","yellow","green","cyan","blue","purple","pink","white","black","rainbow","custom"];
        $colorOptions = "";

        foreach ($colors as $c) {
            $sel = ($data['colormode'] === $c || $data['color'] === $c) ? 'selected' : '';
            $colorOptions .= "<option value='$c' $sel>$c</option>";
        }

        include __DIR__ . '/../../styles/admin_tpl/indexAnkuendigung.tpl.html';
    }

    private function validateColor(string $color): string
    {
        if (preg_match('/^#[0-9a-fA-F]{3,6}$/', $color)) {
            return $color;
        }

        $allowed = ["red","orange","yellow","green","cyan","blue","purple","pink","white","black"];
        return in_array(strtolower($color), $allowed, true) ? $color : "";
    }
}