<?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 AdminRegUserEdit extends ConnectDB
{
    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');

        // Rollenprüfung
        $allowedRoles = ["admin", "co_admin", "chatwache"];
        $userRole = $_SESSION['etchat_' . $this->_prefix . 'user_priv'] ?? '';

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

        $csrfSess = $_SESSION['etchat_' . $this->_prefix . 'csrf_token'] ?? '';
        $csrfGet  = $_GET['csrf_token'] ?? '';
        $csrfPost = $_POST['csrf_token'] ?? '';

        // --- POST: Benutzer löschen ---
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['userids'])) {
            if (!$this->validateCsrf($csrfSess, $csrfPost)) {
                header("Location: ./");
                exit;
            }
            $this->deleteUsers($_POST['userids']);
        }

        // --- GET: Avatar löschen / Rolle ändern / Inaktive löschen ---
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            $id = (int)($_GET['id'] ?? 0);

            if ($id > 0 && isset($_GET['delavatar'])) {
                if (!$this->validateCsrf($csrfSess, $csrfGet)) {
                    header("Location: ./");
                    exit;
                }
                $this->deleteAvatar($id);
            }

            if ($id > 0 && isset($_GET['mod'])) $this->setRole($id, 'mod');
            if ($id > 0 && isset($_GET['admin'])) $this->setRole($id, 'admin');

            if (isset($_GET['deleteinactive'], $_GET['inactive_months'])) {
                if (!$this->validateCsrf($csrfSess, $csrfGet)) {
                    header("Location: ./");
                    exit;
                }
                $months = (int)$_GET['inactive_months'];
                if ($months > 0) $this->deleteInactiveUsers($months);
            }
        }

        $this->close();
        header("Location: ./?AdminRegUserIndex");
        exit;
    }

    private function validateCsrf(string $sessionToken, string $requestToken): bool
    {
        return !empty($sessionToken) && !empty($requestToken) && hash_equals($sessionToken, $requestToken);
    }

    private function deleteUsers(string|array $userids): void
    {
        $ids = is_array($userids) ? array_map('intval', $userids) : array_map('intval', explode(',', $userids));
        $ids = array_filter($ids);

        foreach ($ids as $id) {
            $this->deleteAvatar($id, true);
        }
    }

    private function deleteAvatar(int $id, bool $deleteUser = false): void
    {
        $avatar = $this->sqlGetSingleAvatar($id);

        $protectedAvatars = ['noavatar.jpg', 'mod_ohne_pic.png', 'autodj.jpg'];
        $fileDir = 'avatar';

        if ($avatar && !in_array($avatar, $protectedAvatars, true)) {
            $filePath = "$fileDir/$avatar";
            if (is_file($filePath)) unlink($filePath);
        }

        $this->sqlSet(
            "UPDATE {$this->_prefix}etchat_user SET etchat_avatar='noavatar.jpg' WHERE etchat_user_id = ?",
            [$id]
        );

        if ($deleteUser) {
            $this->sqlSet(
                "DELETE FROM {$this->_prefix}etchat_user WHERE etchat_user_id = ?",
                [$id]
            );
        }
    }

    private function setRole(int $id, string $userRole): void
    {
        $this->sqlSet(
            "UPDATE {$this->_prefix}etchat_user SET etchat_userprivilegien=? WHERE etchat_user_id=?",
            [$userRole, $id]
        );
    }

    private function deleteInactiveUsers(int $months): void
    {
        $cutoff = time() - ($months * 30 * 24 * 60 * 60);

        $protectedRoles = ["admin", "co_admin", "chatwache", "grafik", "mod"];
        $protectedIds   = [-1, 1, 2];

        $rolePlaceholders = implode(',', array_fill(0, count($protectedRoles), '?'));
        $idPlaceholders   = implode(',', array_fill(0, count($protectedIds), '?'));

        $sqlSelect = "SELECT etchat_user_id, etchat_avatar
                      FROM {$this->_prefix}etchat_user
                      WHERE (etchat_logintime < ? OR etchat_logintime IS NULL)
                        AND etchat_userprivilegien NOT IN ($rolePlaceholders)
                        AND etchat_user_id NOT IN ($idPlaceholders)";

        $params = array_merge([$cutoff], $protectedRoles, $protectedIds);
        $inactiveUsers = $this->sqlGet($sqlSelect, $params);

        if (is_array($inactiveUsers)) {
            foreach ($inactiveUsers as $user) {
                $avatar = $user['etchat_avatar'] ?? '';
                if ($avatar && !in_array($avatar, ['noavatar.jpg','mod_ohne_pic.png','autodj.jpg'], true)) {
                    $file = "avatar/$avatar";
                    if (is_file($file)) unlink($file);
                }
            }
        }

        $sqlDelete = "DELETE FROM {$this->_prefix}etchat_user
                      WHERE (etchat_logintime < ? OR etchat_logintime IS NULL)
                        AND etchat_userprivilegien NOT IN ($rolePlaceholders)
                        AND etchat_user_id NOT IN ($idPlaceholders)";

        $this->sqlSet($sqlDelete, $params);
    }

    // -------------------
    // PUBLIC SQL METHODS
    // -------------------
    public function sqlGet(string $sql, array $params = []): array
    {
        $stmt = $this->_connid->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // ✅ Neu: sqlGetSingleAvatar für Kompatibilität ohne Konflikt
    public function sqlGetSingleAvatar(int $id): ?string
    {
        $row = $this->sqlGet(
            "SELECT etchat_avatar FROM {$this->_prefix}etchat_user WHERE etchat_user_id = ?",
            [$id]
        );
        return $row[0]['etchat_avatar'] ?? null;
    }

    public function sqlSet(string $sql, $params = [])
    {
        if (!is_array($params)) $params = [];
        $stmt = $this->_connid->prepare($sql);
        $stmt->execute($params);
    }
}