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

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

        // -------------------------
        // Session starten
        // -------------------------
        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 laden
        // -------------------------
        $langObj = new LangXml();
        $lang = $langObj->getLang()->admin[0]->admin_blacklist[0];

        // -------------------------
        // Rollen prüfen
        // -------------------------
        $userPriv = $_SESSION["etchat_" . $this->_prefix . "user_priv"] ?? '';
        $allowedRoles = ["admin", "grafik", "chatwache", "co_admin"];
        if (!in_array($userPriv, $allowedRoles, true)) {
            echo $lang->error[0]->tagData ?? 'Zugriff verweigert';
            return;
        }

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

        // -------------------------
        // Formularverarbeitung
        // -------------------------
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['manual_blacklist_submit'])) {
            $this->handleForm();
        }

        // -------------------------
        // Alte Blacklist-Einträge löschen
        // -------------------------
        $this->dbObj->sqlSet(
            "DELETE FROM {$this->_prefix}etchat_blacklist 
             WHERE etchat_blacklist_time < :time",
            [':time' => time()]
        );

        // -------------------------
        // Blacklist laden
        // -------------------------
        $feld = $this->dbObj->sqlGet("
            SELECT
                b.etchat_blacklist_ip,
                b.etchat_blacklist_id,
                IFNULL(u.etchat_username, 'Gelöschter Benutzer') AS etchat_username,
                IFNULL(u.etchat_userprivilegien, '-') AS etchat_userprivilegien,
                b.etchat_blacklist_time
            FROM
                {$this->_prefix}etchat_blacklist b
            LEFT JOIN
                {$this->_prefix}etchat_user u
            ON
                b.etchat_blacklist_userid = u.etchat_user_id
        ");
		
		// ⚠️ Sicherstellen, dass immer ein Array übergeben wird
		if (!is_array($feld)) {
			$feld = [];
		}

        $this->dbObj->close();

        $this->initTemplate($lang, $feld);
    }

    private function handleForm(): void
    {
        $ip = substr(trim($_POST['ip'] ?? ''), 0, 40);
        $userID = (int)($_POST['user_id'] ?? 0);
        $duration = max(0, (int)($_POST['duration'] ?? 0));

        if ($ip === '' || $userID <= 0) {
            $this->message = "<p style='color: red;'>Bitte IP und UserID korrekt angeben.</p>";
            return;
        }

        $time_to_hold = $duration > 0 ? time() + $duration : 0;

        if ($duration > 0) {
            // Benutzer sperren
            $this->dbObj->sqlSet(
                "INSERT INTO {$this->_prefix}etchat_blacklist
                 (etchat_blacklist_ip, etchat_blacklist_userid, etchat_blacklist_time)
                 VALUES (:ip, :userid, :time)",
                [
                    ':ip' => $ip,
                    ':userid' => $userID,
                    ':time' => $time_to_hold
                ]
            );
            $this->message = "<p style='color: green;'>Benutzer wurde erfolgreich gebannt.</p>";
        } else {
            // Benutzer nur kicken
            $this->dbObj->sqlSet(
                "DELETE FROM {$this->_prefix}etchat_useronline 
                 WHERE etchat_onlineuser_fid = :userid",
                [
                    ':userid' => $userID
                ]
            );
            $this->message = "<p style='color: orange;'>Benutzer wurde gekickt.</p>";
        }
    }

    private function initTemplate(object $lang, array $feld): void
    {
        include_once("styles/admin_tpl/indexBlacklist.tpl.html");
    }

    public function getMessage(): string
    {
        return $this->message;
    }
}