<?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 AdminUpdateUser extends DbConectionMaker
{
    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');

        // Sprache sicher laden
        $langObj = new LangXml();
        $langData = $langObj->getLang();

        $lang = $langData->admin[0]->admin_user[0] ?? (object)[
            'error' => [(object)['tagData' => 'Fehler']]
        ];

        // Prototype-unabhängig
        $req = array_merge($_GET, $_POST);

        $role   = (string)($_SESSION['etchat_' . $this->_prefix . 'user_priv'] ?? '');
        $userId = (int)($req['id'] ?? 0);
        $token  = (string)($req['csrf_token'] ?? '');

        // 🔐 CSRF prüfen
        if ($token === '' || !$this->isValidCsrfToken($token)) {
            $this->showError(($lang->error[0]->tagData ?? 'Fehler') . ' (CSRF)', "./");
            exit;
        }

        // 🔐 Zugriff prüfen
        if (!in_array($role, ["admin", "chatwache", "co_admin"], true) || $userId <= 0) {
            $this->showError($lang->error[0]->tagData ?? 'Fehler', "./");
            exit;
        }

        // Eingaben
        $username = trim((string)($req['user'] ?? ''));
        $priv     = trim((string)($req['priv'] ?? ''));
        $email    = trim((string)($req['mail'] ?? ''));
        $password = trim((string)($req['pw'] ?? ''));

        if ($username === '' || $priv === '') {
            $this->showError("Pflichtfelder fehlen.", "./?AdminUserIndex");
            exit;
        }

        // 🔐 letzter Admin darf nicht entfernt werden
        if ($priv !== "admin") {
            $res = $this->dbObj->sqlGet(
                "SELECT COUNT(etchat_user_id) as cnt
                 FROM {$this->_prefix}etchat_user
                 WHERE etchat_user_id <> :id
                   AND etchat_userprivilegien = 'admin'",
                [':id' => $userId]
            );

            if (!$res || (int)$res[0]['cnt'] === 0) {
                $this->showError("Not possible. There will be no administrators in chat.", "./?AdminUserIndex");
                exit;
            }
        }

        // 🔐 Username prüfen
        $res_dop = $this->dbObj->sqlGet(
            "SELECT COUNT(etchat_user_id) as cnt
             FROM {$this->_prefix}etchat_user
             WHERE etchat_username = :username
               AND etchat_userprivilegien <> 'gast'
               AND etchat_user_id <> :id",
            [
                ':username' => $username,
                ':id'       => $userId
            ]
        );

        if ($res_dop && (int)$res_dop[0]['cnt'] > 0) {
            $this->showError("Ein User mit diesem Namen existiert schon.", "./?AdminUserIndex");
            exit;
        }

        // Update vorbereiten
        $setParts = [
            "etchat_username = :username",
            "etchat_userprivilegien = :priv",
            "etchat_email = :email"
        ];

        $params = [
            ':username' => $username,
            ':priv'     => $priv,
            ':email'    => $email,
            ':id'       => $userId
        ];

        if ($password !== '') {
            $setParts[] = "etchat_userpw = :pw";
            $params[':pw'] = password_hash($password, PASSWORD_DEFAULT);
        }

        $sql = "UPDATE {$this->_prefix}etchat_user 
                SET " . implode(", ", $setParts) . " 
                WHERE etchat_user_id = :id";

        $this->dbObj->sqlSet($sql, $params);
        $this->dbObj->close();

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

    private function isValidCsrfToken(string $token): bool
    {
        $key = 'etchat_' . $this->_prefix . 'csrf_token';
        return isset($_SESSION[$key]) && hash_equals($_SESSION[$key], $token);
    }

    private function showError(string $message, string $backLink): void
    {
        $msg   = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');

        ?>
        <!DOCTYPE html>
        <html lang="de">
        <head>
            <meta charset="UTF-8">
            <title>Adminbereich</title>
            <link href="styles/admin_tpl/admin.css" rel="stylesheet">
        </head>
        <body id="adminbereich_body">

        <a href="./?AdminIndex">&lt;&lt;&lt; zurück zum Adminmenü</a>
        <hr>

        <div class="error">
            <?php echo $msg; ?><br><br>
            <a href="<?php echo htmlspecialchars($backLink, ENT_QUOTES, 'UTF-8'); ?>">Zurück</a>
        </div>

        </body>
        </html>
        <?php
        exit;
    }
}