<?php
// /admin/apk_analysis.php - APK Analysis with MobSF Public API
require_once dirname(__DIR__) . '/config.php';
requireAdmin();

// MobSF Public API Configuration
define('MOBSF_API_KEY', '35b01fd767a747be3a8c71260d55eabf3c4d853aaa378d79998314274bf3f65d');
define('MOBSF_BASE_URL', 'https://mobsf.live');
define('MOBSF_API_URL', 'https://mobsf.live/api/v1');

define('APK_UPLOAD_DIR', __DIR__ . '/uploads/apk/');

// Create upload directory if not exist
if (!is_dir(APK_UPLOAD_DIR)) mkdir(APK_UPLOAD_DIR, 0755, true);

// Database table for scans (create if not exists)
$pdo = getDBConnection();
$pdo->exec("CREATE TABLE IF NOT EXISTS apk_scans (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    hash TEXT UNIQUE,
    filename TEXT,
    app_name TEXT,
    package_name TEXT,
    version_name TEXT,
    icon_path TEXT,
    score TEXT,
    scan_date DATETIME DEFAULT CURRENT_TIMESTAMP,
    status TEXT DEFAULT 'completed',
    user_id INTEGER,
    FOREIGN KEY (user_id) REFERENCES users(id)
)");

// Handle API requests via AJAX
if (isset($_GET['action'])) {
    header('Content-Type: application/json');
    
    switch ($_GET['action']) {
        case 'upload':
            echo json_encode(uploadAPK());
            break;
        case 'get_recent_scans':
            echo json_encode(getRecentScans());
            break;
        case 'delete_scan':
            echo json_encode(deleteScan());
            break;
        case 'get_report':
            echo json_encode(getReport());
            break;
        case 'download_pdf':
            downloadPDF();
            break;
    }
    exit;
}

function uploadAPK() {
    global $error;
    
    if (!isset($_FILES['apk_file']) || $_FILES['apk_file']['error'] !== UPLOAD_ERR_OK) {
        return ['success' => false, 'error' => 'Upload failed'];
    }
    
    $file = $_FILES['apk_file'];
    
    if (pathinfo($file['name'], PATHINFO_EXTENSION) !== 'apk') {
        return ['success' => false, 'error' => 'Only .apk files are allowed'];
    }
    
    $originalName = $file['name'];
    $safeName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $originalName);
    $uploadPath = APK_UPLOAD_DIR . $safeName;
    
    if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
        return ['success' => false, 'error' => 'Failed to save file'];
    }
    
    // Upload to MobSF
    $ch = curl_init(MOBSF_API_URL . '/upload');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => ['file' => new CURLFile($uploadPath)],
        CURLOPT_HTTPHEADER => ['Authorization: ' . MOBSF_API_KEY],
        CURLOPT_TIMEOUT => 60,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    @unlink($uploadPath);
    
    if ($httpCode !== 200) {
        return ['success' => false, 'error' => 'MobSF upload failed: HTTP ' . $httpCode];
    }
    
    $uploadResult = json_decode($response, true);
    
    if (!isset($uploadResult['hash'])) {
        return ['success' => false, 'error' => 'No hash returned'];
    }
    
    $hash = $uploadResult['hash'];
    
    // Start scan
    $ch = curl_init(MOBSF_API_URL . '/scan');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['hash' => $hash, 'scan_type' => 'file']),
        CURLOPT_HTTPHEADER => [
            'Authorization: ' . MOBSF_API_KEY,
            'Content-Type: application/json'
        ],
        CURLOPT_TIMEOUT => 120,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        return ['success' => false, 'error' => 'Scan failed'];
    }
    
    $scanResult = json_decode($response, true);
    
    // Save to database
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("INSERT OR REPLACE INTO apk_scans 
            (hash, filename, app_name, package_name, version_name, icon_path, score, user_id) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $hash,
            $originalName,
            $scanResult['app_name'] ?? null,
            $scanResult['package_name'] ?? null,
            $scanResult['version_name'] ?? null,
            $scanResult['icon_path'] ?? null,
            $scanResult['score'] ?? null,
            $_SESSION['user_id']
        ]);
    } catch (Exception $e) {}
    
    logUserActivity($_SESSION['user_id'], 'APK Analysis', 'Analyzed: ' . $originalName);
    
    return ['success' => true, 'hash' => $hash, 'data' => $scanResult];
}

