<?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();

// 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_create.php: SMTP-Accounts erfolgreich geladen.');
} catch (PDOException $e) {
    ErrorLogger::logSqlError('smtp_domain_rule_create.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("INSERT INTO smtp_domain_rules (domain, smtp_account_id, max_per_20min) 
                              VALUES (:domain, :smtp_account_id, :max)");
        $stmt->execute([
            ':domain' => $domain,
            ':smtp_account_id' => $smtp_account_id,
            ':max' => $max_per_20min
        ]);

        // Logging mit IP + Admin-ID
        $adminId = $_SESSION['admin_id'] ?? 0;
        ErrorLogger::logSqlSuccess("Neue Domain-Regel erstellt für '$domain' über SMTP-ID $smtp_account_id von Admin #$adminId");

        header('Location: smtp_domain_rules.php?success=Regel erfolgreich erstellt');
        exit;
    } catch (PDOException $e) {
        ErrorLogger::logSqlError('smtp_domain_rule_create.php: Fehler beim Erstellen der Regel: ' . $e->getMessage());
        $errorMsg = "Fehler beim Erstellen 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-plus-circle"></i> Neue SMTP-Domain-Regel</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 (z. B. gmail.com)</label>
            <input type="text" class="form-control" id="domain" name="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>
                <option value="">-- bitte wählen --</option>
                <?php foreach ($smtpAccounts as $smtp): ?>
                    <option value="<?= $smtp['id'] ?>">
                        <?= 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 (optional)</label>
            <input type="number" class="form-control" id="max_per_20min" name="max_per_20min" min="1">
        </div>
        <button type="submit" class="btn btn-success"><i class="bi bi-check-lg"></i> Regel 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';
