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

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

        if (!headers_sent()) {
            header('Cache-Control: no-store, no-cache, must-revalidate');
            header('Pragma: no-cache');
        }

        $username   = $_SESSION['etchat_' . $this->_prefix . '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';
        $chatPic    = $_SESSION['etchat_' . $this->_prefix . 'chat_pic'] ?? '0';

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

        $userColor = $this->getUserColor($userPriv);

        if (!empty($username) && $userStatus !== "status_invisible") {

            $usernameStyled = '<span style="' . $userColor . '"><b>'
                . htmlspecialchars($username, ENT_QUOTES, 'UTF-8')
                . '</b></span>';

            if ($chatPic === '1') {
                $avatarHTML = $this->getUserAvatarHTML($username);
                $message = $avatarHTML . $usernameStyled . " " . $lang->exit[0]->tagData;
            } else {
                $message = $usernameStyled . " " . $lang->exit[0]->tagData;
            }

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

        // Online-Zeit speichern (PDO Prepared)
        if ($userId > 0) {

            $sql = "
                SELECT etchat_logintime, etchat_onlinetime
                FROM {$this->_prefix}etchat_user
                WHERE etchat_user_id = :uid
                LIMIT 1
            ";

            $row = $this->dbObj->sqlGet($sql, [':uid' => $userId]);

            if (!empty($row)) {

                $loginTime   = (int)$row[0]['etchat_logintime'];
                $onlineTotal = (int)$row[0]['etchat_onlinetime'];

                $sessionTime   = max(0, time() - $loginTime);
                $creditedTime  = floor($sessionTime / 600) * 600;

                if ($creditedTime > 0) {

                    $newOnlineTime = $onlineTotal + $creditedTime;

                    $update = "
                        UPDATE {$this->_prefix}etchat_user
                        SET etchat_onlinetime = :ontime
                        WHERE etchat_user_id = :uid
                    ";

                    $this->dbObj->sqlSet($update, [
                        ':ontime' => $newOnlineTime,
                        ':uid'    => $userId
                    ]);
                }
            }
        }

        // Aus Online-Liste löschen (PDO)
        $delete = "
            DELETE FROM {$this->_prefix}etchat_useronline
            WHERE etchat_onlineuser_fid = :uid
        ";

        $this->dbObj->sqlSet($delete, [':uid' => $userId]);

        $redirectURL = $_SESSION['etchat_' . $this->_prefix . 'logout_url'] ?? './';

        $_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();

        if (!headers_sent()) {
            header("Location: " . $redirectURL);
        }

        exit;
    }

    private function getUserAvatarHTML(string $username): string
    {
        $sql = "
            SELECT etchat_avatar
            FROM {$this->_prefix}etchat_user
            WHERE etchat_username = :name
            LIMIT 1
        ";

        $row = $this->dbObj->sqlGet($sql, [':name' => $username]);

        $avatarFile = $row[0]['etchat_avatar'] ?? 'noavatar.png';

        return '<img src="avatar/' . htmlspecialchars($avatarFile, ENT_QUOTES, 'UTF-8') . '" class="avatar_w" alt="">';
    }

    private function getUserColor(string $priv): string
    {
        $prefix = 'etchat_' . $this->_prefix;

        return match ($priv) {
            'admin', 'grafik', 'chatwache', 'co_admin'
                => "color: " . ($_SESSION[$prefix . 'admin_color'] ?? '#FFFFFF'),
            'mod'
                => "color: " . ($_SESSION[$prefix . 'mod_color'] ?? '#FFFFFF'),
            'user'
                => "color: " . ($_SESSION[$prefix . 'user_color'] ?? '#FFFFFF'),
            'gast'
                => "color: " . ($_SESSION[$prefix . 'gast_color'] ?? '#FFFFFF'),
            default
                => "color: #FFFFFF",
        };
    }
}