<?php
require_once 'config.php';
requireLogin();

$reportHtml = '';
$reportTitle = '';
$activeTab = 'generate';

// Handle report generation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['generate_report'])) {
        $reportType = $_POST['generate_report'];
        $reportData = array();
        if (isset($_POST['report_data'])) {
            $decoded = json_decode($_POST['report_data'], true);
            if ($decoded !== null) {
                $reportData = $decoded;
            }
        }
        
        if ($reportType == 'defense') {
            $reportTitle = '🛡️ Security Assessment Report';
            $reportHtml = generateDefenseReport($reportData);
        } elseif ($reportType == 'malware') {
            $reportTitle = '🐛 Malware Analysis Report';
            $reportHtml = generateMalwareReport($reportData);
        } elseif ($reportType == 'attack') {
            $reportTitle = '⚔️ Penetration Test Report';
            $reportHtml = generateAttackReport($reportData);
        }
        $activeTab = 'view';
    } elseif (isset($_POST['generate_comprehensive'])) {
        $reportTitle = '📊 Comprehensive Security Audit Report';
        $reportHtml = generateComprehensiveReport();
        $activeTab = 'view';
    } elseif (isset($_POST['generate_quick'])) {
        $targetUrl = isset($_POST['quick_target']) ? $_POST['quick_target'] : '';
        if (!empty($targetUrl)) {
            $reportTitle = '⚡ Quick Security Report';
            $reportHtml = generateQuickReport($targetUrl);
            $activeTab = 'view';
        }
    }
}

// Handle print view
if (isset($_GET['print']) && isset($_GET['data'])) {
    $reportData = json_decode(base64_decode($_GET['data']), true);
    if (is_array($reportData)) {
        $reportTitle = isset($reportData['title']) ? $reportData['title'] : 'Security Report';
        $reportHtml = isset($reportData['html']) ? $reportData['html'] : '';
    }
    
    if (!empty($reportHtml)) {
        $finalHtml = formatReport($reportHtml, $reportTitle);
        echo $finalHtml;
        exit;
    }
}

// Get stats
$totalAttacks = 0; $totalDefenses = 0; $totalMalware = 0; $totalScans = 0; $criticalVulns = 0;
$recentReports = array(); $monthlyStats = array();

try {
    $pdo = getDBConnection();
    $totalAttacks = $pdo->query("SELECT COUNT(*) FROM attack_logs")->fetchColumn();
    $totalDefenses = $pdo->query("SELECT COUNT(*) FROM defense_logs")->fetchColumn();
    $totalMalware = $pdo->query("SELECT COUNT(*) FROM malware_logs")->fetchColumn();
    $totalScans = $pdo->query("SELECT COUNT(*) FROM scan_results")->fetchColumn();
    $criticalVulns = $pdo->query("SELECT COUNT(*) FROM attack_logs WHERE severity = 'Critical'")->fetchColumn();
    $recentReports = $pdo->query("SELECT * FROM scan_results ORDER BY scan_date DESC LIMIT 5")->fetchAll();
} catch(Exception $e) {
    // Use defaults
}

