<?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();
$userId = (int) ($_SESSION['user_id'] ?? 0);
$title = 'Automationsregeln';
$errors = [];
$info = '';

$validEventTypes = ['tag_assigned', 'tag_removed'];
$validActionTypes = ['assign_tag', 'remove_tag', 'subscribe_list', 'unsubscribe_list'];

if (isset($_GET['toggle'])) {
    $toggleId = (int) $_GET['toggle'];
    try {
        $sql = 'UPDATE automation_rules SET is_active = IF(is_active = 1, 0, 1) WHERE id = ?';
        $stmt = $db->prepare($sql);
        $stmt->execute([$toggleId]);
        ErrorLogger::logSqlSuccess('automation_rules admin: toggle rule | SQL: ' . $sql . ' | params: ' . json_encode([$toggleId], JSON_UNESCAPED_UNICODE));
        logSettingChange($userId, 'toggle_automation_rule', 'automation_rules', json_encode(['id' => $toggleId], JSON_UNESCAPED_UNICODE));
        $info = 'Regelstatus wurde aktualisiert.';
    } catch (Throwable $e) {
        ErrorLogger::logSqlError('automation_rules admin: toggle failed | error: ' . $e->getMessage());
        $errors[] = 'Regelstatus konnte nicht ge&auml;ndert werden.';
    }
}

if (isset($_GET['delete'])) {
    $deleteId = (int) $_GET['delete'];
    try {
        $sql = 'DELETE FROM automation_rules WHERE id = ?';
        $stmt = $db->prepare($sql);
        $stmt->execute([$deleteId]);
        ErrorLogger::logSqlSuccess('automation_rules admin: delete rule | SQL: ' . $sql . ' | params: ' . json_encode([$deleteId], JSON_UNESCAPED_UNICODE));
        logSettingChange($userId, 'delete_automation_rule', 'automation_rules', json_encode(['id' => $deleteId], JSON_UNESCAPED_UNICODE));
        $info = 'Regel wurde gel&ouml;scht.';
    } catch (Throwable $e) {
        ErrorLogger::logSqlError('automation_rules admin: delete failed | error: ' . $e->getMessage());
        $errors[] = 'Regel konnte nicht gel&ouml;scht werden.';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim((string) ($_POST['name'] ?? ''));
    $eventType = (string) ($_POST['event_type'] ?? '');
    $eventTagId = (int) ($_POST['event_tag_id'] ?? 0);
    $actionType = (string) ($_POST['action_type'] ?? '');
    $actionTargetTagId = (int) ($_POST['action_target_tag_id'] ?? 0);
    $actionTargetListId = (int) ($_POST['action_target_list_id'] ?? 0);
    $onlyOnce = isset($_POST['only_once_per_recipient']) ? 1 : 0;
    $isActive = isset($_POST['is_active']) ? 1 : 0;

    if ($name === '') {
        $errors[] = 'Bitte einen Regel-Namen angeben.';
    }
    if (!in_array($eventType, $validEventTypes, true)) {
        $errors[] = 'Bitte einen g&uuml;ltigen Ausl&ouml;ser w&auml;hlen.';
    }
    if ($eventTagId <= 0) {
        $errors[] = 'Bitte ein Ausl&ouml;ser-Tag w&auml;hlen.';
    }
    if (!in_array($actionType, $validActionTypes, true)) {
        $errors[] = 'Bitte eine g&uuml;ltige Aktion w&auml;hlen.';
    }
    if (in_array($actionType, ['assign_tag', 'remove_tag'], true) && $actionTargetTagId <= 0) {
        $errors[] = 'Bitte ein Ziel-Tag f&uuml;r die Aktion w&auml;hlen.';
    }
    if (in_array($actionType, ['subscribe_list', 'unsubscribe_list'], true) && $actionTargetListId <= 0) {
        $errors[] = 'Bitte eine Ziel-Liste f&uuml;r die Aktion w&auml;hlen.';
    }

    if ($errors === []) {
        try {
            $sql = 'INSERT INTO automation_rules (name, is_active, event_type, event_tag_id, action_type, action_target_tag_id, action_target_list_id, only_once_per_recipient, created_at, updated_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())';
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $name,
                $isActive,
                $eventType,
                $eventTagId,
                $actionType,
                $actionTargetTagId > 0 ? $actionTargetTagId : null,
                $actionTargetListId > 0 ? $actionTargetListId : null,
                $onlyOnce,
            ]);
            ErrorLogger::logSqlSuccess('automation_rules admin: create rule | SQL: ' . $sql . ' | params: ' . json_encode([$name, $eventType, $eventTagId, $actionType], JSON_UNESCAPED_UNICODE));
            logSettingChange($userId, 'create_automation_rule', 'automation_rules', json_encode($_POST, JSON_UNESCAPED_UNICODE));
            $info = 'Regel wurde gespeichert.';
            $_POST = [];
        } catch (Throwable $e) {
            ErrorLogger::logSqlError('automation_rules admin: create failed | error: ' . $e->getMessage());
            $errors[] = 'Regel konnte nicht gespeichert werden.';
        }
    }
}

