<?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 Gallery extends DbConectionMaker
{
    private string $style = 'default';

    public function __construct()
    {
        parent::__construct();

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

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

        $this->loadStyle();
        $this->render();
    }

    private function loadStyle(): void
    {
        $result = $this->dbObj->sqlGet(
            "SELECT etchat_config_style
             FROM {$this->_prefix}etchat_config
             WHERE etchat_config_id = 1
             LIMIT 1"
        );

        if ($result !== false && isset($result[0]['etchat_config_style'])) {
            $this->style = $result[0]['etchat_config_style'];
        }
    }

    private function render(): void
    {
        $uploadDir = dirname(__DIR__) . "/userpic/";
        $webPath   = "userpic/";

        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $imageFiles = glob($uploadDir . "*.{jpg,jpeg,png,gif}", GLOB_BRACE);

        if ($imageFiles === false) {
            $imageFiles = [];
        }

        $images = [];
        $metaCache = [];

        // 🚀 Performance: Meta-Daten einmal lesen
        foreach ($imageFiles as $file) {

            $name = basename($file);
            $metaFile = $file . ".txt";

            $uploader = "Unbekannt";
            $datum = "";
            $timestamp = 0;

            if (is_file($metaFile)) {

                $meta = @file_get_contents($metaFile);

                if ($meta !== false) {

                    $parts = explode("|", $meta);

                    $uploader = trim($parts[0] ?? "Unbekannt");
                    $datum = trim($parts[1] ?? "");

                    $ts = strtotime($datum);

                    if ($ts !== false) {
                        $timestamp = $ts;
                    }
                }
            }

            $images[] = $name;

            $metaCache[$name] = [
                'uploader' => $uploader,
                'datum' => $datum,
                'ts' => $timestamp
            ];
        }

        // 🚀 schnellere Sortierung
        usort($images, function ($a, $b) use ($metaCache) {
            return $metaCache[$b]['ts'] <=> $metaCache[$a]['ts'];
        });

        $this->renderHTML($images, $metaCache, $webPath);
    }

    private function renderHTML(array $images, array $metaCache, string $webPath): void
    {
?>
<!DOCTYPE html>
<html lang="de">
<head>

<meta charset="UTF-8">
<title>Galerie</title>

<link href="styles/<?php echo htmlspecialchars($this->style, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); ?>/style.css" rel="stylesheet">

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">

<script>

if (window.top === window.self) {
    window.location.replace('./');
}

function sendToChat(imageUrl)
{
    var imgCode = "[img]" + imageUrl.trim() + "[/img]";

    var chatInput = window.parent.document.getElementById("message");
    var sendButton = window.parent.document.getElementById("link_sagen");

    if (chatInput && sendButton) {

        chatInput.value = chatInput.value
            ? chatInput.value + " " + imgCode
            : imgCode;

        sendButton.click();
        window.close();

    } else {

        alert("Fehler: Chat-Eingabe oder Senden-Button nicht gefunden.");

    }
}

</script>

</head>

<body id="body">

<div class="gallery">

<?php if (empty($images)): ?>

<p style="text-align:center;width:100%;">
Zurzeit keine Bilder in der Galerie.
</p>

<?php else: ?>

<?php foreach ($images as $image):

    $meta = $metaCache[$image];

    $safeImage = htmlspecialchars($image, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');

?>

<div class="image-container">

<div class="meta">

Bild gepostet von<br>

<?php echo htmlspecialchars($meta['uploader'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); ?><br>

<?php echo htmlspecialchars($meta['datum'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); ?><br>

</div>

<div class="image-wrapper">

<img
class="imgg"
src="<?php echo $webPath . $safeImage; ?>"
alt="Bild"
loading="lazy"
decoding="async">

</div>

<div class="bottom">

<button
class="button"
onclick="sendToChat('<?php echo $webPath . $safeImage; ?>')"
title="Bild in den Chat posten">

Bild posten

</button>

</div>

</div>

<?php endforeach; ?>

<?php endif; ?>

</div>

</body>
</html>
<?php
    }
}