<?php

/*
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.
*/

declare(strict_types=1);

class AdminInsertSmiliesCat extends DbConectionMaker
{
    private array $allowedRoles = ["admin", "grafik", "co_admin"];

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

        $langObj = new LangXml();
        $lang = $langObj->getLang()->admin[0]->admin_smilies[0];

        $userRole = $_SESSION['etchat_' . $this->_prefix . 'user_priv'] ?? '';
        if (!in_array($userRole, $this->allowedRoles, true)) {
            echo '<span style="color:red;">' . htmlspecialchars($lang->error[0]->tagData) . '</span>';
            exit;
        }

        // 🔐 CSRF prüfen
        $csrfToken = $_POST['csrf_token'] ?? $_GET['csrf_token'] ?? '';
        $sessionToken = $_SESSION['etchat_' . $this->_prefix . 'csrf_token'] ?? '';

        if (empty($csrfToken) || empty($sessionToken) || !hash_equals($sessionToken, $csrfToken)) {
            echo '<span style="color:red;">Ungültiger CSRF-Token.</span>';
            exit;
        }
        unset($_SESSION['etchat_' . $this->_prefix . 'csrf_token']);

        // 🔹 Name säubern, Umlaute & ß erlaubt, andere Sonderzeichen entfernen
        $name = trim((string)($_POST['name'] ?? ''));
        $name = preg_replace('/[^a-zA-Z0-9 _\-\x{00C0}-\x{017F}]/u', '', $name);

        $onOff = ($_POST['on_off'] ?? '') === 'on' ? 'on' : 'off';
        $gw = (int)($_POST['gw'] ?? 0);

        if ($name === '') {
            echo '<span style="color:red;">Name darf nicht leer sein.</span>';
            echo "<br><a href='./?AdminCreateNewSmiliesCat'>" . htmlspecialchars($lang->back[0]->tagData) . "</a>";
            return;
        }

        $this->handleInsert($name, $onOff, $gw, $lang);
    }

    private function handleInsert(string $name, string $onOff, int $gw, object $lang): void
    {
        // Prüfen, ob Name existiert
        $res = $this->dbObj->sqlGet(
            "SELECT id FROM {$this->_prefix}etchat_smileys_cat WHERE name = ?",
            [$name]
        );

        if (!empty($res)) {
            $print_result  = '<span style="color:red;">' . htmlspecialchars($lang->name_exists[0]->tagData) . '</span><br>';
            $print_result .= "<a href='./?AdminCreateNewSmiliesCat'>" . htmlspecialchars($lang->back[0]->tagData) . "</a>";
        } else {
            // Insert in DB
            $this->dbObj->sqlSet(
                "INSERT INTO {$this->_prefix}etchat_smileys_cat (`name`, `aktiv`, `gewicht`) VALUES (?, ?, ?)",
                [$name, $onOff, $gw]
            );

            $print_result  = '<span style="color:green;">' . htmlspecialchars($lang->isupload1[0]->tagData) . '</span><br>';
            $print_result .= "<br><a href='./?AdminCreateNewSmiliesCat'>" . htmlspecialchars($lang->cat[3]->tagData) . "</a>";
        }

        include_once "styles/admin_tpl/insertSmiliesCatMessage.tpl.html";
    }
}