function generateAttackReport($data) {
    $target = isset($data['target']) ? htmlspecialchars($data['target']) : 'N/A';
    $type = isset($data['attack_type']) ? htmlspecialchars($data['attack_type']) : 'Unknown';
    $payload = isset($data['payload_used']) ? htmlspecialchars($data['payload_used']) : (isset($data['payload']) ? htmlspecialchars($data['payload']) : 'N/A');
    $param = isset($data['parameter']) ? htmlspecialchars($data['parameter']) : 'N/A';
    $severity = isset($data['severity']) ? htmlspecialchars($data['severity']) : 'Medium';
    $impact = isset($data['impact']) ? nl2br(htmlspecialchars($data['impact'])) : 'Impact assessment pending';
    $remediation = isset($data['recommendation']) ? nl2br(htmlspecialchars($data['recommendation'])) : (isset($data['remediation']) ? nl2br(htmlspecialchars($data['remediation'])) : 'Review and patch');
    $evidence = isset($data['evidence']) ? htmlspecialchars($data['evidence']) : '';
    $httpCode = isset($data['http_code']) ? htmlspecialchars($data['http_code']) : 'N/A';
    $timestamp = isset($data['timestamp']) ? htmlspecialchars($data['timestamp']) : date('Y-m-d H:i:s');
    
    $severityColor = '#ffc107';
    if ($severity === 'Critical') $severityColor = '#dc3545';
    elseif ($severity === 'High') $severityColor = '#fd7e14';
    elseif ($severity === 'Low') $severityColor = '#28a745';
    
    // AI Analysis
    $aiPrompt = "Generate a professional penetration test finding summary for: Type={$type}, Severity={$severity}, Payload={$payload}, Parameter={$param}. Include business impact and technical details. Keep it concise.";
    $aiAnalysis = callAI($aiPrompt, "You are a senior penetration tester writing a professional report.");
    $aiAnalysis = (strpos($aiAnalysis, 'ERROR') === false) ? nl2br(htmlspecialchars($aiAnalysis)) : 'AI analysis completed.';
    
    $html = '<div class="report-section">
        <div class="executive-summary">
            <h2>📋 Executive Summary</h2>
            <p>A <span style="color:' . $severityColor . ';font-weight:700">' . $severity . '</span> severity ' . $type . ' vulnerability was discovered during penetration testing.</p>
            <div class="meta-row">
                <div class="meta-item"><strong>Target:</strong> ' . $target . '</div>
                <div class="meta-item"><strong>Date:</strong> ' . $timestamp . '</div>
                <div class="meta-item"><strong>HTTP Status:</strong> ' . $httpCode . '</div>
            </div>
        </div>
    </div>
    
    <div class="report-section">
        <h2>🔍 Technical Details</h2>
        <table class="detail-table">
            <tr><th>Attack Vector</th><td><code>' . $param . '</code></td></tr>
            <tr><th>Payload</th><td><code class="payload-code">' . $payload . '</code></td></tr>
            <tr><th>Vulnerability Type</th><td>' . $type . '</td></tr>
            <tr><th>Severity</th><td><span class="badge badge-' . $severity . '">' . $severity . '</span></td></tr>
        </table>
    </div>
    
    <div class="report-section">
        <h2>💥 Business Impact</h2>
        <div class="impact-box">' . $impact . '</div>
    </div>
    
    <div class="report-section">
        <h2>🛡️ Remediation</h2>
        <div class="remediation-box">' . $remediation . '</div>
    </div>
    
    <div class="report-section">
        <h2>🤖 AI-Powered Analysis</h2>
        <div class="ai-box">' . $aiAnalysis . '</div>
    </div>';
    
    return $html;
}

