<?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 AdminUpdateSmiliesCat extends DbConectionMaker
{
    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();
        $langData = $langObj->getLang();

        $lang = $langData->admin[0]->admin_smilies[0] ?? (object)[
            'error' => [(object)['tagData' => 'Fehler']]
        ];

        $role  = (string)($_SESSION["etchat_" . $this->_prefix . "user_priv"] ?? '');
        $token = (string)($_POST['csrf_token'] ?? $_GET['csrf_token'] ?? '');

        // 🔐 Rollen + CSRF
        if (!in_array($role, ["admin", "grafik", "co_admin"], true) || $token === '') {
            echo $lang->error[0]->tagData ?? 'Fehler';
            exit;
        }

        if (!$this->isValidCsrfToken($token)) {
            echo ($lang->error[0]->tagData ?? 'Fehler') . ' (CSRF)';
            exit;
        }

        // 🔐 Eingaben
        $id      = (int)($_POST["id"] ?? 0);
        $newName = trim((string)($_POST["name"] ?? ''));
        $oldName = trim((string)($_POST["name_old"] ?? ''));
        $gw      = (int)($_POST["gw"] ?? 0);
        $gw_old  = (int)($_POST["gw_old"] ?? 0);

        if ($id <= 0 || $newName === '') {
            echo "Ungültige Daten";
            exit;
        }

        // 🔒 SAFE Namen (für Ordner)
        $oldSafe = preg_replace("/[^a-zA-Z0-9_-]/", "_", $oldName);
        $newSafe = preg_replace("/[^a-zA-Z0-9_-]/", "_", $newName);

        $print_smil_edit_1 = "";
        $print_smil_edit_2 = "";

        // =========================
        // 🔹 KATEGORIE NAME
        // =========================
        if ($newName === $oldName) {

            $print_smil_edit_1 = "Kategorie nicht geändert<br>";

        } else {

            // 🔍 Existiert Name schon?
            $res = $this->dbObj->sqlGet(
                "SELECT id 
                 FROM {$this->_prefix}etchat_smileys_cat 
                 WHERE name = :name AND id != :id",
                [
                    ':name' => $newName,
                    ':id'   => $id
                ]
            );

            if (!empty($res)) { // ✅ FIX

                $print_smil_edit_1 = "Kategorie schon vorhanden<br>";

            } else {

                // 🔹 Kategorie ändern
                $this->dbObj->sqlSet(
                    "UPDATE {$this->_prefix}etchat_smileys_cat
                     SET name = :name
                     WHERE id = :id",
                    [
                        ':name' => $newName,
                        ':id'   => $id
                    ]
                );

                // 🔹 Smileys Kategorie ändern
                $this->dbObj->sqlSet(
                    "UPDATE {$this->_prefix}etchat_smileys
                     SET etchat_smileys_kat = :newName
                     WHERE etchat_smileys_kat = :oldName",
                    [
                        ':newName' => $newName,
                        ':oldName' => $oldName
                    ]
                );

                // 🔹 Bildpfade anpassen (sauber)
                $oldPath = "./smilies/" . $oldSafe . "/";
                $newPath = "./smilies/" . $newSafe . "/";

                $this->dbObj->sqlSet(
                    "UPDATE {$this->_prefix}etchat_smileys
                     SET etchat_smileys_img = REPLACE(
                        etchat_smileys_img,
                        :oldPath,
                        :newPath
                     )
                     WHERE etchat_smileys_kat = :newName",
                    [
                        ':oldPath' => $oldPath,
                        ':newPath' => $newPath,
                        ':newName' => $newName
                    ]
                );

                $print_smil_edit_1 = "<span class='rot'>Kategorie geändert, Smileys und Pfade aktualisiert</span><br>";

                // 🔹 Ordner umbenennen
                $oldDir = "./smilies/" . $oldSafe;
                $newDir = "./smilies/" . $newSafe;

                if (is_dir($oldDir)) {

                    if (!is_dir($newDir)) {

                        if (@rename($oldDir, $newDir)) {
                            $print_smil_edit_1 .= "<span class='rot'>Ordner wurde umbenannt</span><br>";
                        } else {
                            $print_smil_edit_1 .= "<span class='rot'>Fehler: Ordner konnte nicht umbenannt werden!</span><br>";
                        }

                    } else {
                        $print_smil_edit_1 .= "<span class='rot'>Neuer Ordner existiert bereits!</span><br>";
                    }

                } else {
                    $print_smil_edit_1 .= "<span class='rot'>Alter Ordner nicht gefunden!</span><br>";
                }
            }
        }

        // =========================
        // 🔹 GEWICHT
        // =========================
        if ($gw === $gw_old) {

            $print_smil_edit_2 = "Gewicht nicht geändert<br>";

        } else {

            $this->dbObj->sqlSet(
                "UPDATE {$this->_prefix}etchat_smileys_cat
                 SET gewicht = :gw
                 WHERE id = :id",
                [
                    ':gw' => $gw,
                    ':id' => $id
                ]
            );

            $print_smil_edit_2 = "<span class='rot'>Gewicht geändert</span><br>";
        }

        $this->dbObj->close();

        $this->initTemplate($lang, $print_smil_edit_1, $print_smil_edit_2);
    }

    private function isValidCsrfToken(string $token): bool
    {
        $key = 'etchat_' . $this->_prefix . 'csrf_token';
        return isset($_SESSION[$key]) && hash_equals($_SESSION[$key], $token);
    }

    private function initTemplate($lang, $print_smil_edit_1, $print_smil_edit_2)
    {
        include_once "styles/admin_tpl/errorSmileyCatExists.tpl.html";
    }
}