<?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 AdminUserIndex extends DbConectionMaker
{
    private string $csrfToken = '';

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

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

        // Header setzen
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Content-Type: text/html; charset=utf-8');

        $lang = $this->loadLang();

        // 🔐 Zugriff prüfen
        $allowedRoles = ["admin", "co_admin", "chatwache"];
        $userRole = (string)($_SESSION['etchat_'.$this->_prefix.'user_priv'] ?? '');
        if (!in_array($userRole, $allowedRoles, true)) {
            header("Location: ./");
            exit;
        }

        // 🔐 CSRF Token initialisieren
        $csrfKey = 'etchat_' . $this->_prefix . 'csrf_token';
        if (empty($_SESSION[$csrfKey])) {
            $_SESSION[$csrfKey] = bin2hex(random_bytes(16));
        }
        $this->csrfToken = (string)$_SESSION[$csrfKey];

        // Rollenliste absichern
        $roles = ["admin", "mod", "grafik", "chatwache", "co_admin"];
        $rolesList = "'" . implode("','", $roles) . "'";

        // Sortierung absichern
        $sort = filter_input(INPUT_GET, 'sort', FILTER_SANITIZE_SPECIAL_CHARS) ?? 'username';
        $orderBy = match($sort) {
            'reg'   => "etchat_reg_timestamp DESC",
            'login' => "(etchat_logintime = 0), etchat_logintime DESC",
            default => "etchat_username ASC",
        };

        // Nutzer laden
        $users = $this->dbObj->sqlGet("
            SELECT 
                etchat_user_id,
                etchat_username,
                etchat_userprivilegien,
                etchat_reg_timestamp,
                etchat_reg_ip,
                etchat_logintime,
                etchat_avatar,
                etchat_email,
                etchat_last_ip
            FROM {$this->_prefix}etchat_user
            WHERE etchat_userprivilegien IN ($rolesList)
            ORDER BY $orderBy
        ");

		$userCount = count($users ?? []);

        $this->dbObj->close();

        $userListHtml = $this->buildTable($users ?? [], $lang);

        $this->initTemplate($lang, $userListHtml, $userCount);
    }

    private function loadLang(): object
    {
        $langObj = new LangXml();
        $langData = $langObj->getLang();
        return $langData->admin[0]->admin_user[0] ?? (object)[
            'error' => [(object)['tagData' => 'Sprachdatei unvollständig.']]
        ];
    }

    private function buildTable(array $users, object $lang): string
    {
        $currentSort = filter_input(INPUT_GET, 'sort', FILTER_SANITIZE_SPECIAL_CHARS) ?? 'username';

        $html = '<form method="get" class="user-form">
                    <input type="hidden" name="AdminUserIndex" value="">
                    <label for="sort">Sortieren nach: </label>
                    <select name="sort" id="sort" onchange="this.form.submit()">
                        <option value="username"' . ($currentSort === 'username' ? ' selected' : '') . '>Username</option>
                        <option value="reg"' . ($currentSort === 'reg' ? ' selected' : '') . '>Registrierungsdatum</option>
                        <option value="login"' . ($currentSort === 'login' ? ' selected' : '') . '>Letzter Login</option>
                    </select>
                 </form><br>';

        if (empty($users)) {
            return $html . ($lang->noadmins[0]->tagData ?? 'Keine Nutzer gefunden.');
        }

        $html .= "<table border='1' cellpadding='5' cellspacing='0'>
                    <tr>
                        <th>".($lang->name[0]->tagData ?? 'Username')."</th>
                        <th>".($lang->status[0]->tagData ?? 'Privilegien')."</th>
                        <th>".($lang->reg_date[0]->tagData ?? 'Reg. Datum')."</th>
                        <th>".($lang->reg_ip[0]->tagData ?? 'IP während Reg.')."</th>
                        <th>".($lang->login[0]->tagData ?? 'Letzter Login')."</th>
                        <th>Letzte IP</th>
                        <th>E-Mail</th>
                        <th>Avatar</th>
                    </tr>";

        foreach ($users as $u) {
            $id       = (int)($u['etchat_user_id'] ?? 0);
            $username = htmlspecialchars((string)($u['etchat_username'] ?? ''), ENT_QUOTES, 'UTF-8');
            $priv     = htmlspecialchars((string)($u['etchat_userprivilegien'] ?? ''), ENT_QUOTES, 'UTF-8');
            $regTs    = htmlspecialchars((string)($u['etchat_reg_timestamp'] ?? ''), ENT_QUOTES, 'UTF-8');
            $regIp    = htmlspecialchars((string)($u['etchat_reg_ip'] ?? ''), ENT_QUOTES, 'UTF-8');
            $loginTs  = (int)($u['etchat_logintime'] ?? 0);
            $avatar   = htmlspecialchars((string)($u['etchat_avatar'] ?? ''), ENT_QUOTES, 'UTF-8');
            $email    = htmlspecialchars((string)($u['etchat_email'] ?? ''), ENT_QUOTES, 'UTF-8');
            $lastIp   = htmlspecialchars((string)($u['etchat_last_ip'] ?? ''), ENT_QUOTES, 'UTF-8');

            $loginDate = $loginTs ? date("d.m.Y H:i", $loginTs) : '-';

            $html .= "<tr>
                        <td><b><a href=\"./?AdminEditUser&id={$id}&csrf={$this->csrfToken}\">{$username}</a></b></td>
                        <td>(<i>{$priv}</i>)</td>
                        <td>{$regTs}</td>
                        <td>{$regIp}</td>
                        <td>{$loginDate}</td>
                        <td>{$lastIp}</td>
                        <td><a href=\"mailto:{$email}\">{$email}</a></td>
                        <td>
                            <a href=\"./?AdminDeleteAvatar&delavatar&id={$id}&csrf_token={$this->csrfToken}\" 
                            onclick=\"return confirm('Bist du sicher, dass du diesen Avatar wirklich löschen möchtest?')\">
                            Lösche Avatar</a>&nbsp; 
                            <img class=\"avatar_list_admin\" src=\"avatar/{$avatar}\" width=\"16\" height=\"16\">
                        </td>
                    </tr>";
        }

        $html .= "</table>";

        return $html;
    }

    private function initTemplate(object $lang, string $userListHtml, int $userCount): void
    {
        include_once __DIR__ . "/../../styles/admin_tpl/indexUser.tpl.html";
    }
}