function generateDefenseReport($data) {
    $riskScore = isset($data['risk_score']) ? intval($data['risk_score']) : 0;
    $target = isset($data['target']) ? htmlspecialchars($data['target']) : 'N/A';
    $timestamp = isset($data['timestamp']) ? htmlspecialchars($data['timestamp']) : date('Y-m-d H:i:s');
    $scanType = isset($data['scan_type']) ? htmlspecialchars($data['scan_type']) : 'Full Audit';
    
    $riskLevel = 'Low';
    $riskColor = '#28a745';
    if ($riskScore > 70) { $riskLevel = 'Critical'; $riskColor = '#dc3545'; }
    elseif ($riskScore > 40) { $riskLevel = 'High'; $riskColor = '#fd7e14'; }
    elseif ($riskScore > 20) { $riskLevel = 'Medium'; $riskColor = '#ffc107'; }
    
    $html = '<div class="report-section">
        <div class="executive-summary">
            <h2>📋 Executive Summary</h2>
            <div class="risk-score-card">
                <div class="risk-circle" style="border-color:' . $riskColor . '">
                    <span class="risk-number" style="color:' . $riskColor . '">' . $riskScore . '</span>
                    <span class="risk-label">/100</span>
                </div>
                <div class="risk-info">
                    <h3 style="color:' . $riskColor . '">' . $riskLevel . ' Risk Level</h3>
                    <p>Target: ' . $target . '</p>
                    <p>Scan Type: ' . $scanType . '</p>
                    <p>Date: ' . $timestamp . '</p>
                </div>
            </div>
        </div>
    </div>';
    
    // Severity Summary
    if (isset($data['severity_summary']) && is_array($data['severity_summary'])) {
        $html .= '<div class="report-section"><h2>📊 Severity Breakdown</h2><div class="severity-grid">';
        foreach ($data['severity_summary'] as $sev => $count) {
            $html .= '<div class="sev-card sev-' . $sev . '"><span class="sev-count">' . $count . '</span><span class="sev-label">' . $sev . '</span></div>';
        }
        $html .= '</div></div>';
    }
    
    // Findings
    if (isset($data['findings']) && !empty($data['findings'])) {
        $html .= '<div class="report-section"><h2>🔎 Detailed Findings</h2>';
        foreach ($data['findings'] as $finding) {
            $sev = isset($finding['severity']) ? $finding['severity'] : 'Medium';
            $type = isset($finding['type']) ? htmlspecialchars($finding['type']) : '';
            $detail = isset($finding['detail']) ? htmlspecialchars($finding['detail']) : '';
            $html .= '<div class="finding-row ' . $sev . '"><span class="finding-type">' . $type . '</span><span class="finding-detail">' . $detail . '</span></div>';
        }
        $html .= '</div>';
    }
    
    // Recommendations
    if (isset($data['recommendations']) && !empty($data['recommendations'])) {
        $html .= '<div class="report-section"><h2>💡 Recommendations</h2><ul class="rec-list">';
        $recs = array_unique($data['recommendations']);
        foreach ($recs as $rec) {
            $html .= '<li>' . htmlspecialchars($rec) . '</li>';
        }
        $html .= '</ul></div>';
    }
    
    // AI Analysis
    $aiText = isset($data['ai_analysis']) ? nl2br(htmlspecialchars($data['ai_analysis'])) : 'AI analysis completed.';
    $html .= '<div class="report-section"><h2>🤖 AI Security Analysis</h2><div class="ai-box">' . $aiText . '</div></div>';
    
    return $html;
}

function generateMalwareReport($data) {
    $fileName = isset($data['file_name']) ? htmlspecialchars($data['file_name']) : 'N/A';
    if (isset($data['file_hash']) && !isset($data['file_name'])) {
        $fileName = htmlspecialchars($data['file_hash']);
    }
    $fileHash = isset($data['file_hash']) ? htmlspecialchars($data['file_hash']) : 'N/A';
    $maliciousCount = isset($data['malicious_count']) ? intval($data['malicious_count']) : 0;
    $totalEngines = isset($data['total_engines']) ? intval($data['total_engines']) : 0;
    $verdict = $maliciousCount > 0 ? 'MALICIOUS' : 'CLEAN';
    $verdictColor = $maliciousCount > 0 ? '#dc3545' : '#28a745';
    $timestamp = isset($data['timestamp']) ? htmlspecialchars($data['timestamp']) : date('Y-m-d H:i:s');
    
    $html = '<div class="report-section">
        <div class="executive-summary">
            <h2>📋 Malware Analysis Verdict</h2>
            <h3 style="color:' . $verdictColor . ';font-size:28px">' . $verdict . '</h3>
            <p>Detection Rate: ' . $maliciousCount . '/' . $totalEngines . ' security engines</p>
        </div>
    </div>
    <div class="report-section">
        <h2>📁 File Information</h2>
        <table class="detail-table">
            <tr><th>File/Hash</th><td><code>' . $fileName . '</code></td></tr>
            <tr><th>SHA-256</th><td><code class="hash-code">' . $fileHash . '</code></td></tr>
            <tr><th>Scan Date</th><td>' . $timestamp . '</td></tr>
        </table>
    </div>';
    
    $aiText = isset($data['ai_analysis']) ? nl2br(htmlspecialchars($data['ai_analysis'])) : 'AI analysis completed.';
    $html .= '<div class="report-section"><h2>🤖 AI Threat Intelligence</h2><div class="ai-box">' . $aiText . '</div></div>';
    
    return $html;
}

