{% extends "base.html" %}

{% block title %}Audit Log - NanoIDP{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-journal-text me-2"></i>Audit Log</h2>
    <div>
        <button class="btn btn-outline-danger btn-sm" onclick="clearAudit()">
            <i class="bi bi-trash me-1"></i>Clear Log
        </button>
        <button class="btn btn-outline-primary btn-sm ms-2" onclick="location.reload()">
            <i class="bi bi-arrow-clockwise me-1"></i>Refresh
        </button>
    </div>
</div>

<!-- Stats -->
<div class="row g-3 mb-4">
    <div class="col-md-2">
        <div class="card text-center">
            <div class="card-body py-2">
                <div class="fs-4 fw-bold text-primary">{{ stats.total_requests }}</div>
                <small class="text-muted">Total</small>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card text-center">
            <div class="card-body py-2">
                <div class="fs-4 fw-bold text-success">{{ stats.token_requests }}</div>
                <small class="text-muted">Tokens</small>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card text-center">
            <div class="card-body py-2">
                <div class="fs-4 fw-bold text-info">{{ stats.saml_requests }}</div>
                <small class="text-muted">SAML</small>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card text-center">
            <div class="card-body py-2">
                <div class="fs-4 fw-bold text-warning">{{ stats.login_attempts }}</div>
                <small class="text-muted">Logins</small>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card text-center">
            <div class="card-body py-2">
                <div class="fs-4 fw-bold text-success">{{ stats.successful_logins }}</div>
                <small class="text-muted">Success</small>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <div class="card text-center">
            <div class="card-body py-2">
                <div class="fs-4 fw-bold text-danger">{{ stats.failed_logins }}</div>
                <small class="text-muted">Failed</small>
            </div>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body py-2">
        <form method="GET" class="row g-2 align-items-center" id="filterForm">
            <div class="col-auto">
                <label class="col-form-label">Filter:</label>
            </div>
            <div class="col-auto">
                <input type="text" name="search" class="form-control form-control-sm" placeholder="Search..."
                       value="{{ search or '' }}" style="width: 150px;">
            </div>
            <div class="col-auto">
                <select name="event_type" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="">All Events</option>
                    <option value="token_request" {% if event_type == 'token_request' %}selected{% endif %}>Token Requests</option>
                    <option value="saml_request" {% if event_type == 'saml_request' %}selected{% endif %}>SAML Requests</option>
                    <option value="login" {% if event_type == 'login' %}selected{% endif %}>Login Attempts</option>
                    <option value="logout" {% if event_type == 'logout' %}selected{% endif %}>Logouts</option>
                </select>
            </div>
            <div class="col-auto">
                <select name="client_id" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="">All Clients</option>
                    {% for cid in client_ids %}
                    <option value="{{ cid }}" {% if client_id == cid %}selected{% endif %}>{{ cid }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-auto">
                <select name="limit" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="25" {% if limit == 25 %}selected{% endif %}>25 entries</option>
                    <option value="50" {% if limit == 50 %}selected{% endif %}>50 entries</option>
                    <option value="100" {% if limit == 100 %}selected{% endif %}>100 entries</option>
                </select>
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-sm btn-primary">
                    <i class="bi bi-search"></i>
                </button>
            </div>
            <div class="col-auto ms-auto">
                <div class="form-check form-switch">
                    <input class="form-check-input" type="checkbox" id="autoRefresh">
                    <label class="form-check-label small" for="autoRefresh">Auto-refresh</label>
                </div>
            </div>
            <div class="col-auto">
                <div class="dropdown">
                    <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <i class="bi bi-download me-1"></i>Export
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="{{ url_for('ui.audit_export', format='json', event_type=event_type or '', client_id=client_id or '', limit=limit) }}">
                            <i class="bi bi-filetype-json me-2"></i>Export as JSON
                        </a></li>
                        <li><a class="dropdown-item" href="{{ url_for('ui.audit_export', format='csv', event_type=event_type or '', client_id=client_id or '', limit=limit) }}">
                            <i class="bi bi-filetype-csv me-2"></i>Export as CSV
                        </a></li>
                    </ul>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Log Entries -->
<div class="card">
    <div class="card-header">
        <i class="bi bi-list-ul me-2"></i>Recent Events ({{ entries|length }})
    </div>
    <div class="card-body p-0">
        {% if entries %}
        <div class="list-group list-group-flush">
            {% for entry in entries %}
            <div class="list-group-item log-entry {{ entry.status }}">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <span class="badge {% if entry.status == 'success' %}bg-success{% else %}bg-danger{% endif %} me-2">
                            {{ entry.status }}
                        </span>
                        <span class="badge bg-secondary me-2">{{ entry.event_type }}</span>
                        <strong>{{ entry.method }}</strong> {{ entry.endpoint }}
                        {% if entry.username %}
                        <span class="text-muted ms-2">
                            <i class="bi bi-person"></i> {{ entry.username }}
                        </span>
                        {% endif %}
                        {% if entry.client_id %}
                        <span class="text-muted ms-2">
                            <i class="bi bi-app"></i> {{ entry.client_id }}
                        </span>
                        {% endif %}
                    </div>
                    <small class="text-muted">{{ entry.timestamp }}</small>
                </div>
                {% if entry.details %}
                <small class="text-muted mt-1 d-block">
                    {% for key, value in entry.details.items() %}
                    <span class="me-3">{{ key }}: <code>{{ value }}</code></span>
                    {% endfor %}
                </small>
                {% endif %}
            </div>
            {% endfor %}
        </div>
        {% else %}
        <div class="text-center py-5 text-muted">
            <i class="bi bi-inbox" style="font-size: 3rem;"></i>
            <p class="mt-2">No audit entries yet</p>
        </div>
        {% endif %}
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function clearAudit() {
    if (confirm('Are you sure you want to clear the audit log?')) {
        fetch('/api/audit/clear', { method: 'POST' })
            .then(() => location.reload());
    }
}

// Auto-refresh functionality
let refreshInterval = null;

document.getElementById('autoRefresh').addEventListener('change', function() {
    if (this.checked) {
        refreshInterval = setInterval(() => {
            location.reload();
        }, 5000); // Refresh every 5 seconds
    } else {
        if (refreshInterval) {
            clearInterval(refreshInterval);
            refreshInterval = null;
        }
    }
});

// Restore auto-refresh state from localStorage
if (localStorage.getItem('auditAutoRefresh') === 'true') {
    document.getElementById('autoRefresh').checked = true;
    document.getElementById('autoRefresh').dispatchEvent(new Event('change'));
}

document.getElementById('autoRefresh').addEventListener('change', function() {
    localStorage.setItem('auditAutoRefresh', this.checked);
});
</script>
{% endblock %}
