<?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 AdminInsertSmilies 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();

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

        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];

        $userRole = $_SESSION['etchat_' . $this->_prefix . 'user_priv'] ?? '';
        if (!in_array($userRole, $this->allowedRoles, true)) {
            echo '<span style="color:red;">' . htmlspecialchars($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;
        }
        unset($_SESSION['etchat_' . $this->_prefix . 'csrf_token']); // Token verbrauchen

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cat'], $_POST['sign'], $_POST['gw'], $_FILES['smiliefile'])) {
            $this->handleUpload($_POST, $_FILES, $lang);
        } else {
            include_once "styles/admin_tpl/insertSmiliesMessage.tpl.html";
        }
    }

    private function handleUpload(array $post, array $files, object $lang): void
    {
        $catName = preg_replace("/[^a-zA-Z0-9_-]/", "_", $post['cat']);
        $catFolder = $this->uploaddir . $catName . DIRECTORY_SEPARATOR;
        if (!is_dir($catFolder) && !mkdir($catFolder, 0775, true)) {
			throw new RuntimeException('Konnte Kategorie-Ordner nicht erstellen.');
		}

        $originalName = preg_replace('/[^a-zA-Z0-9._-]/', '_', basename($files['smiliefile']['name']));
        $targetFile = $catFolder . $originalName;
        $notes = '';

        if (file_exists($targetFile)) {
            $nowname = time() . "_" . $originalName;
            $targetFile = $catFolder . $nowname;
            $notes = htmlspecialchars($lang->file_exists[0]->tagData) . " " . htmlspecialchars($nowname) . "<br>";
        } else {
            $nowname = $originalName;
        }

        // Prüfen, ob Zeichen schon existiert
        $res = $this->dbObj->sqlGet(
            "SELECT etchat_smileys_id FROM {$this->_prefix}etchat_smileys WHERE etchat_smileys_sign = ?",
            [$post['sign']]
        );

        if (!empty($res)) {
            $print_result = '<span style="color:red;">' . htmlspecialchars($lang->sign_exists[0]->tagData) . '</span><br>';
            $print_result .= "<a href='./?AdminSmiliesIndex'>" . htmlspecialchars($lang->back[0]->tagData) . "</a>";
        } else {
            $mimeType = mime_content_type($files['smiliefile']['tmp_name']);
            $allowedTypes = ['image/png', 'image/gif', 'image/jpeg', 'image/webp'];
			$imageInfo = @getimagesize($files['smiliefile']['tmp_name']);

			if (!in_array($mimeType, $allowedTypes, true) || $imageInfo === false) {
				@unlink($files['smiliefile']['tmp_name']);

				$print_result = '<span style="color:red;">' . htmlspecialchars($lang->noupload[0]->tagData) . '</span>';
				$print_result .= "<br /><a href='./?AdminSmiliesIndex'>" . htmlspecialchars($lang->back[0]->tagData) . "</a>";
			} else {
                if (!move_uploaded_file($files['smiliefile']['tmp_name'], $targetFile)) {
                    $print_result = '<span style="color:red;">Fehler beim Upload</span><br>';
                    $print_result .= "<a href='./?AdminSmiliesIndex'>" . htmlspecialchars($lang->back[0]->tagData) . "</a>";
                } else {
                    $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 (?, ?, ?, ?)",
                        [$post['cat'], $post['sign'], $relativePath, (int)$post['gw']]
                    );

                    $print_result = '<span style="color:green;">' . htmlspecialchars($lang->isupload[0]->tagData) . '</span><br>' . $notes;
                    $print_result .= "<br><a href='./?AdminCreateNewSmilies'>" . htmlspecialchars($lang->smilie[0]->tagData) . "</a>";
                }
            }
        }

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