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

{% block title %}Security Compliance Report{% endblock %}

{% block extra_css %}
<link href="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css" rel="stylesheet">
<style>
    .compliance-card {
        background: white;
        border-radius: 10px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
    }
    
    .security-metric {
        text-align: center;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        color: white;
    }
    
    .security-metric.critical {
        background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
    }
    
    .security-metric.warning {
        background: linear-gradient(135deg, #feca57 0%, #ff9ff3 100%);
    }
    
    .security-metric.good {
        background: linear-gradient(135deg, #48dbfb 0%, #0abde3 100%);
    }
    
    .security-metric.info {
        background: linear-gradient(135deg, #54a0ff 0%, #2e86de 100%);
    }
    
    .metric-value {
        font-size: 2.5rem;
        font-weight: bold;
        margin-bottom: 5px;
    }
    
    .metric-label {
        font-size: 0.9rem;
        opacity: 0.9;
    }
    
    .alert-item {
        border-left: 4px solid #dc3545;
        padding: 15px;
        margin-bottom: 10px;
        background: #f8f9fa;
        border-radius: 0 5px 5px 0;
    }
    
    .alert-item.resolved {
        border-left-color: #28a745;
        background: #f8fff9;
    }
    
    .alert-item.warning {
        border-left-color: #ffc107;
        background: #fffdf5;
    }
    
    .alert-item.info {
        border-left-color: #17a2b8;
        background: #f7fdff;
    }
    
    .severity-badge {
        padding: 3px 8px;
        border-radius: 12px;
        font-size: 0.75rem;
        font-weight: 500;
    }
    
    .severity-critical {
        background: #f8d7da;
        color: #721c24;
    }
    
    .severity-high {
        background: #fff3cd;
        color: #856404;
    }
    
    .severity-medium {
        background: #d1ecf1;
        color: #0c5460;
    }
    
    .severity-low {
        background: #d4edda;
        color: #155724;
    }
    
    .compliance-score {
        font-size: 3rem;
        font-weight: bold;
        text-align: center;
        margin: 20px 0;
    }
    
    .compliance-score.excellent {
        color: #28a745;
    }
    
    .compliance-score.good {
        color: #17a2b8;
    }
    
    .compliance-score.warning {
        color: #ffc107;
    }
    
    .compliance-score.poor {
        color: #dc3545;
    }
    
    .export-section {
        margin-bottom: 20px;
    }
    
    .suspicious-ip {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        border-radius: 5px;
        padding: 10px;
        margin-bottom: 10px;
    }
</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><i class="fas fa-shield-alt"></i> Security Compliance Report</h2>
                <div class="d-flex align-items-center">
                    <div class="btn-group mr-3">
                        <a href="?days=7" class="btn btn-outline-primary {% if days == 7 %}active{% endif %}">7 Days</a>
                        <a href="?days=30" class="btn btn-outline-primary {% if days == 30 %}active{% endif %}">30 Days</a>
                        <a href="?days=90" class="btn btn-outline-primary {% if days == 90 %}active{% endif %}">90 Days</a>
                    </div>
                    <div class="export-section">
                        <div class="btn-group">
                            <button type="button" class="btn btn-outline-success 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>
    </div>
    
    <!-- Security Metrics -->
    <div class="row">
        <div class="col-md-3">
            <div class="security-metric {% if total_security_events > 50 %}critical{% elif total_security_events > 20 %}warning{% else %}good{% endif %}">
                <div class="metric-value">{{ total_security_events }}</div>
                <div class="metric-label">Security Events</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="security-metric info">
                <div class="metric-value">{{ compliance_metrics.password_changes }}</div>
                <div class="metric-label">Password Changes</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="security-metric {% if compliance_metrics.role_changes > 10 %}warning{% else %}good{% endif %}">
                <div class="metric-value">{{ compliance_metrics.role_changes }}</div>
                <div class="metric-label">Role Changes</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="security-metric {% if compliance_metrics.critical_permission_grants > 5 %}critical{% elif compliance_metrics.critical_permission_grants > 2 %}warning{% else %}good{% endif %}">
                <div class="metric-value">{{ compliance_metrics.critical_permission_grants }}</div>
                <div class="metric-label">Critical Permissions</div>
            </div>
        </div>
    </div>
    
    <!-- Compliance Score -->
    <div class="row">
        <div class="col-md-4">
            <div class="compliance-card">
                <h5><span>📊</span> Compliance Score</h5>
                {% with score=85 %}
                <div class="compliance-score {% if score >= 90 %}excellent{% elif score >= 75 %}good{% elif score >= 60 %}warning{% else %}poor{% endif %}">
                    {{ score }}%
                </div>
                <div class="text-center">
                    <small class="text-muted">Based on security events, failed access attempts, and policy violations</small>
                </div>
                {% endwith %}
            </div>
        </div>
        <div class="col-md-8">
            <div class="compliance-card">
                <h5><span>📊</span> Security Alerts by Severity</h5>
                <canvas id="severityChart" width="400" height="200"></canvas>
            </div>
        </div>
    </div>
    
    <!-- Failed Access Attempts -->
    <div class="row">
        <div class="col-md-6">
            <div class="compliance-card">
                <h5><i class="fas fa-ban"></i> Failed Access Attempts</h5>
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>IP Address</th>
                                <th>Attempts</th>
                                <th>Risk Level</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for attempt in failed_access %}
                            <tr>
                                <td>{{ attempt.user__first_name }} {{ attempt.user__last_name }}</td>
                                <td>{{ attempt.ip_address|default:"-" }}</td>
                                <td>{{ attempt.count }}</td>
                                <td>
                                    {% if attempt.count > 10 %}
                                    <span class="severity-badge severity-critical">High</span>
                                    {% elif attempt.count > 5 %}
                                    <span class="severity-badge severity-high">Medium</span>
                                    {% else %}
                                    <span class="severity-badge severity-low">Low</span>
                                    {% endif %}
                                </td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="4" class="text-center text-muted">No failed access attempts</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="compliance-card">
                <h5><span>🛡️</span> Permission Escalations</h5>
                <div style="max-height: 400px; overflow-y: auto;">
                    {% for escalation in permission_escalations %}
                    <div class="alert-item warning">
                        <div class="d-flex justify-content-between">
                            <div>
                                <strong>{{ escalation.user.get_full_name }}</strong>
                                <br>
                                <small>Permission: {{ escalation.permission_name }}</small>
                                <br>
                                <small class="text-muted">Changed by: {{ escalation.changed_by.get_full_name }}</small>
                            </div>
                            <div class="text-right">
                                <small>{{ escalation.timestamp|timesince }} ago</small>
                                <br>
                                <span class="severity-badge severity-high">Escalation</span>
                            </div>
                        </div>
                    </div>
                    {% empty %}
                    <p class="text-muted text-center">No permission escalations detected</p>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
    
    <!-- Suspicious IPs and Data Exports -->
    <div class="row">
        <div class="col-md-6">
            <div class="compliance-card">
                <h5><span>🌐</span> Suspicious IP Addresses</h5>
                {% for ip in suspicious_ips %}
                <div class="suspicious-ip">
                    <div class="d-flex justify-content-between">
                        <div>
                            <strong>{{ ip.ip_address }}</strong>
                            <br>
                            <small>{{ ip.unique_users }} unique users</small>
                        </div>
                        <div class="text-right">
                            <span class="severity-badge severity-critical">{{ ip.event_count }} events</span>
                        </div>
                    </div>
                </div>
                {% empty %}
                <p class="text-muted text-center">No suspicious IP addresses detected</p>
                {% endfor %}
            </div>
        </div>
        <div class="col-md-6">
            <div class="compliance-card">
                <h5><span>⬇️</span> Data Export Activities</h5>
                <div style="max-height: 400px; overflow-y: auto;">
                    {% for export in data_exports %}
                    <div class="alert-item info">
                        <div class="d-flex justify-content-between">
                            <div>
                                <strong>{{ export.user.get_full_name }}</strong>
                                <br>
                                <small>{{ export.action }}</small>
                                <br>
                                <small class="text-muted">{{ export.description|truncatechars:60 }}</small>
                            </div>
                            <div class="text-right">
                                <small>{{ export.timestamp|timesince }} ago</small>
                                <br>
                                <span class="severity-badge severity-medium">Export</span>
                            </div>
                        </div>
                    </div>
                    {% empty %}
                    <p class="text-muted text-center">No data exports in this period</p>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
    
    <!-- Open Security Alerts -->
    <div class="row">
        <div class="col-12">
            <div class="compliance-card">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5><span>⚠️</span> Open Security Alerts</h5>
                    <a href="{% url 'users:security_alerts' %}" class="btn btn-outline-primary">
                        View All Alerts
                    </a>
                </div>
                {% for alert in open_alerts %}
                <div class="alert-item {% if alert.severity == 'critical' %}{% elif alert.severity == 'high' %}warning{% else %}info{% endif %}">
                    <div class="d-flex justify-content-between">
                        <div>
                            <div class="d-flex align-items-center mb-2">
                                <strong>{{ alert.title }}</strong>
                                <span class="severity-badge severity-{{ alert.severity }} ml-2">{{ alert.severity|title }}</span>
                                <span class="badge badge-secondary ml-2">{{ alert.alert_type|title }}</span>
                            </div>
                            <p class="mb-1">{{ alert.description|truncatechars:150 }}</p>
                            {% if alert.user %}
                            <small class="text-muted">User: {{ alert.user.get_full_name }}</small>
                            {% endif %}
                            {% if alert.ip_address %}
                            <small class="text-muted"> | IP: {{ alert.ip_address }}</small>
                            {% endif %}
                        </div>
                        <div class="text-right">
                            <small>{{ alert.created_at|timesince }} ago</small>
                            <br>
                            <button class="btn btn-sm btn-outline-success" onclick="resolveAlert('{{ alert.id }}')">
                                Resolve
                            </button>
                        </div>
                    </div>
                </div>
                {% empty %}
                <div class="text-center py-4">
                    <span>✓</span>
                    <h5 class="text-success">No Open Security Alerts</h5>
                    <p class="text-muted">All security alerts have been resolved.</p>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>
    
    <!-- Compliance Recommendations -->
    <div class="row">
        <div class="col-12">
            <div class="compliance-card">
                <h5><span>💡</span> Security Recommendations</h5>
                <div class="row">
                    <div class="col-md-6">
                        <h6>Immediate Actions</h6>
                        <ul class="list-unstyled">
                            {% if total_security_events > 20 %}
                            <li><span>⚠️</span> Review and address {{ total_security_events }} security events</li>
                            {% endif %}
                            {% if compliance_metrics.critical_permission_grants > 2 %}
                            <li><span>🔑</span> Audit {{ compliance_metrics.critical_permission_grants }} critical permission grants</li>
                            {% endif %}
                            {% for attempt in failed_access %}
                            {% if attempt.count > 10 %}
                            <li><i class="fas fa-ban text-danger"></i> Investigate {{ attempt.count }} failed attempts from {{ attempt.user__first_name }} {{ attempt.user__last_name }}</li>
                            {% endif %}
                            {% endfor %}
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <h6>Preventive Measures</h6>
                        <ul class="list-unstyled">
                            <li><i class="fas fa-shield-alt text-info"></i> Implement multi-factor authentication</li>
                            <li><span>⏰</span> Set up automated security monitoring</li>
                            <li><i class="fas fa-graduation-cap text-info"></i> Conduct security awareness training</li>
                            <li><span>🔄</span> Regular permission audits</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Resolve Alert Modal -->
<div class="modal fade" id="resolveAlertModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Resolve Security Alert</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="resolveAlertForm">
                    <div class="form-group">
                        <label for="resolution_notes">Resolution Notes</label>
                        <textarea class="form-control" id="resolution_notes" name="resolution_notes" rows="3" 
                                  placeholder="Describe how this alert was resolved..."></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" onclick="submitResolveAlert()">Resolve Alert</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Severity Chart
    const severityCtx = document.getElementById('severityChart').getContext('2d');
    const severityData = {
        labels: [
            {% for alert in alerts_by_severity %}
            '{{ alert.severity|title }}'{% if not forloop.last %},{% endif %}
            {% endfor %}
        ],
        datasets: [{
            label: 'Alerts',
            data: [
                {% for alert in alerts_by_severity %}
                {{ alert.count }}{% if not forloop.last %},{% endif %}
                {% endfor %}
            ],
            backgroundColor: [
                '#dc3545', '#ffc107', '#17a2b8', '#28a745'
            ]
        }]
    };
    
    new Chart(severityCtx, {
        type: 'bar',
        data: severityData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
});

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

let currentAlertId = null;

function resolveAlert(alertId) {
    currentAlertId = alertId;
    $('#resolveAlertModal').modal('show');
}

function submitResolveAlert() {
    if (!currentAlertId) return;
    
    const notes = document.getElementById('resolution_notes').value;
    
    fetch(`/users/audit/alerts/${currentAlertId}/resolve/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
        },
        body: `resolution_notes=${encodeURIComponent(notes)}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            $('#resolveAlertModal').modal('hide');
            location.reload();
        } else {
            alert('Error resolving alert: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error resolving alert');
    });
}
</script>
{% endblock %}