<?php
// admin/absender_bearbeiten.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 bearbeiten';
$db = Database::getInstance();
$error = '';
$id = (int)($_GET['id'] ?? 0);

$sqlLoadSender = "SELECT * FROM sender_identities WHERE id = ?";
try {
    $stmt = $db->prepare($sqlLoadSender);
    $stmt->execute([$id]);
    ErrorLogger::logSqlSuccess('absender_bearbeiten: load sender | SQL: ' . $sqlLoadSender . ' | params: ' . json_encode([$id], JSON_UNESCAPED_UNICODE));
    $sender = $stmt->fetch();
} catch (Throwable $e) {
    ErrorLogger::logSqlError('absender_bearbeiten: load sender failed | SQL: ' . $sqlLoadSender . ' | params: ' . json_encode([$id], JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
    die("Fehler beim Laden des Absenders.");
}

if (!$sender) {
    die("Absender nicht gefunden.");
}

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("UPDATE sender_identities SET name = ?, email = ?, dkim_selector = ?, dkim_private_key = ?, is_active = ? WHERE id = ?");
            $stmt->execute([$name, $email, $dkim_selector, $dkim_private_key, $is_active, $id]);
            $userId = $_SESSION['admin_id'] ?? ($_SESSION['user_id'] ?? 0);
            if ($userId) {
                logSettingChange($userId, 'update_sender_identity', 'sender_identities', json_encode([
                    'id' => (int)$id,
                    'name' => $name,
                    'email' => $email,
                    'is_active' => $is_active
                ], JSON_UNESCAPED_UNICODE));
            }

            $_SESSION['success_message'] = "Absender wurde aktualisiert.";
            header('Location: absender.php');
            exit;
        } catch (PDOException $e) {
            ErrorLogger::log("Fehler beim Bearbeiten 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; Bearbeiten
</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" value="<?= htmlspecialchars($sender['name']) ?>" required>
    </div>

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

    <div class="mb-3">
      <label class="form-label">DKIM Selector</label>
      <input type="text" name="dkim_selector" class="form-control" value="<?= htmlspecialchars($sender['dkim_selector']) ?>">
    </div>

    <div class="mb-3">
      <label class="form-label">DKIM Private Key</label>
      <textarea name="dkim_private_key" rows="5" class="form-control"><?= htmlspecialchars($sender['dkim_private_key']) ?></textarea>
    </div>

    <div class="form-check mb-3">
      <input class="form-check-input" type="checkbox" name="is_active" id="is_active" value="1" <?= $sender['is_active'] ? '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';

