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

        if ($_SERVER["REQUEST_METHOD"] !== "POST") {
            header("Location: ./");
            exit();
        }

        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        if (!isset($_SESSION["etchat_" . $this->_prefix . "user_id"])) {
            exit();
        }

        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Content-Type: text/html; charset=utf-8");

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

        $userId = (int) $_SESSION["etchat_" . $this->_prefix . "user_id"];
        $userPriv = $_SESSION["etchat_" . $this->_prefix . "user_priv"];

        /* Raumlogik */
        $roomId = $_POST["roomid"] ?? 1;
        if ($roomId === "" || $roomId === null) {
            $roomId = 1;
        }

        $privates = $roomId === "priv";

        if (!$privates) {
            $roomId = (int) $roomId;
        }

        $_POST["roomid"] = $roomId;

        $includeLobby = !$privates && $roomId === 1;

        /* Pagination */
        $pro_seite = 40;

        $site = isset($_POST["site"]) ? (int) $_POST["site"] : 1;
        $site = max(0, $site - 1);

        $von = $site * $pro_seite;

        $limit =
            $this->_usedDatabase === "mysql"
                ? "LIMIT $von, $pro_seite"
                : "LIMIT $pro_seite OFFSET $von";

        /* Loginzeit */
        $zeit = 0;

        $tmp = $this->dbObj->sqlGet(
            "SELECT etchat_logintime 
             FROM {$this->_prefix}etchat_useronline 
             WHERE etchat_onlineuser_fid = ?",
            [$userId]
        );

        if (!empty($tmp)) {
            $zeit = (int) $tmp[0][0] - 2;
        }

        /* Nachrichten laden */

        if ($privates) {
            $counted = $this->dbObj->sqlGet(
                "SELECT COUNT(etchat_id)
                 FROM {$this->_prefix}etchat_messages
                 WHERE (etchat_user_fid = ? AND etchat_privat > 0)
                 OR etchat_privat = ?",
                [$userId, $userId]
            );

            $feld = $this->dbObj->sqlGet(
                "SELECT
                    m.etchat_id,
                    sender.etchat_username,
                    receiver.etchat_username,
                    m.etchat_text,
                    m.etchat_timestamp,
                    r.etchat_roomname,
                    m.etchat_privat,
                    m.etchat_user_fid,
                    m.etchat_text_css,
                    m.etchat_user_ip
                 FROM {$this->_prefix}etchat_messages m
                 
                 LEFT JOIN {$this->_prefix}etchat_user sender
                 ON sender.etchat_user_id = m.etchat_user_fid

                 LEFT JOIN {$this->_prefix}etchat_user receiver
                 ON receiver.etchat_user_id = m.etchat_privat

                 LEFT JOIN {$this->_prefix}etchat_rooms r
                 ON r.etchat_id_room = m.etchat_fid_room

                 WHERE
                 (m.etchat_user_fid = ? AND m.etchat_privat > 0)
                 OR m.etchat_privat = ?

                 ORDER BY m.etchat_id DESC
                 $limit",
                [$userId, $userId]
            );
        } else {
            $where = "m.etchat_privat = 0 AND m.etchat_fid_room = ?";
            $params = [$roomId];

            if ($includeLobby) {
                $where =
                    "m.etchat_privat = 0 AND (m.etchat_fid_room = ? OR m.etchat_fid_room = 0)";
            }

            if ($userPriv !== "admin") {
                $where .= " AND m.etchat_timestamp >= ?";
                $params[] = $zeit;
            }

            $counted = $this->dbObj->sqlGet(
                "SELECT COUNT(etchat_id)
                 FROM {$this->_prefix}etchat_messages m
                 WHERE $where",
                $params
            );

            $feld = $this->dbObj->sqlGet(
                "SELECT
                    m.etchat_id,
                    sender.etchat_username,
                    NULL,
                    m.etchat_text,
                    m.etchat_timestamp,
                    r.etchat_roomname,
                    m.etchat_privat,
                    m.etchat_user_fid,
                    m.etchat_text_css,
                    m.etchat_user_ip

                 FROM {$this->_prefix}etchat_messages m

                 LEFT JOIN {$this->_prefix}etchat_user sender
                 ON sender.etchat_user_id = m.etchat_user_fid

                 LEFT JOIN {$this->_prefix}etchat_rooms r
                 ON r.etchat_id_room = m.etchat_fid_room

                 WHERE $where

                 ORDER BY m.etchat_id DESC
                 $limit",
                $params
            );
        }

        /* Seiten */

        echo "<div id='history_seiten' style='margin:2px;'>";

        $sitemakerObj = new Sitemaker($pro_seite, $counted[0][0] ?? 0);

        $sitemakerObj->make(
            $_POST["site"] ?? 1,
            "historysite_#site#",
            $lang->site[0]->tagData,
            $lang->site_of[0]->tagData
        );

        $sitemakerObj->show();

        echo "<form style='display:inline;'>&nbsp;&nbsp;&nbsp; " .
            $lang->room[0]->tagData .
            ": <select name='raum_in_history' id='raum_in_history'>";

        echo "<option value='priv' " .
            ($privates ? "selected" : "") .
            ">" .
            $lang->priv[0]->tagData .
            "</option>";

        $rooms = $this->dbObj->sqlGet(
            "SELECT etchat_id_room, etchat_roomname, etchat_room_goup 
 FROM {$this->_prefix}etchat_rooms"
        );

        if (!empty($rooms)) {
            foreach ($rooms as $each_room) {
                $room_allowed = new RoomAllowed($each_room[2], $each_room[0]);

                if ($room_allowed->room_status == 1) {
                    $selected =
                        !$privates && $roomId == $each_room[0]
                            ? "selected"
                            : "";

                    echo "<option value='" .
                        $each_room[0] .
                        "' $selected>" .
                        $each_room[1] .
                        "</option>";
                }
            }
        }

        if ($userPriv === "admin") {
            echo "</select>&nbsp;&nbsp;&nbsp;" .
                $lang->export[0]->tagData .
                "
<a href='#' id='export_excel'>Excel</a> |
<a href='#' id='export_csv'>CSV</a> |
<a href='#' id='export_xml'>XML</a></form>";
        } else {
            echo "</select></form>";
        }

        /* Smileys */

        if (!isset($_SESSION["etchat_smileys"])) {
            $_SESSION["etchat_smileys"] = $this->dbObj->sqlGet(
                "SELECT etchat_smileys_sign, etchat_smileys_img
                 FROM {$this->_prefix}etchat_smileys"
            );
        }

        $sml = $_SESSION["etchat_smileys"];

        /* Tabelle */

        echo '<div class="table-container">';
		echo '<table class="table-fixed" cellpadding="5" cellspacing="0" border="0">';

		echo '<thead>
				<tr class="kopf">
				
				<th style="width:14%"><b>'.$lang->user[0]->tagData.'</b></th>

				<th style="width:10.5%"><b>User-IP</b></th>
				<th style="width:14.5%"><b>'.$lang->date[0]->tagData.'</b></th>
				<th style="width:51.5%"><b>'.$lang->text[0]->tagData.'</b></th>
				<th style="width:9.5%"><b>'.$lang->room[0]->tagData.'</b></th>
				</tr>
				</thead>
			<tbody>';

		if (!empty($feld) && is_array($feld)) {

			foreach ($feld as $a => $row) {

				$class = $a % 2 == 0 ? "gerade" : "ungerade";

				$sender = $row[1] ?: "User " . $row[7];

				$empfaenger = "";

				if ($row[6] != 0) {
					$empName = $row[2] ?: "User " . $row[6];

					$empfaenger =
						"&nbsp;<span style='font-size:1.2em'><b>>>>></b></span>&nbsp;" .
						$empName;
				}

				$message = StaticMethods::filtering($row[3], $sml, $this->_prefix);

				if (substr($message, 0, 8) == "/window:") {
					$message =
						"<img src='./img/privat_win.png' /> " . substr($message, 8);
				}

				echo "<tr class='$class'>
				<td>" . $sender . $empfaenger . "</td>
				<td>" . $row[9] . "</td>
				<td><center>" . date("d.m.Y (H:i)", $row[4]) . "</center></td>
				<td>" . $message . "</td>
				<td>" . $row[5] . "</td>
				</tr>";
			}

		} else {

			echo "<tr><td colspan='5'><center>Keine Daten gefunden oder DB-Fehler</center></td></tr>";
		}

        echo '</tbody></table></div>';

        $this->dbObj->close();
    }
}
