<?php
// admin/smtp_bearbeiten.php

// ------------------------------------------------------
// Session + Projekt-Initialisierung (Admin-Standard)
// ------------------------------------------------------
session_start();
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../auth/AuthController.php';

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

$title = 'SMTP-Zugang bearbeiten';
$db = Database::getInstance();

// ------------------------------------------------------
// ID validieren
// ------------------------------------------------------
$id = (int)($_GET['id'] ?? 0);
$success = '';
$error = '';

// ------------------------------------------------------
// Auto-Dismiss für Hinweise (Vorgabe)
// ------------------------------------------------------
$autoDismissMs = 5000;

// ------------------------------------------------------
// Datensatz laden (mit Fehler-Logging)
// ------------------------------------------------------
try {
    $sqlLoad = "SELECT * FROM smtp_accounts WHERE id = ?";
    $stmt = $db->prepare($sqlLoad);
    $stmt->execute([$id]);
    $data = $stmt->fetch();

    ErrorLogger::logSqlSuccess('smtp_edit: load account | SQL: ' . $sqlLoad . ' | params: ' . json_encode(['id' => $id], JSON_UNESCAPED_UNICODE));
} catch (PDOException $e) {
    ErrorLogger::logSqlError('smtp_edit: load account failed | SQL: ' . ($sqlLoad ?? 'n/a') . ' | params: ' . json_encode(['id' => $id], JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
    ErrorLogger::log("Fehler beim Laden des SMTP-Accounts: " . $e->getMessage(), 'ERROR');
    header('Location: smtp.php?error=load_failed');
    exit;
}

if (!$data) {
    header('Location: smtp.php?error=not_found');
    exit;
}

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

    // --------------------------------------------------
    // Eingaben lesen/normalisieren
    // --------------------------------------------------
    $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'] ?? 587);
    $smtp_secure = $_POST['smtp_secure'] ?? 'tls';
    $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: Update (inkl. smtp_email)
            // ----------------------------------------------
            $sqlUpdate = "UPDATE smtp_accounts
                          SET smtp_host = ?,
                              smtp_user = ?,
                              smtp_email = ?,
                              smtp_pass = ?,
                              smtp_port = ?,
                              smtp_secure = ?,
                              is_active = ?,
                              max_global_20min = ?
                          WHERE id = ?";

            $update = $db->prepare($sqlUpdate);
            $update->execute([
                $smtp_host,
                $smtp_user,
                $smtp_email,
                $smtp_pass,
                $smtp_port,
                $smtp_secure,
                $is_active,
                $max_global_20min,
                $id
            ]);

            // ----------------------------------------------
            // SQL-Erfolg loggen (Vorgabe)
            // ----------------------------------------------
            ErrorLogger::logSqlSuccess('smtp_edit: update account | SQL: ' . $sqlUpdate . ' | params: ' . json_encode([
                'id' => $id,
                '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)
            // Hinweis: Datensatzänderung wird als Aktion geloggt.
            // ----------------------------------------------
            $userId = $_SESSION['user_id'] ?? null;
            if ($userId) {
                logSettingChange($userId, 'smtp_account_update', 'smtp_accounts', json_encode([
                    'id' => $id,
                    '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));
            }

            // ----------------------------------------------
            // UI Erfolg + lokale Daten aktualisieren
            // ----------------------------------------------
            $success = "Änderungen wurden gespeichert.";
            $data['smtp_host'] = $smtp_host;
            $data['smtp_user'] = $smtp_user;
            $data['smtp_email'] = $smtp_email;
            $data['smtp_pass'] = $smtp_pass;
            $data['smtp_port'] = $smtp_port;
            $data['smtp_secure'] = $smtp_secure;
            $data['is_active'] = $is_active;
            $data['max_global_20min'] = $max_global_20min;

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

            ErrorLogger::log("Fehler beim SMTP-Update: " . $e->getMessage(), 'ERROR');
            $error = "Fehler beim Speichern.";
        }
    } else {
        $error = "Bitte alle Pflichtfelder ausfüllen.";
    }
}

$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; Zugang bearbeiten
</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">
      <form method="post" class="w-50">

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

        <div class="mb-3">
          <label for="smtp_user" class="form-label">Benutzername *</label>
          <input type="text" name="smtp_user" id="smtp_user"
                 value="<?= htmlspecialchars($data['smtp_user'] ?? '') ?>"
                 required class="form-control">
        </div>

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

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

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

        <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" <?= (($data['smtp_secure'] ?? '') === 'tls') ? 'selected' : '' ?>>TLS</option>
            <option value="ssl" <?= (($data['smtp_secure'] ?? '') === 'ssl') ? 'selected' : '' ?>>SSL</option>
          </select>
        </div>

        <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)($data['max_global_20min'] ?? '')) ?>">
        </div>

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

        <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-secondary">
            <i class="tml tml-arrow-left"></i> Zurück
          </a>
        </div>

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

</div>

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

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



