<?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 OnlinePing extends DbConectionMaker
{
    private ?string $cachedSystemColor = null;
    private ?array $cachedPrivColors   = null;

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

        $this->handlePing();
    }

    private function handlePing(): void
    {
        $userId = (int)($_POST['user_id'] ?? $_GET['user_id'] ?? 0);

        if ($userId <= 0) {
            return;
        }

        $prefix = $this->_prefix;

        // Eigenen Ping aktualisieren
        $this->dbObj->sqlSet("
            UPDATE {$prefix}etchat_useronline
            SET etchat_last_ping = NOW()
            WHERE etchat_onlineuser_fid = {$userId}
        ");

        $this->checkOfflineUsers();
    }

    private function checkOfflineUsers(): void
    {
        $timeout = 60;
        $prefix  = $this->_prefix;

        $offlineUsers = $this->dbObj->sqlGet("
            SELECT
                uo.etchat_onlineuser_fid AS user_id,
                uo.etchat_avatar AS online_avatar,
                u.etchat_username,
                u.etchat_userprivilegien,
                u.etchat_avatar AS user_avatar
            FROM {$prefix}etchat_useronline uo
            JOIN {$prefix}etchat_user u
                ON u.etchat_user_id = uo.etchat_onlineuser_fid
            WHERE TIMESTAMPDIFF(SECOND, uo.etchat_last_ping, NOW()) > {$timeout}
        ");

        if (!$offlineUsers) {
            return;
        }

        // 🔹 Lazy Cache wird hier automatisch aktiv
        $sysColor   = $this->getSystemColor();
        $privColors = $this->getAllPrivColors();

        foreach ($offlineUsers as $u) {

            $name = htmlspecialchars(
                $u['etchat_username'] ?? '',
                ENT_QUOTES | ENT_SUBSTITUTE,
                'UTF-8'
            );

            $priv      = $u['etchat_userprivilegien'] ?? 'user';
            $nameColor = $privColors[$priv] ?? 'color:#fff';

            $avatarFile = $u['online_avatar']
                ?: $u['user_avatar']
                ?: 'noavatar.jpg';

            $avatarPath = 'avatar/' . basename($avatarFile);

            $avatar = sprintf(
                '<img src="%s" class="avatar_w">',
                htmlspecialchars($avatarPath, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
            );

            $msg =
                $avatar .
                '<span style="' . $sysColor . '">' .
                    '<span style="' . $nameColor . '"><b>' . $name . '</b></span>' .
                    ' hat den Tab/Browser geschlossen.' .
                '</span>';

            new SysMessage($this->dbObj, $msg, 0, 0);

            $this->dbObj->sqlSet("
                DELETE FROM {$prefix}etchat_useronline
                WHERE etchat_onlineuser_fid = " . (int)$u['user_id']
            );
        }
    }

    /* ==============================
       🔹 SYSTEMFARBE (mit Cache)
    ============================== */

    private function getSystemColor(): string
    {
        if ($this->cachedSystemColor !== null) {
            return $this->cachedSystemColor;
        }

        $prefix = $this->_prefix;

        $styleData = $this->dbObj->sqlGet("
            SELECT etchat_config_style
            FROM {$prefix}etchat_config
            LIMIT 1
        ");

        $style = $styleData[0]['etchat_config_style'] ?? 'default';

        $stylePath     = "styles/{$style}/";
        $variablesFile = $stylePath . "variables.css";
        $styleFile     = $stylePath . "style.css";

        if (is_file($variablesFile)) {
            $content = file_get_contents($variablesFile);
            if ($content !== false &&
                preg_match('/--\s*Systemfarbe\s*:\s*#?([0-9a-f]{3,6})\s*;/i', $content, $m)) {

                return $this->cachedSystemColor = 'color:#' . strtolower($m[1]);
            }
        }

        if (is_file($styleFile)) {
            foreach (file($styleFile) as $line) {
                if (preg_match('/^Systemfarbe\s*:\s*#?([0-9a-f]{3,6})/i', trim($line), $m)) {
                    return $this->cachedSystemColor = 'color:#' . strtolower($m[1]);
                }
            }
        }

        return $this->cachedSystemColor = 'color:#fff';
    }

    /* ==============================
       🔹 PRIVILEG-FARBEN (mit Cache)
    ============================== */

    private function getAllPrivColors(): array
    {
        if ($this->cachedPrivColors !== null) {
            return $this->cachedPrivColors;
        }

        $prefix = $this->_prefix;

        $cfg = $this->dbObj->sqlGet("
            SELECT
                etchat_config_admin_color,
                etchat_config_mod_color,
                etchat_config_user_color,
                etchat_config_gast_color
            FROM {$prefix}etchat_config
            LIMIT 1
        ");

        if (!$cfg) {
            return $this->cachedPrivColors = [];
        }

        $row = $cfg[0];

        return $this->cachedPrivColors = [
            'admin' => $this->formatColor($row['etchat_config_admin_color'] ?? null),
            'mod'   => $this->formatColor($row['etchat_config_mod_color']   ?? null),
            'user'  => $this->formatColor($row['etchat_config_user_color']  ?? null),
            'gast'  => $this->formatColor($row['etchat_config_gast_color']  ?? null),
        ];
    }

    private function formatColor(?string $color): string
    {
        if (!$color) {
            return 'color:#fff';
        }

        return 'color:#' . ltrim(strtolower($color), '#');
    }
}