<?php
declare(strict_types=1);

/**
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.)
und wird unter der Namenserweiterung M.C.v.x.x.x. geführt. 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
 */

class AdminGallery extends DbConectionMaker
{
    private const UPLOAD_DIR = './userpic/';
    private const ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif'];
    private const ALLOWED_ROLES = ['admin', 'grafik', 'co_admin', 'chatwache'];

    private string $csrfKey;

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

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

        $this->csrfKey = 'etchat_' . $this->_prefix . 'csrf_token';
        $csrfToken = $this->initCsrf();

        $config = $this->loadConfig();
        $style  = $config[0][0] ?? 'default';

        $langObj = new LangXml();
        $lang = $langObj->getLang();

        $role = $this->checkAccess($lang);

        // 🔥 ACTIONS (sauber getrennt)
        if (isset($_GET['cleanup'])) {
            $this->handleCleanup($csrfToken);
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->handleDelete(
                $_POST['delete'] ?? '',
                $_POST['csrf_token'] ?? '',
                $csrfToken
            );
        }

        // 🔹 DATA
        $images = $this->scanImages();
		$categoryCount = count($images);

        $vari1 = $this->buildGallery($images);
        $vari2 = $csrfToken;
        $vari3 = htmlspecialchars($style, ENT_QUOTES, 'UTF-8');
		$vari4 = $categoryCount;

        // 🔹 TEMPLATE
        $tplPath = __DIR__ . '/../../styles/admin_tpl/indexGallery.tpl.html';

        if (!is_file($tplPath)) {
            exit('Template fehlt: ' . $tplPath);
        }

        include $tplPath;
    }

    private function initCsrf(): string
    {
        if (empty($_SESSION[$this->csrfKey])) {
            $_SESSION[$this->csrfKey] = bin2hex(random_bytes(16));
        }

        return $_SESSION[$this->csrfKey];
    }

    private function loadConfig(): array
    {
        return $this->dbObj->sqlGet(
            "SELECT etchat_config_style FROM {$this->_prefix}etchat_config WHERE etchat_config_id = ?",
            [1]
        ) ?? [];
    }

    private function checkAccess($lang): string
    {
        $role = $_SESSION['etchat_' . $this->_prefix . 'user_priv'] ?? '';

        if (!in_array($role, self::ALLOWED_ROLES, true)) {
            exit($lang->error[0]->tagData ?? 'Zugriff verweigert');
        }

        return $role;
    }

    private function handleDelete(string $imageName, string $token, string $sessionToken): void
    {
        if (!$sessionToken || !$token || !hash_equals($sessionToken, $token)) {
            exit('Ungültiger CSRF-Token.');
        }

        if ($imageName === '') return;

        $imageName = basename($imageName);

        $baseDir = realpath(self::UPLOAD_DIR);
        $imagePath = realpath(self::UPLOAD_DIR . $imageName);

        if (!$baseDir || !$imagePath) return;
        if (!str_starts_with($imagePath, $baseDir)) return;

        if (is_file($imagePath)) {
            unlink($imagePath);

            $meta = $imagePath . '.txt';
            if (is_file($meta)) {
                unlink($meta);
            }
        }

        header('Location: ./?AdminGallery');
        exit;
    }

    private function handleCleanup(string $csrfToken): void
    {
        if (!isset($_GET['cleanup'])) {
            return;
        }

        $token = $_GET['csrf_token'] ?? '';

        if (!$token || !hash_equals($csrfToken, $token)) {
            exit('Ungültiger CSRF-Token.');
        }

        $days = (int)($_GET['days'] ?? 7);

        if ($days < 1) {
            $days = 7;
        }

        $limitTime = time() - ($days * 86400);

        $dir = self::UPLOAD_DIR;

        if (!is_dir($dir)) {
            exit;
        }

        foreach (scandir($dir) as $file) {
            if ($file === '.' || $file === '..') continue;

            $path = $dir . $file;

            if (!is_file($path)) continue;

            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));

            if (!in_array($ext, self::ALLOWED_EXTENSIONS, true)) {
                continue;
            }

            if (filemtime($path) < $limitTime) {
                unlink($path);

                $meta = $path . '.txt';
                if (is_file($meta)) {
                    unlink($meta);
                }
            }
        }

        header('Location: ./?AdminGallery');
        exit;
    }

    private function scanImages(): array
    {
        if (!is_dir(self::UPLOAD_DIR)) return [];

        $files = scandir(self::UPLOAD_DIR);
        if ($files === false) return [];

        return array_values(array_filter($files, function ($file) {
            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));

            return in_array($ext, self::ALLOWED_EXTENSIONS, true)
                && is_file(self::UPLOAD_DIR . $file);
        }));
    }

    private function readMeta(string $image): array
    {
        $metaFile = self::UPLOAD_DIR . $image . '.txt';

        if (!is_file($metaFile)) {
            return ['Unbekannt', '', ''];
        }

        $content = file_get_contents($metaFile);
        if ($content === false) return ['Unbekannt', '', ''];

        $p = explode('|', $content);

        return [
            trim($p[0] ?? ''),
            trim($p[1] ?? ''),
            trim($p[2] ?? '')
        ];
    }

    private function buildGallery(array $images): string
    {
        if (!$images) {
            return '<p>Keine Bilder vorhanden.</p>';
        }

        $html = '';

        foreach ($images as $image) {

            $safe = htmlspecialchars($image, ENT_QUOTES, 'UTF-8');
            $url  = self::UPLOAD_DIR . $safe;

            [$uploader, $datum, $ip] = $this->readMeta($image);

            $html .= '
            <div style="
				border:1px solid #444;
				padding:10px;
				background:rgba(0,0,0,0.3);
				display:flex;
				flex-direction:column;
			">

                <div style="margin-bottom:5px;">
                    <b>' . htmlspecialchars($uploader) . '</b><br>
                    ' . htmlspecialchars($datum) . '<br>
                    IP: ' . htmlspecialchars($ip) . '
                </div>

                <div style="text-align:center; margin:10px 0;">
                    <img src="' . $url . '" style="max-height:150px; max-width:95%;">
                </div>

                <div style="text-align:center; margin-top:auto;">
                    <button onclick="sendToChat(\'' . $safe . '\')">posten</button>
                    <button class="rot" onclick="deleteImage(\'' . $safe . '\')">X</button>
                </div>

            </div>';
        }

        return $html;
    }
}