function generateComprehensiveReport() {
    $stats = array('attacks'=>0, 'defenses'=>0, 'malware'=>0, 'scans'=>0, 'critical'=>0);
    $severityBreakdown = array(); $recentAttacks = array(); $topTargets = array(); $monthlyTrend = array();
    
    try {
        $pdo = getDBConnection();
        $stats['attacks'] = $pdo->query("SELECT COUNT(*) FROM attack_logs")->fetchColumn();
        $stats['defenses'] = $pdo->query("SELECT COUNT(*) FROM defense_logs")->fetchColumn();
        $stats['malware'] = $pdo->query("SELECT COUNT(*) FROM malware_logs")->fetchColumn();
        $stats['scans'] = $pdo->query("SELECT COUNT(*) FROM scan_results")->fetchColumn();
        $stats['critical'] = $pdo->query("SELECT COUNT(*) FROM attack_logs WHERE severity='Critical' OR severity='High'")->fetchColumn();
        $severityBreakdown = $pdo->query("SELECT severity, COUNT(*) as c FROM attack_logs GROUP BY severity ORDER BY c DESC")->fetchAll();
        $recentAttacks = $pdo->query("SELECT * FROM attack_logs ORDER BY timestamp DESC LIMIT 20")->fetchAll();
        $topTargets = $pdo->query("SELECT target_url, COUNT(*) as c FROM attack_logs GROUP BY target_url ORDER BY c DESC LIMIT 5")->fetchAll();
        $monthlyTrend = $pdo->query("SELECT strftime('%Y-%m', timestamp) as m, COUNT(*) as c FROM attack_logs GROUP BY m ORDER BY m DESC LIMIT 6")->fetchAll();
    } catch(Exception $e) {}
    
    // AI Executive Summary
    $aiPrompt = "Generate a professional executive summary for a security audit report. Stats: {$stats['scans']} scans, {$stats['attacks']} attacks, {$stats['critical']} critical/high findings. Keep it professional and concise.";
    $aiSummary = callAI($aiPrompt, "You are a CISO writing an executive summary.");
    $aiSummary = (strpos($aiSummary, 'ERROR') === false) ? $aiSummary : 'Comprehensive security assessment completed.';
    
    $html = '<div class="report-section"><div class="executive-summary"><h2>📋 Executive Overview</h2><p>' . nl2br(htmlspecialchars($aiSummary)) . '</p></div></div>';
    
    // Stats Grid
    $html .= '<div class="report-section"><h2>📊 Key Metrics</h2><div class="stats-grid-print">';
    $metrics = array(
        array('label'=>'Total Scans','value'=>$stats['scans'],'icon'=>'🔍'),
        array('label'=>'Attacks','value'=>$stats['attacks'],'icon'=>'⚔️'),
        array('label'=>'Defense Audits','value'=>$stats['defenses'],'icon'=>'🛡️'),
        array('label'=>'Critical Findings','value'=>$stats['critical'],'icon'=>'🔥'),
        array('label'=>'Malware Analyses','value'=>$stats['malware'],'icon'=>'🐛')
    );
    foreach($metrics as $m) {
        $html .= '<div class="stat-card-print"><span class="stat-icon-print">' . $m['icon'] . '</span><span class="stat-value-print">' . $m['value'] . '</span><span class="stat-label-print">' . $m['label'] . '</span></div>';
    }
    $html .= '</div></div>';
    
    // Severity Breakdown
    if (!empty($severityBreakdown)) {
        $html .= '<div class="report-section"><h2>📈 Severity Distribution</h2><table class="detail-table"><tr><th>Severity</th><th>Count</th></tr>';
        foreach($severityBreakdown as $s) {
            $html .= '<tr><td><span class="badge badge-' . $s['severity'] . '">' . $s['severity'] . '</span></td><td>' . $s['c'] . '</td></tr>';
        }
        $html .= '</table></div>';
    }
    
    // Top Targets
    if (!empty($topTargets)) {
        $html .= '<div class="report-section"><h2>🎯 Most Tested Targets</h2><table class="detail-table"><tr><th>Target</th><th>Tests</th></tr>';
        foreach($topTargets as $t) {
            $html .= '<tr><td>' . htmlspecialchars($t['target_url']) . '</td><td>' . $t['c'] . '</td></tr>';
        }
        $html .= '</table></div>';
    }
    
    // Recent Activity
    if (!empty($recentAttacks)) {
        $html .= '<div class="report-section"><h2>🕐 Recent Activity</h2><table class="detail-table"><tr><th>Date</th><th>Type</th><th>Target</th><th>Severity</th></tr>';
        foreach(array_slice($recentAttacks,0,15) as $a) {
            $html .= '<tr><td>' . date('Y-m-d H:i', strtotime($a['timestamp'])) . '</td><td>' . htmlspecialchars($a['attack_type']) . '</td><td>' . htmlspecialchars(substr($a['target_url'],0,40)) . '</td><td><span class="badge badge-' . $a['severity'] . '">' . $a['severity'] . '</span></td></tr>';
        }
        $html .= '</table></div>';
    }
    
    return $html;
}

