<?php

session_start();

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

include('../config.php');

require '../PHPMailer/src/Exception.php';
require '../PHPMailer/src/PHPMailer.php';
require '../PHPMailer/src/SMTP.php';

$radioName = 'Unbekannt';
foreach ($_SESSION as $key => $value) {
    if (strpos($key, '_radio_name') !== false) {
        $radioName = $value;
        break;
    }
}


if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $action = $_POST["action"] ?? "";
    $messageText = trim($_POST["nachricht"] ?? "");

    if (empty($messageText)) {
        echo '<script>alert("Bitte eine Nachricht eingeben!"); window.history.back();</script>';
        exit();
    }

    if ($action === "textnachricht") {
	    $subject = "Neue Nachricht von " . $radioName;
    	$body = "?? Neue Nachricht von " . $radioName . ":\n\n" . $messageText;
	} elseif ($action === "bugreport") {
	    $subject = "Neuer Bug-Report von " . $radioName;
    	$body = "?? Neuer Bug-Report von " . $radioName . ":\n\n" . $messageText;
	} else {
    	echo '<script>alert("Ungültige Aktion."); window.history.back();</script>';
	    exit();
	}

	$empfaenger = 'et-chat-mod@abwesend.de';

    $mail = new PHPMailer(true);

    try {
        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host = $host;
        $mail->SMTPAuth = true;
        $mail->Username = $sendemail;
        $mail->Password = $mailpass;
        $mail->SMTPSecure = $smtpsecure;
        $mail->Port = $port;

        $cleanedName = preg_replace('/[^a-zA-Z0-9\-\.\s]/', '', $radioName); // Sonderzeichen sicher entfernen
        $cleanedName = mb_substr($cleanedName, 0, 40); // max. 40 Zeichen

		$mail->setFrom($sendemail, $cleanedName);

        $mail->addAddress($empfaenger);
        $mail->Subject = $subject;
        $mail->Body = $body;

        $mail->send();
        echo '<script>alert("Nachricht erfolgreich per E-Mail gesendet!"); window.history.back();</script>';
    } catch (Exception $e) {
        echo '<script>alert("Fehler beim E-Mail-Versand: ' . addslashes($mail->ErrorInfo) . '"); window.history.back();</script>';
    }
}


