<?php
/**
 * admin/smtp_domain_rules.php
 * ------------------------------------------------------------------
 * Übersicht aller Domain-Regeln mit optionalem Filter
 *  • Anzeige der Limits je Domain + zugehörigem SMTP
 *  • Filtermöglichkeit nach SMTP-Account
 * ------------------------------------------------------------------
 */

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

/* ======================================================================
 * 1) SMTP-Auswahl vorbereiten
 * ==================================================================== */
try {
    // Alle verfügbaren SMTP-Accounts für das Dropdown abrufen
    $smtpStmt = $db->query("SELECT id, smtp_user FROM smtp_accounts ORDER BY smtp_user");
    $smtpAccounts = $smtpStmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('smtp_domain_rules | file: ' . __FILE__ . ' | message: SMTP-Liste geladen');
} catch (PDOException $e) {
    ErrorLogger::logSqlError('smtp_domain_rules | file: ' . __FILE__ . ' | error: SMTP_LIST_ERR: ' . $e->getMessage());
    $smtpAccounts = [];
}

// Gewählter Filter (0 = alle)
$selectedSmtpId = isset($_GET['smtp_id']) ? (int)$_GET['smtp_id'] : 0;

/* ======================================================================
 * 2) Domain-Regeln laden (mit optionalem Filter)
 * ==================================================================== */
try {
    $sql = "
        SELECT r.id,
               r.domain,
               r.max_per_20min,
               s.smtp_host,
               s.smtp_user
        FROM   smtp_domain_rules r
        JOIN   smtp_accounts     s ON r.smtp_account_id = s.id
        " . ($selectedSmtpId > 0 ? "WHERE s.id = :smtp_id" : "") . "
        ORDER  BY r.domain ASC
    ";

    $stmt = $db->prepare($sql);
    if ($selectedSmtpId > 0) {
        $stmt->bindValue(':smtp_id', $selectedSmtpId, PDO::PARAM_INT);
    }
    $stmt->execute();
    $rules = $stmt->fetchAll(PDO::FETCH_ASSOC);

    ErrorLogger::logSqlSuccess('smtp_domain_rules | file: ' . __FILE__ . ' | message: Domain-Regeln erfolgreich geladen (Filter SMTP_ID=' . $selectedSmtpId . ')');
} catch (PDOException $e) {
    ErrorLogger::logSqlError('smtp_domain_rules | file: ' . __FILE__ . ' | error: RULE_QUERY_ERR: ' . $e->getMessage());
    $rules = [];
}

/* ======================================================================
 * 3) HTML-Ausgabe
 * ==================================================================== */
ob_start();
?>
<div class="container mt-4">
    <h2><i class="bi bi-envelope-at"></i> SMTP Domain-Regeln</h2>

    <!-- Erfolg- / Fehlermeldungen ------------------------------------------------------------ -->
    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show mt-3" role="alert">
            ✅ <?= htmlspecialchars($_GET['success']) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <?php if (isset($_GET['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show mt-3" role="alert">
            ❌ <?= htmlspecialchars($_GET['error']) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Toolbar ------------------------------------------------------------------------------ -->
    <div class="row mb-3">
        <div class="col-auto">
            <a href="smtp_domain_rule_create.php" class="btn btn-primary">
                <i class="bi bi-plus-circle"></i> Neue Regel hinzufügen
            </a>
        </div>
        <div class="col-auto">
            <!-- SMTP-Filter -->
            <form method="get" class="d-flex align-items-center">
                <label for="smtp_id" class="me-2 fw-semibold"><i class="bi bi-funnel"></i> SMTP filtern:</label>
                <select name="smtp_id" id="smtp_id" class="form-select me-2" onchange="this.form.submit()">
                    <option value="0">Alle SMTPs anzeigen</option>
                    <?php foreach ($smtpAccounts as $smtp): ?>
                        <option value="<?= $smtp['id'] ?>" <?= $smtp['id'] == $selectedSmtpId ? 'selected' : '' ?>>
                            <?= htmlspecialchars($smtp['smtp_user']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <noscript><button type="submit" class="btn btn-outline-secondary">Filtern</button></noscript>
            </form>
        </div>
    </div>

    <!-- Tabelle ------------------------------------------------------------------------------ -->
    <div class="table-responsive">
        <table class="table table-bordered align-middle">
            <thead class="table-light">
            <tr>
                <th>Domain</th>
                <th>SMTP-Host</th>
                <th>SMTP-Benutzer</th>
                <th>Max. Mails / 20&nbsp;Min</th>
                <th class="text-center">Aktionen</th>
            </tr>
            </thead>
            <tbody>
            <?php if (empty($rules)): ?>
                <tr>
                    <td colspan="5" class="text-center">Keine Domain-Regeln gefunden.</td>
                </tr>
            <?php else: ?>
                <?php foreach ($rules as $rule): ?>
                    <tr>
                        <td><?= htmlspecialchars($rule['domain']) ?></td>
                        <td><?= htmlspecialchars($rule['smtp_host']) ?></td>
                        <td><?= htmlspecialchars($rule['smtp_user']) ?></td>
                        <td>
                            <?= $rule['max_per_20min'] !== null
                                ? (int)$rule['max_per_20min']
                                : '<em>kein Limit</em>' ?>
                        </td>
                        <td class="text-center">
                            <a href="smtp_domain_rule_edit.php?id=<?= $rule['id'] ?>" class="btn btn-sm btn-warning">
                                <i class="bi bi-pencil-square"></i>
                            </a>
                            <a href="smtp_domain_rule_delete.php?id=<?= $rule['id'] ?>"
                               class="btn btn-sm btn-danger"
                               onclick="return confirm('Diese Regel wirklich löschen?');">
                                <i class="bi bi-trash3"></i>
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php
$pageContent = ob_get_clean();
include_once __DIR__ . '/template.php';
