<?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 AdminHalloAnreden extends DbConectionMaker
{
    private const ALLOWED_ROLES = ['admin', 'co_admin'];
    private const TYPES = ['hallo', 'bye'];

    private string $txtFile;
    private array $desei = [];
    private string $meldung = '';
    private string $csrfToken = '';

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

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

        $this->checkAccess();
        $this->loadStyle();

        $typ = $this->validateType($_REQUEST['typ'] ?? 'hallo');
        $this->txtFile = $this->resolveFile($typ);

        // CSRF
        $this->csrfToken = $this->generateCsrfToken();

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

        $this->showPage($typ);
    }

    private function getCsrfKey(): string
    {
        return 'etchat_' . $this->_prefix . 'csrf_token';
    }

    private function checkAccess(): void
    {
        $role = $_SESSION['etchat_' . $this->_prefix . 'user_priv'] ?? '';

        if (!in_array($role, self::ALLOWED_ROLES, true)) {
            header('Location: ./');
            exit;
        }
    }

    private function loadStyle(): void
    {
        $result = $this->dbObj->sqlGet(
            "SELECT etchat_config_style FROM {$this->_prefix}etchat_config WHERE etchat_config_id = ?",
            [1]
        );

        if (is_array($result)) {
            $this->desei = $result;
        }
    }

    private function validateType(string $typ): string
    {
        return in_array($typ, self::TYPES, true) ? $typ : 'hallo';
    }

    private function resolveFile(string $typ): string
    {
        return __DIR__ . '/../../cache/' . ($typ === 'hallo'
            ? 'anreden.txt'
            : 'verabschieden.txt');
    }

    private function generateCsrfToken(): string
    {
        $key = $this->getCsrfKey();

        if (empty($_SESSION[$key])) {
            $_SESSION[$key] = bin2hex(random_bytes(16));
        }

        return $_SESSION[$key];
    }

    private function handlePost(): void
    {
        $key = $this->getCsrfKey();

        $sessionToken = $_SESSION[$key] ?? '';
        $postToken = $_POST['csrf_token'] ?? '';

        if (!$sessionToken || !$postToken || !hash_equals($sessionToken, (string)$postToken)) {
            $this->meldung = '<div class="error">Ungültiger CSRF Token!</div>';
            return;
        }

        if (isset($_POST['anreden'])) {
            $this->speichereAnreden((string)$_POST['anreden']);
        }
    }

    private function ladeAnreden(): array
    {
        if (!is_file($this->txtFile)) {
            return [];
        }

        $lines = file($this->txtFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        return array_map('trim', $lines ?: []);
    }

    private function speichereAnreden(string $inhalt): void
    {
        $lines = array_filter(
            array_map('trim', explode("\n", $inhalt)),
            fn(string $line) => $line !== ''
        );

        file_put_contents(
            $this->txtFile,
            implode(PHP_EOL, $lines),
            LOCK_EX
        );

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

    private function showPage(string $typ): void
    {
        $anreden = $this->ladeAnreden();

        $inhalt = implode("\n", $anreden);
        $titel = $typ === 'hallo' ? 'Hallo-Anreden' : 'Verabschiedungen';

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

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