<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;

require 'vendor/autoload.php';

function sendmail($subject, $from, $body, $cc=[], $bcc=[], $to=[]) {
    global $develop;

    $ret = [];
    $ret['error'] = false;

    $develop = 'true';

    $mail = new PHPMailer(true);
    
    try {
        // Debug-Einstellungen
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->Debugoutput = function($str, $level) {
            file_put_contents(__DIR__ . '/phpmailer_debug.log',
                date('Y-m-d H:i:s') . " [Level $level] $str\n", FILE_APPEND);
        };
        
        // Basis-Einstellungen
        $mail->CharSet = 'UTF-8';
        $mail->isSMTP();
        
        if ($develop == 'true') {
            $mail->Host = 'mailhog';
            $mail->Port = 1025;
            $mail->SMTPAuth = false;
        } else {
            // GMX Einstellungen
            $mail->Host = 'smtp.gmx.com';  // ✅ Korrekter Host
            $mail->Port = 465;
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->SMTPAuth = true;
            $mail->Username = 'sternwarte.welzheim@gmx.de';
            $mail->Password = '4NT&%nH9&5wz';  // ✅ Tippfehler korrigiert
            
            // Optional: Zusätzliche Authentifizierung
            $mail->AuthType = 'LOGIN';
            
            // Optional: Timeout erhöhen
            $mail->Timeout = 60;
        }
        
        // Absender
        $mail->setFrom('sternwarte.welzheim@gmx.de', 'Sternwarte-Welzheim');
        
        // Empfänger
        if (count($to) != 0) {
            foreach ($to as $t) {
                $mail->addAddress($t);
            }
        }
        
        // CC
        if (count($cc) != 0) {
            foreach ($cc as $c) {
                $mail->addCC($c);
            }
        }
        
        // BCC
        if (count($bcc) != 0) {
            foreach ($bcc as $bc) {
                if ($develop == 'true') {
                    $mail->addCC($bc);
                } else {
                    $mail->addBCC($bc);
                }
            }
        }
        
        // Reply-To
        if (!empty($from)) {
            $mail->addReplyTo($from);
        }
        
        // Inhalt
        $mail->Subject = $subject;
        $mail->isHTML(false);  // Oder true, je nach Bedarf
        $mail->Body = $body;
        
        // Senden
        $mail->send();
        $ret['oktext'] = 'Mail erfolgreich versendet';
        
    } catch (Exception $e) {
        $ret['error'] = true;
        $ret['errortext'] = "Mailer Error: {$mail->ErrorInfo}";
        error_log("PHPMailer Error: " . $e->getMessage());
    }
    
    return $ret;
}
