<?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 Index extends DbConectionMaker
{
    public $lang = [];
    public int $aktuell_date_u;

    public function __construct()
    {
        parent::__construct();

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

        if (!headers_sent()) {
            header('Content-Type: text/html; charset=utf-8');
        }

        // Cookie sicher setzen
        setcookie(
            $this->_prefix . "cookie_test",
            (string) time(),
            [
                'expires'  => time() + 3600,
                'path'     => '/',
                'secure'   => ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || ($_SERVER['SERVER_PORT'] ?? 80) == 443),
                'httponly' => true,
                'samesite' => 'Lax'
            ]
        );

        $this->configTabData2Session();

        $this->runCleanupIfDue();

        $this->aktuell_date_u = time();
        $_SESSION[$this->_prefix . 'set_check'] = hash('sha256', (string) $this->aktuell_date_u);

        $this->loadLanguage();

        $this->initTemplate();
    }

    private function runCleanupTasks(): void
    {
        $deleteDays = (int) ($_SESSION['etchat_' . $this->_prefix . 'loeschen_nach'] ?? 30);

        $messageExpireTime = time() - ($deleteDays * 86400);
        $guestExpireTime    = time() - ($deleteDays * 86400 * 2);
        $currentTime        = time();

        // Prepared deletes
        $this->dbObj->sqlSet(
            "DELETE FROM {$this->_prefix}etchat_messages WHERE etchat_timestamp < :ts",
            [':ts' => $messageExpireTime]
        );

        $this->dbObj->sqlSet(
            "DELETE FROM {$this->_prefix}etchat_blacklist WHERE etchat_blacklist_time < :t",
            [':t' => $currentTime]
        );

        $this->dbObj->sqlSet(
            "DELETE FROM {$this->_prefix}etchat_kick_user WHERE etchat_kicked_user_time < :t",
            [':t' => $currentTime]
        );

        $this->dbObj->sqlSet(
            "DELETE FROM {$this->_prefix}etchat_user
             WHERE etchat_userprivilegien = 'gast'
             AND etchat_logintime < :gt",
            [':gt' => $guestExpireTime]
        );
    }

    private function loadLanguage(): void
    {
        try {
            $langObj = new LangXml();
            $langData = $langObj->getLang();
            $this->lang = $langData->index_php[0] ?? [];
        } catch (Throwable $e) {
            error_log("Language load error: " . $e->getMessage());
            $this->lang = [];
        }
    }

    private function initTemplate(): void
    {
        $style = preg_replace('/[^a-zA-Z0-9_\-]/', '', $_SESSION['etchat_' . $this->_prefix . 'style'] ?? 'default');
        $templatePath = "styles/{$style}/index.tpl.html";

        if (is_file($templatePath)) {
            include_once $templatePath;
        } else {
            error_log("Template not found: " . $templatePath);
        }
    }

    private function monthlyMaintenance(): void
    {
        if ((int) date('d') !== 31) {
            return;
        }

        try {
            $this->dbObj->sqlSet("SET @a = 0");
            $this->dbObj->sqlSet("UPDATE {$this->_prefix}etchat_messages SET etchat_id = (@a := @a + 1)");
            $this->dbObj->sqlSet("ALTER TABLE {$this->_prefix}etchat_messages AUTO_INCREMENT = 1");
			
			$this->dbObj->sqlSet("OPTIMIZE TABLE {$this->_prefix}etchat_messages");
			
        } catch (Throwable $e) {
            error_log("Monthly maintenance error: " . $e->getMessage());
        }
	}

    private function runCleanupIfDue(): void
    {
        $interval = 3600;
        $file = __DIR__ . '/../cache/cleanup_last_run.txt';

        $lastRun = is_file($file) ? (int) file_get_contents($file) : 0;

        if (time() - $lastRun >= $interval) {
            $this->runCleanupTasks();
			// $this->monthlyMaintenance(); //Aktivieren wenn man an jeden 31 eines Monats also 5 mal im Jahr die ID der Messages zurücksetzen will
            file_put_contents($file, (string) time(), LOCK_EX);
        }
    }
}