<?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 AdminUpdateSmilies 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');

        // Sprache laden (Fallback sicher)
        $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'] ?? '');
        $id    = (int)($_POST['id'] ?? 0);

        if (!in_array($role, ['admin', 'grafik', 'co_admin'], true) || $id <= 0 || $token === '') {
            echo $lang->error[0]->tagData ?? 'Fehler';
            exit;
        }

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

        // Template kompatibel lassen
        $print_smil_edit_1 = '';
        $print_smil_edit_2 = '';
        $print_smil_edit_3 = '';

        try {
            $pdo = $this->dbObj->getConnection();

            // =========================
            // 🔹 1. KÜRZEL
            // =========================
            $newSign = trim((string)($_POST['smileys_sing'] ?? ''));
            $oldSign = trim((string)($_POST['osing'] ?? ''));

            if ($newSign === '' || $newSign === $oldSign) {
                $print_smil_edit_1 = "Kürzel nicht geändert<br>";
            } else {

                $stmt = $pdo->prepare("
                    SELECT etchat_smileys_id 
                    FROM {$this->_prefix}etchat_smileys 
                    WHERE etchat_smileys_sign = :sign 
                    AND etchat_smileys_id <> :id
                ");
                $stmt->execute([
                    ':sign' => $newSign,
                    ':id'   => $id
                ]);

                if ($stmt->fetch()) {
                    $print_smil_edit_1 = "Kürzel nicht geändert (existiert bereits)<br>";
                } else {
                    $stmt = $pdo->prepare("
                        UPDATE {$this->_prefix}etchat_smileys 
                        SET etchat_smileys_sign = :sign 
                        WHERE etchat_smileys_id = :id
                    ");
                    $stmt->execute([
                        ':sign' => $newSign,
                        ':id'   => $id
                    ]);

                    $print_smil_edit_1 = "<span class='rot'>Kürzel geändert</span><br>";
                }
            }

            // =========================
            // 🔹 2. KATEGORIE + DATEI
            // =========================
            $oldPath = (string)($_POST['opfad'] ?? '');
            $oldName = (string)($_POST['oname'] ?? '');
            $newName = trim((string)($_POST['name'] ?? ''));

            if ($oldPath !== '' && $newName !== '' && $newName !== $oldName) {

                $filename = basename($oldPath);
                $safeCat  = preg_replace('/[^a-zA-Z0-9_-]/', '_', $newName);

                $baseDir = realpath(__DIR__ . '/../../smilies/');
                $newDir  = $baseDir . '/' . $safeCat;

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

                $targetFile = $newDir . '/' . $filename;

                if (file_exists($targetFile)) {
                    $targetFile = $newDir . '/' . time() . '_' . $filename;
                }

                $oldReal = realpath($oldPath);

                if ($oldReal && str_starts_with($oldReal, $baseDir) && file_exists($oldReal)) {

                    if (@rename($oldReal, $targetFile)) {
                        $print_smil_edit_2 = "<span class='rot'>Kategorie geändert und Datei verschoben</span><br>";
                    } else {
                        $print_smil_edit_2 = "<span class='rot'>Kategorie geändert, Datei konnte nicht verschoben werden</span><br>";
                    }

                    // 🔥 WICHTIG: richtiger relativer Pfad
                    $relativePath = './smilies/' . $safeCat . '/' . basename($targetFile);
                    $relativePath = str_replace(['\\', '//'], '/', $relativePath);

                    $stmt = $pdo->prepare("
                        UPDATE {$this->_prefix}etchat_smileys
                        SET etchat_smileys_kat = :kat, etchat_smileys_img = :img
                        WHERE etchat_smileys_id = :id
                    ");

                    $stmt->execute([
                        ':kat' => $safeCat,
                        ':img' => $relativePath,
                        ':id'  => $id
                    ]);
                }

            } else {
                $print_smil_edit_2 = "Kategorie nicht geändert<br>";
            }

            // =========================
            // 🔹 3. GEWICHT
            // =========================
            $oldWeight = (int)($_POST['ogw'] ?? 0);
            $newWeight = (int)($_POST['gw'] ?? 0);

            if ($newWeight !== $oldWeight) {
                $stmt = $pdo->prepare("
                    UPDATE {$this->_prefix}etchat_smileys 
                    SET etchat_smileys_gewicht = :weight 
                    WHERE etchat_smileys_id = :id
                ");
                $stmt->execute([
                    ':weight' => $newWeight,
                    ':id'     => $id
                ]);

                $print_smil_edit_3 = "<span class='rot'>Gewicht geändert</span><br>";
            } else {
                $print_smil_edit_3 = "Gewicht nicht geändert<br>";
            }

            $this->dbObj->close();

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

        } catch (PDOException $e) {
            echo $lang->error[0]->tagData ?? 'Fehler';
            exit;
        }
    }

    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, string $m1, string $m2, string $m3): void
    {
        $print_smil_edit_1 = $m1;
        $print_smil_edit_2 = $m2;
        $print_smil_edit_3 = $m3;

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