<?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.) 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
*/

class AdminSmiliesIndex extends DbConectionMaker
{
    private string $csrfToken = '';

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

        // CSRF Token
        $csrfKey = 'etchat_' . $this->_prefix . 'csrf_token';
        if (empty($_SESSION[$csrfKey])) {
            $_SESSION[$csrfKey] = bin2hex(random_bytes(16));
        }
        $this->csrfToken = $_SESSION[$csrfKey];

        // AJAX
        if (isset($_GET["SaveSmileyOrder"])) {
            $this->saveSmileyOrder();
            exit;
        }

        // Rechte
        $allowedRoles = ["admin", "co_admin", "grafik"];
        $userRole = $_SESSION['etchat_' . $this->_prefix . 'user_priv'] ?? '';

        if (!in_array($userRole, $allowedRoles, true)) {
            header("Location: ./");
            exit;
        }

        // Kategorie
        $kategorie = isset($_GET['kat']) ? (string)$_GET['kat'] : '';
        $where = '';
        $params = [];

        if ($kategorie !== '') {
            $where = "WHERE etchat_smileys_kat = :kat";
            $params[':kat'] = $kategorie;
        }

        // Kategorien
        $alle_kategorien = $this->dbObj->sqlGet(
            "SELECT DISTINCT etchat_smileys_kat 
             FROM {$this->_prefix}etchat_smileys 
             ORDER BY etchat_smileys_kat ASC"
        );

        // Dropdown
        $print_smil_list4 = "<form method='get' action='' style='display:inline;'>\n";
        $print_smil_list4 .= "<input type='hidden' name='AdminSmiliesIndex' value='1'>\n";
        $print_smil_list4 .= "<select name='kat' onchange='this.form.submit()'>\n";
        $print_smil_list4 .= "<option value=''>Alle Kategorien</option>\n";

