<?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 AdminMenusIndex 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
        $langObj = new LangXml();
        $langData = $langObj->getLang();
        $lang = $langData->admin[0]->admin_menus[0] ?? (object)[];

        // Rollenprüfung
        $allowedRoles = ["admin"];
        $userRole = (string)($_SESSION['etchat_'.$this->_prefix.'user_priv'] ?? '');

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

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

        // Daten holen
        $menuItems = $this->dbObj->sqlGet(
            "SELECT id, menu, link_text, image_active, image, url, target, gewicht
             FROM {$this->_prefix}etchat_menu
             ORDER BY menu, gewicht"
        );

        $this->dbObj->close();

        // Tabelle bauen
        $print_menu_list = $this->buildMenuTable($menuItems, $csrfToken);

        $this->initTemplate($lang, $print_menu_list);
    }

    private function buildMenuTable(array|false $menuItems, string $csrfToken): string
    {
        ob_start();
        ?>

        <table border="1" cellpadding="5" cellspacing="0">
            <thead>
                <tr>
                    <th>Link Name</th>
                    <th>URL</th>
                    <th>Fenster</th>
                    <th>Aktionen</th>
                    <th>Menu</th>
                    <th>Gewichtung</th>
                    <th>Bild</th>
                </tr>
            </thead>
            <tbody>

        <?php if (is_array($menuItems)): ?>
            <?php foreach ($menuItems as $row): 

                $id       = (int)($row['id'] ?? 0);
                $menu     = (int)($row['menu'] ?? 0);
                $text     = htmlspecialchars($row['link_text'] ?? '', ENT_QUOTES, 'UTF-8');
                $url      = htmlspecialchars($row['url'] ?? '', ENT_QUOTES, 'UTF-8');
                $image    = basename((string)($row['image'] ?? ''));
                $target   = in_array($row['target'] ?? '', ['_top','_blank'], true) ? $row['target'] : '_blank';
                $gewicht  = (int)($row['gewicht'] ?? 0);
                $imgAktiv = (int)($row['image_active'] ?? 0);

                $ort = match ($menu) {
                    1 => 'Chat',
                    2 => 'Index',
                    3 => 'Banner',
                    default => 'Unbekannt',
                };

                $urlShort = mb_strimwidth($url, 0, 75, '...', 'UTF-8');
                $fenster = ($target === '_top') ? 'Selbes Fenster' : 'Neues Fenster';

            ?>
                <tr>
                    <td><b><?= $text ?></b></td>
                    <td><?= $urlShort ?></td>
                    <td><?= htmlspecialchars($fenster) ?></td>

                    <td>
						<a href="./?AdminEditMenu&id=<?= $id ?>&csrf_token=<?= $csrfToken ?>">Editieren</a>
					<br><br>
						<a href="./?AdminDeleteMenu&id=<?= $id ?>&csrf_token=<?= $csrfToken ?>">Löschen</a>
                    </td>

                    <td><i><?= htmlspecialchars($ort) ?></i></td>
                    <td><?= $gewicht ?></td>

                    <td>
                        <?php if ($imgAktiv === 1 && $image !== ''): ?>
                            <img height="30" src="img/menu/<?= htmlspecialchars($image) ?>" alt="">
                        <?php endif; ?>
                    </td>
                </tr>

            <?php endforeach; ?>
        <?php endif; ?>

            </tbody>
        </table>

        <?php
        return ob_get_clean();
    }

    private function initTemplate(object $lang, string $print_menu_list): void
    {
        include_once("styles/admin_tpl/indexMenus.tpl.html");
    }
}