<?php
// Session starten und Basis-Dateien einbinden
session_start();
require_once __DIR__ . '/../../includes/init.php';
require_once __DIR__ . '/../../auth/AuthController.php';

// Authentifizierung prüfen
$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    header('Location: ' . $adminLoginPath);
    exit;
}

// Datenbankverbindung herstellen
$db = Database::getInstance();

// Filter aus GET übernehmen
$actionFilter = $_GET['action'] ?? '';
$emailFilter = $_GET['email'] ?? '';
$formIdFilter = $_GET['form_id'] ?? '';

// Grundabfrage aufbauen
$sql = 'SELECT * FROM formular_logs WHERE 1=1';
$params = [];

if (!empty($actionFilter)) {
    $sql .= ' AND action = :action';
    $params[':action'] = $actionFilter;
}
if (!empty($emailFilter)) {
    $sql .= ' AND email LIKE :email';
    $params[':email'] = '%' . $emailFilter . '%';
}
if (!empty($formIdFilter)) {
    $sql .= ' AND form_id = :form_id';
    $params[':form_id'] = $formIdFilter;
}

$sql .= ' ORDER BY created_at DESC LIMIT 500';
$logs = [];

try {
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    ErrorLogger::logSqlSuccess('formular_log: load logs | SQL: ' . $sql . ' | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE));
} catch (Throwable $e) {
    ErrorLogger::logSqlError('formular_log: load logs failed | SQL: ' . $sql . ' | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
    $logs = [];
}

ErrorLogger::log('Formular-Log-Übersicht aufgerufen', 'INFO');

ob_start();
?>

<div class="page-header h2">
  Formulare &raquo; Logs
</div>

<form method="get" class="mb-3">
    <label for="form_id">Formular ID:</label>
    <input type="text" name="form_id" value="<?= htmlspecialchars($formIdFilter) ?>" class="form-control form-control-sm d-inline-block w-auto mx-2" />

    <label for="email">E-Mail:</label>
    <input type="text" name="email" value="<?= htmlspecialchars($emailFilter) ?>" class="form-control form-control-sm d-inline-block w-auto mx-2" />

    <label for="action">Aktion:</label>
    <select name="action" class="form-control form-control-sm d-inline-block w-auto mx-2">
        <option value="">-- Alle --</option>
        <option value="SUCCESS" <?= $actionFilter == 'SUCCESS' ? 'selected' : '' ?>>Erfolg</option>
        <option value="VALIDATION_ERROR" <?= $actionFilter == 'VALIDATION_ERROR' ? 'selected' : '' ?>>Validierungsfehler</option>
        <option value="MISSING_FIELD" <?= $actionFilter == 'MISSING_FIELD' ? 'selected' : '' ?>>Fehlendes Feld</option>
        <option value="INVALID_EMAIL" <?= $actionFilter == 'INVALID_EMAIL' ? 'selected' : '' ?>>Ungültige E-Mail</option>
    </select>

    <button type="submit" class="btn btn-primary btn-sm mx-2">Filtern</button>
</form>

<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <th>Zeitpunkt</th>
            <th>Formular ID</th>
            <th>E-Mail</th>
            <th>IP-Adresse</th>
            <th>Aktion</th>
            <th>Nachricht</th>
            <th>Admin-Vorschau</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($logs as $log): ?>
            <tr>
                <td><?= htmlspecialchars($log['created_at']) ?></td>
                <td><?= (int)$log['form_id'] ?></td>
                <td><?= htmlspecialchars($log['email']) ?></td>
                <td><?= htmlspecialchars($log['ip_address']) ?></td>
                <td><?= htmlspecialchars($log['action']) ?></td>
                <td><?= nl2br(htmlspecialchars($log['message'])) ?></td>
                <td><?= $log['is_admin_preview'] ? 'Ja' : 'Nein' ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

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