<?php
/**
 * Test-E-Mail mit Debug-Informationen
 */

// 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_debug') {
    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'];
    }
    
    $toEmail = $input['to_email'] ?? 'admin@boxxenstopp.de';
    
    // Erstelle PHPMailer-Instanz
    $mail = new PHPMailer(true);
    
    // Debug-Output in String umleiten
    $mail->SMTPDebug = 2; // Level 2 für Verbindungs-Debug
    $mail->Debugoutput = function($str, $level) {
        $logFile = __DIR__ . '/../logs/email_debug.log';
        file_put_contents($logFile, date('Y-m-d H:i:s') . " Level $level: $str\n", FILE_APPEND | LOCK_EX);
    };
    
    // 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';
    
    // 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 = 'Debug Test-E-Mail - Boxenstop Volvo Service';
    
    $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>🔍 Debug Test-E-Mail</h1>
            </div>
            <div class="content">
                <p class="success">Debug-E-Mail erfolgreich gesendet!</p>
                
                <div class="info">
                    <h3>📧 SMTP-Details:</h3>
                    <ul>
                        <li><strong>Server:</strong> ' . htmlspecialchars($settings['smtp_server'] ?? 'smtp-mail.outlook.com') . '</li>
                        <li><strong>Port:</strong> ' . htmlspecialchars($settings['smtp_port'] ?? '587') . '</li>
                        <li><strong>Verschlüsselung:</strong> ' . (($settings['smtp_use_tls'] ?? '1') === '1' ? 'TLS' : 'SSL') . '</li>
                        <li><strong>Benutzername:</strong> ' . htmlspecialchars($settings['smtp_username'] ?? 'rentacar-kiel@be-automobile.de') . '</li>
                        <li><strong>Zeitstempel:</strong> ' . date('d.m.Y H:i:s') . '</li>
                    </ul>
                </div>
                
                <p>Debug-Logs wurden in <code>logs/email_debug.log</code> gespeichert.</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 = 'Debug Test-E-Mail erfolgreich! SMTP-Verbindung funktioniert.';
    
    // Send email
    $mail->send();
    
    // Alle Ausgaben vor JSON löschen
    ob_clean();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Debug-E-Mail erfolgreich gesendet an ' . $toEmail,
        'debug_log' => 'Debug-Informationen in logs/email_debug.log gespeichert'
    ]);
    
} catch (Exception $e) {
    // Alle Ausgaben vor JSON löschen
    ob_clean();
    
    echo json_encode([
        'success' => false, 
        'error' => 'E-Mail-Fehler: ' . $e->getMessage(),
        'debug_log' => 'Debug-Informationen in logs/email_debug.log gespeichert'
    ]);
}
?>
