<?php
// admin/smtp_neu.php

// ------------------------------------------------------
// Admin-Login + Initialisierung (Projektstandard)
// ------------------------------------------------------
session_start();
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../auth/AuthController.php';

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

$title = 'Neuer SMTP-Zugang';
$success = '';
$error = '';

/**
 * Kleine Helper-Funktion für Auto-Dismiss Alerts
 * (Bootstrap 5: via JS, falls bei dir Bootstrap 4 läuft, funktioniert es trotzdem meist)
 */
$autoDismissMs = 5000;

// ------------------------------------------------------
// POST: Formular absenden
// ------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // --------------------------------------------------
    // Eingaben holen + trimmen
    // --------------------------------------------------
    $smtp_host = trim($_POST['smtp_host'] ?? '');
    $smtp_user = trim($_POST['smtp_user'] ?? '');
    $smtp_email = trim($_POST['smtp_email'] ?? ''); // <-- NEU
    $smtp_pass = trim($_POST['smtp_pass'] ?? '');
    $smtp_port = (int)($_POST['smtp_port'] ?? 465);
    $smtp_secure = $_POST['smtp_secure'] ?? 'ssl';
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $max_global_20min = is_numeric($_POST['max_global_20min']) ? (int)$_POST['max_global_20min'] : null;

    // --------------------------------------------------
    // Pflichtfelder prüfen
    // --------------------------------------------------
    if ($smtp_host && $smtp_user && $smtp_email && $smtp_pass && $smtp_port) {
        try {
            // --------------------------------------------------
            // SQL: SMTP Account speichern (mit neuem smtp_email)
            // --------------------------------------------------
            $sql = "INSERT INTO smtp_accounts
                    (smtp_host, smtp_user, smtp_email, smtp_pass, smtp_port, smtp_secure, is_active, max_global_20min)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

            $stmt = Database::getInstance()->prepare($sql);

            $stmt->execute([
                $smtp_host,
                $smtp_user,
                $smtp_email,
                $smtp_pass,
                $smtp_port,
                $smtp_secure,
                $is_active,
                $max_global_20min
            ]);

            // --------------------------------------------------
            // SQL-Erfolg loggen (Vorgabe)
            // --------------------------------------------------
            ErrorLogger::logSqlSuccess('smtp_create: insert account | SQL: ' . $sql . ' | params: ' . json_encode([
                'smtp_host' => $smtp_host,
                'smtp_user' => $smtp_user,
                'smtp_email' => $smtp_email,
                'smtp_port' => $smtp_port,
                'smtp_secure' => $smtp_secure,
                'is_active' => $is_active,
                'max_global_20min' => $max_global_20min
            ], JSON_UNESCAPED_UNICODE));

            // --------------------------------------------------
            // Setting-Änderung loggen (Vorgabe: immer via logSettingChange)
            // Hinweis: Streng genommen ist es kein Setting, aber wir loggen die Aktion sauber mit.
            // --------------------------------------------------
            $userId = $_SESSION['user_id'] ?? null;
            if ($userId) {
                logSettingChange($userId, 'smtp_account_create', 'smtp_accounts', json_encode([
                    'smtp_host' => $smtp_host,
                    'smtp_user' => $smtp_user,
                    'smtp_email' => $smtp_email,
                    'smtp_port' => $smtp_port,
                    'smtp_secure' => $smtp_secure,
                    'is_active' => $is_active,
                    'max_global_20min' => $max_global_20min
                ], JSON_UNESCAPED_UNICODE));
            }

            $success = "SMTP-Zugang erfolgreich gespeichert.";

            // Formular leeren nach Erfolg
            $smtp_host = $smtp_user = $smtp_email = $smtp_pass = '';
            $smtp_port = 587;
            $smtp_secure = 'tls';
            $is_active = 1;
            $max_global_20min = null;

        } catch (PDOException $e) {
            // --------------------------------------------------
            // SQL-Fehler loggen (Vorgabe)
            // --------------------------------------------------
            ErrorLogger::logSqlError('smtp_create: insert failed | SQL: ' . ($sql ?? 'n/a') . ' | params: ' . json_encode([
                'smtp_host' => $smtp_host,
                'smtp_user' => $smtp_user,
                'smtp_email' => $smtp_email
            ], JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());

            // Generisches UI-Fehlerfeedback
            ErrorLogger::log("Fehler beim SMTP-Speichern: " . $e->getMessage(), 'ERROR');
            $error = "Fehler beim Speichern des SMTP-Zugangs.";
        }
    } else {
        $error = "Bitte füllen Sie alle erforderlichen Felder aus.";
    }
}

