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

$analysisResult = null;
$urlAnalysisResult = null;
$message = '';
$activeTab = isset($_POST['tab']) ? $_POST['tab'] : 'file';

// Create uploads directory
$uploadDir = __DIR__ . '/uploads';
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// ============================================
// FILE UPLOAD ANALYSIS
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file_to_analyze']) && $_FILES['file_to_analyze']['error'] === UPLOAD_ERR_OK) {
    $activeTab = 'file';
    $fileName = basename($_FILES['file_to_analyze']['name']);
    $fileSize = $_FILES['file_to_analyze']['size'];
    $filePath = $uploadDir . time() . '_' . $fileName;
    $fileHash = hash_file('sha256', $_FILES['file_to_analyze']['tmp_name']);
    $fileMd5 = hash_file('md5', $_FILES['file_to_analyze']['tmp_name']);
    $fileSha1 = hash_file('sha1', $_FILES['file_to_analyze']['tmp_name']);
    
    if (move_uploaded_file($_FILES['file_to_analyze']['tmp_name'], $filePath)) {
        // Check cache first
        $cachedResult = getAPICache('vt_file_' . $fileHash, 'virustotal');
        
        if ($cachedResult) {
            $vtReport = $cachedResult;
        } else {
            // Upload to VirusTotal
            $vtReport = uploadAndScanVirusTotal($filePath);
            if ($vtReport && !isset($vtReport['error'])) {
                setAPICache('vt_file_' . $fileHash, 'virustotal', $vtReport, 86400);
            }
        }
        
        $maliciousCount = 0;
        $suspiciousCount = 0;
        $harmlessCount = 0;
        $totalEngines = 0;
        $scanResults = [];
        $threatLabels = [];
        
        if (isset($vtReport['data']['attributes'])) {
            $stats = $vtReport['data']['attributes']['last_analysis_stats'] ?? $vtReport['data']['attributes']['stats'] ?? [];
            $maliciousCount = $stats['malicious'] ?? 0;
            $suspiciousCount = $stats['suspicious'] ?? 0;
            $harmlessCount = $stats['harmless'] ?? 0;
            $undetectedCount = $stats['undetected'] ?? 0;
            $totalEngines = $maliciousCount + $suspiciousCount + $harmlessCount + $undetectedCount;
            
            $scanResults = $vtReport['data']['attributes']['last_analysis_results'] ?? $vtReport['data']['attributes']['results'] ?? [];
            
            // Extract threat labels
            if (isset($vtReport['data']['attributes']['popular_threat_classification']['suggested_threat_label'])) {
                $threatLabels[] = $vtReport['data']['attributes']['popular_threat_classification']['suggested_threat_label'];
            }
            if (isset($vtReport['data']['attributes']['popular_threat_classification']['popular_threat_name'])) {
                foreach ($vtReport['data']['attributes']['popular_threat_classification']['popular_threat_name'] as $threat) {
                    $threatLabels[] = $threat['value'];
                }
            }
        }
        
        // AI Analysis
        $aiPrompt = "Analyze this file for malware:\n";
        $aiPrompt .= "Filename: {$fileName}\n";
        $aiPrompt .= "Size: " . formatBytes($fileSize) . "\n";
        $aiPrompt .= "SHA256: {$fileHash}\n";
        $aiPrompt .= "VirusTotal: {$maliciousCount}/{$totalEngines} malicious\n";
        if (!empty($threatLabels)) {
            $aiPrompt .= "Threats: " . implode(', ', array_slice($threatLabels, 0, 5)) . "\n";
        }
        $aiPrompt .= "Provide: 1) Threat Level, 2) Likely Behavior, 3) Recommendations. Be specific.";
        
        $aiAnalysis = callAI($aiPrompt, "You are a senior malware analyst. Provide technical analysis.");
        
        $analysisResult = [
            'file_name' => $fileName,
            'file_hash' => $fileHash,
            'file_md5' => $fileMd5,
            'file_sha1' => $fileSha1,
            'file_size' => $fileSize,
            'file_type' => mime_content_type($filePath),
            'malicious_count' => $maliciousCount,
            'suspicious_count' => $suspiciousCount,
            'harmless_count' => $harmlessCount,
            'total_engines' => $totalEngines,
            'scan_results' => $scanResults,
            'threat_labels' => $threatLabels,
            'ai_analysis' => $aiAnalysis,
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        logMalwareAnalysis($fileHash, $fileName, json_encode($analysisResult), $aiAnalysis, $maliciousCount, $totalEngines);
        $message = $maliciousCount > 0 ? "⚠️ MALICIOUS! {$maliciousCount}/{$totalEngines} engines detected threats!" : "✅ Analysis complete. File appears clean.";
        
        // Clean up
        @unlink($filePath);
    } else {
        $message = "❌ File upload failed!";
    }
}

