<?php
/**
 * admin/tools/testmail.php
 * ---------------------------------------------------------------
 * ▸ Sendet eine Test-E-Mail mit frei wählbarem Absender, SMTP-Konto,
 *   Template und Layout
 * ▸ Vollständiges Logging über ErrorLogger (Success / Error)
 * ▸ DKIM-Key wird – falls vorhanden – direkt als PEM-String an
 *   PHPMailer übergeben (PHPMailer ≥ 6 → DKIM_private_string)
 * ▸ Bootstrap-Alerts mit Auto-Dismiss & TML-Icons
 * ---------------------------------------------------------------
 */

/* ------------------------------------------------------------------
 * 1. Bootstrap & Auth
 * ---------------------------------------------------------------- */
session_start();
require_once __DIR__ . '/../../includes/init.php';
require_once __DIR__ . '/../../auth/AuthController.php';
require_once __DIR__ . '/../../includes/core/ErrorLogger.php';
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';

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

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


/**  ------------------------------------------------------------
 *  Hilfs-Funktion: HTML → Plain-Text
 *  ------------------------------------------------------------
 *  - Entfernt <head>, <style> und <script> Blöcke vollständig
 *  - Wandelt <br> / </p> in Zeilenumbrüche um
 *  - Entfernt alle übrigen HTML-Tags
 *  - Dekodiert HTML-Entities ( &nbsp; → Leerzeichen usw. )
 *  - Gibt sauberen, getrimmten Klartext zurück
 */
function htmlToPlain(string $html): string
{
    // 1) HEAD komplett entfernen
    $html = preg_replace('/<head\b[^>]*>.*?<\/head>/is', '', $html);

    // 2) STYLE- und SCRIPT-Blöcke entfernen
    $html = preg_replace('/<(style|script)\b[^>]*>.*?<\/\1>/is', '', $html);

    // 3) Struktur-Tags in Zeilenumbrüche umwandeln
    $html = preg_replace('/<\s*br\s*\/?>/i', "\n", $html);
    $html = preg_replace('/<\s*\/p\s*>/i', "\n\n", $html);

    // 4) Restliche Tags strippen
    $text = strip_tags($html);

    // 5) HTML-Entities dekodieren
    $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');

    // 6) Whitespace säubern
    return trim(preg_replace('/[ \t]+\n/', "\n", $text));
}


/* ------------------------------------------------------------------
 * 2. Grundvariablen
 * ---------------------------------------------------------------- */
$title   = 'Testmail senden';
$db      = Database::getInstance();
$config  = include __DIR__ . '/../../includes/config.php';
$info    = $error = $debug = '';

$pageHelp = renderPageHelp([
    'sections' => [
        [
            'heading' => 'Was macht diese Seite?',
            'items' => [
                'Hier sendest du eine Testmail mit ausgewähltem Absender, SMTP-Konto, Template und Layout.',
                'So prüfst du Inhalte und technische Zustellung vor einem echten Versand.',
            ],
        ],
        [
            'heading' => 'Was muss ich eingeben oder auswählen?',
            'items' => [
                'Trage eine gültige Empfängeradresse ein und wähle Absender sowie SMTP-Konto aus.',
                'Nutze optional ein Template und ein Layout, wenn du den späteren Versand realistisch prüfen willst.',
            ],
        ],
        [
            'heading' => 'Worauf sollte ich achten?',
            'items' => [
                'Die Testmail geht sofort an die eingetragene Adresse.',
                'Verwende für Tests möglichst ein kontrolliertes Postfach und prüfe auch Betreff, Inhalt und Links.',
            ],
        ],
    ],
    'warning' => 'Mit dem Absenden wird sofort eine echte E-Mail verschickt.',
]);

/* ------------------------------------------------------------------
 * 3. Stammdaten aus DB laden (Sender, SMTP, Templates, Layouts)
 * ---------------------------------------------------------------- */