$fieldTooltips = [
    '[name="smtp_host"]' => 'Hostname des SMTP-Servers, zum Beispiel smtp.example.com.',
    '[name="smtp_user"]' => 'Benutzername für die Anmeldung am SMTP-Server.',
    '[name="smtp_email"]' => 'Absenderadresse oder Return-Path-Adresse dieses SMTP-Zugangs.',
    '[name="smtp_pass"]' => 'Passwort für die Anmeldung am SMTP-Server.',
    '[name="smtp_port"]' => 'Server-Port, typischerweise 587 für TLS oder 465 für SSL.',
    '[name="smtp_secure"]' => 'Verschlüsselung der Verbindung zum SMTP-Server.',
    '[name="max_global_20min"]' => 'Optionale Obergrenze für Mails dieses SMTP-Zugangs innerhalb von 20 Minuten.',
    '[name="is_active"]' => 'Nur aktive SMTP-Zugänge werden für den Versand berücksichtigt.',
];

ob_start();
?>

<div class="page-header">
  <i class="tml tml-mail"></i> SMTP-Rotation &raquo; Neuen Zugang hinzufügen
</div>

<div class="page-contend">

  <?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert" data-autodismiss="<?= (int)$autoDismissMs ?>">
      <i class="tml tml-check"></i> <?= htmlspecialchars($success) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Schließen"></button>
    </div>
  <?php endif; ?>

  <?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert" data-autodismiss="<?= (int)$autoDismissMs ?>">
      <i class="tml tml-warning"></i> <?= htmlspecialchars($error) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Schließen"></button>
    </div>
  <?php endif; ?>

  <div class="card shadow-sm">
    <div class="card-body">
      <div class="mb-3 text-muted">

      <form method="post" class="w-50">

        <!-- SMTP Host -->
        <div class="mb-3">
          <label for="smtp_host" class="form-label">SMTP-Host *</label>
          <input type="text" name="smtp_host" id="smtp_host" required class="form-control"
                 value="<?= htmlspecialchars($smtp_host ?? '') ?>">
        </div>

        <!-- Benutzername -->
        <div class="mb-3">
          <label for="smtp_user" class="form-label">Benutzername *</label>
          <input type="text" name="smtp_user" id="smtp_user" required class="form-control"
                 value="<?= htmlspecialchars($smtp_user ?? '') ?>">
          <div class="form-text">Wird als Login/Username für SMTP verwendet.</div>
        </div>

        <!-- NEU: Absender E-Mail -->
        <div class="mb-3">
          <label for="smtp_email" class="form-label">Absender E-Mail-Adresse *</label>
          <input type="email" name="smtp_email" id="smtp_email" required class="form-control"
                 value="<?= htmlspecialchars($smtp_email ?? '') ?>">
        </div>

        <!-- Passwort -->
        <div class="mb-3">
          <label for="smtp_pass" class="form-label">Passwort *</label>
          <input type="text" name="smtp_pass" id="smtp_pass" required class="form-control"
                 value="<?= htmlspecialchars($smtp_pass ?? '') ?>">
        </div>

        <!-- Port -->
        <div class="mb-3">
          <label for="smtp_port" class="form-label">Port *</label>
          <input type="number" name="smtp_port" id="smtp_port" value="<?= (int)($smtp_port ?? 587) ?>" required class="form-control">
        </div>

        <!-- Verschlüsselung -->
        <div class="mb-3">
          <label for="smtp_secure" class="form-label">Verschlüsselung</label>
          <select name="smtp_secure" id="smtp_secure" class="form-select">
            <option value="tls" <?= (($smtp_secure ?? '') === 'tls') ? 'selected' : '' ?>>TLS</option>
            <option value="ssl" <?= (($smtp_secure ?? '') === 'ssl') ? 'selected' : '' ?>>SSL</option>
          </select>
        </div>

        <!-- Limit -->
        <div class="mb-3">
          <label for="max_global_20min" class="form-label">Global-Limit (Mails pro 20 Minuten, optional)</label>
          <input type="number" name="max_global_20min" id="max_global_20min" class="form-control"
                 value="<?= htmlspecialchars((string)($max_global_20min ?? '')) ?>">
        </div>

        <!-- Aktiv -->
        <div class="form-check mb-3">
          <input type="checkbox" name="is_active" id="is_active" class="form-check-input" <?= (!isset($is_active) || $is_active) ? 'checked' : '' ?>>
          <label for="is_active" class="form-check-label">Aktiv</label>
        </div>

        <!-- Buttons -->
        <div class="d-flex gap-2">
          <button type="submit" class="btn btn-primary">
            <i class="tml tml-save"></i> Speichern
          </button>
          <a href="smtp.php" class="btn btn-outline-secondary">
            <i class="tml tml-arrow-left"></i> Zurück
          </a>
        </div>

      </form>
    </div>
  </div>

</div>

<script>
// ------------------------------------------------------
// Auto-dismiss für Alerts (Vorgabe)
// ------------------------------------------------------
document.addEventListener('DOMContentLoaded', function () {
  document.querySelectorAll('[data-autodismiss]').forEach(function (el) {
    const ms = parseInt(el.getAttribute('data-autodismiss'), 10) || 5000;
    window.setTimeout(function () {
      // Bootstrap 5: fade out
      el.classList.remove('show');
      // Entfernen nach Animation
      window.setTimeout(function () {
        if (el && el.parentNode) el.parentNode.removeChild(el);
      }, 300);
    }, ms);
  });
});
</script>

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