function getRecentScans() {
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->query("SELECT * FROM apk_scans ORDER BY scan_date DESC LIMIT 50");
        $scans = $stmt->fetchAll();
        
        // Fetch fresh data from MobSF for each scan
        foreach ($scans as &$scan) {
            $ch = curl_init(MOBSF_API_URL . '/report_json');
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode(['hash' => $scan['hash']]),
                CURLOPT_HTTPHEADER => [
                    'Authorization: ' . MOBSF_API_KEY,
                    'Content-Type: application/json'
                ],
                CURLOPT_SSL_VERIFYPEER => false
            ]);
            
            $response = curl_exec($ch);
            curl_close($ch);
            
            if ($response) {
                $data = json_decode($response, true);
                $scan['report_data'] = $data;
            }
        }
        
        return ['success' => true, 'scans' => $scans];
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

function deleteScan() {
    $hash = $_POST['hash'] ?? '';
    if (!$hash) return ['success' => false, 'error' => 'No hash provided'];
    
    try {
        $pdo = getDBConnection();
        $stmt = $pdo->prepare("DELETE FROM apk_scans WHERE hash = ?");
        $stmt->execute([$hash]);
        
        // Also delete from MobSF
        $ch = curl_init(MOBSF_API_URL . '/delete_scan');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode(['hash' => $hash]),
            CURLOPT_HTTPHEADER => [
                'Authorization: ' . MOBSF_API_KEY,
                'Content-Type: application/json'
            ],
            CURLOPT_SSL_VERIFYPEER => false
        ]);
        curl_exec($ch);
        curl_close($ch);
        
        return ['success' => true, 'deleted' => 'yes'];
    } catch (Exception $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

function getReport() {
    $hash = $_GET['hash'] ?? '';
    if (!$hash) return ['success' => false, 'error' => 'No hash provided'];
    
    $ch = curl_init(MOBSF_API_URL . '/report_json');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['hash' => $hash]),
        CURLOPT_HTTPHEADER => [
            'Authorization: ' . MOBSF_API_KEY,
            'Content-Type: application/json'
        ],
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

function downloadPDF() {
    $hash = $_GET['hash'] ?? '';
    if (!$hash) die('No hash provided');
    
    $ch = curl_init(MOBSF_API_URL . '/download_pdf');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['hash' => $hash]),
        CURLOPT_HTTPHEADER => [
            'Authorization: ' . MOBSF_API_KEY,
            'Content-Type: application/json'
        ],
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="mobsf_report_' . $hash . '.pdf"');
    echo $response;
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>APK Analysis - Soul Guard Admin</title>
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --bg-primary: #0a0a0f;
            --bg-secondary: #13131a;
            --bg-card: rgba(255, 255, 255, 0.03);
            --border-color: rgba(255, 255, 255, 0.06);
            --text-primary: #e4e4e7;
            --text-secondary: #a1a1aa;
            --accent-blue: #3b82f6;
            --accent-red: #ef4444;
            --accent-green: #22c55e;
            --accent-yellow: #eab308;
            --accent-purple: #a855f7;
            --accent-cyan: #06b6d4;
            --accent-orange: #f97316;
        }

        body {
            font-family: 'Source Sans Pro', -apple-system, BlinkMacSystemFont, sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
        }

        .navbar {
            background: var(--bg-secondary);
            border-bottom: 1px solid var(--border-color);
            padding: 0 30px;
            height: 65px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #3b82f6, #a855f7);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .nav-links {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .nav-links a {
            color: var(--text-secondary);
            text-decoration: none;
            padding: 8px 14px;
            border-radius: 8px;
            font-size: 13px;
            transition: all 0.2s;
        }

        .nav-links a:hover, .nav-links a.active {
            background: rgba(59, 130, 246, 0.15);
            color: var(--accent-blue);
        }

        .user-badge {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 6px 12px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 20px;
            font-size: 12px;
            margin-left: 10px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 30px;
        }

        /* Upload Card */
        .upload-card {
            background: var(--bg-card);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 30px;
            margin-bottom: 30px;
            text-align: center;
        }

        .upload-area {
            border: 2px dashed var(--border-color);
            border-radius: 12px;
            padding: 50px;
            margin-top: 20px;
            transition: all 0.3s;
            cursor: pointer;
        }

        .upload-area:hover, .upload-area.dragover {
            border-color: var(--accent-blue);
            background: rgba(59, 130, 246, 0.05);
        }

        .upload-icon {
            font-size: 48px;
            margin-bottom: 15px;
        }

        #apk_file {
            display: none;
        }

        .upload-btn {
            background: linear-gradient(135deg, #3b82f6, #a855f7);
            color: white;
            padding: 12px 30px;
            border-radius: 10px;
            cursor: pointer;
            display: inline-block;
            font-weight: 600;
            margin: 15px 0;
            transition: all 0.2s;
        }

        .upload-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(59, 130, 246, 0.3);
        }

        /* Table */
        .scans-card {
            background: var(--bg-card);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            overflow: hidden;
        }

        .card-header {
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
            background: rgba(255, 255, 255, 0.02);
        }

        .card-header h2 {
            font-size: 18px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .table-responsive {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th {
            text-align: left;
            padding: 15px;
            color: var(--text-secondary);
            font-size: 12px;
            font-weight: 600;
            border-bottom: 1px solid var(--border-color);
        }

        td {
            padding: 15px;
            border-bottom: 1px solid var(--border-color);
            vertical-align: middle;
        }

        tr:hover {
            background: rgba(255, 255, 255, 0.02);
        }

        .app-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            object-fit: cover;
        }

        .app-info {
            text-align: center;
        }

        .app-name {
            font-weight: 600;
            margin-top: 5px;
            font-size: 13px;
        }

        .package-name {
            font-size: 10px;
            color: var(--text-secondary);
            margin-top: 3px;
        }

        .badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }

        .badge-success {
            background: rgba(34, 197, 94, 0.2);
            color: #86efac;
        }

        .badge-warning {
            background: rgba(234, 179, 8, 0.2);
            color: #fde047;
        }

        .badge-danger {
            background: rgba(239, 68, 68, 0.2);
            color: #fca5a5;
        }

        .score-A { background: rgba(34, 197, 94, 0.2); color: #86efac; }
        .score-B { background: rgba(234, 179, 8, 0.2); color: #fde047; }
        .score-C { background: rgba(245, 158, 11, 0.2); color: #fdba74; }
        .score-D { background: rgba(239, 68, 68, 0.2); color: #fca5a5; }
        .score-F { background: rgba(127, 29, 29, 0.3); color: #fecaca; }

        .btn-icon {
            background: transparent;
            border: 1px solid var(--border-color);
            padding: 6px 12px;
            border-radius: 8px;
            cursor: pointer;
            color: var(--text-secondary);
            font-size: 12px;
            transition: all 0.2s;
            margin: 2px;
            text-decoration: none;
            display: inline-block;
        }

        .btn-icon:hover {
            background: rgba(255, 255, 255, 0.05);
            color: var(--text-primary);
        }

        .btn-danger {
            border-color: rgba(239, 68, 68, 0.3);
            color: #fca5a5;
        }

        .btn-danger:hover {
            background: rgba(239, 68, 68, 0.1);
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            width: 90%;
            max-width: 800px;
            max-height: 80vh;
            overflow-y: auto;
            padding: 20px;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid var(--border-color);
        }

        .close-modal {
            cursor: pointer;
            font-size: 24px;
            color: var(--text-secondary);
        }

        .loading {
            display: none;
            text-align: center;
            padding: 40px;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 3px solid var(--border-color);
            border-top-color: var(--accent-blue);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .vuln-item {
            padding: 10px;
            margin-bottom: 10px;
            border-left: 3px solid;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 6px;
        }

        .vuln-high { border-left-color: #ef4444; }
        .vuln-medium { border-left-color: #eab308; }
        .vuln-low { border-left-color: #22c55e; }

        @media (max-width: 768px) {
            .container { padding: 15px; }
            .navbar { padding: 0 15px; }
            th, td { padding: 10px; font-size: 12px; }
        }
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="logo">
            <div class="logo-icon">🛡️</div>
            <div class="logo-text">
                <h1>Soul Guard Admin</h1>
            </div>
        </div>
        <div class="nav-links">
            <a href="index.php">📊 Dashboard</a>
            <a href="users.php">👥 Users</a>
            <a href="services.php">📋 Services</a>
            <a href="apk_analysis.php" class="active">📱 APK Analysis</a>
            <span class="user-badge">
                <div class="user-avatar"><?php echo strtoupper(substr($_SESSION['username'], 0, 1)); ?></div>
                <?php echo htmlspecialchars($_SESSION['username']); ?>
            </span>
            <a href="/logout.php" class="logout-btn">🚪 Logout</a>
        </div>
    </nav>

    <div class="container">
        <!-- Upload Card -->
        <div class="upload-card">
            <h2>📱 APK Security Analysis</h2>
            <p style="color: var(--text-secondary); margin-top: 5px;">Upload APK for static analysis using MobSF (Mobile Security Framework)</p>
            
            <div class="upload-area" id="dropZone">
                <div class="upload-icon">📦</div>
                <p>Drag & drop APK file here or click to upload</p>
                <p style="font-size: 11px; color: var(--text-secondary);">Max file size: 100MB</p>
                <label class="upload-btn">
                    Choose APK File
                    <input type="file" id="apk_file" accept=".apk">
                </label>
            </div>
        </div>

        <!-- Loading Indicator -->
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>Uploading and analyzing APK with MobSF...</p>
            <p style="font-size: 12px; color: var(--text-secondary);">This may take 30-60 seconds</p>
        </div>

        <!-- Recent Scans Table -->
        <div class="scans-card">
            <div class="card-header">
                <h2>📋 Recent Scans</h2>
            </div>
            <div class="table-responsive">
                <table id="scansTable">
                    <thead>
                        <tr>
                            <th>APP</th>
                            <th>FILE</th>
                            <th>TYPE</th>
                            <th>HASH</th>
                            <th>SCAN DATE</th>
                            <th>ACTIONS</th>
                        </tr>
                    </thead>
                    <tbody id="scansBody">
                        <tr>
                            <td colspan="6" style="text-align: center;">Loading scans...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Report Modal -->
    <div id="reportModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>📊 Detailed Analysis Report</h3>
                <span class="close-modal">&times;</span>
            </div>
            <div id="reportContent">
                Loading...
            </div>
        </div>
    </div>

    <script>
        const MOBSF_API_URL = 'https://mobsf.live/api/v1';
        const API_KEY = '35b01fd767a747be3a8c71260d55eabf3c4d853aaa378d79998314274bf3f65d';

        // Load recent scans on page load
        document.addEventListener('DOMContentLoaded', loadRecentScans);

        // Upload handling
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('apk_file');
        const loading = document.getElementById('loading');

        dropZone.addEventListener('click', () => fileInput.click());
        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('dragover');
        });
        dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('dragover');
            const file = e.dataTransfer.files[0];
            if (file && file.name.endsWith('.apk')) {
                uploadAPK(file);
            } else {
                alert('Please upload an APK file');
            }
        });
        fileInput.addEventListener('change', (e) => {
            if (e.target.files[0]) uploadAPK(e.target.files[0]);
        });

        async function uploadAPK(file) {
            const formData = new FormData();
            formData.append('apk_file', file);
            
            loading.style.display = 'block';
            
            try {
                const response = await fetch('?action=upload', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                
                if (result.success) {
                    alert('Analysis complete!');
                    loadRecentScans();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                alert('Upload failed: ' + error.message);
            } finally {
                loading.style.display = 'none';
            }
        }

        async function loadRecentScans() {
            try {
                const response = await fetch('?action=get_recent_scans');
                const result = await response.json();
                
                if (result.success && result.scans) {
                    renderScansTable(result.scans);
                } else {
                    document.getElementById('scansBody').innerHTML = '<tr><td colspan="6" style="text-align: center;">No scans found</td></tr>';
                }
            } catch (error) {
                console.error('Failed to load scans:', error);
                document.getElementById('scansBody').innerHTML = '<tr><td colspan="6" style="text-align: center;">Failed to load scans</td></tr>';
            }
        }

        function renderScansTable(scans) {
            const tbody = document.getElementById('scansBody');
            tbody.innerHTML = '';
            
            scans.forEach(scan => {
                const row = tbody.insertRow();
                const reportData = scan.report_data || {};
                const appName = reportData.app_name || scan.app_name || 'Unknown';
                const packageName = reportData.package_name || scan.package_name || '';
                const score = reportData.score || scan.score || 'N/A';
                const scoreClass = getScoreClass(score);
                
                // App column
                row.insertCell(0).innerHTML = `
                    <div class="app-info">
                        <img class="app-icon" src="https://mobsf.live/static/img/no_icon.png" alt="icon">
                        <div class="app-name">${escapeHtml(appName)}</div>
                        <div class="package-name">${escapeHtml(packageName)}</div>
                        ${score !== 'N/A' ? `<span class="badge ${scoreClass}">Score: ${score}</span>` : ''}
                    </div>
                `;
                
                // File column
                row.insertCell(1).innerHTML = `<span style="word-break: break-all;">${escapeHtml(scan.filename || 'Unknown')}</span>`;
                
                // Type column
                row.insertCell(2).innerHTML = `<i class="fab fa-android" style="font-size: 24px;"></i>`;
                
                // Hash column
                row.insertCell(3).innerHTML = `<code style="font-size: 11px;">${scan.hash.substring(0, 16)}...</code>`;
                
                // Date column
                row.insertCell(4).innerHTML = formatDate(scan.scan_date);
                
                // Actions column
                row.insertCell(5).innerHTML = `
                    <button class="btn-icon" onclick="viewReport('${scan.hash}')"><i class="fas fa-eye"></i> View</button>
                    <button class="btn-icon" onclick="downloadPDF('${scan.hash}')"><i class="fas fa-file-pdf"></i> PDF</button>
                    <button class="btn-icon btn-danger" onclick="deleteScan('${scan.hash}')"><i class="fas fa-trash"></i> Delete</button>
                `;
            });
        }

        async function viewReport(hash) {
            const modal = document.getElementById('reportModal');
            const content = document.getElementById('reportContent');
            
            modal.style.display = 'flex';
            content.innerHTML = '<div class="loading" style="display:block;"><div class="spinner"></div><p>Loading report...</p></div>';
            
            try {
                const response = await fetch(`?action=get_report&hash=${hash}`);
                const report = await response.json();
                
                content.innerHTML = renderReportHTML(report);
            } catch (error) {
                content.innerHTML = '<p style="color: var(--accent-red);">Failed to load report</p>';
            }
        }

        function renderReportHTML(report) {
            if (!report || !report.app_name) {
                return '<p>No report data available</p>';
            }
            
            let html = `
                <div style="margin-bottom: 20px;">
                    <h4>📱 App Information</h4>
                    <table style="width: 100%;">
                        <tr><td style="padding: 5px;"><strong>App Name:</strong></td><td>${escapeHtml(report.app_name || 'N/A')}</td></tr>
                        <tr><td style="padding: 5px;"><strong>Package:</strong></td><td>${escapeHtml(report.package_name || 'N/A')}</td></tr>
                        <tr><td style="padding: 5px;"><strong>Version:</strong></td><td>${escapeHtml(report.version_name || 'N/A')} (${escapeHtml(report.version_code || 'N/A')})</td></tr>
                        <tr><td style="padding: 5px;"><strong>Main Activity:</strong></td><td>${escapeHtml(report.main_activity || 'N/A')}</td></tr>
                        <tr><td style="padding: 5px;"><strong>Min SDK:</strong></td><td>${escapeHtml(report.min_sdk_version || 'N/A')}</td></tr>
                        <tr><td style="padding: 5px;"><strong>Target SDK:</strong></td><td>${escapeHtml(report.target_sdk_version || 'N/A')}</td></tr>
                    </table>
                </div>
            `;
            
            // Score
            if (report.score) {
                html += `
                    <div style="margin-bottom: 20px;">
                        <h4>📊 Security Score</h4>
                        <div style="font-size: 36px; font-weight: bold;">${escapeHtml(report.score)}<span style="font-size: 14px;">/100</span></div>
                    </div>
                `;
            }
            
            // Permissions
            if (report.permissions && report.permissions.length > 0) {
                html += `
                    <div style="margin-bottom: 20px;">
                        <h4>🔐 Permissions (${report.permissions.length})</h4>
                        <div style="max-height: 200px; overflow-y: auto;">
                            ${report.permissions.map(p => `<span class="badge" style="background: rgba(59,130,246,0.1); margin: 3px;">${escapeHtml(p)}</span>`).join('')}
                        </div>
                    </div>
                `;
            }
            
            // Vulnerabilities
            if (report.vulnerabilities && Object.keys(report.vulnerabilities).length > 0) {
                html += `<div style="margin-bottom: 20px;"><h4>⚠️ Vulnerabilities</h4>`;
                for (const [severity, vulns] of Object.entries(report.vulnerabilities)) {
                    if (vulns && vulns.length > 0) {
                        html += `<h5 style="margin-top: 10px;">${severity.toUpperCase()}</h5>`;
                        vulns.forEach(v => {
                            html += `
                                <div class="vuln-item vuln-${severity.toLowerCase()}">
                                    <strong>${escapeHtml(v.title || 'Unknown')}</strong>
                                    <p style="font-size: 12px; margin-top: 5px;">${escapeHtml(v.description || '')}</p>
                                </div>
                            `;
                        });
                    }
                }
                html += `</div>`;
            }
            
            // Binary analysis
            if (report.binary_analysis) {
                html += `
                    <div style="margin-bottom: 20px;">
                        <h4>🔧 Binary Analysis</h4>
                        <table style="width: 100%;">
                            <tr><td><strong>Total Files:</strong></td><td>${report.binary_analysis.total_files || 0}</td></tr>
                            <tr><td><strong>DEX Files:</strong></td><td>${report.binary_analysis.dex_files || 0}</td></tr>
                            <tr><td><strong>Native Files:</strong></td><td>${report.binary_analysis.native_files || 0}</td></tr>
                        </table>
                    </div>
                `;
            }
            
            return html;
        }

        async function downloadPDF(hash) {
            window.location.href = `?action=download_pdf&hash=${hash}`;
        }

        async function deleteScan(hash) {
            if (!confirm('Are you sure you want to delete this scan?')) return;
            
            try {
                const formData = new FormData();
                formData.append('hash', hash);
                
                const response = await fetch('?action=delete_scan', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();
                
                if (result.success) {
                    loadRecentScans();
                } else {
                    alert('Delete failed: ' + result.error);
                }
            } catch (error) {
                alert('Delete failed: ' + error.message);
            }
        }

        function getScoreClass(score) {
            if (score === 'N/A') return '';
            const num = parseInt(score);
            if (num >= 80) return 'score-A';
            if (num >= 60) return 'score-B';
            if (num >= 40) return 'score-C';
            if (num >= 20) return 'score-D';
            return 'score-F';
        }

        function formatDate(dateStr) {
            if (!dateStr) return 'N/A';
            const date = new Date(dateStr);
            return date.toLocaleString();
        }

        function escapeHtml(str) {
            if (!str) return '';
            return str.replace(/[&<>]/g, function(m) {
                if (m === '&') return '&amp;';
                if (m === '<') return '&lt;';
                if (m === '>') return '&gt;';
                return m;
            });
        }

        // Modal close
        document.querySelector('.close-modal').onclick = () => {
            document.getElementById('reportModal').style.display = 'none';
        };
        window.onclick = (e) => {
            if (e.target === document.getElementById('reportModal')) {
                document.getElementById('reportModal').style.display = 'none';
            }
        };
    </script>
</body>
</html>