<?php
/**
 * VulnerabilityResults — Filterable CVE results table.
 *
 * FREE USER: Table is fully visible. Action buttons (Virtual Patch, Update Now)
 * are hidden for free users — replaced by a single inline_hint() nudge above
 * the table. The Ignore button remains available (non-destructive read action).
 *
 * @package UltraguardPro\modules\vulnerability\pages
 */

namespace UltraguardPro\modules\vulnerability\pages;

use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;
use UltraguardPro\support\LicenseInfo;
use UltraguardPro\support\UpgradeManager;

if ( ! defined( 'ABSPATH' ) ) { exit; }

class VulnerabilityResults extends BasePage {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        $this->ajax_nonce_action = 'ultraguard_admin_nonce';
    }

    public function get_scheme( $context ): array {
        $is_pro = LicenseInfo::instance()->isPro();
        $preview_mode = $this->is_soft_gated_module_preview( 'vulnerability' );
        $nonce  = $this->create_nonce( 'ultraguard_admin_nonce' );

        if ( $preview_mode ) {
            $summary = [
                'total'           => 12,
                'open'            => 8,
                'critical'        => 2,
                'high'            => 3,
                'medium'          => 2,
                'low'             => 1,
                'virtual_patched' => 2,
            ];
            $items = [ 'records' => $this->preview_records() ];
        } else {
            $table   = $this->plugin->modules->get_db_tables()->get_table( 'vulnerability_results' );
            $summary = $table ? $table->get_summary() : [
                'total' => 0, 'open' => 0, 'critical' => 0, 'high' => 0,
                'medium' => 0, 'low' => 0, 'virtual_patched' => 0,
            ];
            $items = $table
                ? $table->paginate( 1, 100, [ 'status' => 'open' ], 'cvss_score', 'DESC' )
                : [ 'records' => [] ];
        }

        $rows = array_map( function ( $r ) use ( $is_pro ) {
            $r = (array) $r;

            $sev_class = match ( $r['severity'] ?? '' ) {
                'critical' => 'danger', 'high' => 'warning', 'medium' => 'info', default => 'secondary',
            };

            $cvss_display    = $r['cvss_score'] ? number_format( (float) $r['cvss_score'], 1 ) : '—';
            $patch_available = ! empty( $r['patched_in_version'] );
            $actions         = [];

            if ( $is_pro ) {
                // Virtual Patch button — Pro + no official fix
                if ( ! $patch_available && empty( $r['virtual_patch_active'] ) ) {
                    $actions[] = $this->create_ajax_button(
                        __( 'Virtual Patch', 'ultraguard-security-suite' ),
                        'ultraguard_vuln_apply_virtual_patch',
                        [ 'vuln_id' => $r['id'] ],
                        'primary', 'dashicons-shield',
                        __( 'Apply a virtual WAF rule to block exploit attempts for this CVE?', 'ultraguard-security-suite' )
                    );
                }
                // Update button — official patch available
                if ( $patch_available && $r['component_type'] !== 'core' ) {
                    $actions[] = $this->create_ajax_button(
                        __( 'Update Now', 'ultraguard-security-suite' ),
                        'ultraguard_vuln_update_component',
                        [ 'slug' => $r['component_slug'], 'type' => $r['component_type'] ],
                        'success', 'dashicons-update',
                        sprintf(
                            /* translators: %1$s: plugin/theme name, %2$s: version number */
__( '                        Update %1$s to version %2$s?', 'ultraguard-security-suite' ),
                            esc_html( $r['component_slug'] ),
                            esc_html( $r['patched_in_version'] )
                        )
                    );
                }
            }

            // Ignore is available to all users (non-destructive)
            $actions[] = $this->create_ajax_button(
                __( 'Ignore', 'ultraguard-security-suite' ),
                'ultraguard_vuln_ignore_vulnerability',
                [ 'vuln_id' => $r['id'] ],
                'secondary', 'dashicons-hidden',
                __( 'Mark this vulnerability as ignored?', 'ultraguard-security-suite' )
            );

            return [
                'id'            => 'ug-vuln-row-' . $r['id'],
                'component'     => esc_html( $r['component_slug']    ?? '' ),
                'type'          => esc_html( ucfirst( $r['component_type'] ?? '' ) ),
                'version'       => esc_html( $r['component_version'] ?? '—' ),
                'cve'           => esc_html( $r['cve_id']            ?? '—' ),
                'cvss'          => $cvss_display,
                'severity'      => [ 'content' => esc_html( ucfirst( $r['severity'] ?? '' ) ), 'class' => $sev_class ],
                'title'         => esc_html( mb_substr( $r['title'] ?? '', 0, 100 ) ),
                'fix'           => $patch_available
                    /* translators: %s: string */
                    ? esc_html( sprintf( __( 'Update to %s', 'ultraguard-security-suite' ), $r['patched_in_version'] ) )
                    : esc_html__( 'No patch yet', 'ultraguard-security-suite' ),
                'status'        => [ 'content' => esc_html( ucfirst( str_replace( '_', ' ', $r['status'] ?? '' ) ) ), 'class' => 'secondary' ],
                'patch_actions' => $actions,
            ];
        }, $items['records'] ?? [] );

        return [
            'type'      => 'page',
            'id'        => 'ultraguard-vulnerability-results',
            'page_slug' => 'vulnerability-results',
            'class'     => 'ultraguard-vulnerability-results-page ultraguard-page-no-sidebar',
            'header'    => [
                'title'    => __( 'Vulnerability Results', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Full CVE list for installed components. Apply virtual patches or trigger updates directly.', 'ultraguard-security-suite' ),
                'icon'     => 'dashicons-warning',
                'badge'    => [
                    /* translators: %d: integer */
                    'text'       => sprintf( __( '%d open CVEs', 'ultraguard-security-suite' ), (int) $summary['open'] ),
                    'badge_type' => $summary['critical'] > 0 ? 'danger' : 'warning',
                ],
            ],
            'data' => array_values( array_filter( [
                $preview_mode ? $this->soft_gated_preview_data_notice(
                    __( 'Vulnerability Results', 'ultraguard-security-suite' ),
                    __( 'These CVEs, severities, and patch actions are sample findings based on a typical WooCommerce stack. Upgrade to scan your installed plugins, themes, and core for real vulnerabilities.', 'ultraguard-security-suite' )
                ) : null,

                // ── Soft nudge for free users ──────────────────────────────────
                UpgradeManager::should_show_nudge()
                    ? UpgradeManager::inline_hint(
                        'vulnerability_scan',
                        __( 'Run a scan with Pro to populate this table with real CVE data for your installed plugins and themes.', 'ultraguard-security-suite' )
                    )
                    : null,

                // ── Virtual patch teaser for free users ───────────────────────
                UpgradeManager::should_show_nudge()
                    ? UpgradeManager::inline_hint(
                        'virtual_patching',
                        __( 'Pro users can apply a WAF rule for any CVE with no official fix — directly from this table.', 'ultraguard-security-suite' )
                    )
                    : null,

                // ── Stat cards ─────────────────────────────────────────────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Critical',        'ultraguard-security-suite' ), 'value' => $summary['critical'],        'icon' => 'dashicons-dismiss',   'class' => $summary['critical']  > 0 ? 'danger'   : 'success' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'High',            'ultraguard-security-suite' ), 'value' => $summary['high'],            'icon' => 'dashicons-flag',      'class' => $summary['high']      > 0 ? 'warning'  : 'success' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Medium',          'ultraguard-security-suite' ), 'value' => $summary['medium'],          'icon' => 'dashicons-info',      'class' => 'secondary' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Low',             'ultraguard-security-suite' ), 'value' => $summary['low'],             'icon' => 'dashicons-minus',     'class' => 'secondary' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Virtual Patched', 'ultraguard-security-suite' ), 'value' => $summary['virtual_patched'], 'icon' => 'dashicons-shield',    'class' => 'success' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total',           'ultraguard-security-suite' ), 'value' => $summary['total'],           'icon' => 'dashicons-list-view', 'class' => 'info' ] ],
                    ],
                ],

                // ── Results table (visible to all — empty for free users) ──────
                [
                    'type'  => 'card',
                    'title' => __( 'Open Vulnerabilities', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-warning',
                    'data'  => [ [
                        'type'       => 'data-table',
                        'id'         => 'vuln-results-table',
                        'columns'    => [
                            'component'     => [ 'title' => __( 'Component', 'ultraguard-security-suite' ), 'sortable' => true ],
                            'type'          => [ 'title' => __( 'Type',      'ultraguard-security-suite' ) ],
                            'version'       => [ 'title' => __( 'Version',   'ultraguard-security-suite' ) ],
                            'cve'           => [ 'title' => __( 'CVE',       'ultraguard-security-suite' ) ],
                            'cvss'          => [ 'title' => __( 'CVSS',      'ultraguard-security-suite' ), 'sortable' => true ],
                            'severity'      => [ 'title' => __( 'Severity',  'ultraguard-security-suite' ), 'sortable' => true ],
                            'title'         => [ 'title' => __( 'Title',     'ultraguard-security-suite' ) ],
                            'fix'           => [ 'title' => __( 'Fix',       'ultraguard-security-suite' ) ],
                            'status'        => [ 'title' => __( 'Status',    'ultraguard-security-suite' ) ],
                            'patch_actions' => [ 'title' => __( 'Actions',   'ultraguard-security-suite' ) ],
                        ],
                        'data'        => $rows,
                        'searchable'  => true,
                        'pagination'  => [ 'enabled' => count( $rows ) > 25, 'page_size' => 25 ],
                        'empty_state' => [
                            'title'       => __( 'No vulnerabilities found', 'ultraguard-security-suite' ),
                            'description' => $is_pro
                                ? __( 'Run a scan to check your installed components for known CVEs.', 'ultraguard-security-suite' )
                                : __( 'Upgrade to Pro and run your first scan to see CVE results here.', 'ultraguard-security-suite' ),
                        ],
                    ] ],
                ],

            ] ) ),
        ];
    }

    private function preview_records(): array {
        return [
            [
                'id'                  => 201,
                'component_slug'      => 'woocommerce',
                'component_type'      => 'plugin',
                'component_version'   => '9.1.0',
                'cve_id'              => 'CVE-2026-1042',
                'cvss_score'          => 9.1,
                'severity'            => 'critical',
                'title'               => 'Privilege escalation through insecure checkout endpoint',
                'patched_in_version'  => '9.1.3',
                'status'              => 'open',
                'virtual_patch_active'=> 0,
            ],
            [
                'id'                  => 202,
                'component_slug'      => 'elementor',
                'component_type'      => 'plugin',
                'component_version'   => '3.25.1',
                'cve_id'              => 'CVE-2026-1188',
                'cvss_score'          => 8.2,
                'severity'            => 'high',
                'title'               => 'Stored XSS in template import workflow',
                'patched_in_version'  => '',
                'status'              => 'open',
                'virtual_patch_active'=> 1,
            ],
            [
                'id'                  => 203,
                'component_slug'      => 'wordpress',
                'component_type'      => 'core',
                'component_version'   => '6.9.0',
                'cve_id'              => 'CVE-2026-0914',
                'cvss_score'          => 6.4,
                'severity'            => 'medium',
                'title'               => 'Information disclosure in XML-RPC parser',
                'patched_in_version'  => '6.9.1',
                'status'              => 'open',
                'virtual_patch_active'=> 0,
            ],
        ];
    }
}
