<?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 AdminInsertUser extends DbConectionMaker
{
    private array $allowedRoles = ["admin", "co_admin", "chatwache"];

    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_user[0] ?? (object)[];

        // -------------------------
        // Rolle prüfen
        // -------------------------
        $role = isset($_SESSION["etchat_" . $this->_prefix . "user_priv"])
			? (string) $_SESSION["etchat_" . $this->_prefix . "user_priv"]
			: '';
			
        if (!in_array($role, $this->allowedRoles, true)) {
            $this->showError($lang->error[0]->tagData ?? 'Keine Berechtigung', "./?AdminIndex");
            return;
        }

        // -------------------------
        // CSRF Token prüfen (POST)
        // -------------------------
        $csrfKey = 'etchat_' . $this->_prefix . 'csrf_token';
        $csrfTokenSession = $_SESSION[$csrfKey] ?? '';
        $csrfTokenPost = $_POST['csrf_token'] ?? '';

        if (empty($csrfTokenPost) || !hash_equals($csrfTokenSession, $csrfTokenPost)) {
            $this->showError("Ungültiger CSRF-Token.", "./?AdminCreateNewUser");
            return;
        }
		
		unset($_SESSION[$csrfKey]);

        // -------------------------
        // Eingaben (POST) validieren
        // -------------------------
        $user  = trim($_POST['user'] ?? '');
        $priv  = trim($_POST['priv'] ?? '');
        $mail  = trim($_POST['mail'] ?? '');
        $pwRaw = trim($_POST['pw'] ?? '');

        if (strlen($user) < 3 || strlen($user) > 50) {
            $this->showError("Username muss zwischen 3 und 50 Zeichen lang sein.", "./?AdminCreateNewUser");
            return;
        }

        $validPrivs = ["admin","mod","user","grafik","chatwache","co_admin"];
        if (!in_array($priv, $validPrivs, true)) {
            $this->showError("Ungültige Benutzerrolle.", "./?AdminCreateNewUser");
            return;
        }

        if (!empty($mail) && !filter_var($mail, FILTER_VALIDATE_EMAIL)) {
            $this->showError("Ungültige E-Mail-Adresse.", "./?AdminCreateNewUser");
            return;
        }

        // -------------------------
        // Existenz prüfen
        // -------------------------
        $res = $this->dbObj->sqlGet(
            "SELECT etchat_user_id FROM {$this->_prefix}etchat_user WHERE etchat_username = ?",
            [$user]
        );

        if (!empty($res)) {
            $this->showError("Benutzer mit diesem Namen existiert bereits.", "./?AdminCreateNewUser");
            return;
        }

        // Passwort hashen
        $pwHash = $pwRaw !== '' ? password_hash($pwRaw, PASSWORD_DEFAULT) : null;

        // Insert
        $this->dbObj->sqlSet(
            "INSERT INTO {$this->_prefix}etchat_user
            (etchat_username, etchat_userpw, etchat_userprivilegien, etchat_reg_timestamp, etchat_email)
            VALUES (?, ?, ?, ?, ?)",
            [$user, $pwHash, $priv, date("Y-m-d H:i:s"), $mail]
        );

        $this->dbObj->close();

        header("Location: ./?AdminIndex");
        exit;
    }

    private function showError(string $message, string $backLink)
    {
        ?>
        <!DOCTYPE html>
        <html lang="de">
        <head>
            <meta charset="UTF-8">
            <title>Adminbereich</title>
            <link href="styles/admin_tpl/admin.css" rel="stylesheet" type="text/css"/>
        </head>
        <body id="adminbereich_body">
            <a href="./?AdminIndex">&lt;&lt;&lt; zurück zum Adminmenü</a><hr>
            <div class="error" style="color: red;">
                <?php echo htmlspecialchars($message); ?><br><br>
                <a href="<?php echo htmlspecialchars($backLink); ?>">Zurück</a>
            </div>
        </body>
        </html>
        <?php
    }
}