// ============================================
// HASH LOOKUP
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['lookup_hash']) && !empty($_POST['file_hash'])) {
    $activeTab = 'hash';
    $fileHash = trim($_POST['file_hash']);
    
    if (strlen($fileHash) >= 32) {
        $vtReport = getVirusTotalFileReport($fileHash);
        
        $maliciousCount = $vtReport['malicious'] ?? 0;
        $totalEngines = $vtReport['total'] ?? 0;
        $threatNames = $vtReport['threat_names'] ?? [];
        
        $aiPrompt = "Hash lookup: {$fileHash}. VT Detection: {$maliciousCount}/{$totalEngines}. Threats: " . implode(', ', array_slice($threatNames, 0, 5)) . ". Provide analysis.";
        $aiAnalysis = callAI($aiPrompt, "Malware analyst. Brief analysis.");
        
        $analysisResult = [
            'file_hash' => $fileHash,
            'malicious_count' => $maliciousCount,
            'suspicious_count' => $vtReport['suspicious'] ?? 0,
            'harmless_count' => $vtReport['harmless'] ?? 0,
            'total_engines' => $totalEngines,
            'scan_results' => [],
            'threat_labels' => $threatNames,
            'threat_label' => $vtReport['threat_label'] ?? 'Unknown',
            'file_type' => $vtReport['file_type'] ?? 'Unknown',
            'file_size' => $vtReport['file_size'] ?? 0,
            'first_seen' => $vtReport['first_seen'] ?? null,
            'ai_analysis' => $aiAnalysis,
            'timestamp' => date('Y-m-d H:i:s')
        ];
        
        logMalwareAnalysis($fileHash, 'Hash Lookup', json_encode($analysisResult), $aiAnalysis, $maliciousCount, $totalEngines);
        $message = $maliciousCount > 0 ? "⚠️ MALICIOUS! {$maliciousCount}/{$totalEngines} detections!" : "✅ Hash not flagged as malicious.";
    }
}

// ============================================
// URL ANALYSIS
// ============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['analyze_url']) && !empty($_POST['scan_url'])) {
    $activeTab = 'url';
    $scanUrl = $_POST['scan_url'];
    if (!preg_match('#^https?://#', $scanUrl)) $scanUrl = 'https://' . $scanUrl;
    
    // Get URL scan from VirusTotal
    $urlId = base64_encode($scanUrl);
    $urlId = rtrim(str_replace(['+', '/', '='], ['-', '_', ''], $urlId), '=');
    
    $ch = curl_init(VIRUSTOTAL_URL . '/urls/' . $urlId);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => ['x-apikey: ' . VIRUSTOTAL_API_KEY],
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    $urlMalicious = 0;
    $urlTotal = 0;
    $urlResults = [];
    $urlCategories = [];
    
    if ($httpCode == 200) {
        $urlData = json_decode($response, true);
        $urlStats = $urlData['data']['attributes']['last_analysis_stats'] ?? [];
        $urlMalicious = $urlStats['malicious'] ?? 0;
        $urlTotal = array_sum($urlStats);
        $urlResults = $urlData['data']['attributes']['last_analysis_results'] ?? [];
        $urlCategories = $urlData['data']['attributes']['categories'] ?? [];
    }
    
    // AI URL Analysis
    $aiPrompt = "Analyze URL: {$scanUrl}\nVirusTotal: {$urlMalicious}/{$urlTotal} malicious\nCategories: " . json_encode($urlCategories) . "\nProvide security assessment.";
    $urlAiAnalysis = callAI($aiPrompt, "URL security analyst. Brief assessment.");
    
    $urlAnalysisResult = [
        'url' => $scanUrl,
        'malicious_count' => $urlMalicious,
        'total_engines' => $urlTotal,
        'scan_results' => $urlResults,
        'categories' => $urlCategories,
        'ai_analysis' => $urlAiAnalysis,
        'timestamp' => date('Y-m-d H:i:s')
    ];
    
    $message = $urlMalicious > 0 ? "⚠️ URL flagged by {$urlMalicious} engines!" : "✅ URL appears safe.";
}

