<?php
/**
 * Test-E-Mail an verschiedene Empfänger senden
 */

// Alle Ausgaben vor JSON unterdrücken
ob_start();

// PHP-Warnings und Errors unterdrücken
error_reporting(0);
ini_set('display_errors', 0);

header('Content-Type: application/json');
require_once '../config/database.php';
require_once '../api/phpmailer/PHPMailer.php';
require_once '../api/phpmailer/SMTP.php';
require_once '../api/phpmailer/Exception.php';

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

session_start();

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    ob_clean();
    echo json_encode(['success' => false, 'error' => 'Nicht angemeldet']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

if (!$input || $input['action'] !== 'test_email_different_recipient') {
    ob_clean();
    echo json_encode(['success' => false, 'error' => 'Ungültige Anfrage']);
    exit;
}

try {
    $db = new Database();
    $conn = $db->getConnection();
    
    // Hole E-Mail-Einstellungen
    $stmt = $conn->prepare("
        SELECT setting_key, setting_value FROM settings 
        WHERE setting_key IN ('smtp_server', 'smtp_port', 'smtp_username', 'smtp_password', 'smtp_use_tls', 'smtp_use_ssl', 'mail_from_email', 'mail_from_name')
    ");
    $stmt->execute();
    $settings = [];
    while ($row = $stmt->fetch()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
    
    // Teste verschiedene Empfänger
    $testRecipients = [
        'duludag16@gmail.com',
        'rentacar-kiel@be-automobile.de',
        'admin@boxxenstopp.de'
    ];
    
    $results = [];
    
    foreach ($testRecipients as $toEmail) {
        error_log("Teste E-Mail an: " . $toEmail);
        
        // Erstelle PHPMailer-Instanz
        $mail = new PHPMailer(true);
        
        // Server settings
        $mail->isSMTP();
        $mail->Host = $settings['smtp_server'] ?? 'smtp-mail.outlook.com';
        $mail->SMTPAuth = true;
        $mail->Username = $settings['smtp_username'] ?? 'rentacar-kiel@be-automobile.de';
        $mail->Password = $settings['smtp_password'] ?? 'W@050373011206af';
        
        // Verschlüsselung basierend auf Einstellungen
        if (($settings['smtp_use_ssl'] ?? '0') === '1') {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        } elseif (($settings['smtp_use_tls'] ?? '1') === '1') {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        }
        
        $mail->Port = (int)($settings['smtp_port'] ?? 587);
        $mail->CharSet = 'UTF-8';
        $mail->SMTPDebug = 0; // Debug deaktiviert für saubere Ausgabe
        
        // Recipients
        $mail->setFrom($settings['mail_from_email'] ?? 'rentacar-kiel@be-automobile.de', $settings['mail_from_name'] ?? 'Boxenstop Volvo Service');
        $mail->addAddress($toEmail, 'Test Empfänger');
        
        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Test-E-Mail an verschiedene Empfänger - ' . date('H:i:s');
        
        $mail->Body = '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: #007bff; color: white; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }
                .content { background: #f8f9fa; padding: 30px; border-radius: 0 0 8px 8px; }
                .success { color: #28a745; font-weight: bold; }
                .info { background: #e3f2fd; padding: 15px; border-radius: 4px; margin: 20px 0; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>📧 Test-E-Mail an verschiedene Empfänger</h1>
                </div>
                <div class="content">
                    <p class="success">Diese E-Mail wurde erfolgreich gesendet!</p>
                    
                    <div class="info">
                        <h3>📧 E-Mail-Details:</h3>
                        <ul>
                            <li><strong>Empfänger:</strong> ' . htmlspecialchars($toEmail) . '</li>
                            <li><strong>Absender:</strong> ' . htmlspecialchars($settings['mail_from_email'] ?? 'rentacar-kiel@be-automobile.de') . '</li>
                            <li><strong>Zeitstempel:</strong> ' . date('d.m.Y H:i:s') . '</li>
                            <li><strong>Test-ID:</strong> ' . uniqid() . '</li>
                        </ul>
                    </div>
                    
                    <p>Falls Sie diese E-Mail erhalten, funktioniert das E-Mail-System korrekt!</p>
                    
                    <hr style="margin: 30px 0; border: none; border-top: 1px solid #ddd;">
                    <p style="font-size: 12px; color: #666;">
                        Diese E-Mail wurde automatisch vom Boxenstop Volvo Service System gesendet.
                    </p>
                </div>
            </div>
        </body>
        </html>';
        
        $mail->AltBody = 'Test-E-Mail erfolgreich gesendet an ' . $toEmail . ' um ' . date('H:i:s');
        
        try {
            $mail->send();
            $results[$toEmail] = ['success' => true, 'message' => 'E-Mail erfolgreich gesendet'];
            error_log("✅ E-Mail erfolgreich gesendet an: " . $toEmail);
        } catch (Exception $e) {
            $results[$toEmail] = ['success' => false, 'error' => $e->getMessage()];
            error_log("❌ E-Mail-Fehler für " . $toEmail . ": " . $e->getMessage());
        }
    }
    
    // Alle Ausgaben vor JSON löschen
    ob_clean();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Test-E-Mails an verschiedene Empfänger gesendet',
        'results' => $results,
        'note' => 'Prüfen Sie alle E-Mail-Postfächer (auch Spam-Ordner)'
    ]);
    
} catch (Exception $e) {
    // Alle Ausgaben vor JSON löschen
    ob_clean();
    
    echo json_encode([
        'success' => false, 
        'error' => 'Fehler: ' . $e->getMessage()
    ]);
}
?>
