<?php
require_once __DIR__ . '/../includes/config.php';
$me = require_login('internal');

$pdo = db();
$q       = trim((string) input('q'));
$action  = trim((string) input('action_filter'));
$entity  = trim((string) input('entity_type'));
$userId  = (int) input('user_id');
$from    = trim((string) input('from'));
$to      = trim((string) input('to'));

$where = '1=1';
$params = [];
if ($q !== '')      { $where .= ' AND (a.action LIKE ? OR a.entity_type LIKE ?)'; $params[]="%$q%"; $params[]="%$q%"; }
if ($action !== '') { $where .= ' AND a.action = ?';       $params[] = $action; }
if ($entity !== '') { $where .= ' AND a.entity_type = ?';  $params[] = $entity; }
if ($userId)        { $where .= ' AND a.user_id = ?';      $params[] = $userId; }
if ($from !== '')   { $where .= ' AND a.created_at >= ?';  $params[] = $from . ' 00:00:00'; }
if ($to   !== '')   { $where .= ' AND a.created_at <= ?';  $params[] = $to   . ' 23:59:59'; }

$rows = $pdo->prepare("SELECT a.*, u.name AS user_name, u.email AS user_email
                       FROM audit_logs a LEFT JOIN users u ON u.id = a.user_id
                       WHERE $where ORDER BY a.created_at DESC LIMIT 500");
$rows->execute($params);
$rows = $rows->fetchAll();

$actions  = $pdo->query('SELECT DISTINCT action FROM audit_logs ORDER BY action')->fetchAll(PDO::FETCH_COLUMN);
$entities = $pdo->query('SELECT DISTINCT entity_type FROM audit_logs ORDER BY entity_type')->fetchAll(PDO::FETCH_COLUMN);
$users    = $pdo->query('SELECT id, name, email FROM users ORDER BY name')->fetchAll();

$pageTitle = 'Audit log';
require __DIR__ . '/../includes/header.php';
?>
<div class="page-header"><div class="container-xl">
    <h2 class="page-title">Audit log</h2>
    <div class="text-secondary">Every config change and sensitive action. Read-only. Up to 500 most recent.</div>
</div></div>

<div class="page-body"><div class="container-xl">
    <div class="card mb-3"><div class="card-body">
        <form method="GET" class="row g-2">
            <div class="col-md-3"><input type="text" name="q" class="form-control" placeholder="Search action/entity" value="<?= e($q) ?>"></div>
            <div class="col-md-2">
                <select name="action_filter" class="form-select"><option value="">All actions</option>
                    <?php foreach ($actions as $a): ?><option <?= $a===$action?'selected':'' ?>><?= e($a) ?></option><?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <select name="entity_type" class="form-select"><option value="">All entities</option>
                    <?php foreach ($entities as $e): ?><option <?= $e===$entity?'selected':'' ?>><?= e($e) ?></option><?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <select name="user_id" class="form-select"><option value="">All users</option>
                    <?php foreach ($users as $u): ?><option value="<?= (int)$u['id'] ?>" <?= $u['id']==$userId?'selected':'' ?>><?= e($u['name']) ?></option><?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-1"><input type="date" name="from" class="form-control" value="<?= e($from) ?>"></div>
            <div class="col-md-1"><input type="date" name="to"   class="form-control" value="<?= e($to) ?>"></div>
            <div class="col-md-1"><button class="btn btn-primary w-100"><i class="ti ti-search"></i></button></div>
        </form>
    </div></div>

    <div class="card">
        <div class="table-responsive">
            <table class="table table-vcenter card-table">
                <thead><tr><th>When</th><th>User</th><th>Action</th><th>Entity</th><th>ID</th><th>IP</th><th>Diff</th></tr></thead>
                <tbody>
                <?php if (!$rows): ?><tr><td colspan="7" class="text-center text-secondary py-4">No audit events match.</td></tr>
                <?php else: foreach ($rows as $r): ?>
                    <tr>
                        <td class="text-secondary small"><?= e($r['created_at']) ?></td>
                        <td><?= e($r['user_name'] ?? '--') ?><div class="small text-secondary"><?= e($r['user_email'] ?? '') ?></div></td>
                        <td><span class="badge bg-blue-lt"><?= e($r['action']) ?></span></td>
                        <td><?= e($r['entity_type']) ?></td>
                        <td><?= e($r['entity_id']) ?></td>
                        <td class="small text-secondary"><?= e($r['ip']) ?></td>
                        <td>
                            <?php if ($r['before_json'] || $r['after_json']): ?>
                                <details><summary class="text-primary small" style="cursor:pointer">view</summary>
                                <?php if ($r['before_json']): ?><div class="small text-secondary mt-1">before</div><pre class="small text-danger"><?= e(json_encode(json_decode($r['before_json'], true), JSON_PRETTY_PRINT)) ?></pre><?php endif; ?>
                                <?php if ($r['after_json']): ?><div class="small text-secondary mt-1">after</div><pre class="small text-success"><?= e(json_encode(json_decode($r['after_json'], true), JSON_PRETTY_PRINT)) ?></pre><?php endif; ?>
                                </details>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
