<?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.
*/

declare(strict_types=1);

class AdminInsertSmiliesgrupp extends DbConectionMaker
{
    private array $allowedRoles = ["admin", "grafik", "co_admin"];
    private string $uploaddir;

    public function __construct()
    {
        parent::__construct();
        if (session_status() !== PHP_SESSION_ACTIVE) session_start();

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

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

        $role = isset($_SESSION["etchat_" . $this->_prefix . "user_priv"])
			? (string) $_SESSION["etchat_" . $this->_prefix . "user_priv"]
			: '';
			
        if (!in_array($role, $this->allowedRoles, true)) {
            echo '<span style="color:red;">' . $lang->error[0]->tagData . '</span>';
            exit;
        }
		
		// CSRF prüfen
		$csrfToken = $_POST['csrf_token'] ?? $_GET['csrf_token'] ?? '';
		$sessionToken = $_SESSION['etchat_' . $this->_prefix . 'csrf_token'] ?? '';

		if (empty($csrfToken) || empty($sessionToken) || !hash_equals($sessionToken, $csrfToken)) {
			echo '<span style="color:red;">Ungültiger CSRF-Token.</span>';
			exit;
		}

		// Token verbrauchen
		unset($_SESSION['etchat_' . $this->_prefix . 'csrf_token']);

        $basePath = realpath(__DIR__ . '/../../smilies');
		if ($basePath === false) {
			throw new RuntimeException('Smilies-Verzeichnis nicht gefunden.');
		}
		$this->uploaddir = $basePath . DIRECTORY_SEPARATOR;

        $notes = "";
        $catRaw  = $_POST['cat'] ?? $_GET['cat'] ?? 'default';
        $catDb   = trim($catRaw);
        $catName = preg_replace("/[^a-zA-Z0-9_-]/", "_", $catRaw);
        $catFolder = $this->uploaddir . $catName . DIRECTORY_SEPARATOR;
        if (!is_dir($catFolder) && !mkdir($catFolder, 0775, true)) {
			throw new RuntimeException('Ordner konnte nicht erstellt werden.');
		}

        $gw_start = (int)($_POST['gw'] ?? $_GET['gw'] ?? 0);
        $gw_step   = 5;
        $gw_current = $gw_start;

        if (!isset($_FILES['smiliefiles']['tmp_name']) || !is_array($_FILES['smiliefiles']['tmp_name'])) {
            echo '<span style="color:red;">Keine Dateien hochgeladen.</span>';
            exit;
        }

        foreach ($_FILES['smiliefiles']['tmp_name'] as $key => $tmp_name) {
            if (!is_uploaded_file($tmp_name)) continue;

            $originalName = preg_replace('/[^a-zA-Z0-9._-]/', '_', basename($_FILES['smiliefiles']['name'][$key]));
            $basename = pathinfo($originalName, PATHINFO_FILENAME);
            $basename = preg_replace('/[^a-zA-Z0-9_-]/', '_', $basename);
            $basename = substr($basename, 0, 19);

            $sign = ':' . $basename;
            $counter = 1;
            while (true) {
                $res = $this->dbObj->sqlGet(
                    "SELECT etchat_smileys_id FROM {$this->_prefix}etchat_smileys WHERE etchat_smileys_sign = ?",
                    [$sign]
                );
                if (empty($res)) break;

                $maxBaseLen = 19 - strlen((string)$counter);
                $shortBase = substr($basename, 0, $maxBaseLen);
                $sign = ':' . $shortBase . $counter;
                $counter++;
            }

            if (@getimagesize($tmp_name) === false) {
                $notes .= '<span style="color:red;">Datei ' . htmlspecialchars($originalName) . ' ist kein Bild, übersprungen.</span><br>';
                continue;
            }
			
			$allowedTypes = ['image/png', 'image/gif', 'image/jpeg', 'image/webp'];
			$mimeType = mime_content_type($tmp_name);

			if (!in_array($mimeType, $allowedTypes, true)) {
				$notes .= '<span style="color:red;">Datei ' . htmlspecialchars($originalName) . ' hat ungültigen Dateityp.</span><br>';
				continue;
			}

            $targetFile = $catFolder . $originalName;
            if (file_exists($targetFile)) {
                $nowname = time() . "_" . $originalName;
                $targetFile = $catFolder . $nowname;
                $notes .= '<span style="color:red;">Datei existiert, umbenannt zu ' . htmlspecialchars($nowname) . '</span><br>';
            } else {
                $nowname = $originalName;
            }

            if (!move_uploaded_file($tmp_name, $targetFile)) {
                $notes .= '<span style="color:red;">Fehler beim Upload von ' . htmlspecialchars($originalName) . '</span><br>';
                continue;
            }

            $relativePath = "./smilies/{$catName}/" . $nowname;
            $this->dbObj->sqlSet(
                "INSERT INTO {$this->_prefix}etchat_smileys
                (etchat_smileys_kat, etchat_smileys_sign, etchat_smileys_img, etchat_smileys_gewicht)
                VALUES (?, ?, ?, ?)",
                [$catDb, $sign, $relativePath, $gw_current]
            );

            $notes .= '<span style="color:green;">Smilie ' . htmlspecialchars($sign) . ' hochgeladen (Gewicht ' . $gw_current . ').</span><br>';
            $gw_current += $gw_step;
        }

        $print_result  = "<b>Upload abgeschlossen</b><br>" . $notes;
        $print_result .= "<br><a href='./?AdminCreateNewSmiliesgrupp'>Weitere hochladen</a><br>";

        include_once "styles/admin_tpl/insertSmiliesMessage.tpl.html";
    }
}