<?php $pageTitle = t('security_log_title'); ?>
<div class="page-header">
    <div class="page-header-left">
        <a href="/dashboard" class="btn btn-ghost btn-sm">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
            <?= t('dashboard') ?>
        </a>
        <h1 class="page-title"><?= t('security_log_title') ?></h1>
    </div>
</div>

<div class="card">
    <div class="card-header"><h2 class="card-title"><?= t('security_log_title') ?></h2></div>
    <div class="card-body">
        <p class="text-muted" style="margin-bottom:1rem;font-size:.9rem"><?= t('security_log_desc', ['days' => (string)$retentionDays]) ?></p>

        <form method="GET" style="display:flex;gap:8px;align-items:flex-end;margin-bottom:1.25rem;flex-wrap:wrap">
            <div class="form-group" style="margin-bottom:0">
                <label class="form-label"><?= t('security_log_filter_type') ?></label>
                <select name="type" class="form-select">
                    <option value=""><?= t('security_log_filter_all') ?></option>
                    <?php foreach ($types as $_t): ?>
                    <option value="<?= Helper::e($_t) ?>" <?= $filterType === $_t ? 'selected' : '' ?>><?= Helper::e($_t) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group" style="margin-bottom:0">
                <label class="form-label"><?= t('security_log_filter_severity') ?></label>
                <select name="severity" class="form-select">
                    <option value=""><?= t('security_log_filter_all') ?></option>
                    <option value="info"     <?= $filterSeverity === 'info'     ? 'selected' : '' ?>>info</option>
                    <option value="warn"     <?= $filterSeverity === 'warn'     ? 'selected' : '' ?>>warn</option>
                    <option value="critical" <?= $filterSeverity === 'critical' ? 'selected' : '' ?>>critical</option>
                </select>
            </div>
            <button type="submit" class="btn btn-primary"><?= t('apply') ?></button>
            <?php if ($filterType !== '' || $filterSeverity !== ''): ?>
            <a href="/admin/security-log" class="btn btn-ghost"><?= t('reset') ?></a>
            <?php endif; ?>
        </form>

        <?php if (empty($events)): ?>
        <p class="text-muted" style="font-size:.875rem"><?= t('security_log_empty') ?></p>
        <?php else: ?>
        <table class="data-table" id="security-log-table">
            <thead>
                <tr>
                    <th><?= t('security_log_col_time') ?></th>
                    <th><?= t('security_log_col_severity') ?></th>
                    <th><?= t('security_log_col_type') ?></th>
                    <th><?= t('security_log_col_user') ?></th>
                    <th><?= t('security_log_col_ip') ?></th>
                    <th><?= t('security_log_col_details') ?></th>
                </tr>
                <tr class="security-log-filter-row">
                    <th><input type="search" class="form-input" style="padding:4px 8px;font-size:.8rem;width:100%" data-seclog-filter="0" placeholder="<?= Helper::e(t('security_log_filter_placeholder')) ?>"></th>
                    <th>
                        <select class="form-select form-select-sm" style="width:100%" data-seclog-filter="1" data-seclog-exact="1">
                            <option value=""><?= t('security_log_filter_all') ?></option>
                            <option value="info">info</option>
                            <option value="warn">warn</option>
                            <option value="critical">critical</option>
                        </select>
                    </th>
                    <th><input type="search" class="form-input" style="padding:4px 8px;font-size:.8rem;width:100%" data-seclog-filter="2" placeholder="<?= Helper::e(t('security_log_filter_placeholder')) ?>"></th>
                    <th><input type="search" class="form-input" style="padding:4px 8px;font-size:.8rem;width:100%" data-seclog-filter="3" placeholder="<?= Helper::e(t('security_log_filter_placeholder')) ?>"></th>
                    <th><input type="search" class="form-input" style="padding:4px 8px;font-size:.8rem;width:100%" data-seclog-filter="4" placeholder="<?= Helper::e(t('security_log_filter_placeholder')) ?>"></th>
                    <th><input type="search" class="form-input" style="padding:4px 8px;font-size:.8rem;width:100%" data-seclog-filter="5" placeholder="<?= Helper::e(t('security_log_filter_placeholder')) ?>"></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($events as $e): ?>
                <?php
                    $sevClass = match ($e['severity']) {
                        'critical' => 'badge-danger',
                        'warn'     => 'badge-warning',
                        default    => 'badge-neutral',
                    };
                    $userLabel = $e['username'] ?? ($e['user_id'] ? '#' . $e['user_id'] . ' (' . t('security_log_deleted_user') . ')' : '—');
                ?>
                <tr>
                    <td style="white-space:nowrap;font-family:monospace;font-size:.78rem"><?= Helper::formatDateTime($e['created_at']) ?></td>
                    <td data-seclog-value="<?= Helper::e($e['severity']) ?>"><span class="badge <?= $sevClass ?>"><?= Helper::e($e['severity']) ?></span></td>
                    <td style="font-family:monospace;font-size:.8rem"><?= Helper::e($e['event_type']) ?></td>
                    <td><?= Helper::e($userLabel) ?></td>
                    <td style="font-family:monospace;font-size:.78rem;color:var(--text-muted)"><?= Helper::e($e['ip'] ?? '—') ?></td>
                    <td style="font-family:monospace;font-size:.75rem;color:var(--text-muted);max-width:340px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="<?= Helper::e((string)$e['details']) ?>"><?= Helper::e((string)$e['details'] ?: '—') ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr class="security-log-empty-row" hidden>
                    <td colspan="6" class="text-muted" style="text-align:center;font-size:.875rem;padding:1rem"><?= t('security_log_filter_no_match') ?></td>
                </tr>
            </tfoot>
        </table>
        <p class="text-muted" style="margin-top:.75rem;font-size:.78rem"><?= t('security_log_max_rows') ?></p>
        <script nonce="<?= csp_nonce() ?>">
        (function () {
            var table = document.getElementById('security-log-table');
            if (!table) return;
            var filters = table.querySelectorAll('[data-seclog-filter]');
            var rows = table.tBodies[0] ? table.tBodies[0].rows : [];
            var emptyRow = table.querySelector('.security-log-empty-row');

            function apply() {
                var values = [];
                filters.forEach(function (el) {
                    values.push({
                        idx: parseInt(el.getAttribute('data-seclog-filter'), 10),
                        val: (el.value || '').trim().toLowerCase(),
                        exact: el.getAttribute('data-seclog-exact') === '1'
                    });
                });
                var visible = 0;
                for (var i = 0; i < rows.length; i++) {
                    var row = rows[i];
                    var show = true;
                    for (var j = 0; j < values.length; j++) {
                        var f = values[j];
                        if (!f.val) continue;
                        var cell = row.cells[f.idx];
                        if (!cell) { show = false; break; }
                        var raw = cell.getAttribute('data-seclog-value');
                        var text = (raw !== null ? raw : (cell.textContent || '')).toLowerCase();
                        if (f.exact ? text !== f.val : text.indexOf(f.val) === -1) { show = false; break; }
                    }
                    row.style.display = show ? '' : 'none';
                    if (show) visible++;
                }
                if (emptyRow) emptyRow.hidden = (visible !== 0 || rows.length === 0);
            }

            filters.forEach(function (el) {
                el.addEventListener('input', apply);
                el.addEventListener('change', apply);
            });
        })();
        </script>
        <?php endif; ?>
    </div>
</div>
