{% extends "base.html" %}

{% block title %}Scan Reports - Malware Website Crawler{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h4><i class="fas fa-chart-bar"></i> Scan Reports</h4>
                <button class="btn btn-primary" onclick="refreshReports()">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
            </div>
            <div class="card-body">
                <div id="reportsList">
                    <div class="text-center">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Report Details Modal -->
<div class="modal fade" id="reportModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Scan Report Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="reportDetails">
                <!-- Report details will be loaded here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    loadReports();
});

async function loadReports() {
    try {
        const response = await axios.get('/api/reports');
        displayReports(response.data);
    } catch (error) {
        console.error('Error loading reports:', error);
        document.getElementById('reportsList').innerHTML = `
            <div class="alert alert-danger">
                Error loading reports: ${error.response?.data?.error || error.message}
            </div>
        `;
    }
}

function displayReports(reports) {
    const reportsList = document.getElementById('reportsList');
    
    if (reports.length === 0) {
        reportsList.innerHTML = `
            <div class="text-center text-muted">
                <i class="fas fa-inbox fa-3x mb-3"></i>
                <p>No scan reports found. Start a new scan to see results here.</p>
            </div>
        `;
        return;
    }
    
    reportsList.innerHTML = reports.map(report => `
        <div class="card mb-3">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-6">
                        <h6 class="card-title mb-1">
                            <i class="fas fa-globe"></i> ${report.target_url}
                        </h6>
                        <small class="text-muted">
                            <i class="fas fa-clock"></i> ${new Date(report.created_at).toLocaleString()}
                        </small>
                    </div>
                    <div class="col-md-3 text-center">
                        <span class="badge status-badge ${getStatusClass(report.status)}">
                            ${getStatusIcon(report.status)} ${report.status.toUpperCase()}
                        </span>
                    </div>
                    <div class="col-md-2 text-center">
                        <span class="badge bg-info">${report.findings_count} findings</span>
                    </div>
                    <div class="col-md-1 text-end">
                        <button class="btn btn-sm btn-outline-primary" onclick="viewReport(${report.id})">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

function getStatusClass(status) {
    switch (status) {
        case 'completed': return 'bg-success';
        case 'running': return 'bg-warning';
        case 'failed': return 'bg-danger';
        default: return 'bg-secondary';
    }
}

function getStatusIcon(status) {
    switch (status) {
        case 'completed': return '<i class="fas fa-check"></i>';
        case 'running': return '<i class="fas fa-spinner fa-spin"></i>';
        case 'failed': return '<i class="fas fa-times"></i>';
        default: return '<i class="fas fa-clock"></i>';
    }
}

async function viewReport(jobId) {
    try {
        const response = await axios.get(`/api/scan/${jobId}`);
        showReportModal(response.data);
    } catch (error) {
        console.error('Error loading report details:', error);
        alert('Error loading report details: ' + (error.response?.data?.error || error.message));
    }
}

function showReportModal(data) {
    const modal = new bootstrap.Modal(document.getElementById('reportModal'));
    const detailsDiv = document.getElementById('reportDetails');
    
    const job = data.job;
    const findings = data.findings || [];
    
    const malwareCount = findings.filter(f => f.malware_name).length;
    const suspiciousCount = findings.filter(f => f.confidence > 0.3 && !f.malware_name).length;
    const safeCount = findings.length - malwareCount - suspiciousCount;
    
    detailsDiv.innerHTML = `
        <div class="row mb-3">
            <div class="col-md-6">
                <h6>Scan Information</h6>
                <p><strong>URL:</strong> ${job.target_url}</p>
                <p><strong>Status:</strong> <span class="badge ${getStatusClass(job.status)}">${job.status.toUpperCase()}</span></p>
                <p><strong>Started:</strong> ${new Date(job.created_at).toLocaleString()}</p>
                ${job.completed_at ? `<p><strong>Completed:</strong> ${new Date(job.completed_at).toLocaleString()}</p>` : ''}
            </div>
            <div class="col-md-6">
                <h6>Summary</h6>
                <div class="row text-center">
                    <div class="col-4">
                        <div class="text-danger">
                            <h4>${malwareCount}</h4>
                            <small>Malware</small>
                        </div>
                    </div>
                    <div class="col-4">
                        <div class="text-warning">
                            <h4>${suspiciousCount}</h4>
                            <small>Suspicious</small>
                        </div>
                    </div>
                    <div class="col-4">
                        <div class="text-success">
                            <h4>${safeCount}</h4>
                            <small>Safe</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <h6>Findings</h6>
        <div class="table-responsive">
            <table class="table table-sm">
                <thead>
                    <tr>
                        <th>File</th>
                        <th>Type</th>
                        <th>Hash</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    ${findings.map(finding => `
                        <tr>
                            <td>${finding.filename}</td>
                            <td>${finding.malware_name || 'Unknown'}</td>
                            <td><code>${finding.file_hash.substring(0, 16)}...</code></td>
                            <td>
                                ${finding.malware_name ? `
                                    <span class="badge bg-danger">Malware</span>
                                ` : finding.confidence > 0.3 ? `
                                    <span class="badge bg-warning">Suspicious</span>
                                ` : `
                                    <span class="badge bg-success">Safe</span>
                                `}
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
    
    modal.show();
}

function refreshReports() {
    loadReports();
}
</script>
{% endblock %}