        if (is_array($alle_kategorien)) {
            foreach ($alle_kategorien as $kat_row) {
                $katVal = (string)($kat_row[0] ?? '');
                $selected = ($kategorie === $katVal) ? " selected" : "";

                $print_smil_list4 .= "<option value='" .
                    htmlspecialchars($katVal, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . "'$selected>" .
                    htmlspecialchars($katVal, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') .
                    "</option>\n";
            }
        }

        $print_smil_list4 .= "</select>\n</form>\n";

        // Count
        $countQuery = "SELECT count(etchat_smileys_id) FROM {$this->_prefix}etchat_smileys $where";
        $counted = $this->dbObj->sqlGet($countQuery, $params);
        $countTotal = (int)($counted[0][0] ?? 0);

        $print_smil_list3 = " {$countTotal} Smileys gefunden<br>";

        // Pagination
        $site = max(1, (int)($_GET['site'] ?? 1)) - 1;
        $pro_seite = 30;
        $von = $site * $pro_seite;
        $limit = ($this->_usedDatabase === "mysql") ? "LIMIT $von, $pro_seite" : "";

        // Smileys
        $feld = $this->dbObj->sqlGet("
            SELECT * FROM {$this->_prefix}etchat_smileys
            $where
            ORDER BY etchat_smileys_kat, etchat_smileys_gewicht, etchat_smileys_sign ASC
            $limit
        ", $params);

        // Pagination
        $sitemakerObj = new Sitemaker($pro_seite, $countTotal);
        $sitemakerObj->href = true;

        $katQuery = ($kategorie !== '') ? '&kat=' . urlencode($kategorie) : '';
        $siteParam = (int)($_GET['site'] ?? 1);

        $sitemakerObj->make(
            $siteParam,
            "./?AdminSmiliesIndex&site=#site#" . $katQuery,
            $lang->site[0]->tagData,
            $lang->site_of[0]->tagData
        );

        $print_smil_list2 = $sitemakerObj->get();

        // Tabelle
        $print_smil_list = '';

        if (is_array($feld)) {
            $i = 0;

            foreach ($feld as $datasets) {
                $i++;

                $id   = (int)($datasets[0] ?? 0);
                $kat  = (string)($datasets[1] ?? '');
                $text = (string)($datasets[2] ?? '');
                $pic  = (string)($datasets[3] ?? '');
                $gew  = (int)($datasets[4] ?? 0);

                $bgcolor = ($i % 2 === 0) ? "class=\"ungerade\"" : "class=\"gerade\"";

                $print_smil_list .= "
                <tr $bgcolor draggable='true'
                    data-id='{$id}'
                    data-kat='" . htmlspecialchars($kat, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . "'>
                    <td><img class='img_verschieben' src='./img/verschieben.png'></td>
                    <td><img class='img_smiley' src='./" . htmlspecialchars($pic, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . "'></td>
                    <td>" . htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . "</td>
                    <td>" . htmlspecialchars($kat, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . "</td>
                    <td><a href='./?AdminRenameSmilies&id={$id}&csrf_token={$this->csrfToken}'>" . $lang->rename[0]->tagData . "</a></td>
                    <td><a href='./?AdminDeleteSmilies&id={$id}&pic=" . urlencode($pic) . "&csrf_token={$this->csrfToken}'
                        onclick=\"return confirm('Wirklich löschen?')\">" . $lang->delete[0]->tagData . "</a></td>
                    <td>{$gew}</td>
                </tr>";
            }
        }


		// Reihenfolge gespeichert
$savedMsg = '';

if (!empty($_GET['saved']) && $_GET['saved'] === '1') {

    $savedMsg = "
    <div class='success-banner' id='successBanner'>
        <span>Reihenfolge gespeichert</span>
        <span class='close-btn' onclick='closeSuccessBanner()'>&times;</span>
    </div>";

    // 🔥 WICHTIG: Flag sofort entfernen (damit kein Reload-Loop entsteht)
    unset($_GET['saved']);
}

        // 🔥 BUTTON GETRENNT
        $print_smil_list5 = '';

        if ($kategorie !== '') {
            $print_smil_list5 = "
                <button id='saveSmileyBtn'
                    type='button'
                    onclick='saveOrder()'
                    class='admin-button'>
                    Neue Reihenfolge speichern
                </button>";
        } else {
            $print_smil_list5 = "
                <button id='saveSmileyBtn'
                    type='button'
                    class='admin-button'
                    disabled
                    title='Nur mit Kategorie'>
                    Neue Reihenfolge speichern
                </button>";
        }

        // TEMPLATE
        $this->initTemplate(
            $lang,
            $print_smil_list2,
            $print_smil_list,
            $print_smil_list3,
            $print_smil_list4,
            $print_smil_list5,
			$savedMsg 
        );
    }

    private function saveSmileyOrder(): void
    {
        $allowedRoles = ["admin", "grafik", "co_admin"];

        $userRole = $_SESSION['etchat_' . $this->_prefix . 'user_priv'] ?? '';

        if (!in_array($userRole, $allowedRoles, true)) {
            exit("Keine Rechte");
        }

        $headers = function_exists('getallheaders') ? getallheaders() : [];
        $token = $headers['X-CSRF-Token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
        $sessionToken = $_SESSION['etchat_' . $this->_prefix . 'csrf_token'] ?? '';

        if (!hash_equals($sessionToken, $token)) {
            exit("CSRF Fehler");
        }

        $data = json_decode(file_get_contents("php://input"), true);

        $kat = (string)($data['kat'] ?? '');
        $site = max(1, (int)($data['site'] ?? 1));
        $ids = $data['ids'] ?? [];

        if ($kat === '' || empty($ids)) {
            exit("Fehler");
        }

        $pro_seite = 30;
        $offset = ($site - 1) * $pro_seite;
        $gewicht = ($offset * 5) + 5;

        foreach ($ids as $id) {
            $this->dbObj->sqlSet(
                "UPDATE {$this->_prefix}etchat_smileys
                 SET etchat_smileys_gewicht = :gewicht
                 WHERE etchat_smileys_id = :id
                 AND etchat_smileys_kat = :kat",
                [
                    ':gewicht' => $gewicht,
                    ':id' => (int)$id,
                    ':kat' => $kat
                ]
            );
            $gewicht += 5;
        }

        echo "Gespeichert";
    }

    private function initTemplate($lang, $list2, $list, $list3, $list4, $list5, $savedMsg): void
    {
        include "styles/admin_tpl/indexSmilies.tpl.html";
    }
}