<?php
// Fehlerausgabe komplett deaktivieren
error_reporting(0);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require_once dirname(__DIR__) . '/phpmailer/src/Exception.php';
require_once dirname(__DIR__) . '/phpmailer/src/PHPMailer.php';
require_once dirname(__DIR__) . '/phpmailer/src/SMTP.php';

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

class PHP_Email_Form {
    public string $to;
    public string $from_name;
    public string $from_email;
    public string $subject;
    public string $message = '';
    public array $smtp = [];
    public bool $ajax = false;
    public ?string $reply_to = null;

    private string $error = '';
    private array $error_messages = [
        'invalid' => 'Etwas ist schiefgelaufen. Bitte versuchen Sie es später noch einmal.',
        'invalid_email' => 'E-Mail-Adresse scheint ungültig zu sein.',
        'short' => 'ist zu kurz oder leer.',
        'file_error' => 'Fehler beim Hochladen der Datei.'
    ];

    private $attachments = [];

    private function preSend(): bool {
        if (empty($this->to)) {
            $this->error = 'Empfänger-E-Mail fehlt.';
            return false;
        }

        if (empty($this->from_email)) {
            $this->error = 'Absender-E-Mail fehlt.';
            return false;
        }

        if (empty($this->subject)) {
            $this->error = 'Betreff fehlt.';
            return false;
        }

        if (empty($this->message)) {
            $this->error = 'Nachricht fehlt.';
            return false;
        }

        return true;
    }

    public function add_message(string $content, string $label = '', ?int $length_check = null): void {
        $content = strip_tags($content);
        
        if ($length_check !== null && strlen($content) < $length_check) {
            $this->error .= $label . ' ' . $this->error_messages['short'] . '<br>';
            return;
        }
        
        $escaped_content = htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
        $escaped_content = nl2br($escaped_content); // Zeilenumbrüche in <br> konvertieren
        
        if (!empty($label)) {
            $this->message .= "
                <tr>
                    <td style='padding: 12px 15px; border-bottom: 1px solid #e0e0e0; background: #f8f9fa; font-weight: 600; color: #2c3e50; width: 150px;'>
                        $label:
                    </td>
                    <td style='padding: 12px 15px; border-bottom: 1px solid #e0e0e0; color: #34495e;'>
                        $escaped_content
                    </td>
                </tr>";
        } else {
            $this->message .= "
                <tr>
                    <td colspan='2' style='padding: 12px 15px; border-bottom: 1px solid #e0e0e0; color: #34495e;'>
                        $escaped_content
                    </td>
                </tr>";
        }
    }

    public function add_attachment($field_name, $max_size = 20, $allowed_types = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png', 'gif']): void {
        if (!isset($_FILES[$field_name]) || $_FILES[$field_name]['error'] !== UPLOAD_ERR_OK) {
            return;
        }

        $file = $_FILES[$field_name];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if (!in_array($ext, $allowed_types)) {
            $this->error .= 'Ungültiger Dateityp. Erlaubt sind: ' . implode(', ', $allowed_types) . '<br>';
            return;
        }
        
        if ($file['size'] > $max_size * 1024 * 1024) {
            $this->error .= "Datei ist zu groß. Maximum: {$max_size}MB<br>";
            return;
        }

        $this->attachments[] = [
            'path' => $file['tmp_name'],
            'name' => $file['name'],
            'type' => $file['type']
        ];
    }

    public function send(): string {
        try {
            if (!$this->preSend()) {
                return $this->error;
            }

            $mail = new PHPMailer(true);

            // Server settings
            $mail->isSMTP();
            $mail->Host = $this->smtp['host'];
            $mail->SMTPAuth = $this->smtp['auth'] ?? true;
            $mail->Username = $this->smtp['username'];
            $mail->Password = $this->smtp['password'];
            $mail->SMTPSecure = $this->smtp['secure'] ?? PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = $this->smtp['port'];
            $mail->CharSet = 'UTF-8';

            // Recipients
            $mail->setFrom($this->from_email, $this->from_name);
            $mail->addAddress($this->to);
            if (!empty($this->reply_to)) {
                $mail->addReplyTo($this->reply_to);
            }

            // Attachments
            foreach ($this->attachments as $attachment) {
                $mail->addAttachment(
                    $attachment['path'],
                    $attachment['name'],
                    'base64',
                    $attachment['type']
                );
            }

            // HTML Template für professionelle E-Mail
            $html_body = $this->buildHtmlTemplate();

            // Content
            $mail->isHTML(true);
            $mail->Subject = $this->subject;
            $mail->Body = $html_body;
            $mail->AltBody = strip_tags(str_replace(['<br>', '</tr>'], ["\n", "\n"], $this->message));

            $mail->send();
            return 'OK';

        } catch (Exception $e) {
            return 'Mailer Error: ' . $mail->ErrorInfo;
        }
    }

    private function buildHtmlTemplate(): string {
        $current_year = date('Y');
        return <<<HTML
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{$this->subject}</title>
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background-color: #f4f4f4;">
    <table role="presentation" style="width: 100%; border-collapse: collapse; background-color: #f4f4f4;">
        <tr>
            <td style="padding: 40px 20px;">
                <table role="presentation" style="width: 100%; max-width: 600px; margin: 0 auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                    <!-- Header -->
                    <tr>
                        <td style="padding: 30px 30px 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 8px 8px 0 0; text-align: center;">
                            <h1 style="margin: 0; color: #ffffff; font-size: 24px; font-weight: 600;">
                                Neue Kontaktanfrage
                            </h1>
                            <p style="margin: 10px 0 0; color: #e0e7ff; font-size: 14px;">
                                HKW Anwälte Webformular
                            </p>
                        </td>
                    </tr>
                    
                    <!-- Content -->
                    <tr>
                        <td style="padding: 30px;">
                            <p style="margin: 0 0 20px; color: #555; font-size: 15px; line-height: 1.6;">
                                Sie haben eine neue Nachricht über das Kontaktformular erhalten:
                            </p>
                            
                            <table role="presentation" style="width: 100%; border-collapse: collapse; border: 1px solid #e0e0e0; border-radius: 6px; overflow: hidden;">
                                {$this->message}
                            </table>
                        </td>
                    </tr>
                    
                    <!-- Footer -->
                    <tr>
                        <td style="padding: 20px 30px 30px; background-color: #f8f9fa; border-radius: 0 0 8px 8px; text-align: center;">
                            <p style="margin: 0; color: #888; font-size: 13px; line-height: 1.5;">
                                Diese E-Mail wurde automatisch generiert.<br>
                                Bitte antworten Sie nicht auf diese E-Mail.<br>
                                <strong style="color: #555;">HKW Anwälte</strong> &copy; {$current_year}
                            </p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>
HTML;
    }
}