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

class AdminLoginVerbotendeUserNamen extends DbConectionMaker
{
    private $message = '';
    private $wordsFile = 'cache/verbotene_user_namen.json';
    
    public function __construct()
    {
        parent::__construct();

        if (session_id() == '') {
            session_start();
        }
		
        header('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0');
        header('content-type: text/html; charset=utf-8');

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

        // Admin-Prüfung
        if ($_SESSION['etchat_' . $this->_prefix . 'user_priv'] != "admin") {
            echo "Zugriff verweigert.";
            return false;
        }
		
        // Wenn AJAX Request (für GET der Wortliste)
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
            if ($_SERVER['REQUEST_METHOD'] === 'GET') {
                header('Content-Type: application/json');
                $current_words = $this->loadWords();
                $words_array = explode("\n", $current_words);
                $words_array = array_filter($words_array, function($w) { return trim($w) !== ''; });
                echo json_encode(['words' => array_values($words_array)]);
                exit;
            }
        }		

        // Wörter laden für die Anzeige
        $current_words = $this->loadWords();
        
        // POST: Einzelnes Wort hinzufügen (per AJAX)
        if (isset($_POST['add_single_word'])) {
            $this->addSingleWord($_POST['new_word'] ?? '');
            exit;
        }
        
        // POST: Einzelnes Wort löschen (per AJAX)
        if (isset($_POST['delete_single_word'])) {
            $this->deleteSingleWord($_POST['delete_word'] ?? '');
            exit;
        }

        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
        $chat_url = $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
        $chat_url = rtrim($chat_url, '/\\') . '/';

        $this->initTemplate($lang, $chat_url, $current_words);
    }
    
    private function loadWords()
    {
        if (file_exists($this->wordsFile)) {
            $content = file_get_contents($this->wordsFile);
            $words = json_decode($content, true);
            if (is_array($words)) {
                return implode("\n", $words);
            }
        }
        // Standard-Wörter, falls Datei nicht existiert
        $defaultWords = ["@","adolf","arsch","fick","geil","göbbels","hitler","homo","hure","kack","moderator","nazi","scheiß","wixer","www","xxx"];
        return implode("\n", $defaultWords);
    }
    
    private function addSingleWord($new_word)
    {
        $new_word = trim(strtolower($new_word));
        if (empty($new_word)) {
            echo json_encode(['success' => false, 'error' => 'Wort ist leer']);
            return;
        }
        
        $current_words = [];
        if (file_exists($this->wordsFile)) {
            $current_words = json_decode(file_get_contents($this->wordsFile), true);
            if (!is_array($current_words)) $current_words = [];
        }
        
        if (!in_array($new_word, $current_words)) {
            $current_words[] = $new_word;
            sort($current_words);
            file_put_contents($this->wordsFile, json_encode($current_words, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
            echo json_encode(['success' => true, 'words' => $current_words]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Wort existiert bereits']);
        }
    }
    
    private function deleteSingleWord($delete_word)
    {
        $delete_word = trim(strtolower($delete_word));
        if (empty($delete_word)) {
            echo json_encode(['success' => false, 'error' => 'Kein Wort zum Löschen']);
            return;
        }
        
        $current_words = [];
        if (file_exists($this->wordsFile)) {
            $current_words = json_decode(file_get_contents($this->wordsFile), true);
            if (!is_array($current_words)) $current_words = [];
        }
        
        $key = array_search($delete_word, $current_words);
        if ($key !== false) {
            array_splice($current_words, $key, 1);
            sort($current_words);
            file_put_contents($this->wordsFile, json_encode($current_words, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
            echo json_encode(['success' => true, 'words' => $current_words]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Wort nicht gefunden']);
        }
    }

    private function initTemplate($lang, $chat_url, $current_words)
    {
        $message = $this->message;
        include_once("styles/admin_tpl/indexLoginVerbotendeUserNamen.tpl.html");
    }
}
?>