<?php
declare(strict_types=1);

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();
$title = 'Bounce Systematik';

$allowedBounceTypes = ['hard', 'soft', 'spam', 'other'];
$editPattern = [
    'id' => 0,
    'pattern' => '',
    'bounce_type' => 'other',
    'description' => '',
];
$errorMessage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string) ($_POST['action'] ?? '');
    $id = (int) ($_POST['id'] ?? 0);

    if ($action === 'save') {
        $pattern = trim((string) ($_POST['pattern'] ?? ''));
        $bounceType = (string) ($_POST['bounce_type'] ?? 'other');
        $description = trim((string) ($_POST['description'] ?? ''));

        if ($pattern === '') {
            $errorMessage = 'Bitte ein Suchmuster angeben.';
        } elseif (!in_array($bounceType, $allowedBounceTypes, true)) {
            $errorMessage = 'Der Bounce-Typ ist ungueltig.';
        } else {
            try {
                if ($id > 0) {
                    $stmt = $db->prepare(
                        'UPDATE bounce_patterns
                         SET pattern = :pattern,
                             bounce_type = :bounce_type,
                             description = :description
                         WHERE id = :id'
                    );
                    $stmt->execute([
                        ':pattern' => $pattern,
                        ':bounce_type' => $bounceType,
                        ':description' => $description !== '' ? $description : null,
                        ':id' => $id,
                    ]);
                    ErrorLogger::logSqlSuccess('bounce_systematic | Regel aktualisiert | id=' . $id);
                    header('Location: bounce_systematic.php?success=' . urlencode('Regel erfolgreich aktualisiert') . '&edit=' . $id);
                    exit;
                }

                $stmt = $db->prepare(
                    'INSERT INTO bounce_patterns (pattern, bounce_type, description)
                     VALUES (:pattern, :bounce_type, :description)'
                );
                $stmt->execute([
                    ':pattern' => $pattern,
                    ':bounce_type' => $bounceType,
                    ':description' => $description !== '' ? $description : null,
                ]);

                $newId = (int) $db->lastInsertId();
                ErrorLogger::logSqlSuccess('bounce_systematic | Regel erstellt | id=' . $newId);
                header('Location: bounce_systematic.php?success=' . urlencode('Regel erfolgreich erstellt') . '&edit=' . $newId);
                exit;
            } catch (Throwable $e) {
                ErrorLogger::logSqlError('bounce_systematic | Speichern fehlgeschlagen | error: ' . $e->getMessage());
                $errorMessage = 'Die Regel konnte nicht gespeichert werden.';
                $editPattern = [
                    'id' => $id,
                    'pattern' => $pattern,
                    'bounce_type' => $bounceType,
                    'description' => $description,
                ];
            }
        }
    } elseif ($action === 'delete') {
        if ($id <= 0) {
            $errorMessage = 'Die zu loeschende Regel ist ungueltig.';
        } else {
            try {
                $stmt = $db->prepare('DELETE FROM bounce_patterns WHERE id = :id');
                $stmt->execute([':id' => $id]);

                if ($stmt->rowCount() === 0) {
                    header('Location: bounce_systematic.php?error=' . urlencode('Regel nicht gefunden'));
                    exit;
                }

                ErrorLogger::logSqlSuccess('bounce_systematic | Regel geloescht | id=' . $id);
                header('Location: bounce_systematic.php?success=' . urlencode('Regel erfolgreich geloescht'));
                exit;
            } catch (Throwable $e) {
                ErrorLogger::logSqlError('bounce_systematic | Loeschen fehlgeschlagen | error: ' . $e->getMessage());
                $errorMessage = 'Die Regel konnte nicht geloescht werden.';
            }
        }
    }
}

try {
    $patternsStmt = $db->query(
        "SELECT id, pattern, bounce_type, description
         FROM bounce_patterns
         ORDER BY FIELD(bounce_type, 'hard', 'soft', 'spam', 'other'), pattern ASC"
    );
    $patterns = $patternsStmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('bounce_systematic | Regeln geladen');
} catch (Throwable $e) {
    ErrorLogger::logSqlError('bounce_systematic | Laden fehlgeschlagen | error: ' . $e->getMessage());
    $patterns = [];
    if ($errorMessage === '') {
        $errorMessage = 'Die Bounce-Systematik konnte nicht geladen werden.';
    }
}

$editId = (int) ($_GET['edit'] ?? 0);
if ($editId > 0 && $editPattern['id'] === 0) {
    foreach ($patterns as $patternRow) {
        if ((int) $patternRow['id'] === $editId) {
            $editPattern = [
                'id' => (int) $patternRow['id'],
                'pattern' => (string) $patternRow['pattern'],
                'bounce_type' => (string) $patternRow['bounce_type'],
                'description' => (string) ($patternRow['description'] ?? ''),
            ];
            break;
        }
    }
}

