<?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.
*/

class TeamView extends DbConectionMaker
{
    public array $rolesFound = [];
    protected string $styleName = 'default';
    protected string $defaultRole = 'mod';

    protected string $adminColor = '#FF0000';
    protected string $modColor = '#00AAFF';
    protected string $userColor = '#CCCCCC';

    public function __construct()
    {
        parent::__construct();
        $this->loadConfig();
        $this->renderHTML();
        $this->dbObj->close();
    }

    private function loadConfig(): void
    {
        $config = $this->dbObj->sqlGet(
            "SELECT etchat_config_admin_color, etchat_config_mod_color, etchat_config_user_color, etchat_config_style
             FROM {$this->_prefix}etchat_config
             WHERE etchat_config_id = ?",
            [1]
        );

        if (!empty($config[0])) {
            $this->styleName = $config[0]['etchat_config_style'] ?? 'default';
            $this->adminColor = $config[0]['etchat_config_admin_color'] ?? '#FF0000';
            $this->modColor   = $config[0]['etchat_config_mod_color'] ?? '#00AAFF';
            $this->userColor  = $config[0]['etchat_config_user_color'] ?? '#CCCCCC';
        }
    }

    private function getUsers(): array
    {
        return $this->dbObj->sqlGet(
            "SELECT etchat_username, etchat_userprivilegien, etchat_reg_timestamp, etchat_usersex,
                    etchat_avatar, etchat_email, etchat_geb_tag, etchat_geb_monat, etchat_geb_jahr,
                    etchat_ort, etchat_beschreibung
             FROM {$this->_prefix}etchat_user
             WHERE etchat_userprivilegien IN ('admin','co_admin','mod','chatwache','grafik')
             ORDER BY etchat_user_id DESC"
        ) ?: [];
    }

    private function renderHTML(): void
    {
        $users = $this->getUsers();

        echo '<!DOCTYPE html><html lang="de"><head>';
        echo '<meta charset="UTF-8">';
        echo '<title>Teamübersicht</title>';
        echo '<link href="styles/' . htmlspecialchars($this->styleName, ENT_QUOTES | ENT_SUBSTITUTE) . '/style.css" rel="stylesheet">';
        echo '<link href="styles/' . htmlspecialchars($this->styleName, ENT_QUOTES | ENT_SUBSTITUTE) . '/style-mobil-index.css" rel="stylesheet">';
        echo '</head><body id="body">';

        $roles = [];
        foreach ($users as $user) {
            $roles[$user['etchat_userprivilegien']] = true;
        }
        $this->rolesFound = $roles;
        $this->defaultRole = $this->determineDefaultRole($roles);

        echo '<center><h2 id="role-title">Unsere Moderatoren</h2></center>';
        echo '<div class="role-tabs" data-default-role="' . htmlspecialchars($this->defaultRole) . '">';
        if (!empty($roles['mod'])) echo '<button class="role-tab" data-role="mod">Moderatoren</button>';
        if (!empty($roles['admin']) || !empty($roles['co_admin'])) echo '<button class="role-tab" data-role="admin-group">Administratoren</button>';
        if (!empty($roles['chatwache'])) echo '<button class="role-tab" data-role="chatwache">Chatwache</button>';
        if (!empty($roles['grafik'])) echo '<button class="role-tab" data-role="grafik">Grafiker</button>';
        echo '</div>';

        echo '<div class="compact-mod-row">';
        foreach ($users as $user) {
            $this->renderCard($user);
        }
        echo '</div>';

        $this->renderJS();
        echo '</body></html>';
    }

    private function determineDefaultRole(array $roles): string
    {
        if (!empty($roles['mod'])) return 'mod';
        if (!empty($roles['admin']) || !empty($roles['co_admin'])) return 'admin-group';
        if (!empty($roles['chatwache'])) return 'chatwache';
        if (!empty($roles['grafik'])) return 'grafik';
        return 'mod';
    }

