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

        $this->handleStatusRestore();
        $this->sendHeaders();
        $this->processReloadSequence();

        $feld = $this->dbObj->sqlGet(
            "SELECT
                etchat_user_online_user_name,
                etchat_user_online_room_name,
                etchat_fid_room,
                etchat_onlineuser_fid,
                etchat_onlineip,
                etchat_user_online_user_priv,
                etchat_user_online_room_goup,
                etchat_user_online_user_sex,
                etchat_user_online_user_status_img,
                etchat_user_online_user_status_text,
                etchat_avatar
             FROM {$this->_prefix}etchat_useronline
             ORDER BY etchat_fid_room, etchat_user_online_user_name"
        );

        $roomarray = $this->dbObj->sqlGet(
            "SELECT etchat_id_room, etchat_roomname, etchat_room_goup
             FROM {$this->_prefix}etchat_rooms
             WHERE etchat_id_room NOT IN (
                 SELECT DISTINCT etchat_fid_room FROM {$this->_prefix}etchat_useronline
             )"
        );

        if (!$feld) {
            $this->makeJsonOutput([], $roomarray);
        } else {
            if (!$this->anyChangesSinceLastPolling($feld, $roomarray)) {
                $this->dbObj->close();
            } else {
                $this->makeJsonOutput($feld, $roomarray);
            }
        }
    }


    private function handleStatusRestore(): void
    {
        if (!isset($_SESSION['etchat_'.$this->_prefix.'user_id'])) {
            return;
        }

        $userID = (int)$_SESSION['etchat_'.$this->_prefix.'user_id'];

        $result = $this->dbObj->sqlGet(
            "SELECT etchat_user_online_user_status_img,
                    etchat_user_online_user_status_text
             FROM {$this->_prefix}etchat_useronline
             WHERE etchat_onlineuser_fid = :uid
             LIMIT 1",
            [':uid' => $userID]
        );

        if ($result && ($result[0]['etchat_user_online_user_status_img'] ?? '') === 'status_off') {

            $oldImg  = $_SESSION['etchat_'.$this->_prefix.'old_status_img']  ?? '';
            $oldText = $_SESSION['etchat_'.$this->_prefix.'old_status_text'] ?? '';

            $this->dbObj->sqlSet(
                "UPDATE {$this->_prefix}etchat_useronline
                 SET etchat_user_online_user_status_img = :img,
                     etchat_user_online_user_status_text = :txt
                 WHERE etchat_onlineuser_fid = :uid
                   AND etchat_user_online_user_status_img = 'status_off'",
                [
                    ':img' => $oldImg,
                    ':txt' => $oldText,
                    ':uid' => $userID
                ]
            );

            unset($_SESSION['etchat_'.$this->_prefix.'old_status_img']);
            unset($_SESSION['etchat_'.$this->_prefix.'old_status_text']);
        }
    }


    private function sendHeaders(): void
    {
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Content-Type: application/json; charset=utf-8');
    }


    private function processReloadSequence(): void
    {
        if (empty($_SESSION['etchat_'.$this->_prefix.'config_reloadsequenz'])) {
            return;
        }

        $interval = (int)$_SESSION['etchat_'.$this->_prefix.'config_reloadsequenz'] / 1000;

        $grenzzeit1 = time() - ($interval * 8);
        $grenzzeit2 = time() - ($interval * 16);

        $userID = (int)($_SESSION['etchat_'.$this->_prefix.'user_id'] ?? 0);

        $statusRes = $this->dbObj->sqlGet(
            "SELECT etchat_user_online_user_status_img,
                    etchat_user_online_user_status_text
             FROM {$this->_prefix}etchat_useronline
             WHERE etchat_onlineuser_fid = :uid
               AND etchat_user_online_user_status_img != 'status_off'
             LIMIT 1",
            [':uid' => $userID]
        );

        if ($statusRes) {
            $_SESSION['etchat_'.$this->_prefix.'old_status_img'] = $statusRes[0]['etchat_user_online_user_status_img'] ?? '';
            $_SESSION['etchat_'.$this->_prefix.'old_status_text'] = $statusRes[0]['etchat_user_online_user_status_text'] ?? '';
        }

        $this->dbObj->sqlSet(
            "UPDATE {$this->_prefix}etchat_useronline
             SET etchat_user_online_user_status_img = 'status_off',
                 etchat_user_online_user_status_text = 'Verbindung verloren'
             WHERE etchat_onlinetimestamp < :t1",
            [':t1' => $grenzzeit1]
        );

        $this->dbObj->sqlSet(
            "DELETE FROM {$this->_prefix}etchat_useronline
             WHERE etchat_onlinetimestamp < :t2",
            [':t2' => $grenzzeit2]
        );
    }


    private function anyChangesSinceLastPolling($feld, $roomarray): bool
    {
        $rel = '';

        if (is_array($feld)) {
            foreach ($feld as $row) {
                if (is_array($row)) {
                    $rel .= implode('', $row);
                }
            }
        }

        if (is_array($roomarray)) {
            foreach ($roomarray as $row) {
                if (is_array($row)) {
                    $rel .= implode('', $row);
                }
            }
        }

        $blockAll = $_SESSION['etchat_'.$this->_prefix.'block_all'] ?? [];
        if (is_array($blockAll) && !empty($blockAll)) {
            $rel .= implode('-', $blockAll);
        }

        $blockPriv = $_SESSION['etchat_'.$this->_prefix.'block_priv'] ?? [];
        if (is_array($blockPriv) && !empty($blockPriv)) {
            $rel .= implode('-', $blockPriv);
        }

        $roomPw = $_SESSION['etchat_'.$this->_prefix.'roompw_array'] ?? [];
        if (is_array($roomPw) && !empty($roomPw)) {
            $rel .= implode('-', $roomPw);
        }

        if (($_SESSION['etchat_'.$this->_prefix.'reload_user_anz'] ?? '') === $rel) {
            return false;
        }

        $_SESSION['etchat_'.$this->_prefix.'reload_user_anz'] = $rel;
        return true;
    }


    private function makeJsonOutput($feld, $roomarray): void
    {
        $data = [
            'userOnline' => [],
            'all_empty_rooms' => []
        ];

        if (is_array($feld)) {

            foreach ($feld as $row) {

                $user_id = (int)($row[3] ?? 0);

                $timestamp = 0;
                $regResult = $this->dbObj->sqlGet(
                    "SELECT etchat_reg_timestamp
                     FROM {$this->_prefix}etchat_user
                     WHERE etchat_user_id = :uid
                     LIMIT 1",
                    [':uid' => $user_id]
                );

                if ($regResult && isset($regResult[0]['etchat_reg_timestamp'])) {
                    $timestamp = strtotime($regResult[0]['etchat_reg_timestamp']);
                }

                $blockAll = $_SESSION['etchat_'.$this->_prefix.'block_all'] ?? [];
                if (is_array($blockAll) && in_array($user_id, $blockAll, true)) {
                    $row[0] = '<strike>'.$row[0];
                }

                $blockPriv = $_SESSION['etchat_'.$this->_prefix.'block_priv'] ?? [];
                if (is_array($blockPriv) && in_array($user_id, $blockPriv, true)) {
                    $row[0] = '<strike>'.$row[0];
                }

                $room_allowed = new RoomAllowed($row[6] ?? 0, $row[2] ?? 0);

                if (isset($_SESSION['etchat_'.$this->_prefix.'user_id']) &&
                    $_SESSION['etchat_'.$this->_prefix.'user_id'] == $row[3]) {
                    $_SESSION['etchat_'.$this->_prefix.'userstatus'] = $row[8] ?? '';
                }

                $data['userOnline'][] = [
					'user'            => $row[0] ?? '',
					'user_id'          => $row[3] ?? 0,
					'user_priv'         => $row[5] ?? '',
					'user_sex'           => $row[7] ?? '',
					'user_simg'          => $row[8] ?? '',
					'user_stext'          => $row[9] ?? '',
					'room_id'             => $row[2] ?? 0,
					'room_allowed'         => $room_allowed->room_status,
					'room'                 => $row[1] ?? '',
					'reg_timestamp'         => $timestamp,
					'etchat_avatar'           => $row[10] ?? '',
					'user_ip'                 => addslashes(str_replace("@", " - ", $row[4] ?? ''))
				];
            }
        }

        if (is_array($roomarray)) {

            foreach ($roomarray as $row) {

                $room_allowed2 = new RoomAllowed($row[2] ?? 0, $row[0] ?? 0);

                $data['all_empty_rooms'][] = [
                    'room_id' => $row[0] ?? 0,
                    'room_allowed' => $room_allowed2->room_status,
                    'room' => $row[1] ?? ''
                ];
            }
        }

        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }
}