try {
    $tags = $db->query('SELECT id, name FROM tags ORDER BY name ASC')->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('automation_rules admin: load tags | SQL: SELECT id, name FROM tags ORDER BY name ASC');
} catch (Throwable $e) {
    ErrorLogger::logSqlError('automation_rules admin: load tags failed | error: ' . $e->getMessage());
    $tags = [];
    $errors[] = 'Tags konnten nicht geladen werden.';
}

try {
    $lists = $db->query('SELECT id, name FROM lists ORDER BY name ASC')->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('automation_rules admin: load lists | SQL: SELECT id, name FROM lists ORDER BY name ASC');
} catch (Throwable $e) {
    ErrorLogger::logSqlError('automation_rules admin: load lists failed | error: ' . $e->getMessage());
    $lists = [];
    $errors[] = 'Listen konnten nicht geladen werden.';
}

try {
    $sql = "SELECT ar.*, et.name AS event_tag_name, att.name AS action_target_tag_name, l.name AS action_target_list_name
              FROM automation_rules ar
              JOIN tags et ON et.id = ar.event_tag_id
         LEFT JOIN tags att ON att.id = ar.action_target_tag_id
         LEFT JOIN lists l ON l.id = ar.action_target_list_id
          ORDER BY ar.id DESC";
    $rules = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('automation_rules admin: load rules | SQL: ' . $sql);
} catch (Throwable $e) {
    ErrorLogger::logSqlError('automation_rules admin: load rules failed | error: ' . $e->getMessage());
    $rules = [];
    $errors[] = 'Regeln konnten nicht geladen werden.';
}

try {
    $sql = "SELECT l.created_at, l.status, l.event_type, l.event_reference, l.details, l.recipient_id, r.name
              FROM automation_rule_logs l
         LEFT JOIN automation_rules r ON r.id = l.rule_id
          ORDER BY l.id DESC
             LIMIT 30";
    $logs = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('automation_rules admin: load logs | SQL: ' . $sql);
} catch (Throwable $e) {
    ErrorLogger::logSqlError('automation_rules admin: load logs failed | error: ' . $e->getMessage());
    $logs = [];
    $errors[] = 'Regel-Logs konnten nicht geladen werden.';
}

$fieldTooltips = [
    '[name="name"]' => 'Interner Name zur Wiedererkennung der Regel.',
    '[name="event_type"]' => 'Ereignis, das die Regel startet.',
    '[name="event_tag_id"]' => 'Tag, auf dessen Setzen oder Entfernen reagiert wird.',
    '[name="action_type"]' => 'Aktion, die nach dem Ereignis ausgef&uuml;hrt wird.',
    '[name="action_target_tag_id"]' => 'Ziel-Tag f&uuml;r Tag-Aktionen.',
    '[name="action_target_list_id"]' => 'Ziel-Liste f&uuml;r Listen-Aktionen.',
    '[name="only_once_per_recipient"]' => 'F&uuml;hrt die Regel pro Empf&auml;nger nur einmal erfolgreich aus.',
];

ob_start();
?>
<div class="page-header h2 mb-4">
    <i class="ti ti-bolt"></i> E-Mail &raquo; Automationsregeln
</div>

