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

        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Pragma: no-cache');

        $this->handleOffline();
    }

    private function handleOffline(): void
    {
        $username   = $_SESSION['etchat_' . $this->_prefix . 'username'] ?? ($_POST['fallback_username'] ?? '');
        $userId     = (int)($_SESSION['etchat_' . $this->_prefix . 'user_id'] ?? 0);
        $userPriv   = $_SESSION['etchat_' . $this->_prefix . 'user_priv'] ?? 'user';
        $userStatus = $_SESSION['etchat_' . $this->_prefix . 'userstatus'] ?? 'status_online';
        $showAvatar = $_SESSION['etchat_' . $this->_prefix . 'chat_pic'] ?? '1';

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

        if ($userStatus !== "status_invisible") {
            $color = $this->getUserColor($userPriv);

            $usernameStyled = sprintf(
                '<span style="%s"><b>%s</b></span>',
                $color,
                htmlspecialchars($username, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')
            );

            $message = ($showAvatar === '1' ? $this->getUserAvatarHTML($username) : '')
                     . $usernameStyled
                     . " hat den Tab/Browser geschlossen.";

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

        $this->removeUserFromOnlineList($userId);
        $this->destroySession();
    }

    private function getUserAvatarHTML(string $username): string
    {
        $usernameSafe = $this->dbObj->escape($username); // falls escape-Methode existiert

        $sql = "SELECT etchat_avatar 
                FROM {$this->_prefix}etchat_user 
                WHERE etchat_username = '{$usernameSafe}'
                LIMIT 1";

        $result = $this->dbObj->sqlGet($sql);

        $avatarFilename = $result[0][0] ?? 'default.png';

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

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

    private function getUserColor(string $priv): string
    {
        $colorKey = match ($priv) {
            'admin', 'grafik', 'chatwache', 'co_admin' => 'admin_color',
            'mod'   => 'mod_color',
            'gast'  => 'gast_color',
            default => 'user_color',
        };

        $color = $_SESSION['etchat_' . $this->_prefix . $colorKey] ?? '#FFFFFF';

        return 'color: ' . htmlspecialchars($color, ENT_QUOTES, 'UTF-8');
    }

    private function removeUserFromOnlineList(int $userId): void
    {
        $sql = "DELETE FROM {$this->_prefix}etchat_useronline 
                WHERE etchat_onlineuser_fid = {$userId}";

        $this->dbObj->sqlSet($sql);
    }

    private function destroySession(): void
    {
        $_SESSION = [];

        if (ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(
                session_name(),
                '',
                time() - 42000,
                $params["path"],
                $params["domain"],
                $params["secure"],
                $params["httponly"]
            );
        }

        session_destroy();
    }
}