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

require_once __DIR__ . '/ConnectDB.class.php';
require_once __DIR__ . '/DbConectionMaker.class.php';

require_once __DIR__ . '/../PHPMailer/src/Exception.php';
require_once __DIR__ . '/../PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/../PHPMailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class Kontakt extends DbConectionMaker
{
    protected string $styleName = 'default';

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

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

        $config = $this->dbObj->sqlGet("
            SELECT etchat_config_style
            FROM {$this->_prefix}etchat_config
            WHERE etchat_config_id = 1
            LIMIT 1
        ");

        if (is_array($config) && isset($config[0][0])) {
            $this->styleName = (string)$config[0][0];
        }
    }

    public function getStyleName(): string
    {
        return $this->styleName;
    }

    public function getDb(): ConnectDB
    {
        return $this->dbObj;
    }

    public function senden(array $daten): string
    {
        // Honeypot
        if (!empty($daten['https_ceck']) || !empty($daten['www'])) {
            return "Spam erkannt!";
        }

        // Captcha prüfen (case-insensitive)
        $captchaInput   = trim($daten['web_php_de'] ?? '');
        $captchaSession = $_SESSION['captcha_text'] ?? '';

        if ($captchaInput === '' || $captchaSession === '' ||
            strcasecmp($captchaInput, $captchaSession) !== 0) {
            return "Falsches Captcha! Bitte erneut versuchen.";
        }

        // Daten vorbereiten
        $saveData = $daten;
        unset($saveData['https_ceck'], $saveData['www'], $saveData['web_php_de'], $saveData['action']);

        $json = json_encode($saveData, JSON_UNESCAPED_UNICODE);

        if ($json === false || json_last_error() !== JSON_ERROR_NONE) {
            return "Fehler beim Speichern der Daten.";
        }

        // DB speichern – Prepared über sqlSet
        try {
            $ok = $this->dbObj->sqlSet("
                INSERT INTO {$this->_prefix}etchat_kontakt
                (etchat_kontakt_daten, etchat_status)
                VALUES (:daten, 'neu')
            ", [
                ':daten' => $json
            ]);

            if ($ok === false) {
                return "Fehler beim Speichern in der Datenbank.";
            }

        } catch (Exception) {
            return "Fehler beim Speichern in der Datenbank.";
        }

        // Mailversand
        global $host, $sendemail, $mailpass, $smtpsecure, $port;

        try {
            $betreff = trim($daten['Betreff'] ?? 'Kontaktanfrage');

            // Admin Mail
            $mailAdmin = new PHPMailer(true);
            $this->configureMailer($mailAdmin, $host, $sendemail, $mailpass, $smtpsecure, $port);

            $mailAdmin->setFrom($sendemail, 'Chat Kontaktformular');
            $mailAdmin->addAddress($sendemail);
            $mailAdmin->Subject = "Neue Kontaktanfrage: {$betreff}";

            $message = $this->buildMessageTable($daten);

            $mailAdmin->isHTML(true);
            $mailAdmin->Body = $message;
            $mailAdmin->AltBody = strip_tags($message);
            $mailAdmin->send();

            // Bestätigung an Nutzer
            $email = $daten['E_Mail'] ?? '';

            if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

                $mailUser = new PHPMailer(true);
                $this->configureMailer($mailUser, $host, $sendemail, $mailpass, $smtpsecure, $port);

                $mailUser->setFrom($sendemail, 'Chat Kontaktformular');
                $mailUser->addAddress($email, $daten['Name'] ?? 'Kontakt');
                $mailUser->Subject = "Ihre Mitteilung: {$betreff}";

                $text = "Hallo " . ($daten['Name'] ?? '') . ",\n\n"
                    . "vielen Dank für Ihre Nachricht zum Thema: {$betreff}.\n"
                    . "Wir haben Ihre Mitteilung erhalten und melden uns zeitnah bei Ihnen.\n\n"
                    . "Viele Grüße\nDas Team";

                $mailUser->isHTML(true);
                $mailUser->Body = nl2br(htmlspecialchars($text));
                $mailUser->AltBody = $text;
                $mailUser->send();
            }

            return "Mitteilung erfolgreich gesendet!";

        } catch (Exception) {
            return "Fehler beim Versenden der E-Mail.";
        }
    }

    private function configureMailer(
        PHPMailer $mail,
        $host,
        $user,
        $pass,
        $secure,
        $port
    ): void {
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';
        $mail->isSMTP();
        $mail->Host = $host;
        $mail->SMTPAuth = true;
        $mail->Username = $user;
        $mail->Password = $pass;
        $mail->SMTPSecure = $secure;
        $mail->Port = (int)$port;
    }

    private function buildMessageTable(array $daten): string
    {
        $fixedOrder = ['Betreff', 'Anrede', 'Name', 'E_Mail'];
        $skip = array_merge($fixedOrder, ['https_ceck','www','web_php_de','action']);

        $message = "<h2>Neue Kontaktanfrage eingegangen</h2><table>";

        foreach ($fixedOrder as $field) {
            if (!empty($daten[$field])) {
                $message .= "<tr><td><strong>{$field}:</strong></td><td>"
                    . htmlspecialchars((string)$daten[$field])
                    . "</td></tr>";
            }
        }

        foreach ($daten as $key => $val) {
            if (in_array($key, $skip, true)) {
                continue;
            }

            if (is_array($val)) {
                $val = implode(", ", $val);
            }

            $message .= "<tr><td><strong>{$key}:</strong></td><td>"
                . htmlspecialchars((string)$val)
                . "</td></tr>";
        }

        $message .= "</table>";

        return $message;
    }
}