try {
    $senderList    = $db->query('SELECT id, name, email, dkim_selector, dkim_private_key
                                   FROM sender_identities
                                  WHERE is_active = 1
                               ORDER BY name')->fetchAll();
    $smtpList      = $db->query('SELECT id, smtp_host
                                   FROM smtp_accounts
                                  WHERE is_active = 1
                               ORDER BY smtp_host')->fetchAll();
    $templateList  = $db->query('SELECT id, name, subject, body_html
                                   FROM email_templates
                               ORDER BY name')->fetchAll();
    $layoutList    = $db->query('SELECT id, name, editor_mode, source_content, header_html, footer_html
                                   FROM email_layouts
                               ORDER BY name')->fetchAll();

    ErrorLogger::logSqlSuccess('testmail | file: ' . __FILE__ . ' | line: ' . __LINE__ . ' | message: Stammdaten geladen');
} catch (Throwable $e) {
    ErrorLogger::logSqlError('testmail | file: ' . __FILE__ . ' | line: ' . __LINE__ . ' | error: ' . $e->getMessage());
    exit('Fehler beim Laden der Stammdaten.');
}

/* ------------------------------------------------------------------
 * 4. Formular-Verarbeitung
 * ---------------------------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    /* 4.1 Eingaben validieren -------------------------------------- */
    $empfaenger  = filter_var(trim($_POST['empfaenger'] ?? ''), FILTER_VALIDATE_EMAIL);
    $absender_id = (int)($_POST['absender'] ?? 0);
    $smtp_id     = (int)($_POST['smtp'] ?? 0);
    $templateId  = (int)($_POST['template_id'] ?? 0);
    $layoutId    = (int)($_POST['layout_id'] ?? 0);

    if (!$empfaenger || !$absender_id || !$smtp_id) {
        $error = 'Bitte alle Pflichtfelder korrekt ausfüllen.';
        ErrorLogger::log(__FILE__ . ': Testmail-Formular unvollständig', 'WARN');
    } else {
        try {
            /* 4.2 Absender & SMTP holen ----------------------------- */
            $stmt = $db->prepare('SELECT * FROM sender_identities WHERE id = :id');
            $stmt->execute([':id' => $absender_id]);
            $absender = $stmt->fetch();

            $stmt = $db->prepare('SELECT * FROM smtp_accounts WHERE id = :id');
            $stmt->execute([':id' => $smtp_id]);
            $smtp = $stmt->fetch();

            if (!$absender || !$smtp) {
                throw new Exception('Absender oder SMTP nicht gefunden');
            }

            $placeholders = [
                '[anrede]'          => 'Herr',
                '[vorname]'         => 'Max',
                '[nachname]'        => 'Mustermann',
                '[email]'           => $empfaenger,
                '[unsubscribe_url]' => $config['app']['base_url'] . '/unsubscribe.php?token=test',
                '[online_view_url]' => $config['app']['base_url'] . '/view.php?token=test',
                '[pause_url]'       => $config['app']['base_url'] . '/versandpause.php?token=test',
            ];

            $subject  = 'Testmail Mailresponder';
            $htmlBody = '<p>Dies ist eine Testmail.</p>';




            /* Template anwenden */
            if ($templateId) {
                foreach ($templateList as $tpl) {
                    if ($tpl['id'] == $templateId) {
                        $subject  = strtr($tpl['subject'],  $placeholders);
                        $htmlBody = strtr($tpl['body_html'], $placeholders);
                        break;
                    }
                }
            }


            /* Layout umschließen */
            if ($layoutId) {
                foreach ($layoutList as $layout) {
                    if ($layout['id'] == $layoutId) {
                        $layout = mrPrepareLayoutEditorState($layout);
                        $htmlBody = ($layout['header_html'] ?? '') .
                                    $htmlBody .
                                    ($layout['footer_html'] ?? '');
                        break;
                    }
                }
            }

            $htmlBody = mrWrapEmailShell($htmlBody);





            /* 4.4 PHPMailer-Objekt konfigurieren -------------------- */
            $mail = new PHPMailer(true);
            $mail->SMTPDebug  = 3;
            $mail->Debugoutput = function ($str, $level) use (&$debug) {
                $debug .= '<div><code>[' . $level . '] ' .
                          htmlspecialchars($str) . '</code></div>';
            };

            $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->Encoding = 'base64';


            $mail->setFrom($absender['email'], $absender['name']);
            $mail->addAddress($empfaenger);
            $mail->Sender   = $smtp['smtp_email'];        // Return-Path
           

            $mail->isHTML(true);
            $mail->Subject  = $subject;
            $mail->Body     = $htmlBody;
            $mail->AltBody = htmlToPlain($htmlBody);

            /* 4.5 DKIM aus DB (falls vorhanden) -------------------- */
            if (!empty($absender['dkim_selector']) && !empty($absender['dkim_private_key'])) {
                $mail->DKIM_domain         = substr(strrchr($absender['email'], '@'), 1);
                $mail->DKIM_selector       = $absender['dkim_selector'];
                $mail->DKIM_private_string = $absender['dkim_private_key']; // PEM direkt als String
                $mail->DKIM_identity       = $absender['email'];
            }

            /* 4.6 Optional: List-Unsubscribe-Header ---------------- */
            $mail->addCustomHeader('List-Unsubscribe',
                                   '<' . $placeholders['[unsubscribe_url]'] . '>');

            /* 4.7 Mail senden -------------------------------------- */
            $mail->send();

            $info = "✅ Testmail erfolgreich an $empfaenger gesendet.";
            ErrorLogger::log(__FILE__ . ": Testmail an $empfaenger gesendet", 'INFO');

        } catch (Exception $e) {
            $error = 'Fehler beim Senden: ' . $e->getMessage();
            ErrorLogger::log(__FILE__ . ': Testmail-Fehler – ' . $e->getMessage(), 'ERROR');
        }
    }
}

/* ------------------------------------------------------------------
 * 5. HTML-Ausgabe
 * ---------------------------------------------------------------- */
ob_start();
?>
<div class="page-header h2">🧪 Testmail senden</div>

<?= $pageHelp ?>

<?php if ($info): ?>
  <div class="alert alert-success auto-dismiss"><?= htmlspecialchars($info) ?></div>
<?php endif; ?>

<?php if ($error): ?>
  <div class="alert alert-danger auto-dismiss"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<?php if ($debug): ?>
  <div class="alert alert-secondary small"><?= $debug ?></div>
<?php endif; ?>

<form method="post" class="row g-3">
  <div class="col-md-6">
    <label class="form-label">Empfänger *</label>
    <input type="email" name="empfaenger" class="form-control" required>
  </div>

  <div class="col-md-6">
    <label class="form-label">Absender *</label>
    <select name="absender" class="form-select" required>
      <option value="">Bitte wählen</option>
      <?php foreach ($senderList as $s): ?>
        <option value="<?= $s['id'] ?>">
          <?= htmlspecialchars($s['name']) ?> &lt;<?= $s['email'] ?>&gt;
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="col-md-6">
    <label class="form-label">SMTP-Zugang *</label>
    <select name="smtp" class="form-select" required>
      <option value="">Bitte wählen</option>
      <?php foreach ($smtpList as $s): ?>
        <option value="<?= $s['id'] ?>">
          <?= htmlspecialchars($s['smtp_host']) ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="col-md-6">
    <label class="form-label">E-Mail-Template</label>
    <select name="template_id" class="form-select">
      <option value="">-- Kein Template --</option>
      <?php foreach ($templateList as $tpl): ?>
        <option value="<?= $tpl['id'] ?>"><?= htmlspecialchars($tpl['name']) ?></option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="col-md-6">
    <label class="form-label">Layout</label>
    <select name="layout_id" class="form-select">
      <option value="">-- Kein Layout --</option>
      <?php foreach ($layoutList as $layout): ?>
        <option value="<?= $layout['id'] ?>"><?= htmlspecialchars($layout['name']) ?></option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="col-12">
    <button type="submit" class="btn btn-primary">Testmail senden</button>
  </div>
</form>

<script>
document.addEventListener('DOMContentLoaded', () => {
  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';

