<?php
// includes/core/Mailer.php

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

require_once __DIR__ . '/../libs/phpmailer/src/PHPMailer.php';
require_once __DIR__ . '/../libs/phpmailer/src/SMTP.php';
require_once __DIR__ . '/../libs/phpmailer/src/Exception.php';
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/ErrorLogger.php';

class Mailer {
    private $mail;

    public function __construct() {
        $config = include __DIR__ . '/../config.php';
        $smtp = $config['mail'];

        $this->mail = new PHPMailer(true);
        $this->mail->CharSet = 'UTF-8'; // Standard auf UTF-8 setzen

        try {
            $this->mail->isSMTP();
            $this->mail->Host = $smtp['smtp_host'];
            $this->mail->SMTPAuth = true;
            $this->mail->Username = $smtp['smtp_user'];
            $this->mail->Password = $smtp['smtp_pass'];
            $this->mail->SMTPSecure = $smtp['smtp_secure'];
            $this->mail->Port = $smtp['smtp_port'];

            $this->mail->setFrom($smtp['from_email'], $smtp['from_name']);
            $this->mail->isHTML(true);
        } catch (Exception $e) {
            ErrorLogger::log("Mailer Init Error: " . $e->getMessage());
        }
    }

    public function setCharset($charset) {
        $this->mail->CharSet = $charset;
    }

    public function send($to, $subject, $htmlBody, $altBody = '') {
        try {
            $this->mail->clearAddresses();
            $this->mail->addAddress($to);
            $this->mail->Subject = $subject;
            $this->mail->Body = $htmlBody;
            $this->mail->AltBody = $altBody ?: strip_tags($htmlBody);

            return $this->mail->send();
        } catch (Exception $e) {
            ErrorLogger::log("Mailer Send Error: " . $this->mail->ErrorInfo);
            return false;
        }
    }
}