// Helper function
function uploadAndScanVirusTotal($filePath) {
    if (!VIRUSTOTAL_ENABLED) return ['error' => 'VirusTotal disabled'];
    
    $ch = curl_init(VIRUSTOTAL_URL . '/files');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ['x-apikey: ' . VIRUSTOTAL_API_KEY],
        CURLOPT_POSTFIELDS => ['file' => new CURLFile($filePath)],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode == 200) {
        $data = json_decode($response, true);
        $analysisId = $data['data']['id'] ?? '';
        
        if ($analysisId) {
            sleep(3);
            return getVirusTotalAnalysis($analysisId);
        }
    }
    
    return ['error' => "Upload failed: HTTP {$httpCode}"];
}

function formatBytes($bytes) {
    if ($bytes >= 1073741824) return number_format($bytes/1073741824,2).' GB';
    if ($bytes >= 1048576) return number_format($bytes/1048576,2).' MB';
    if ($bytes >= 1024) return number_format($bytes/1024,2).' KB';
    return $bytes.' bytes';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🐛 Malware Analysis - <?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(239,68,68,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,#ef4444,#f97316);-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(239,68,68,0.15);color:#ef4444}
        
        .tab-nav{display:flex;gap:4px;margin-bottom:20px;background:rgba(255,255,255,0.02);border:1px solid rgba(255,255,255,0.06);border-radius:10px;padding:4px}
        .tab-btn{padding:10px 20px;border:none;border-radius:8px;background:transparent;color:#a1a1aa;cursor:pointer;font-size:13px;font-weight:500;transition:all 0.2s}
        .tab-btn.active{background:rgba(239,68,68,0.15);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 h3{color:#ef4444;margin-bottom:15px;padding-bottom:10px;border-bottom:1px solid rgba(255,255,255,0.06)}
        
        .form-row{display:grid;grid-template-columns:1fr 1fr;gap:15px;margin-bottom:15px}
        @media(max-width:768px){.form-row{grid-template-columns:1fr}}
        
        .form-group{margin-bottom:15px}
        .form-group label{display:block;margin-bottom:5px;color:#a1a1aa;font-size:11px;text-transform:uppercase;letter-spacing:0.5px}
        .form-group input{width:100%;padding:12px 16px;background:rgba(0,0,0,0.3);border:1px solid rgba(255,255,255,0.1);border-radius:8px;color:#e4e4e7;font-size:14px}
        .form-group input:focus{outline:none;border-color:#ef4444}
        .form-group input[type="file"]{padding:10px;color:#a1a1aa}
        
        .btn{padding:12px 24px;border:none;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s}
        .btn-primary{background:linear-gradient(135deg,#ef4444,#dc2626);color:#fff;width:100%}
        .btn-primary:hover{box-shadow:0 0 30px rgba(239,68,68,0.4);transform:translateY(-1px)}
        .btn-secondary{background:rgba(255,255,255,0.1);color:#e4e4e7}
        
        .alert{padding:14px 18px;border-radius:8px;margin:10px 0;font-size:13px;font-weight:500}
        .alert-success{background:rgba(34,197,94,0.1);border:1px solid rgba(34,197,94,0.3);color:#86efac}
        .alert-danger{background:rgba(239,68,68,0.1);border:1px solid rgba(239,68,68,0.3);color:#fca5a5}
        .alert-warning{background:rgba(234,179,8,0.1);border:1px solid rgba(234,179,8,0.3);color:#fde047}
        
        /* Stats Grid */
        .stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;margin:20px 0}
        .stat-card{background:rgba(0,0,0,0.2);border:1px solid rgba(255,255,255,0.06);border-radius:10px;padding:15px;text-align:center}
        .stat-card.malicious{background:rgba(239,68,68,0.1);border-color:rgba(239,68,68,0.3)}
        .stat-card.suspicious{background:rgba(234,179,8,0.1);border-color:rgba(234,179,8,0.3)}
        .stat-card.clean{background:rgba(34,197,94,0.1);border-color:rgba(34,197,94,0.3)}
        .stat-value{font-size:28px;font-weight:700;display:block}
        .stat-card.malicious .stat-value{color:#ef4444}
        .stat-card.suspicious .stat-value{color:#eab308}
        .stat-card.clean .stat-value{color:#22c55e}
        .stat-label{font-size:10px;color:#a1a1aa;text-transform:uppercase;letter-spacing:0.5px;margin-top:4px;display:block}
        
        /* Progress Bar Style */
        .detection-bar{height:12px;background:rgba(255,255,255,0.05);border-radius:6px;overflow:hidden;margin:10px 0}
        .detection-fill{height:100%;border-radius:6px;transition:width 0.5s}
        .detection-fill.malicious{background:#ef4444}
        .detection-fill.suspicious{background:#eab308}
        .detection-fill.clean{background:#22c55e}
        
        /* Verdict Banner */
        .verdict-banner{padding:20px;border-radius:10px;text-align:center;margin:20px 0;animation:slideIn 0.5s}
        @keyframes slideIn{from{opacity:0;transform:translateY(-10px)}to{opacity:1;transform:translateY(0)}}
        .verdict-malicious{background:rgba(239,68,68,0.1);border:2px solid #ef4444}
        .verdict-malicious h2{color:#ef4444;font-size:28px}
        .verdict-clean{background:rgba(34,197,94,0.1);border:2px solid #22c55e}
        .verdict-clean h2{color:#22c55e;font-size:28px}
        .verdict-suspicious{background:rgba(234,179,8,0.1);border:2px solid #eab308}
        .verdict-suspicious h2{color:#eab308;font-size:28px}
        
        /* Table */
        .data-table{width:100%;border-collapse:collapse;font-size:12px;margin:15px 0}
        .data-table th{background:rgba(255,255,255,0.03);padding:10px;text-align:left;color:#a1a1aa;font-weight:600;font-size:11px;text-transform:uppercase}
        .data-table td{padding:8px 10px;border-bottom:1px solid rgba(255,255,255,0.03)}
        .data-table tr:hover{background:rgba(255,255,255,0.02)}
        .data-table .malicious-row{background:rgba(239,68,68,0.05)}
        .data-table .malicious-row:hover{background:rgba(239,68,68,0.1)}
        
        .badge{display:inline-block;padding:2px 8px;border-radius:10px;font-size:10px;font-weight:600;text-transform:uppercase}
        .badge-malicious{background:rgba(239,68,68,0.2);color:#fca5a5}
        .badge-suspicious{background:rgba(234,179,8,0.2);color:#fde047}
        .badge-clean{background:rgba(34,197,94,0.2);color:#86efac}
        
        .hash-box{background:rgba(0,0,0,0.3);border:1px solid rgba(255,255,255,0.1);padding:8px 12px;border-radius:6px;font-family:'Courier New',monospace;font-size:11px;color:#22c55e;word-break:break-all;margin:5px 0}
        
        .ai-box{background:linear-gradient(135deg,rgba(59,130,246,0.1),rgba(168,85,247,0.1));border:1px solid rgba(59,130,246,0.2);border-radius:10px;padding:15px;margin-top:15px;line-height:1.6;font-size:13px;color:#93c5fd}
        
        .threat-tags{display:flex;flex-wrap:wrap;gap:6px;margin:10px 0}
        .threat-tag{background:rgba(239,68,68,0.15);border:1px solid rgba(239,68,68,0.3);color:#fca5a5;padding:4px 10px;border-radius:15px;font-size:11px}
        
        .file-info{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px;margin:15px 0}
        .file-info-item{background:rgba(0,0,0,0.2);padding:10px;border-radius:6px}
        .file-info-item strong{display:block;color:#a1a1aa;font-size:10px;text-transform:uppercase;margin-bottom:4px}
        .file-info-item span{color:#e4e4e7;font-size:13px}
    </style>
</head>
<body>
    <div class="container">
        <nav class="navbar">
            <h1>🐛 Malware & URL Analysis</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" class="active">Malware</a>
                <a href="cupp.php">CUPP</a>
                <a href="reports.php">Reports</a>
                <a href="index.php?logout=1" style="background:rgba(239,68,68,0.1);color:#ef4444">Logout</a>
            </div>
        </nav>
        
        <?php if($message): ?>
        <div class="alert <?php echo strpos($message,'⚠️')!==false?'alert-danger':(strpos($message,'✅')!==false?'alert-success':'alert-warning'); ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>
        
        <!-- Tab Navigation -->
        <div class="tab-nav">
            <form method="POST" style="display:inline"><input type="hidden" name="tab" value="file"><button type="submit" class="tab-btn <?php echo $activeTab=='file'?'active':''; ?>">📁 File Analysis</button></form>
            <form method="POST" style="display:inline"><input type="hidden" name="tab" value="hash"><button type="submit" class="tab-btn <?php echo $activeTab=='hash'?'active':''; ?>">🔎 Hash Lookup</button></form>
            <form method="POST" style="display:inline"><input type="hidden" name="tab" value="url"><button type="submit" class="tab-btn <?php echo $activeTab=='url'?'active':''; ?>">🌐 URL Analysis</button></form>
        </div>
        
        <!-- File Upload -->
        <?php if($activeTab == 'file'): ?>
        <div class="card">
            <h3>📁 Upload File for Analysis</h3>
            <p style="color:#a1a1aa;font-size:13px;margin-bottom:15px">Upload any file to scan with VirusTotal (70+ antivirus engines) and AI analysis</p>
            <form method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Select File (Max 32MB)</label>
                    <input type="file" name="file_to_analyze" required>
                </div>
                <button type="submit" class="btn btn-primary">🔍 Scan with VirusTotal + AI</button>
            </form>
        </div>
        <?php endif; ?>
        
        <!-- Hash Lookup -->
        <?php if($activeTab == 'hash'): ?>
        <div class="card">
            <h3>🔎 Lookup File Hash</h3>
            <p style="color:#a1a1aa;font-size:13px;margin-bottom:15px">Search VirusTotal database for existing scan results by hash</p>
            <form method="POST">
                <div class="form-group">
                    <label>SHA-256 / MD5 / SHA-1 Hash</label>
                    <input type="text" name="file_hash" placeholder="e.g., 44d88612fea8a8f36de82e1278abb02f..." required>
                </div>
                <button type="submit" name="lookup_hash" class="btn btn-primary">🔍 Lookup Hash</button>
            </form>
        </div>
        <?php endif; ?>
        
        <!-- URL Analysis -->
        <?php if($activeTab == 'url'): ?>
        <div class="card">
            <h3>🌐 URL Security Analysis</h3>
            <p style="color:#a1a1aa;font-size:13px;margin-bottom:15px">Check if a URL is malicious, phishing, or contains malware</p>
            <form method="POST">
                <div class="form-group">
                    <label>URL to Analyze</label>
                    <input type="url" name="scan_url" placeholder="https://example.com" required>
                </div>
                <button type="submit" name="analyze_url" class="btn btn-primary">🌐 Analyze URL</button>
            </form>
        </div>
        <?php endif; ?>
        
        <!-- ============================================ -->
        <!-- FILE ANALYSIS RESULTS -->
        <!-- ============================================ -->
        <?php if($analysisResult && ($activeTab == 'file' || $activeTab == 'hash')): ?>
        
        <!-- Verdict Banner -->
        <?php 
            $malCount = $analysisResult['malicious_count'] ?? 0;
            $suspCount = $analysisResult['suspicious_count'] ?? 0;
            $totalEng = $analysisResult['total_engines'] ?? 0;
            $verdictClass = $malCount > 0 ? 'verdict-malicious' : ($suspCount > 0 ? 'verdict-suspicious' : 'verdict-clean');
            $verdictText = $malCount > 0 ? '⚠️ MALICIOUS DETECTED' : ($suspCount > 0 ? '⚠️ SUSPICIOUS' : '✅ CLEAN');
        ?>
        <div class="verdict-banner <?php echo $verdictClass; ?>">
            <h2><?php echo $verdictText; ?></h2>
            <p style="color:#a1a1aa;margin-top:5px">
                <?php echo $malCount; ?>/<?php echo $totalEng; ?> security engines detected threats
                <?php if(isset($analysisResult['threat_label'])): ?>
                | Threat: <?php echo htmlspecialchars($analysisResult['threat_label']); ?>
                <?php endif; ?>
            </p>
        </div>
        
        <!-- File Info -->
        <?php if(isset($analysisResult['file_name'])): ?>
        <div class="card">
            <h3>📄 File Information</h3>
            <div class="file-info">
                <div class="file-info-item"><strong>Filename</strong><span><?php echo htmlspecialchars($analysisResult['file_name']); ?></span></div>
                <div class="file-info-item"><strong>Size</strong><span><?php echo formatBytes($analysisResult['file_size'] ?? 0); ?></span></div>
                <div class="file-info-item"><strong>Type</strong><span><?php echo htmlspecialchars($analysisResult['file_type'] ?? 'Unknown'); ?></span></div>
                <div class="file-info-item"><strong>Scan Date</strong><span><?php echo $analysisResult['timestamp']; ?></span></div>
            </div>
            <div class="hash-box"><strong>SHA256:</strong> <?php echo htmlspecialchars($analysisResult['file_hash']); ?></div>
            <?php if(isset($analysisResult['file_md5'])): ?>
            <div class="hash-box"><strong>MD5:</strong> <?php echo htmlspecialchars($analysisResult['file_md5']); ?></div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
        <!-- Detection Stats -->
        <div class="card">
            <h3>📊 Detection Statistics</h3>
            <div class="stats-grid">
                <div class="stat-card malicious">
                    <span class="stat-value"><?php echo $malCount; ?></span>
                    <span class="stat-label">Malicious</span>
                </div>
                <div class="stat-card suspicious">
                    <span class="stat-value"><?php echo $suspCount; ?></span>
                    <span class="stat-label">Suspicious</span>
                </div>
                <div class="stat-card clean">
                    <span class="stat-value"><?php echo $analysisResult['harmless_count'] ?? 0; ?></span>
                    <span class="stat-label">Clean</span>
                </div>
                <div class="stat-card">
                    <span class="stat-value" style="color:#a1a1aa"><?php echo $totalEng; ?></span>
                    <span class="stat-label">Total Engines</span>
                </div>
            </div>
            
            <!-- Detection Bar -->
            <?php if($totalEng > 0): ?>
            <div class="detection-bar">
                <?php 
                    $malPct = ($malCount/$totalEng)*100;
                    $suspPct = ($suspCount/$totalEng)*100;
                    $cleanPct = (($analysisResult['harmless_count']??0)/$totalEng)*100;
                ?>
                <div style="display:flex;height:100%">
                    <?php if($malPct > 0): ?><div class="detection-fill malicious" style="width:<?php echo $malPct; ?>%"></div><?php endif; ?>
                    <?php if($suspPct > 0): ?><div class="detection-fill suspicious" style="width:<?php echo $suspPct; ?>%"></div><?php endif; ?>
                    <?php if($cleanPct > 0): ?><div class="detection-fill clean" style="width:<?php echo $cleanPct; ?>%"></div><?php endif; ?>
                </div>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:10px;color:#a1a1aa;margin-top:5px">
                <span>🔴 <?php echo round($malPct,1); ?>% Malicious</span>
                <span>🟡 <?php echo round($suspPct,1); ?>% Suspicious</span>
                <span>🟢 <?php echo round($cleanPct,1); ?>% Clean</span>
            </div>
            <?php endif; ?>
            
            <!-- Threat Labels -->
            <?php if(!empty($analysisResult['threat_labels'])): ?>
            <div class="threat-tags" style="margin-top:15px">
                <strong style="color:#a1a1aa;font-size:11px">Threats: </strong>
                <?php foreach(array_unique(array_slice($analysisResult['threat_labels'],0,10)) as $threat): ?>
                <span class="threat-tag"><?php echo htmlspecialchars(substr($threat,0,50)); ?></span>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- Engine Results Table -->
        <?php if(!empty($analysisResult['scan_results'])): ?>
        <div class="card">
            <h3>🔬 Engine Scan Details</h3>
            <div style="max-height:400px;overflow-y:auto">
                <table class="data-table">
                    <thead><tr><th>Engine</th><th>Category</th><th>Result</th></tr></thead>
                    <tbody>
                    <?php 
                    $count = 0;
                    foreach($analysisResult['scan_results'] as $engine => $result):
                        if(isset($result['category']) && $result['category'] != 'harmless' && $result['category'] != 'undetected'):
                        $count++;
                    ?>
                    <tr class="<?php echo $result['category']=='malicious'?'malicious-row':''; ?>">
                        <td><?php echo htmlspecialchars($engine); ?></td>
                        <td><span class="badge badge-<?php echo $result['category']=='malicious'?'malicious':'suspicious'; ?>"><?php echo $result['category']; ?></span></td>
                        <td style="color:#fca5a5"><?php echo htmlspecialchars($result['result'] ?? 'N/A'); ?></td>
                    </tr>
                    <?php endif; endforeach; ?>
                    <?php if($count == 0): ?>
                    <tr><td colspan="3" style="text-align:center;color:#a1a1aa;padding:20px">No malicious detections</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- AI Analysis -->
        <?php if(!empty($analysisResult['ai_analysis'])): ?>
        <div class="card">
            <h3>🤖 AI Threat Analysis</h3>
            <div class="ai-box"><?php echo nl2br(htmlspecialchars($analysisResult['ai_analysis'])); ?></div>
        </div>
        <?php endif; ?>
        
        <?php endif; ?>
        
        <!-- ============================================ -->
        <!-- URL ANALYSIS RESULTS -->
        <!-- ============================================ -->
        <?php if($urlAnalysisResult && $activeTab == 'url'): ?>
        
        <?php 
            $urlMal = $urlAnalysisResult['malicious_count'] ?? 0;
            $urlTotal = $urlAnalysisResult['total_engines'] ?? 0;
            $urlVerdict = $urlMal > 0 ? 'verdict-malicious' : 'verdict-clean';
            $urlVerdictText = $urlMal > 0 ? '⚠️ MALICIOUS URL' : '✅ SAFE URL';
        ?>
        <div class="verdict-banner <?php echo $urlVerdict; ?>">
            <h2><?php echo $urlVerdictText; ?></h2>
            <p style="color:#a1a1aa;margin-top:5px"><?php echo $urlMal; ?>/<?php echo $urlTotal; ?> engines flagged this URL</p>
        </div>
        
        <div class="card">
            <h3>🌐 URL Information</h3>
            <div class="file-info">
                <div class="file-info-item"><strong>URL</strong><span style="word-break:break-all"><?php echo htmlspecialchars($urlAnalysisResult['url']); ?></span></div>
                <div class="file-info-item"><strong>Scan Date</strong><span><?php echo $urlAnalysisResult['timestamp']; ?></span></div>
                <div class="file-info-item"><strong>Malicious</strong><span style="color:#ef4444"><?php echo $urlMal; ?></span></div>
                <div class="file-info-item"><strong>Total Engines</strong><span><?php echo $urlTotal; ?></span></div>
            </div>
        </div>
        
        <?php if(!empty($urlAnalysisResult['ai_analysis'])): ?>
        <div class="card">
            <h3>🤖 AI URL Analysis</h3>
            <div class="ai-box"><?php echo nl2br(htmlspecialchars($urlAnalysisResult['ai_analysis'])); ?></div>
        </div>
        <?php endif; ?>
        
        <?php endif; ?>
        
        <!-- Security Tips -->
        <div class="card">
            <h3>💡 AI Security Tips</h3>
            <div class="ai-box">
                <?php 
                $tip = callAI("Give 3 short actionable tips for malware prevention. Be specific.", "Security expert.");
                echo nl2br(htmlspecialchars($tip));
                ?>
            </div>
        </div>
    </div>
</body>
</html>