<?php
declare(strict_types=1);

/*
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 AdminBotIndex extends DbConectionMaker
{
    private string $csrfToken = '';

    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
        $langObj = new LangXml();
        $lang = $langObj->getLang()->admin[0]->admin_rooms[0];

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

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

        // Aktionen
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->handlePost($_POST);
        } else {
            $this->showPage();
        }
    }

    private function handlePost(array $post): void
    {
        // CSRF Check (optional hier noch nachrüstbar später)
        $token = $post['csrf_token'] ?? '';
        if (!$token || !hash_equals($this->csrfToken, $token)) {
            die("Ungültiger CSRF Token");
        }

        // Neue Antwort
        if (isset($post["new_answer"])) {
            $this->addAnswer($post["new_answer"]);
        }

        // Bot Toggle
        if (isset($post['toggle_bot'])) {
            $this->toggleBot(isset($post['etchat_bot']));
        }
    }

    private function showPage(): void
    {
        $jsonFile = dirname(__DIR__, 2) . "/cache/bot_answers.json";

        $botAnswers = [];
        if (file_exists($jsonFile)) {
            $decoded = json_decode((string)file_get_contents($jsonFile), true);
            if (is_array($decoded)) {
                $botAnswers = $decoded;
            }
        } else {
            file_put_contents($jsonFile, json_encode([], JSON_PRETTY_PRINT));
        }

        // DELETE (GET bewusst so belassen wie vorher)
        if (isset($_GET["delete"])) {
            $this->deleteAnswer((int)$_GET["delete"], $jsonFile, $botAnswers);
        }

        $botEnabled = (int)($_SESSION['etchat_' . $this->_prefix . 'etchat_bot'] ?? 0);
        $csrfToken = $this->csrfToken;

        include "styles/admin_tpl/indexBot.tpl.html";
    }

    private function addAnswer(string $text): void
    {
        $jsonFile = dirname(__DIR__, 2) . "/cache/bot_answers.json";

        $botAnswers = file_exists($jsonFile)
            ? json_decode((string)file_get_contents($jsonFile), true)
            : [];

        if (!is_array($botAnswers)) {
            $botAnswers = [];
        }

        $new = substr(trim($text), 0, 500);
        if ($new !== "") {
            $botAnswers[] = $new;
            file_put_contents(
                $jsonFile,
                json_encode($botAnswers, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE),
                LOCK_EX
            );
        }

        header("Location: ?AdminBotIndex");
        exit;
    }

    private function toggleBot(bool $enabled): void
    {
        $status = $enabled ? 1 : 0;

        $this->dbObj->sqlSet(
            "UPDATE {$this->_prefix}etchat_config 
             SET etchat_bot = :status 
             WHERE etchat_config_id = 1",
            [':status' => $status]
        );

        $_SESSION['etchat_' . $this->_prefix . 'etchat_bot'] = $status;

        header("Location: ?AdminBotIndex");
        exit;
    }

    private function deleteAnswer(int $index, string $jsonFile, array $botAnswers): void
    {
        if (isset($botAnswers[$index])) {
            unset($botAnswers[$index]);
            $botAnswers = array_values($botAnswers);

            file_put_contents(
                $jsonFile,
                json_encode($botAnswers, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE),
                LOCK_EX
            );
        }

        header("Location: ?AdminBotIndex");
        exit;
    }
}