<?php
// admin/tools/test_smtp_rotation.php

// ✅ Session starten und Authentifizierung prüfen
session_start();
require_once __DIR__ . '/../../includes/init.php';
require_once __DIR__ . '/../../auth/AuthController.php';
require_once __DIR__ . '/../../includes/core/ErrorLogger.php';

$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    header('Location: ' . $adminLoginPath);
    exit;
}

$title = 'SMTP-Rotation testen';
$db = Database::getInstance();
$info = '';
$error = '';
$debug = '';

// ✅ Aktiven SMTP-Zugang laden
$smtpList = $db->query("SELECT * FROM smtp_accounts WHERE is_active = 1 ORDER BY last_used_at ASC, id ASC LIMIT 1")->fetchAll();
ErrorLogger::logSqlSuccess("Aktiver SMTP-Zugang geladen | table: smtp_accounts | context: " . json_encode(["limit" => 1], JSON_UNESCAPED_UNICODE));

if (empty($smtpList)) {
    $error = "Keine aktiven SMTP-Zugänge gefunden.";
    ErrorLogger::log("SMTP-Test: Keine aktiven SMTP-Zugänge gefunden", 'WARN');
} else {
    $smtp = $smtpList[0];
    $smtpId = $smtp['id'];
    ErrorLogger::log("SMTP-Test: Test mit Zugang ID $smtpId gestartet", 'INFO');

    try {
        require_once __DIR__ . '/../../includes/libs/phpmailer/src/PHPMailer.php';
        require_once __DIR__ . '/../../includes/libs/phpmailer/src/SMTP.php';
        require_once __DIR__ . '/../../includes/libs/phpmailer/src/Exception.php';

        $mail = new PHPMailer\PHPMailer\PHPMailer(true);
        $mail->SMTPDebug = 3;
        $mail->Debugoutput = function($str, $level) use (&$debug) {
            $debug .= htmlspecialchars("[{$level}] $str") . "<br>\n";
        };

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

        $mail->setFrom($smtp['smtp_user'], 'SMTP-Rotation-Test');
        $mail->addAddress('you@example.com'); // ⚠️ Beispieladresse anpassen
        $mail->isHTML(true);
        $mail->Subject = 'Rotationstest';
        $mail->Body = '<p>Dies ist ein Rotationstest der aktiven SMTP-Zugänge.</p>';

        if ($mail->send()) {
            $info = "✅ Testmail über SMTP-Zugang #$smtpId erfolgreich gesendet.";
            $db->prepare("UPDATE smtp_accounts SET last_used_at = NOW() WHERE id = ?")->execute([$smtpId]);
            ErrorLogger::logSqlSuccess("SMTP last_used_at aktualisiert | table: smtp_accounts | context: " . json_encode(["smtp_id" => (int)$smtpId], JSON_UNESCAPED_UNICODE));
            $userId = $_SESSION['admin_id'] ?? ($_SESSION['user_id'] ?? 0);
            if ($userId) {
                logSettingChange($userId, 'smtp_rotation_test_last_used', 'smtp_accounts', json_encode([
                    'smtp_id' => (int)$smtpId
                ], JSON_UNESCAPED_UNICODE));
            }

            ErrorLogger::log("SMTP-Test erfolgreich: Versand über SMTP #$smtpId", 'INFO');
        } else {
            $error = "Fehler beim Senden: " . $mail->ErrorInfo;
            ErrorLogger::log("SMTP-Test Fehler: " . $mail->ErrorInfo, 'ERROR');
        }
    } catch (Exception $e) {
        ErrorLogger::logSqlError("Fehler bei SMTP-Rotation-DB-Operation | table: smtp_accounts | error: " . $e->getMessage());
        $error = "PHPMailer Exception: " . $e->getMessage();
        ErrorLogger::log("SMTP-Test Exception: " . $e->getMessage(), 'ERROR');
    }
}

ob_start();
?>
<div class="page-header">
  🔁 SMTP-Rotation testen
</div>
<div class="page-contend">
  <?php if ($info): ?><div class="alert alert-success auto-dismiss"><?= $info ?></div><?php endif; ?>
  <?php if ($error): ?><div class="alert alert-danger auto-dismiss"><?= $error ?></div><?php endif; ?>
  <?php if (!empty($debug)): ?><div class="alert alert-secondary small"><strong>Debug-Ausgabe:</strong><br><?= $debug ?></div><?php endif; ?>
</div>

<script>
// Hinweise nach 5 Sekunden automatisch ausblenden
  document.addEventListener('DOMContentLoaded', function () {
    setTimeout(() => {
      document.querySelectorAll('.auto-dismiss').forEach(el => {
        el.classList.add('fade');
        setTimeout(() => el.remove(), 1000);
      });
    }, 5000);
  });
</script>

<?php
$pageContent = ob_get_clean();
include __DIR__ . '/../template.php';
