<?php
// admin/absender_neu.php

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 = 'Absender hinzufügen';
$db = Database::getInstance();
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $dkim_selector = trim($_POST['dkim_selector'] ?? '');
    $dkim_private_key = trim($_POST['dkim_private_key'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    if (!$name || !$email) {
        $error = "Bitte Name und E-Mail angeben.";
    } else {
        try {
            $stmt = $db->prepare("INSERT INTO sender_identities (name, email, dkim_selector, dkim_private_key, is_active) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$name, $email, $dkim_selector, $dkim_private_key, $is_active]);
            ErrorLogger::logSqlSuccess("Absender erstellt | table: sender_identities | context: " . json_encode(["email" => $email, "is_active" => (int)$is_active], JSON_UNESCAPED_UNICODE));
            $userId = $_SESSION['admin_id'] ?? ($_SESSION['user_id'] ?? 0);
            if ($userId) {
                logSettingChange($userId, 'create_sender_identity', 'sender_identities', json_encode([
                    'name' => $name,
                    'email' => $email,
                    'is_active' => $is_active
                ], JSON_UNESCAPED_UNICODE));
            }

            $_SESSION['success_message'] = "Absender wurde hinzugefügt.";
            header('Location: absender.php');
            exit;
        } catch (PDOException $e) {
            ErrorLogger::logSqlError("Fehler beim Erstellen des Absenders | table: sender_identities | error: " . $e->getMessage());
            ErrorLogger::log("Fehler beim Hinzufügen des Absenders: " . $e->getMessage());
            $error = "Fehler beim Speichern.";
        }
    }
}

$fieldTooltips = [
    '[name="name"]' => 'Anzeigename des Absenders, wie er in ausgehenden E-Mails erscheinen soll.',
    '[name="email"]' => 'Absenderadresse, die für den Versand dieser Identität genutzt wird.',
    '[name="dkim_selector"]' => 'DKIM-Selector des sendenden Systems, falls DKIM genutzt wird.',
    '[name="dkim_private_key"]' => 'Privater DKIM-Schlüssel im PEM-Format für die Signierung ausgehender E-Mails.',
    '[name="is_active"]' => 'Nur aktive Absender können für Versand und Listen verwendet werden.',
];

ob_start();
?>

<div class="page-header">
  Absender &raquo; Hinzufügen
</div>

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

  <form method="post" class="w-75">
    <div class="mb-3">
      <label class="form-label">Name *</label>
      <input type="text" name="name" class="form-control" required>
    </div>

    <div class="mb-3">
      <label class="form-label">E-Mail-Adresse *</label>
      <input type="email" name="email" class="form-control" required>
    </div>

    <div class="mb-3">
      <label class="form-label">DKIM Selector</label>
      <input type="text" name="dkim_selector" class="form-control">
    </div>

    <div class="mb-3">
      <label class="form-label">DKIM Private Key</label>
      <textarea name="dkim_private_key" rows="5" class="form-control"></textarea>
    </div>

    <div class="form-check mb-3">
      <input class="form-check-input" type="checkbox" name="is_active" id="is_active" value="1" checked>
      <label class="form-check-label" for="is_active">Aktivieren</label>
    </div>

    <button type="submit" class="btn btn-primary">Speichern</button>
    <a href="absender.php" class="btn btn-secondary">Zurück</a>
  </form>
</div>

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