    private function renderCard(array $user): void
    {
        $role = $user['etchat_userprivilegien'] ?? 'user';
        $this->rolesFound[$role] = true;

        $colors = [
            'admin' => $this->adminColor,
            'co_admin' => $this->adminColor,
            'mod' => $this->modColor,
            'chatwache' => $this->adminColor,
            'grafik' => $this->adminColor,
            'user' => $this->userColor
        ];
        $color = $colors[$role] ?? '#CCCCCC';

        $roleNames = [
            'admin' => 'Administrator',
            'co_admin' => 'Co-Administrator',
            'mod' => 'Moderator',
            'chatwache' => 'Chatwache',
            'grafik' => 'Grafiker',
            'user' => 'Benutzer'
        ];
        $roleName = $roleNames[$role] ?? ucfirst($role);

        $username = htmlspecialchars($user['etchat_username'] ?? '', ENT_QUOTES | ENT_SUBSTITUTE);
        $avatar = basename($user['etchat_avatar'] ?? '');
        $regDate = !empty($user['etchat_reg_timestamp']) ? date('d.m.Y', strtotime($user['etchat_reg_timestamp'])) : '-';
        $gender = match($user['etchat_usersex'] ?? '') {
            'm' => 'Männlich',
            'f' => 'Weiblich',
            'n' => 'keine Angabe',
            'd' => 'Divers',
            default => ''
        };

        // Geburtstag / Alter
        $birth = '';
        $today = new DateTime('today');
        if (!empty($user['etchat_geb_tag']) && !empty($user['etchat_geb_monat'])) {
            $year = $user['etchat_geb_jahr'] ?? null;
            $birthDate = $year ? sprintf("%04d-%02d-%02d", $year, $user['etchat_geb_monat'], $user['etchat_geb_tag']) : null;
            $birthFormatted = $year
                ? sprintf("%02d.%02d.%04d", $user['etchat_geb_tag'], $user['etchat_geb_monat'], $year)
                : sprintf("%02d.%02d.", $user['etchat_geb_tag'], $user['etchat_geb_monat']);

            try {
                if ($birthDate) {
                    $birthDateObj = new DateTime($birthDate);
                    $age = $birthDateObj->diff($today)->y;
                }
                $isBirthday = ($today->format('d') == $user['etchat_geb_tag'] && $today->format('m') == $user['etchat_geb_monat']);
                if ($isBirthday) {
                    $birth = "<span style='color:red; font-weight:bold;'>{$birthFormatted}" . ($year ? " ({$age})" : "") .
                             " <img src=\"img/cake.png\" alt=\"Geburtstag\" style=\"width:16px;height:16px;vertical-align:middle;\"></span>";
                } else {
                    $birth = $birthFormatted . ($year ? " ({$age})" : "");
                }
            } catch (Exception) {
                $birth = $birthFormatted;
            }
        }

        $email  = htmlspecialchars($user['etchat_email'] ?? '', ENT_QUOTES | ENT_SUBSTITUTE);
        $emailk = mb_strimwidth($email, 0, 15, " ....");
        $ort    = !empty($user['etchat_ort']) ? htmlspecialchars($user['etchat_ort'], ENT_QUOTES | ENT_SUBSTITUTE) : '-';
        $beschreibung = !empty($user['etchat_beschreibung']) ? nl2br(htmlspecialchars($user['etchat_beschreibung'], ENT_QUOTES | ENT_SUBSTITUTE)) : '-';

        $maxLength = 40;
        if (mb_strlen(strip_tags($beschreibung)) > $maxLength) {
            $shortDesc = mb_substr(strip_tags($beschreibung), 0, $maxLength);
            $shortDesc = nl2br($shortDesc);
            $beschreibungHTML = "<div class='beschreibung-full' data-short='{$shortDesc}' data-full='{$beschreibung}'>{$shortDesc}... <a href='#' class='toggle-full'>mehr</a></div>";
        } else {
            $beschreibungHTML = "<div class='beschreibung-full'>{$beschreibung}</div>";
        }

        echo <<<HTML
<div class="compact-mod-card" data-role="{$role}">
    <div class="top-row">
        <div class="avatar-mod" style="border: 3px solid {$color}; border-radius: 10%;">
            <img src="avatar/{$avatar}" alt="{$username}" style="width: 100%; height: 100%; object-fit: cover;">
        </div>
        <div class="modinfo">
            <strong>{$username}</strong><br>
            Rolle: {$roleName}<br>
            Geschlecht: {$gender}<br>
            Registriert: {$regDate}<br>
            Geburtstag: {$birth}<br>
            Ort: {$ort}<br>
            Email: <a href="mailto:{$email}">{$emailk}</a><br>
        </div>
    </div>
    {$beschreibungHTML}
</div>
HTML;
    }

    private function renderJS(): void
    {
        $defaultRoleJS = htmlspecialchars($this->defaultRole);
        echo <<<JS
<script>
// Toggle Beschreibung
document.addEventListener('click', function(e){
    if(e.target.classList.contains('toggle-full')){
        e.preventDefault();
        const container = e.target.parentNode;
        const isShort = container.innerHTML.includes('mehr');
        if(isShort){
            container.innerHTML = container.dataset.full.replace(/\\n/g,'<br>') + ' <a href="#" class="toggle-full">weniger</a>';
        } else {
            container.innerHTML = container.dataset.short + '... <a href="#" class="toggle-full">mehr</a>';
        }
    }
});

// Rollen-Tabs
document.addEventListener("DOMContentLoaded", function() {
    const tabs = document.querySelectorAll(".role-tab");
    const cards = document.querySelectorAll(".compact-mod-card");
    const title = document.getElementById("role-title");

    function showRole(role) {
        cards.forEach(card => {
            if (
                card.dataset.role === role ||
                (role === "admin-group" && (card.dataset.role === "admin" || card.dataset.role === "co_admin"))
            ) {
                card.style.display = "block";
            } else {
                card.style.display = "none";
            }
        });

        const roleNames = {
            "mod": "Unsere Moderatoren",
            "admin-group": "Unsere Administratoren",
            "chatwache": "Unsere Chatwachen",
            "grafik": "Unsere Grafiker"
        };
        title.textContent = roleNames[role] ?? "Benutzer";
    }

    const defaultRole = '{$defaultRoleJS}';
    showRole(defaultRole);
    const defaultTab = document.querySelector('.role-tab[data-role="' + defaultRole + '"]');
    if (defaultTab) defaultTab.classList.add("active");

    tabs.forEach(tab => {
        tab.addEventListener("click", () => {
            tabs.forEach(t => t.classList.remove("active"));
            tab.classList.add("active");
            showRole(tab.dataset.role);
        });
    });
});
</script>
JS;
    }
}