<?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;
}

$db = Database::getInstance();
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Bestehende Regel laden
try {
    $stmt = $db->prepare("SELECT * FROM smtp_domain_rules WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $rule = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$rule) {
        header('Location: smtp_domain_rules.php?error=Regel nicht gefunden');
        exit;
    }
    ErrorLogger::logSqlSuccess("smtp_domain_rule_edit.php: Regel ID $id erfolgreich geladen.");
} catch (PDOException $e) {
    ErrorLogger::logSqlError("smtp_domain_rule_edit.php: Fehler beim Laden der Regel: " . $e->getMessage());
    header('Location: smtp_domain_rules.php?error=Datenbankfehler');
    exit;
}

// SMTP-Accounts laden
try {
    $stmt = $db->prepare("SELECT id, smtp_host, smtp_user FROM smtp_accounts WHERE is_active = 1 ORDER BY smtp_host ASC");
    $stmt->execute();
    $smtpAccounts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('smtp_domain_rule_edit.php: SMTP-Accounts geladen.');
} catch (PDOException $e) {
    ErrorLogger::logSqlError('smtp_domain_rule_edit.php: Fehler beim Laden der SMTP-Accounts: ' . $e->getMessage());
    $smtpAccounts = [];
}

// Formularverarbeitung
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $domain = trim($_POST['domain']);
    $smtp_account_id = (int)$_POST['smtp_account_id'];
    $max_per_20min = is_numeric($_POST['max_per_20min']) ? (int)$_POST['max_per_20min'] : null;

    try {
        $stmt = $db->prepare("UPDATE smtp_domain_rules 
                              SET domain = :domain, smtp_account_id = :smtp_account_id, max_per_20min = :max 
                              WHERE id = :id");
        $stmt->execute([
            ':domain' => $domain,
            ':smtp_account_id' => $smtp_account_id,
            ':max' => $max_per_20min,
            ':id' => $id
        ]);

        $adminId = $_SESSION['admin_id'] ?? 0;
        ErrorLogger::logSqlSuccess("Domain-Regel ID $id aktualisiert von Admin #$adminId: $domain, SMTP-ID $smtp_account_id");

        header('Location: smtp_domain_rules.php?success=Regel erfolgreich aktualisiert');
        exit;
    } catch (PDOException $e) {
        ErrorLogger::logSqlError('smtp_domain_rule_edit.php: Fehler beim Speichern der Regel: ' . $e->getMessage());
        $errorMsg = "Fehler beim Speichern der Regel.";
    }
}

$fieldTooltips = [
    '[name="domain"]' => 'Domain, für die diese Versandregel gelten soll, zum Beispiel gmail.com.',
    '[name="smtp_account_id"]' => 'SMTP-Zugang, der für diese Domain bevorzugt verwendet werden soll.',
    '[name="max_per_20min"]' => 'Optionale Versandobergrenze für diese Domain innerhalb von 20 Minuten.',
];

ob_start();
?>

<div class="container mt-4">
    <h2><i class="bi bi-pencil-square"></i> SMTP-Domain-Regel bearbeiten</h2>

    <?php if (!empty($errorMsg)): ?>
        <div class="alert alert-danger alert-dismissible fade show mt-3" role="alert">
            ❌ <?= htmlspecialchars($errorMsg) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <form method="post" class="mt-4">
        <div class="mb-3">
            <label for="domain" class="form-label">Domain</label>
            <input type="text" class="form-control" id="domain" name="domain" value="<?= htmlspecialchars($rule['domain']) ?>" required>
        </div>
        <div class="mb-3">
            <label for="smtp_account_id" class="form-label">SMTP-Server</label>
            <select class="form-select" id="smtp_account_id" name="smtp_account_id" required>
                <?php foreach ($smtpAccounts as $smtp): ?>
                    <option value="<?= $smtp['id'] ?>" <?= $smtp['id'] == $rule['smtp_account_id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($smtp['smtp_host']) ?> (<?= htmlspecialchars($smtp['smtp_user']) ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="mb-3">
            <label for="max_per_20min" class="form-label">Max. Mails / 20 Minuten</label>
            <input type="number" class="form-control" id="max_per_20min" name="max_per_20min" value="<?= htmlspecialchars($rule['max_per_20min']) ?>">
        </div>
        <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Speichern</button>
        <a href="smtp_domain_rules.php" class="btn btn-secondary">Zurück</a>
    </form>
</div>

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