<?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.)
und wird unter der Namenserweiterung M.C.v.x.x.x. geführt. 
PHP 8/9 Ready, XML Parser, PDO Prepared Statements Get Set sicherheit usw.
 */

class AdminDBGastCleaner extends DbConectionMaker
{
    public function __construct()
    {
        parent::__construct();

        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

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

        if (!in_array($userPriv, $allowedRoles, true)) {
            exit('Keine Berechtigung.');
        }

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

        $csrfToken = $_SESSION['etchat_' . $this->_prefix . 'csrf_token'];

        // 🔥 Aktionen
        $this->handleActions($csrfToken);

        // 🔹 Daten
        $guests = $this->loadGuests();

        // 🔹 HTML vorbereiten
        $vari1 = $this->buildGuestRows($guests, $csrfToken); // Tabelleninhalt
        $vari2 = $csrfToken; // Token für Links

        // 🔹 Template Pfad
        $tplPath = __DIR__ . '/../../styles/admin_tpl/indexGastCleaner.tpl.html';

        if (!is_file($tplPath)) {
            exit('Template nicht gefunden: ' . $tplPath);
        }

        // 🔹 TEMPLATE LADEN (WICHTIG!)
        include $tplPath;
    }

    private function handleActions(string $csrfToken): void
    {
        $action = $_GET['action'] ?? '';

        if ($action === '') {
            return;
        }

        $token = $_GET['csrf_token'] ?? '';

        if (!$token || !hash_equals($csrfToken, $token)) {
            exit('Manipulationsversuch erkannt.');
        }

        if ($action === 'delete' && isset($_GET['id'])) {
            $this->dbObj->sqlSet(
                "DELETE FROM {$this->_prefix}etchat_user 
                 WHERE etchat_user_id = :id 
                 AND etchat_userprivilegien = 'gast'",
                [':id' => (int)$_GET['id']]
            );
        }

		if ($action === 'delete_all') {
			$threshold = time() - 300;  // 3 Minuten
    
			// 1. Normale Gäste (kein Passwort)
			$this->dbObj->sqlSet(
				"DELETE FROM {$this->_prefix}etchat_user
				WHERE etchat_userprivilegien = 'gast'
				AND (etchat_userpw IS NULL OR etchat_userpw = '')
				AND etchat_logintime IS NOT NULL
				AND etchat_logintime < :threshold
				AND NOT EXISTS (
					SELECT 1 FROM {$this->_prefix}etchat_useronline uo 
					WHERE uo.etchat_onlineuser_fid = {$this->_prefix}etchat_user.etchat_user_id
				)",
				[':threshold' => $threshold]
			);
			
			$threshold = time() - 2100;  // 35 Minuten
    
			// 2. Registrierte Gäste (mit Passwort, nicht aktiviert)
			$this->dbObj->sqlSet(
				"DELETE FROM {$this->_prefix}etchat_user
				WHERE etchat_userprivilegien = 'gast'
				AND etchat_userpw IS NOT NULL 
				AND etchat_userpw != ''
				AND etchat_reg_timestamp != '1980-01-01 00:00:00'
				AND UNIX_TIMESTAMP(etchat_reg_timestamp) < :threshold
				AND NOT EXISTS (
					SELECT 1 FROM {$this->_prefix}etchat_useronline uo 
					WHERE uo.etchat_onlineuser_fid = {$this->_prefix}etchat_user.etchat_user_id
				)",
				[':threshold' => $threshold]
			);
		}

        $this->dbObj->close();

        header("Location: ./?AdminDBGastCleaner");
        exit;
    }

	private function loadGuests(): array
	{
		$data = $this->dbObj->sqlGet(
			"SELECT u.etchat_user_id, u.etchat_username, u.etchat_userpw, u.etchat_email, 
					u.etchat_logintime, u.etchat_last_ip, u.etchat_reg_timestamp, u.etchat_reg_ip,
					uo.etchat_onlinetimestamp
			FROM {$this->_prefix}etchat_user u
			LEFT JOIN {$this->_prefix}etchat_useronline uo
			ON uo.etchat_onlineuser_fid = u.etchat_user_id
			WHERE u.etchat_userprivilegien = 'gast'
			ORDER BY u.etchat_username ASC"
		);

		$this->dbObj->close();

		if ($data === false) {
			return [];
		}

		return $data;
	}

	private function buildGuestRows(array $guests, string $csrfToken): string
	{
		if (empty($guests)) {
			return '<tr><td colspan="7">Keine Gäste gefunden.</td></tr>';
		}

		$html = '';
		$threshold = time() - 600;

		foreach ($guests as $g) {
			$online = (!empty($g['etchat_onlinetimestamp']) && (int)$g['etchat_onlinetimestamp'] >= $threshold);

			// 🔥 NULL-Werte sicher behandeln
			$username = $g['etchat_username'] ?? 'Unbekannt';
    
			// 🔥 E-Mail: NULL oder leer = "-", sonst klickbarer mailto: Link
			$email = '-';
			if (!empty($g['etchat_email'])) {
				$emailEncoded = htmlspecialchars($g['etchat_email'], ENT_QUOTES, 'UTF-8');
				$email = '<a href="mailto:' . $emailEncoded . '" style="text-decoration: none;" title="E-Mail schreiben">📧 ' . $emailEncoded . '</a>';
			}
    
			// 🔥 Prüfen ob Passwort vorhanden ist (registriert aber nicht freigeschaltet)
			$hasPassword = !empty($g['etchat_userpw']);
    
			// 🔥 Status bestimmen
			$status = 'Gast';
			$statusClass = '';
			if ($hasPassword) {
				$status = '⏳ Registriert <small>(nicht aktiviert 30min.)</small>';
				$statusClass = 'style="color: orange;"';
			}
    
			// 🔥 Anzeige-Loginzeit
			$logintime = 'unbekannt';
			if ($hasPassword) {
				if (isset($g['etchat_reg_timestamp']) && !empty($g['etchat_reg_timestamp'])) {
					$logintime = date("d.m.Y H:i", strtotime($g['etchat_reg_timestamp']));
				}
			} else {
				if (isset($g['etchat_logintime']) && is_numeric($g['etchat_logintime'])) {
					$logintime = date("d.m.Y H:i", (int)$g['etchat_logintime']);
				}
			}
    
			// 🔥 IP-Adresse
			$displayIp = 'unbekannt';
			if ($hasPassword) {
				$displayIp = $g['etchat_reg_ip'] ?? 'unbekannt';
			} else {
				$displayIp = $g['etchat_last_ip'] ?? 'unbekannt';
			}
			
			$html .= '<tr>
					<td>' . $username . '</td>
					<td class="' . ($online ? 'online' : 'offline') . '">' . ($online ? 'Online' : 'Offline') . '</td>
					<td ' . $statusClass . '>' . $status . '</td>
					<td>' . $email . '</td>  <!-- 📧 NULL wird zu "-" -->
					<td>
						<a href="?AdminDBGastCleaner&action=delete&id=' . (int)$g['etchat_user_id'] . '&csrf_token=' . $csrfToken . '"
						onclick="return confirm(\'Diesen Gast wirklich löschen?\')">Löschen</a>
					</td>
					<td>' . htmlspecialchars($logintime, ENT_QUOTES, 'UTF-8') . '</td>
					<td>' . htmlspecialchars($displayIp, ENT_QUOTES, 'UTF-8') . '</td>
				</tr>';
		}

		return $html;
	}
}