<?php
/**
 * CVE Scanner Admin Page
 *
 * @package VMPFence
 * @since 2.1.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Enqueue toast notification system
wp_enqueue_style('vmpfence-toast-notifications', 
    plugins_url('admin/assets/css/toast-notifications.css', dirname(dirname(__FILE__))), 
    array(), '1.0.0');
wp_enqueue_script('vmpfence-toast-notifications', 
    plugins_url('admin/assets/js/toast-notifications.js', dirname(dirname(__FILE__))), 
    array('jquery'), '1.0.0', true);

// Load CVE classes
require_once VMPFENCE_PLUGIN_DIR . 'includes/cve/class-cve-sync.php';
require_once VMPFENCE_PLUGIN_DIR . 'includes/cve/class-cve-scanner.php';

// Handle form submissions
$scan_message = '';
$scan_error = '';
$scan_results = null;

if (isset($_POST['sync_cve_db']) && check_admin_referer('vmpfence_cve_sync')) {
    $sync_result = VMPFence_CVE_Sync::sync_from_api();
    if ($sync_result['success']) {
        $scan_message = sprintf(
            'Successfully synced %d CVE vulnerabilities (Version: %s)',
            $sync_result['imported'],
            $sync_result['version']
        );
    } else {
        $scan_error = 'Failed to sync CVE database: ' . implode(', ', $sync_result['errors']);
    }
}

if (isset($_POST['scan_now']) && check_admin_referer('vmpfence_cve_scan')) {
    $scanner = new VMPFence_CVE_Scanner();
    $scan_results = $scanner->scan_site();
    
    if ($scan_results['success']) {
        $scan_message = sprintf(
            'Scan completed: %d vulnerabilities found (%d critical, %d high, %d medium, %d low)',
            $scan_results['total_vulnerabilities'],
            $scan_results['severity_counts']['critical'],
            $scan_results['severity_counts']['high'],
            $scan_results['severity_counts']['medium'],
            $scan_results['severity_counts']['low']
        );
    } else {
        $scan_error = 'Scan failed: ' . $scan_results['error'];
    }
}

// Get cached results if no new scan
if (!$scan_results) {
    $scan_results = VMPFence_CVE_Scanner::get_cached_results();
}

// Get statistics
$cve_count = VMPFence_CVE_Sync::get_cve_count();
$cve_version = VMPFence_CVE_Sync::get_cve_version();
$last_sync = get_option('vmpfence_cve_last_sync', 'Never');
$scan_needed = VMPFence_CVE_Scanner::is_scan_needed();

?>

<div class="wrap vmpfence-cve-scanner">
    <h1>
        CVE Vulnerability Scanner
    </h1>

    <!-- CVE Database Status -->
    <div class="vmpfence-card">
        <h2>CVE Database Status</h2>
        <table class="widefat">
            <tbody>
                <tr>
                    <td><strong>Total CVEs:</strong></td>
                    <td><?php echo number_format($cve_count); ?></td>
                </tr>
                <tr>
                    <td><strong>Database Version:</strong></td>
                    <td><?php echo esc_html($cve_version); ?></td>
                </tr>
                <tr>
                    <td><strong>Last Updated:</strong></td>
                    <td><?php echo esc_html($last_sync); ?></td>
                </tr>
            </tbody>
        </table>
        
        <form method="post" style="margin-top: 15px;">
            <?php wp_nonce_field('vmpfence_cve_sync'); ?>
            <button type="submit" name="sync_cve_db" class="button button-secondary">
                Update CVE Database
            </button>
        </form>
    </div>

    <!-- Scan Controls -->
    <div class="vmpfence-card">
        <h2>Vulnerability Scan</h2>
        <?php if ($scan_needed): ?>
            <div class="notice notice-warning inline">
                <p><strong>Scan Recommended:</strong> It's been more than 24 hours since your last scan.</p>
            </div>
        <?php endif; ?>
        
        <form method="post" style="margin-top: 15px;">
            <?php wp_nonce_field('vmpfence_cve_scan'); ?>
            <button type="submit" name="scan_now" class="button button-primary button-large">
                Scan Site for Vulnerabilities
            </button>
            <p class="description">
                Scans WordPress core, all installed plugins, and themes for known CVE vulnerabilities.
            </p>
        </form>
    </div>

    <!-- Scan Results -->
    <?php if ($scan_results && $scan_results['success']): ?>
        
        <!-- Summary Dashboard -->
        <div class="vmpfence-dashboard">
            <h2>Scan Results Summary</h2>
            <div class="vmpfence-stats-grid">
                <div class="stat-card total">
                    <div class="stat-number"><?php echo $scan_results['total_vulnerabilities']; ?></div>
                    <div class="stat-label">Total Vulnerabilities</div>
                </div>
                <div class="stat-card critical">
                    <div class="stat-number"><?php echo $scan_results['severity_counts']['critical']; ?></div>
                    <div class="stat-label">Critical</div>
                </div>
                <div class="stat-card high">
                    <div class="stat-number"><?php echo $scan_results['severity_counts']['high']; ?></div>
                    <div class="stat-label">High</div>
                </div>
                <div class="stat-card medium">
                    <div class="stat-number"><?php echo $scan_results['severity_counts']['medium']; ?></div>
                    <div class="stat-label">Medium</div>
                </div>
                <div class="stat-card low">
                    <div class="stat-number"><?php echo $scan_results['severity_counts']['low']; ?></div>
                    <div class="stat-label">Low</div>
                </div>
            </div>
            <p class="scan-time">
                <em>Last scanned: <?php echo esc_html($scan_results['scanned_at']); ?></em>
            </p>
        </div>

        <!-- WordPress Core Vulnerabilities -->
        <?php if (!empty($scan_results['core_vulnerabilities'])): ?>
            <div class="vmpfence-card">
                <h2>
                    <span class="dashicons dashicons-wordpress-alt"></span>
                    WordPress Core Vulnerabilities (<?php echo count($scan_results['core_vulnerabilities']); ?>)
                </h2>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th width="15%">CVE ID</th>
                            <th width="10%">Severity</th>
                            <th width="10%">CVSS Score</th>
                            <th width="40%">Description</th>
                            <th width="15%">Affected Versions</th>
                            <th width="10%">Fix</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($scan_results['core_vulnerabilities'] as $vuln): ?>
                            <tr>
                                <td><code><?php echo esc_html($vuln['cve_id']); ?></code></td>
                                <td>
                                    <span class="severity-badge severity-<?php echo esc_attr(strtolower($vuln['severity'])); ?>">
                                        <?php echo esc_html($vuln['severity']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if (isset($vuln['cvss_score'])): ?>
                                        <strong><?php echo esc_html($vuln['cvss_score']); ?></strong>
                                    <?php else: ?>
                                        N/A
                                    <?php endif; ?>
                                </td>
                                <td><?php echo esc_html($vuln['description']); ?></td>
                                <td><?php echo esc_html($vuln['affected_versions'] ?? 'All versions'); ?></td>
                                <td>
                                    <?php echo VMPFence_CVE_Scanner::get_fix_action_html($vuln); ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>

        <!-- Plugin Vulnerabilities -->
        <?php if (!empty($scan_results['plugin_vulnerabilities'])): ?>
            <div class="vmpfence-card">
                <h2>
                    <span class="dashicons dashicons-admin-plugins"></span>
                    Plugin Vulnerabilities (<?php echo count($scan_results['plugin_vulnerabilities']); ?>)
                </h2>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th width="20%">Plugin</th>
                            <th width="12%">CVE ID</th>
                            <th width="10%">Severity</th>
                            <th width="10%">CVSS</th>
                            <th width="33%">Description</th>
                            <th width="15%">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($scan_results['plugin_vulnerabilities'] as $vuln): ?>
                            <tr>
                                <td><strong><?php echo esc_html($vuln['component_name']); ?></strong><br>
                                    <small>Version: <?php echo esc_html($vuln['component_version'] ?? 'Unknown'); ?></small>
                                </td>
                                <td><code><?php echo esc_html($vuln['cve_id']); ?></code></td>
                                <td>
                                    <span class="severity-badge severity-<?php echo esc_attr(strtolower($vuln['severity'])); ?>">
                                        <?php echo esc_html($vuln['severity']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if (isset($vuln['cvss_score'])): ?>
                                        <strong><?php echo esc_html($vuln['cvss_score']); ?></strong>
                                    <?php else: ?>
                                        N/A
                                    <?php endif; ?>
                                </td>
                                <td><?php echo esc_html($vuln['description']); ?></td>
                                <td>
                                    <?php echo VMPFence_CVE_Scanner::get_fix_action_html($vuln); ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>

        <!-- Theme Vulnerabilities -->
        <?php if (!empty($scan_results['theme_vulnerabilities'])): ?>
            <div class="vmpfence-card">
                <h2>
                    <span class="dashicons dashicons-admin-appearance"></span>
                    Theme Vulnerabilities (<?php echo count($scan_results['theme_vulnerabilities']); ?>)
                </h2>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th width="20%">Theme</th>
                            <th width="12%">CVE ID</th>
                            <th width="10%">Severity</th>
                            <th width="10%">CVSS</th>
                            <th width="33%">Description</th>
                            <th width="15%">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($scan_results['theme_vulnerabilities'] as $vuln): ?>
                            <tr>
                                <td><strong><?php echo esc_html($vuln['component_name']); ?></strong><br>
                                    <small>Version: <?php echo esc_html($vuln['component_version'] ?? 'Unknown'); ?></small>
                                </td>
                                <td><code><?php echo esc_html($vuln['cve_id']); ?></code></td>
                                <td>
                                    <span class="severity-badge severity-<?php echo esc_attr(strtolower($vuln['severity'])); ?>">
                                        <?php echo esc_html($vuln['severity']); ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if (isset($vuln['cvss_score'])): ?>
                                        <strong><?php echo esc_html($vuln['cvss_score']); ?></strong>
                                    <?php else: ?>
                                        N/A
                                    <?php endif; ?>
                                </td>
                                <td><?php echo esc_html($vuln['description']); ?></td>
                                <td>
                                    <?php echo VMPFence_CVE_Scanner::get_fix_action_html($vuln); ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>

        <!-- No Vulnerabilities Found -->
        <?php if ($scan_results['total_vulnerabilities'] === 0): ?>
            <div class="vmpfence-card">
                <div class="notice notice-success inline">
                    <p><strong>✓ No vulnerabilities found!</strong></p>
                    <p>Your WordPress installation, plugins, and themes are not affected by any known CVEs in our database.</p>
                </div>
            </div>
        <?php endif; ?>

    <?php elseif (!$scan_results): ?>
        <div class="vmpfence-card">
            <p><em>No scan results available. Click "Scan Site for Vulnerabilities" to start a scan.</em></p>
        </div>
    <?php endif; ?>
</div>

<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');

.vmpfence-cve-scanner,
.vmpfence-cve-scanner * {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}

.vmpfence-card {
    background: #fff;
    border: 1px solid #ccd0d4;
    padding: 24px;
    margin: 20px 0;
    border-radius: 12px;
}

.vmpfence-dashboard {
    background: #f9f9f9;
    border: 1px solid #ddd;
    padding: 24px;
    margin: 20px 0;
    border-radius: 12px;
}

.vmpfence-stats-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 16px;
    margin: 20px 0;
}

.stat-card {
    background: #fff;
    border: 2px solid #ddd;
    border-radius: 12px;
    padding: 20px;
    text-align: center;
}

.stat-card.total { border-color: #191970; }
.stat-card.critical { border-color: #dc3232; background: #fff5f5; }
.stat-card.high { border-color: #f56e28; background: #fff9f5; }
.stat-card.medium { border-color: #F5A623; background: #fffef5; }
.stat-card.low { border-color: #46b450; background: #f7fff7; }

.stat-number {
    font-size: 36px;
    font-weight: bold;
    margin-bottom: 5px;
}

.stat-card.critical .stat-number { color: #dc3232; }
.stat-card.high .stat-number { color: #f56e28; }
.stat-card.medium .stat-number { color: #F5A623; }
.stat-card.low .stat-number { color: #46b450; }
.stat-card.total .stat-number { color: #191970; }

.stat-label {
    font-size: 14px;
    color: #666;
}

.severity-badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 12px;
    font-weight: 600;
    font-size: 11px;
    text-transform: uppercase;
}

.severity-critical { background: #dc3232; color: #fff; }
.severity-high { background: #f56e28; color: #fff; }
.severity-medium { background: #ffb900; color: #000; }
.severity-low { background: #46b450; color: #fff; }

.no-patch {
    color: #999;
    font-style: italic;
}

.scan-time {
    text-align: center;
    margin-top: 15px;
    color: #666;
}

.button-large {
    padding: 12px 24px !important;
    height: 48px !important;
    font-size: 14px !important;
    font-family: 'Inter', sans-serif !important;
    font-weight: 600 !important;
    border-radius: 12px !important;
    display: inline-flex !important;
    align-items: center !important;
    gap: 8px !important;
}

.button-primary {
    background: #191970 !important;
    border-color: #191970 !important;
}

.button-primary:hover {
    background: #131450 !important;
    border-color: #131450 !important;
}

.button-secondary {
    background: #fff !important;
    border: 1px solid #191970 !important;
    color: #191970 !important;
}

.button-secondary:hover {
    background: #191970 !important;
    color: #fff !important;
}

.dashicons {
    vertical-align: middle;
}
</style>

<!-- Toast Notification Triggers -->
<?php if ($scan_message): ?>
<script>
jQuery(document).ready(function($) {
    // Initialize toast system
    if (typeof VMPFenceNotifications !== 'undefined') {
        VMPFenceNotifications.init();
        VMPFenceNotifications.showSuccess(
            '<?php echo esc_js($scan_message); ?>',
            6000
        );
    }
});
</script>
<?php endif; ?>

<?php if ($scan_error): ?>
<script>
jQuery(document).ready(function($) {
    // Initialize toast system
    if (typeof VMPFenceNotifications !== 'undefined') {
        VMPFenceNotifications.init();
        VMPFenceNotifications.showError(
            '<?php echo esc_js($scan_error); ?>',
            8000
        );
    }
});
</script>
<?php endif; ?>