function generateQuickReport($url) {
    if (!preg_match('#^https?://#', $url)) $url = 'https://' . $url;
    
    $ch = curl_init($url);
    curl_setopt_array($ch, array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_HEADER => true,
        CURLOPT_USERAGENT => 'SecurityScanner/3.0'
    ));
    $resp = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    curl_close($ch);
    
    $headers = substr($resp, 0, $headerSize);
    
    $missingHeaders = array();
    $requiredHeaders = array('Content-Security-Policy','X-Frame-Options','X-Content-Type-Options','Strict-Transport-Security');
    foreach($requiredHeaders as $h) {
        if(stripos($headers, $h . ':') === false) $missingHeaders[] = $h;
    }
    
    $riskScore = 100 - (count($missingHeaders) * 15);
    $riskLevel = 'Low';
    if ($riskScore > 70) $riskLevel = 'Critical';
    elseif ($riskScore > 40) $riskLevel = 'High';
    elseif ($riskScore > 20) $riskLevel = 'Medium';
    
    $aiPrompt = "Quick security analysis of {$url}. HTTP {$httpCode}. Missing headers: " . implode(', ',$missingHeaders) . ". Give 3 brief recommendations.";
    $aiAnalysis = callAI($aiPrompt, "Security expert. Brief recommendations only.");
    
    $html = '<div class="report-section"><h2>⚡ Quick Security Report</h2><p>Target: ' . htmlspecialchars($url) . '</p><p>Risk Score: ' . $riskScore . '/100 (' . $riskLevel . ')</p></div>';
    $html .= '<div class="report-section"><h2>Missing Security Headers</h2><ul>';
    foreach($missingHeaders as $h) { $html .= '<li>' . $h . '</li>'; }
    $html .= '</ul></div>';
    $html .= '<div class="report-section"><h2>🤖 AI Recommendations</h2><p>' . nl2br(htmlspecialchars($aiAnalysis)) . '</p></div>';
    
    return $html;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>📊 Reports - <?php echo APP_NAME; ?></title>
    <style>
        *{margin:0;padding:0;box-sizing:border-box}
        body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#0a0a0f;color:#e4e4e7;min-height:100vh;background-image:radial-gradient(ellipse at top,rgba(168,85,247,0.05),transparent 50%)}
        .container{max-width:1400px;margin:0 auto;padding:20px}
        
        .navbar{background:#13131a;border:1px solid rgba(255,255,255,0.06);border-radius:12px;padding:15px 25px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:15px;margin-bottom:25px}
        .navbar h1{font-size:20px;background:linear-gradient(135deg,#a855f7,#6366f1);-webkit-background-clip:text;-webkit-text-fill-color:transparent}
        .nav-links{display:flex;gap:8px;flex-wrap:wrap}
        .nav-links a{color:#a1a1aa;text-decoration:none;padding:8px 14px;border-radius:8px;font-size:13px;transition:all 0.2s}
        .nav-links a:hover{background:rgba(255,255,255,0.05);color:#e4e4e7}
        .nav-links a.active{background:rgba(168,85,247,0.15);color:#a855f7}
        .nav-links a.logout{background:rgba(239,68,68,0.1);color:#ef4444}
        
        .card{background:rgba(255,255,255,0.02);border:1px solid rgba(255,255,255,0.06);border-radius:12px;padding:25px;margin-bottom:20px}
        .card h2{color:#a855f7;margin-bottom:15px}
        
        .grid-2{display:grid;grid-template-columns:1fr 1fr;gap:20px}
        .grid-3{display:grid;grid-template-columns:repeat(3,1fr);gap:15px}
        @media(max-width:768px){.grid-2,.grid-3{grid-template-columns:1fr}}
        
        .btn{padding:10px 20px;border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;transition:all 0.3s;margin:3px}
        .btn-primary{background:linear-gradient(135deg,#a855f7,#6366f1);color:#fff}
        .btn-primary:hover{transform:translateY(-1px);box-shadow:0 10px 30px rgba(168,85,247,0.3)}
        .btn-green{background:linear-gradient(135deg,#22c55e,#16a34a);color:#fff}
        .btn-outline{background:transparent;border:1px solid rgba(255,255,255,0.2);color:#e4e4e7}
        
        .form-group{margin-bottom:12px}
        .form-group input{width:100%;padding:10px;background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.1);border-radius:6px;color:#e4e4e7;font-size:13px}
        
        .report-container{background:rgba(255,255,255,0.02);border:1px solid rgba(255,255,255,0.06);border-radius:12px;padding:30px;margin-top:20px}
        .report-section{margin-bottom:30px;padding-bottom:20px;border-bottom:1px solid rgba(255,255,255,0.04)}
        .report-section h2{color:#a855f7;margin-bottom:15px;font-size:18px}
        
        .executive-summary{background:linear-gradient(135deg,rgba(168,85,247,0.1),rgba(99,102,241,0.1));border:1px solid rgba(168,85,247,0.2);border-radius:10px;padding:20px}
        .meta-row{display:flex;gap:20px;margin-top:12px;flex-wrap:wrap}
        .meta-item{font-size:12px;color:#a1a1aa}
        
        .risk-score-card{display:flex;align-items:center;gap:25px}
        .risk-circle{width:80px;height:80px;border-radius:50%;border:4px solid;display:flex;flex-direction:column;align-items:center;justify-content:center}
        .risk-number{font-size:28px;font-weight:700}
        .risk-label{font-size:11px;color:#a1a1aa}
        
        .detail-table{width:100%;border-collapse:collapse}
        .detail-table th,.detail-table td{padding:10px;border:1px solid rgba(255,255,255,0.05);font-size:13px;text-align:left}
        .detail-table th{background:rgba(255,255,255,0.03);color:#a1a1aa;font-weight:600;width:200px}
        
        .badge{display:inline-block;padding:3px 10px;border-radius:12px;font-size:10px;font-weight:600;text-transform:uppercase}
        .badge-Critical{background:rgba(239,68,68,0.2);color:#fca5a5}
        .badge-High{background:rgba(245,158,11,0.2);color:#fcd34d}
        .badge-Medium{background:rgba(59,130,246,0.2);color:#93c5fd}
        .badge-Low{background:rgba(34,197,94,0.2);color:#86efac}
        
        .payload-code,.hash-code{background:rgba(0,0,0,0.3);padding:4px 8px;border-radius:4px;font-family:monospace;font-size:12px;color:#22c55e;word-break:break-all}
        
        .impact-box{background:rgba(239,68,68,0.05);border-left:3px solid #ef4444;padding:15px;border-radius:0 8px 8px 0}
        .remediation-box{background:rgba(34,197,94,0.05);border-left:3px solid #22c55e;padding:15px;border-radius:0 8px 8px 0}
        .ai-box{background:linear-gradient(135deg,rgba(168,85,247,0.1),rgba(99,102,241,0.1));border:1px solid rgba(168,85,247,0.15);padding:15px;border-radius:8px;line-height:1.6;font-size:13px}
        
        .finding-row{padding:10px;border-left:3px solid;margin:8px 0;background:rgba(255,255,255,0.01);border-radius:0 6px 6px 0;display:flex;gap:15px;align-items:center}
        .finding-row.Critical{border-color:#ef4444}.finding-row.High{border-color:#f59e0b}
        .finding-row.Medium{border-color:#3b82f6}.finding-row.Low{border-color:#22c55e}
        .finding-type{font-weight:600;font-size:12px;min-width:180px}
        .finding-detail{font-size:12px;color:#a1a1aa}
        
        .severity-grid{display:flex;gap:10px;flex-wrap:wrap}
        .sev-card{text-align:center;padding:15px;border-radius:8px;border:1px solid;min-width:80px}
        .sev-Critical{border-color:#ef4444;background:rgba(239,68,68,0.05)}.sev-High{border-color:#f59e0b;background:rgba(245,158,11,0.05)}
        .sev-Medium{border-color:#3b82f6;background:rgba(59,130,246,0.05)}.sev-Low{border-color:#22c55e;background:rgba(34,197,94,0.05)}
        .sev-count{font-size:24px;font-weight:700;display:block}
        .sev-label{font-size:10px;color:#a1a1aa;text-transform:uppercase}
        
        .rec-list{list-style:none}
        .rec-list li{padding:8px 0;border-bottom:1px solid rgba(255,255,255,0.03);font-size:13px}
        .rec-list li:before{content:'💡 '}
        
        .stats-grid-print{display:flex;gap:15px;flex-wrap:wrap}
        .stat-card-print{text-align:center;padding:20px;background:rgba(255,255,255,0.02);border:1px solid rgba(255,255,255,0.06);border-radius:10px;min-width:120px}
        .stat-icon-print{font-size:24px;display:block;margin-bottom:8px}
        .stat-value-print{font-size:28px;font-weight:700;display:block;color:#a855f7}
        .stat-label-print{font-size:11px;color:#a1a1aa}
        
        .tab-nav{display:flex;gap:4px;margin-bottom:20px}
        .tab-btn{padding:10px 20px;border:1px solid rgba(255,255,255,0.1);border-radius:8px;background:transparent;color:#a1a1aa;cursor:pointer;font-size:13px}
        .tab-btn.active{background:rgba(168,85,247,0.15);border-color:#a855f7;color:#a855f7}
        
        .btn-group{display:flex;gap:10px;flex-wrap:wrap;margin-top:20px}
        
        @media print{
            .navbar,.btn-group,.tab-nav,.card:first-of-type,.nav-links,form{display:none!important}
            .report-container{margin:0;padding:20px;border:none}
            body{background:#fff;color:#000;padding:0}
        }
    </style>
</head>
<body>
    <div class="container">
        <nav class="navbar">
            <h1>📊 Security Reports</h1>
            <div class="nav-links">
                <a href="index.php">Dashboard</a>
                <a href="attack.php">Attack</a>
                <a href="defense.php">Defense</a>
                <a href="malware_analysis.php">Malware</a>
                <a href="reports.php" class="active">Reports</a>
                <a href="index.php?logout=1" class="logout">Logout</a>
            </div>
        </nav>
        
        <div class="tab-nav">
            <button class="tab-btn <?php echo $activeTab=='generate'?'active':''; ?>" onclick="showTab('generate')">📝 Generate</button>
            <button class="tab-btn <?php echo $activeTab=='view'?'active':''; ?>" onclick="showTab('view')">📄 View Report</button>
            <button class="tab-btn" onclick="showTab('history')">📜 History</button>
        </div>
        
        <div id="tab-generate" style="display:<?php echo $activeTab=='generate'?'block':'none'; ?>">
            <div class="grid-2">
                <div class="card">
                    <h2>📊 Comprehensive Audit Report</h2>
                    <p style="color:#a1a1aa;margin-bottom:15px">Generate a full security audit report with all historical data, trends, and AI analysis.</p>
                    <form method="POST">
                        <button type="submit" name="generate_comprehensive" class="btn btn-primary">📊 Generate Full Report</button>
                    </form>
                </div>
                
                <div class="card">
                    <h2>⚡ Quick Security Report</h2>
                    <p style="color:#a1a1aa;margin-bottom:15px">Generate a fast security report for any URL.</p>
                    <form method="POST">
                        <div class="form-group"><input type="text" name="quick_target" placeholder="https://example.com" required></div>
                        <button type="submit" name="generate_quick" class="btn btn-green">⚡ Quick Report</button>
                    </form>
                </div>
            </div>
            
            <div class="card" style="margin-top:20px">
                <h2>📈 Platform Statistics</h2>
                <div class="grid-3">
                    <div class="stat-card-print"><span class="stat-icon-print">🔍</span><span class="stat-value-print"><?php echo number_format($totalScans); ?></span><span class="stat-label-print">Total Scans</span></div>
                    <div class="stat-card-print"><span class="stat-icon-print">⚔️</span><span class="stat-value-print"><?php echo number_format($totalAttacks); ?></span><span class="stat-label-print">Attacks</span></div>
                    <div class="stat-card-print"><span class="stat-icon-print">🔥</span><span class="stat-value-print"><?php echo number_format($criticalVulns); ?></span><span class="stat-label-print">Critical Findings</span></div>
                </div>
            </div>
        </div>
        
        <div id="tab-view" style="display:<?php echo $activeTab=='view'?'block':'none'; ?>">
            <?php if($reportHtml): ?>
            <div class="report-container">
                <h1 style="text-align:center;margin-bottom:30px;color:#a855f7"><?php echo $reportTitle; ?></h1>
                <?php echo $reportHtml; ?>
                <div class="btn-group">
                    <button onclick="window.print()" class="btn btn-primary">🖨️ Print / Save PDF</button>
                    <button onclick="exportReport()" class="btn btn-outline">📥 Download HTML</button>
                </div>
            </div>
            <?php else: ?>
            <div class="card" style="text-align:center;padding:50px">
                <h3 style="color:#a1a1aa">No report generated yet</h3>
                <p style="color:#a1a1aa">Generate a report from the options above, or run a scan from Attack/Defense mode.</p>
            </div>
            <?php endif; ?>
        </div>
        
        <div id="tab-history" style="display:none">
            <div class="card">
                <h2>📜 Recent Reports</h2>
                <?php if(!empty($recentReports)): ?>
                <table class="detail-table">
                    <tr><th>Date</th><th>Target</th><th>Type</th><th>Vulnerabilities</th><th>AI Provider</th></tr>
                    <?php foreach($recentReports as $r): ?>
                    <?php 
                        $vulnCount = isset($r['vulnerabilities_found']) ? $r['vulnerabilities_found'] : 0;
                        $badgeClass = $vulnCount > 0 ? 'High' : 'Low';
                    ?>
                    <tr>
                        <td><?php echo isset($r['scan_date']) ? date('Y-m-d', strtotime($r['scan_date'])) : 'N/A'; ?></td>
                        <td><?php echo isset($r['target_url']) ? htmlspecialchars(substr($r['target_url'],0,40)) : 'N/A'; ?></td>
                        <td><?php echo isset($r['scan_type']) ? htmlspecialchars($r['scan_type']) : 'N/A'; ?></td>
                        <td><span class="badge badge-<?php echo $badgeClass; ?>"><?php echo $vulnCount; ?></span></td>
                        <td><?php echo isset($r['ai_provider']) ? strtoupper($r['ai_provider']) : 'AI'; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </table>
                <?php else: ?>
                <p style="color:#a1a1aa;text-align:center;padding:30px">No reports generated yet.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <script>
    function showTab(name) {
        var tabs = document.querySelectorAll('[id^="tab-"]');
        for (var i = 0; i < tabs.length; i++) {
            tabs[i].style.display = 'none';
        }
        document.getElementById('tab-' + name).style.display = 'block';
        
        var buttons = document.querySelectorAll('.tab-btn');
        for (var i = 0; i < buttons.length; i++) {
            buttons[i].classList.remove('active');
        }
        if (event && event.target) {
            event.target.classList.add('active');
        }
    }
    
    function exportReport() {
        var report = document.querySelector('.report-container').cloneNode(true);
        var buttons = report.querySelector('.btn-group');
        if (buttons) buttons.remove();
        
        var html = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Security Report</title>';
        html += '<style>body{font-family:Arial;margin:40px;color:#333}.report-section{margin-bottom:20px;padding-bottom:15px;border-bottom:1px solid #ddd}h2{color:#7c3aed}table{width:100%;border-collapse:collapse}th,td{border:1px solid #ddd;padding:8px;text-align:left}th{background:#f5f5f5}.badge{padding:3px 8px;border-radius:12px;font-size:11px;font-weight:bold}</style>';
        html += '</head><body>' + report.innerHTML + '</body></html>';
        
        var blob = new Blob([html], {type: 'text/html'});
        var url = URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = url;
        a.download = 'security_report_' + new Date().toISOString().split('T')[0] + '.html';
        a.click();
        URL.revokeObjectURL(url);
    }
    </script>
</body>
</html>