<?php if ($info): ?>
    <div class="alert alert-success alert-dismissible fade show auto-dismiss" role="alert">
        <?= htmlspecialchars($info) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger alert-dismissible fade show auto-dismiss" role="alert">
        <ul class="mb-0">
            <?php foreach ($errors as $error): ?>
                <li><?= htmlspecialchars($error) ?></li>
            <?php endforeach; ?>
        </ul>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="card mb-4">
    <div class="card-header bg-light fw-bold">Konzept</div>
    <div class="card-body">
        <p class="mb-2">Regeln arbeiten in MR9 aktuell nach dem Muster <code>Link -&gt; Tag -&gt; Automation</code>.</p>
        <p class="mb-2">Ein einzelner Link kann im Template bereits heute eine Link-Aktion tragen, zum Beispiel:</p>
<pre class="mb-2"><code>&lt;a href="https://example.com/angebot" data-mr-action="assign-tag" data-mr-tag="interesse_angebot"&gt;Ja, ich m&ouml;chte das haben&lt;/a&gt;</code></pre>
        <p class="mb-0">Beim echten Klick setzt MR9 zuerst das Tag am Empf&auml;nger. Diese Seite definiert dann, was als Folge passieren soll, zum Beispiel ein weiteres Tag setzen oder in eine Liste einschreiben.</p>
    </div>
</div>

