<?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 Wuerfel extends DbConectionMaker
{
    public function __construct()
    {
        parent::__construct();

        // Nur AJAX POST
        if (
            $_SERVER['REQUEST_METHOD'] !== 'POST' ||
            empty($_SERVER['HTTP_X_REQUESTED_WITH']) ||
            strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest'
        ) {
            $this->forbidden();
        }

        session_start();

        // User muss eingeloggt sein
        $username = $_SESSION['etchat_' . $this->_prefix . 'username'] ?? '';
        if (
            empty($_SESSION['etchat_' . $this->_prefix . 'user_id']) ||
            empty($username)
        ) {
            $this->forbidden();
        }

        // Room validieren
        $roomId = (int) ($_POST['room'] ?? 0);
        if ($roomId <= 0) {
            $this->forbidden();
        }

        header('Content-Type: application/json; charset=utf-8');

        // User sicher laden (Prepared)
        $user = $this->dbObj->sqlGet(
            "SELECT etchat_user_id FROM {$this->_prefix}etchat_user WHERE etchat_username = ? LIMIT 1",
            [$username]
        );

        if (!$user || !isset($user[0][0])) {
            $this->forbidden();
        }

        $userId = (int) $user[0][0];

        // Config: Würfel-Max
        $config = $this->dbObj->sqlGet(
            "SELECT * FROM {$this->_prefix}etchat_config WHERE etchat_config_id = '1'"
        );

        $max = ($config && isset($config[0][8])) ? (int) $config[0][8] : 6;

        try {
            $wurf = random_int(1, max(1, $max));
        } catch (Exception $e) {
            $wurf = 1;
        }

        // Systemfarbe
        $sysColor = $_SESSION['etchat_' . $this->_prefix . 'syscolor'] ?? 'FFFFFF';
        $sysColor = preg_replace('/[^a-fA-F0-9]/', '', $sysColor);

        // Nachricht
        $message =
            '<img src=img/redwuerfel.png width=16 height=16>' .
            '<img src=img/redwuerfel.png width=16 height=16>' .
            '<img src=img/redwuerfel.png width=16 height=16>' .
            '&nbsp; würfelt eine ' . $wurf . ' &nbsp;' .
            '<img src=img/redwuerfel.png width=16 height=16>' .
            '<img src=img/redwuerfel.png width=16 height=16>' .
            '<img src=img/redwuerfel.png width=16 height=16>';

        $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

        // Message speichern (Prepared)
        $this->dbObj->sqlSet(
            "INSERT INTO {$this->_prefix}etchat_messages
             (etchat_user_fid, etchat_text, etchat_text_css, etchat_timestamp,
              etchat_fid_room, etchat_privat, etchat_user_ip)
             VALUES (?, ?, ?, ?, ?, 0, ?)",
            [
                $userId,
                $message,
                "color:#{$sysColor};font-weight:bold;",
                time(),
                $roomId,
                $ip
            ]
        );

        echo json_encode([
            'status' => 'ok',
            'wurf'   => $wurf
        ]);

        exit;
    }

    private function forbidden()
    {
        http_response_code(403);
        echo json_encode(['status' => 'error']);
        exit;
    }
}