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

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

        $priv = $_SESSION['etchat_' . $this->_prefix . 'user_priv'] ?? '';

        if ($priv !== "admin" && $priv !== "mod") {
            exit;
        }

        $exportFormat = $_GET['format'] ?? '';
        $userId = (int)$_SESSION['etchat_' . $this->_prefix . 'user_id'];

        header('Expires: 0');
        header('Pragma: no-cache');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

        /* =========================
           Raum / Privat Auswahl
        ========================== */

        $roomId = $_GET['roomid'] ?? 1;
        $privates = $roomId === "priv";

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

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

        /* =========================
           SELECT
        ========================== */

        if ($privates) {
            // Private Nachrichten
			$feld = $this->dbObj->sqlGet("
				SELECT
					m.etchat_id,
					sender.etchat_username,
					receiver.etchat_username,
					m.etchat_text,
					m.etchat_timestamp,
					COALESCE(r.etchat_roomname, 'Privat') AS roomname,
					m.etchat_privat,
					m.etchat_user_fid
				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
			", [$userId, $userId]);
        } else {
            // Räume
            $params = [$roomId];
            $where = "m.etchat_privat = 0 AND m.etchat_fid_room = ?";
            if ($includeLobby) {
                $where = "m.etchat_privat = 0 AND (m.etchat_fid_room = ? OR m.etchat_fid_room = 0)";
            }

            $feld = $this->dbObj->sqlGet("
                SELECT
                    m.etchat_id,
                    sender.etchat_username,
                    NULL,
                    m.etchat_text,
                    m.etchat_timestamp,
                    COALESCE(r.etchat_roomname, 'Lobby') AS roomname,
                    m.etchat_privat,
                    m.etchat_user_fid
                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
            ", $params);
        }

        $this->dbObj->close();

        /* =========================
           Language
        ========================== */

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

        /* =========================
           Output
        ========================== */

        switch ($exportFormat) {
            case "csv":
                header('Content-Type: text/csv; charset=utf-8');
                header("Content-Disposition: attachment; filename=history.csv");
                $this->printCSV($feld, $lang);
                break;

            case "xls":
                header("Content-Type: application/vnd.ms-excel; charset=utf-8");
                header("Content-Disposition: attachment; filename=history.xls");
                $this->printXLS($feld, $lang);
                break;

            case "xml":
                header("Content-Type: text/xml; charset=utf-8");
                header("Content-Disposition: attachment; filename=history.xml");
                $this->printXML($feld, $lang);
                break;

            default:
                echo "invalid format";
                break;
        }
    }

    /* =========================
       Name Builder
    ========================== */
    private function buildUsername($row)
    {
        $sender = !empty($row[1]) ? $row[1] : "User " . $row[7];

        if (!empty($row[6]) && $row[6] != 0) {
            $emp = !empty($row[2]) ? $row[2] : "User " . $row[6];
            return $sender . " >>> " . $emp;
        }

        return $sender;
    }

    /* =========================
       CSV
    ========================== */
    private function printCSV($feld, $lang)
    {
        if (!$lang) return;

        echo "ID\t" . $lang->user[0]->tagData . "\t"
            . $lang->date[0]->tagData . "\t"
            . $lang->text[0]->tagData . "\t"
            . $lang->room[0]->tagData . "\n";

        if (is_array($feld)) {
            foreach ($feld as $row) {
                $name = $this->buildUsername($row);
                echo (int)$row[0] . "\t"
                    . html_entity_decode(strip_tags($name), ENT_QUOTES, "UTF-8") . "\t"
                    . date("d.m.Y (H:i)", (int)$row[4]) . "\t"
                    . html_entity_decode(strip_tags($row[3]), ENT_QUOTES, "UTF-8") . "\t"
                    . html_entity_decode(strip_tags($row[5]), ENT_QUOTES, "UTF-8") . "\n";
            }
        }
    }

    /* =========================
       XLS
    ========================== */
    private function printXLS($feld, $lang)
    {
        if (!$lang) return;

        echo "<html><head><meta charset=\"utf-8\"></head><body>";
        echo "<table border=\"1\">";
        echo "<tr>
                <th>ID</th>
                <th>" . $lang->user[0]->tagData . "</th>
                <th>" . $lang->date[0]->tagData . "</th>
                <th>" . $lang->text[0]->tagData . "</th>
                <th>" . $lang->room[0]->tagData . "</th>
              </tr>";

        if (is_array($feld)) {
            foreach ($feld as $row) {
                $name = $this->buildUsername($row);
                echo "<tr>
                        <td>" . (int)$row[0] . "</td>
                        <td>" . html_entity_decode(strip_tags($name), ENT_QUOTES, "UTF-8") . "</td>
                        <td>" . date("d.m.Y (H:i)", (int)$row[4]) . "</td>
                        <td>" . html_entity_decode(strip_tags($row[3]), ENT_QUOTES, "UTF-8") . "</td>
                        <td>" . html_entity_decode(strip_tags($row[5]), ENT_QUOTES, "UTF-8") . "</td>
                      </tr>";
            }
        }

        echo "</table></body></html>";
    }

    /* =========================
       XML
    ========================== */
    private function printXML($feld, $lang)
    {
        if (!$lang) return;

        echo "<?xml version='1.0' encoding='utf-8'?>";
        echo "<etchat>";

        if (is_array($feld)) {
            foreach ($feld as $row) {
                $name = $this->buildUsername($row);
                echo "<dataset>
                        <id>" . (int)$row[0] . "</id>
                        <user>" . html_entity_decode(strip_tags($name), ENT_QUOTES, "UTF-8") . "</user>
                        <date>" . date("d.m.Y (H:i)", (int)$row[4]) . "</date>
                        <message>" . html_entity_decode(strip_tags($row[3]), ENT_QUOTES, "UTF-8") . "</message>
                        <room>" . html_entity_decode(strip_tags($row[5]), ENT_QUOTES, "UTF-8") . "</room>
                      </dataset>";
            }
        }

        echo "</etchat>";
    }
}