{% extends 'base.html' %}
{% load static %}

{% block title %}Audit Trail Report{% endblock %}

{% block extra_css %}
<style>
    .filter-card {
        background: white;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
    }
    
    .audit-log-item {
        background: white;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 10px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        border-left: 4px solid #007bff;
    }
    
    .audit-log-item.security {
        border-left-color: #dc3545;
    }
    
    .audit-log-item.permission {
        border-left-color: #ffc107;
    }
    
    .audit-log-item.data {
        border-left-color: #28a745;
    }
    
    .log-header {
        display: flex;
        justify-content: between;
        align-items: center;
        margin-bottom: 10px;
    }
    
    .log-meta {
        font-size: 0.85rem;
        color: #6c757d;
    }
    
    .event-badge {
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 500;
    }
    
    .event-badge.login { background: #d4edda; color: #155724; }
    .event-badge.logout { background: #f8d7da; color: #721c24; }
    .event-badge.permission_change { background: #fff3cd; color: #856404; }
    .event-badge.data_access { background: #d1ecf1; color: #0c5460; }
    .event-badge.security_violation { background: #f5c6cb; color: #721c24; }
    .event-badge.export_data { background: #e2e3e5; color: #383d41; }
    
    .permission-status {
        padding: 2px 6px;
        border-radius: 4px;
        font-size: 0.7rem;
        font-weight: bold;
    }
    
    .permission-granted {
        background: #d4edda;
        color: #155724;
    }
    
    .permission-denied {
        background: #f8d7da;
        color: #721c24;
    }
    
    .export-buttons {
        margin-bottom: 20px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><span>📋</span> Audit Trail Report</h2>
                <div class="export-buttons">
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-primary dropdown-toggle" data-toggle="dropdown">
                            <span>⬇️</span> Export
                        </button>
                        <div class="dropdown-menu">
                            <a class="dropdown-item" href="#" onclick="exportReport('csv')">
                                <i class="fas fa-file-csv"></i> Export as CSV
                            </a>
                            <a class="dropdown-item" href="#" onclick="exportReport('pdf')">
                                <span>📄</span> Export as PDF
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Filters -->
    <div class="row">
        <div class="col-12">
            <div class="filter-card">
                <h5><span>🔍</span> Filters</h5>
                <form method="get" id="filterForm">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="user_id">User</label>
                                <select name="user_id" id="user_id" class="form-control">
                                    <option value="">All Users</option>
                                    {% for user in users %}
                                    <option value="{{ user.id }}" {% if filters.user_id == user.id|stringformat:"s" %}selected{% endif %}>
                                        {{ user.get_full_name }} ({{ user.role|title }})
                                    </option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label for="event_type">Event Type</label>
                                <select name="event_type" id="event_type" class="form-control">
                                    <option value="">All Types</option>
                                    {% for event_type in event_types %}
                                    <option value="{{ event_type }}" {% if filters.event_type == event_type %}selected{% endif %}>
                                        {{ event_type|title }}
                                    </option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label for="module">Module</label>
                                <select name="module" id="module" class="form-control">
                                    <option value="">All Modules</option>
                                    {% for module in modules %}
                                    <option value="{{ module }}" {% if filters.module == module %}selected{% endif %}>
                                        {{ module|title }}
                                    </option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label for="start_date">Start Date</label>
                                <input type="date" name="start_date" id="start_date" class="form-control" value="{{ filters.start_date }}">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                <label for="end_date">End Date</label>
                                <input type="date" name="end_date" id="end_date" class="form-control" value="{{ filters.end_date }}">
                            </div>
                        </div>
                        <div class="col-md-1">
                            <div class="form-group">
                                <label>&nbsp;</label>
                                <button type="submit" class="btn btn-primary btn-block">
                                    <span>🔍</span>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <input type="text" name="search" id="search" class="form-control" 
                                       placeholder="Search in descriptions, actions, users..." 
                                       value="{{ filters.search_query }}">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-check">
                                <input type="checkbox" name="security_only" id="security_only" class="form-check-input" 
                                       value="true" {% if filters.security_only %}checked{% endif %}>
                                <label class="form-check-label" for="security_only">
                                    Security Events Only
                                </label>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <a href="{% url 'users:audit_trail_report' %}" class="btn btn-outline-secondary">
                                <span>✕</span> Clear
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Results -->
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5>Audit Logs ({{ page_obj.paginator.count }} total)</h5>
                <div class="text-muted">
                    Showing {{ page_obj.start_index }}-{{ page_obj.end_index }} of {{ page_obj.paginator.count }}
                </div>
            </div>
            
            {% for log in page_obj %}
            <div class="audit-log-item {% if log.is_security_event %}security{% elif log.event_type == 'permission_change' %}permission{% elif log.event_type == 'data_access' %}data{% endif %}">
                <div class="log-header">
                    <div class="d-flex align-items-center">
                        <span class="event-badge {{ log.event_type }}">{{ log.event_type|title }}</span>
                        <strong class="ml-2">{{ log.user.get_full_name|default:"Anonymous" }}</strong>
                        <span class="badge badge-secondary ml-2">{{ log.role_at_time|default:"Unknown"|title }}</span>
                        {% if log.permission_checked %}
                        <span class="permission-status ml-2 {% if log.permission_granted %}permission-granted{% else %}permission-denied{% endif %}">
                            {{ log.permission_checked }} - {% if log.permission_granted %}Granted{% else %}Denied{% endif %}
                        </span>
                        {% endif %}
                    </div>
                    <div class="log-meta">
                        {{ log.timestamp|date:"M d, Y H:i:s" }}
                        {% if log.ip_address %}
                        <br>IP: {{ log.ip_address }}
                        {% endif %}
                    </div>
                </div>
                
                <div class="log-content">
                    <strong>{{ log.action }}</strong> in {{ log.module|title }}
                    {% if log.branch_context %}
                    <span class="badge badge-info ml-1">{{ log.branch_context }}</span>
                    {% endif %}
                    <br>
                    <span class="text-muted">{{ log.description }}</span>
                    
                    {% if log.request_path %}
                    <br>
                    <small class="text-muted">
                        <span>🔗</span> {{ log.request_method|default:"GET" }} {{ log.request_path }}
                        {% if log.response_time %}
                        ({{ log.response_time|floatformat:0 }}ms)
                        {% endif %}
                    </small>
                    {% endif %}
                    
                    {% if log.is_security_event and log.severity %}
                    <br>
                    <span class="badge badge-{% if log.severity == 'critical' %}danger{% elif log.severity == 'high' %}warning{% else %}info{% endif %}">
                        {{ log.severity|title }} Security Event
                    </span>
                    {% endif %}
                </div>
            </div>
            {% empty %}
            <div class="text-center py-5">
                <span>🔍</span>
                <h5 class="text-muted">No audit logs found</h5>
                <p class="text-muted">Try adjusting your filters or search criteria.</p>
            </div>
            {% endfor %}
            
            <!-- Pagination -->
            {% if page_obj.has_other_pages %}
            <nav aria-label="Audit log pagination" class="mt-4">
                <ul class="pagination justify-content-center">
                    {% if page_obj.has_previous %}
                    <li class="page-item">
                        <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.previous_page_number }}">Previous</a>
                    </li>
                    {% endif %}
                    
                    {% for num in page_obj.paginator.page_range %}
                    {% if page_obj.number == num %}
                    <li class="page-item active">
                        <span class="page-link">{{ num }}</span>
                    </li>
                    {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                    <li class="page-item">
                        <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ num }}">{{ num }}</a>
                    </li>
                    {% endif %}
                    {% endfor %}
                    
                    {% if page_obj.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.next_page_number }}">Next</a>
                    </li>
                    {% endif %}
                </ul>
            </nav>
            {% endif %}
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
function exportReport(format) {
    const params = new URLSearchParams(window.location.search);
    params.set('type', 'audit_trail');
    params.set('format', format);
    
    const exportUrl = '{% url "users:export_audit_report" %}?' + params.toString();
    window.open(exportUrl, '_blank');
}

// Auto-submit form on filter change
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('filterForm');
    const selects = form.querySelectorAll('select');
    const checkboxes = form.querySelectorAll('input[type="checkbox"]');
    
    selects.forEach(select => {
        select.addEventListener('change', () => form.submit());
    });
    
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', () => form.submit());
    });
});
</script>
{% endblock %}