ob_start();
?>
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h1 class="mb-0">Bounce Systematik</h1>
        <?php if ($editPattern['id'] > 0): ?>
            <a href="bounce_systematic.php" class="btn btn-outline-secondary">Neue Regel</a>
        <?php endif; ?>
    </div>

    <p class="text-muted">
        Hier pflegst du die Muster, mit denen der Bounce-Handler Zustellfehler klassifiziert.
        Das Muster wird im Mailinhalt per Textsuche geprueft.
    </p>

    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success auto-dismiss"><?= htmlspecialchars((string) $_GET['success'], ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>

    <?php if (isset($_GET['error'])): ?>
        <div class="alert alert-danger"><?= htmlspecialchars((string) $_GET['error'], ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>

    <?php if ($errorMessage !== ''): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($errorMessage, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>

    <div class="card mb-4">
        <div class="card-header bg-light fw-bold">
            <?= $editPattern['id'] > 0 ? 'Regel bearbeiten' : 'Neue Regel anlegen' ?>
        </div>
        <div class="card-body">
            <form method="post">
                <input type="hidden" name="action" value="save">
                <input type="hidden" name="id" value="<?= (int) $editPattern['id'] ?>">

                <div class="row">
                    <div class="col-md-5 mb-3">
                        <label for="pattern" class="form-label">Suchmuster</label>
                        <input
                            type="text"
                            class="form-control"
                            id="pattern"
                            name="pattern"
                            value="<?= htmlspecialchars((string) $editPattern['pattern'], ENT_QUOTES, 'UTF-8') ?>"
                            placeholder="%user unknown%"
                            required
                        >
                        <div class="form-text">
                            Beispiel: <code>%user unknown%</code> oder <code>%mailbox full%</code>
                        </div>
                    </div>

                    <div class="col-md-3 mb-3">
                        <label for="bounce_type" class="form-label">Bounce-Typ</label>
                        <select class="form-select" id="bounce_type" name="bounce_type" required>
                            <?php foreach ($allowedBounceTypes as $bounceType): ?>
                                <option value="<?= htmlspecialchars($bounceType, ENT_QUOTES, 'UTF-8') ?>" <?= $editPattern['bounce_type'] === $bounceType ? 'selected' : '' ?>>
                                    <?= htmlspecialchars(strtoupper($bounceType), ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label for="description" class="form-label">Beschreibung</label>
                        <input
                            type="text"
                            class="form-control"
                            id="description"
                            name="description"
                            value="<?= htmlspecialchars((string) $editPattern['description'], ENT_QUOTES, 'UTF-8') ?>"
                            placeholder="Optional"
                        >
                    </div>
                </div>

                <button type="submit" class="btn btn-success">
                    <?= $editPattern['id'] > 0 ? 'Aenderungen speichern' : 'Regel speichern' ?>
                </button>
                <?php if ($editPattern['id'] > 0): ?>
                    <a href="bounce_systematic.php" class="btn btn-secondary">Abbrechen</a>
                <?php endif; ?>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-header bg-light fw-bold">Vorhandene Regeln</div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-striped table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th style="width: 80px;">ID</th>
                            <th>Muster</th>
                            <th style="width: 140px;">Typ</th>
                            <th>Beschreibung</th>
                            <th class="text-end" style="width: 180px;">Aktionen</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($patterns)): ?>
                            <tr>
                                <td colspan="5" class="text-center py-4">Keine Bounce-Regeln gefunden.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($patterns as $patternRow): ?>
                                <tr>
                                    <td><?= (int) $patternRow['id'] ?></td>
                                    <td><code><?= htmlspecialchars((string) $patternRow['pattern'], ENT_QUOTES, 'UTF-8') ?></code></td>
                                    <td><?= htmlspecialchars((string) strtoupper((string) $patternRow['bounce_type']), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= htmlspecialchars((string) ($patternRow['description'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td class="text-end">
                                        <a href="bounce_systematic.php?edit=<?= (int) $patternRow['id'] ?>" class="btn btn-sm btn-warning">
                                            Bearbeiten
                                        </a>
                                        <form method="post" class="d-inline" onsubmit="return confirm('Diese Bounce-Regel wirklich loeschen?');">
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="id" value="<?= (int) $patternRow['id'] ?>">
                                            <button type="submit" class="btn btn-sm btn-danger">Loeschen</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php
$pageContent = ob_get_clean();
include __DIR__ . '/template.php';