<form method="post" class="card mb-4">
    <div class="card-header bg-light fw-bold">Neue Regel</div>
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-6">
                <label for="name" class="form-label">Regel-Name</label>
                <input type="text" class="form-control" id="name" name="name" value="<?= htmlspecialchars((string) ($_POST['name'] ?? '')) ?>" required>
            </div>
            <div class="col-md-3">
                <label for="event_type" class="form-label">Ausl&ouml;ser</label>
                <select class="form-select" id="event_type" name="event_type" required>
                    <option value="tag_assigned" <?= (($_POST['event_type'] ?? '') === 'tag_assigned') ? 'selected' : '' ?>>Tag wurde gesetzt</option>
                    <option value="tag_removed" <?= (($_POST['event_type'] ?? '') === 'tag_removed') ? 'selected' : '' ?>>Tag wurde entfernt</option>
                </select>
            </div>
            <div class="col-md-3">
                <label for="event_tag_id" class="form-label">Ausl&ouml;ser-Tag</label>
                <select class="form-select" id="event_tag_id" name="event_tag_id" required>
                    <option value="">-- Tag w&auml;hlen --</option>
                    <?php foreach ($tags as $tag): ?>
                        <option value="<?= (int) $tag['id'] ?>" <?= ((int) ($_POST['event_tag_id'] ?? 0) === (int) $tag['id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars((string) $tag['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label for="action_type" class="form-label">Aktion</label>
                <select class="form-select" id="action_type" name="action_type" required>
                    <option value="assign_tag" <?= (($_POST['action_type'] ?? '') === 'assign_tag') ? 'selected' : '' ?>>Tag setzen</option>
                    <option value="remove_tag" <?= (($_POST['action_type'] ?? '') === 'remove_tag') ? 'selected' : '' ?>>Tag entfernen</option>
                    <option value="subscribe_list" <?= (($_POST['action_type'] ?? '') === 'subscribe_list') ? 'selected' : '' ?>>In Liste einschreiben</option>
                    <option value="unsubscribe_list" <?= (($_POST['action_type'] ?? '') === 'unsubscribe_list') ? 'selected' : '' ?>>Aus Liste austragen</option>
                </select>
            </div>
            <div class="col-md-4">
                <label for="action_target_tag_id" class="form-label">Ziel-Tag</label>
                <select class="form-select" id="action_target_tag_id" name="action_target_tag_id">
                    <option value="">-- optional --</option>
                    <?php foreach ($tags as $tag): ?>
                        <option value="<?= (int) $tag['id'] ?>" <?= ((int) ($_POST['action_target_tag_id'] ?? 0) === (int) $tag['id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars((string) $tag['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label for="action_target_list_id" class="form-label">Ziel-Liste</label>
                <select class="form-select" id="action_target_list_id" name="action_target_list_id">
                    <option value="">-- optional --</option>
                    <?php foreach ($lists as $list): ?>
                        <option value="<?= (int) $list['id'] ?>" <?= ((int) ($_POST['action_target_list_id'] ?? 0) === (int) $list['id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars((string) $list['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <div class="form-check mt-4 pt-2">
                    <input class="form-check-input" type="checkbox" value="1" id="only_once_per_recipient" name="only_once_per_recipient" <?= isset($_POST['only_once_per_recipient']) || !isset($_POST['name']) ? 'checked' : '' ?>>
                    <label class="form-check-label" for="only_once_per_recipient">Nur einmal pro Empf&auml;nger</label>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-check mt-4 pt-2">
                    <input class="form-check-input" type="checkbox" value="1" id="is_active" name="is_active" <?= isset($_POST['is_active']) || !isset($_POST['name']) ? 'checked' : '' ?>>
                    <label class="form-check-label" for="is_active">Regel aktiv</label>
                </div>
            </div>
        </div>
    </div>
    <div class="card-footer bg-white">
        <button type="submit" class="btn btn-primary">Regel speichern</button>
    </div>
</form>

<div class="card mb-4">
    <div class="card-header bg-light fw-bold">Vorhandene Regeln</div>
    <div class="card-body table-responsive">
        <table class="table table-striped align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th>Name</th>
                    <th>Ausl&ouml;ser</th>
                    <th>Aktion</th>
                    <th>Status</th>
                    <th class="text-end">Aktionen</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rules as $rule): ?>
                    <tr>
                        <td><?= htmlspecialchars((string) $rule['name']) ?></td>
                        <td>
                            <?= ($rule['event_type'] === 'tag_removed') ? 'Tag entfernt' : 'Tag gesetzt' ?><br>
                            <span class="text-muted small"><?= htmlspecialchars((string) $rule['event_tag_name']) ?></span>
                        </td>
                        <td>
                            <?php if (in_array($rule['action_type'], ['assign_tag', 'remove_tag'], true)): ?>
                                <?= ($rule['action_type'] === 'assign_tag') ? 'Tag setzen' : 'Tag entfernen' ?><br>
                                <span class="text-muted small"><?= htmlspecialchars((string) ($rule['action_target_tag_name'] ?? '')) ?></span>
                            <?php else: ?>
                                <?= ($rule['action_type'] === 'subscribe_list') ? 'In Liste einschreiben' : 'Aus Liste austragen' ?><br>
                                <span class="text-muted small"><?= htmlspecialchars((string) ($rule['action_target_list_name'] ?? '')) ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?= !empty($rule['is_active']) ? '<span class="badge text-bg-success">aktiv</span>' : '<span class="badge text-bg-secondary">inaktiv</span>' ?>
                            <?php if (!empty($rule['only_once_per_recipient'])): ?>
                                <div class="small text-muted">nur einmal</div>
                            <?php endif; ?>
                        </td>
                        <td class="text-end">
                            <a href="?toggle=<?= (int) $rule['id'] ?>" class="btn btn-sm btn-outline-secondary">Status</a>
                            <a href="?delete=<?= (int) $rule['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Regel wirklich l&ouml;schen?');">L&ouml;schen</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if ($rules === []): ?>
                    <tr>
                        <td colspan="5" class="text-muted">Noch keine Regeln vorhanden.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="card">
    <div class="card-header bg-light fw-bold">Letzte Regel-Logs</div>
    <div class="card-body table-responsive">
        <table class="table table-sm table-striped align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th>Zeit</th>
                    <th>Regel</th>
                    <th>Empf&auml;nger</th>
                    <th>Ereignis</th>
                    <th>Status</th>
                    <th>Details</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($logs as $log): ?>
                    <tr>
                        <td><?= htmlspecialchars((string) $log['created_at']) ?></td>
                        <td><?= htmlspecialchars((string) ($log['name'] ?? 'unbekannt')) ?></td>
                        <td><?= (int) $log['recipient_id'] ?></td>
                        <td><?= htmlspecialchars((string) $log['event_type']) ?><?= $log['event_reference'] ? ' / ' . htmlspecialchars((string) $log['event_reference']) : '' ?></td>
                        <td><?= htmlspecialchars((string) $log['status']) ?></td>
                        <td><code><?= htmlspecialchars((string) ($log['details'] ?? '')) ?></code></td>
                    </tr>
                <?php endforeach; ?>
                <?php if ($logs === []): ?>
                    <tr>
                        <td colspan="6" class="text-muted">Noch keine Ausf&uuml;hrungen vorhanden.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function () {
    document.querySelectorAll('.alert.auto-dismiss').forEach(function (alert) {
        setTimeout(function () {
            bootstrap.Alert.getOrCreateInstance(alert).close();
        }, 5000);
    });
})();
</script>
<?php
$pageContent = ob_get_clean();
include __DIR__ . '/../template.php';