<?php
/**
 * VirtualPatchesPage — Active virtual patches list.
 *
 * FREE USER: The full page is visible. A teaser_card() explains what virtual
 * patches are and what they protect against. The table renders with an empty
 * state that explains how to get patches (upgrade + run a scan).
 *
 * @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 VirtualPatchesPage 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' );
        $patch_table = $this->plugin->modules->get_db_tables()->get_table( 'virtual_patches' );
        $patches     = $preview_mode
            ? $this->preview_patches()
            : ( ( $is_pro && $patch_table ) ? $patch_table->get_active_patches() : [] );
        $total       = count( $patches );

        $rows = array_map( function ( $p ) {
            $p          = (array) $p;
            $expires_at = $p['expires_at'] ?? '';
            $now        = time();

            if ( $expires_at ) {
                $expires_ts   = strtotime( $expires_at );
                $days_left    = max( 0, (int) ceil( ( $expires_ts - $now ) / DAY_IN_SECONDS ) );
                $expiry_label = $days_left > 0
                    /* translators: %d: number */
                    ? sprintf( _n( '%d day', '%d days', $days_left, 'ultraguard-security-suite' ), $days_left )
                    : esc_html__( 'Expiring soon', 'ultraguard-security-suite' );
                $expiry_class = $days_left <= 3 ? 'warning' : 'info';
            } else {
                $expiry_label = esc_html__( 'No expiry', 'ultraguard-security-suite' );
                $expiry_class = 'success';
            }

            return [
                'id'          => 'ug-patch-row-' . $p['id'],
                'cve_id'      => esc_html( $p['cve_id']         ?? '—' ),
                'component'   => esc_html( $p['component_slug'] ?? '—' ),
                'versions'    => esc_html( $p['component_version_range'] ?? '—' ),
                'waf_rule_id' => esc_html( (string) ( $p['waf_rule_id'] ?? '—' ) ),
                'applied_at'  => esc_html( $this->format_date_time( $p['applied_at'] ?? '' ) ),
                'expiry'      => [ 'content' => esc_html( $expiry_label ), 'class' => $expiry_class ],
            ];
        }, $patches );

        return [
            'type'      => 'page',
            'id'        => 'ultraguard-virtual-patches',
            'page_slug' => 'virtual-patches',
            'class'     => 'ultraguard-virtual-patches-page ultraguard-page-no-sidebar',
            'header'    => [
                'title'    => __( 'Virtual Patches', 'ultraguard-security-suite' ),
                'subtitle' => __( 'WAF rules auto-generated for CVEs with no official fix yet. Patches expire automatically when the component is updated.', 'ultraguard-security-suite' ),
                'icon'     => 'dashicons-shield',
                'badge'    => [
                    'text'       => $is_pro
                        /* translators: %d: integer */
                        ? sprintf( __( '%d active', 'ultraguard-security-suite' ), $total )
                        : __( 'Pro', 'ultraguard-security-suite' ),
                    'badge_type' => $is_pro ? ( $total > 0 ? 'info' : 'success' ) : 'warning',
                ],
            ],
            'data' => array_values( array_filter( [
                $preview_mode ? $this->soft_gated_preview_data_notice(
                    __( 'Virtual Patches', 'ultraguard-security-suite' ),
                    __( 'These WAF patch rules are sample protections that show how UltraGuard shields known CVEs before an official fix ships. Upgrade to apply real virtual patches to your site.', 'ultraguard-security-suite' )
                ) : null,

                // ── Teaser for free users — full feature explanation ────────────
                UpgradeManager::should_show_nudge()
                    ? UpgradeManager::teaser_card( 'virtual_patching' )
                    : null,

                // ── How virtual patches work (shown to all users) ──────────────
                [
                    'type'       => 'alert-box',
                    'alert_type' => 'info',
                    'title'      => __( 'How Virtual Patches Work', 'ultraguard-security-suite' ),
                    'message'    => __( 'Each virtual patch inserts a WAF rule that blocks known exploit patterns targeting the vulnerable component. Patches expire after 30 days or are automatically deactivated once you install the official fix.', 'ultraguard-security-suite' ),
                ],

                // ── Stat cards ─────────────────────────────────────────────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 6, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Active Patches',   'ultraguard-security-suite' ), 'value' => $total, 'icon' => 'dashicons-shield',  'class' => $total > 0 ? 'info' : 'success' ] ],
                        [ 'span' => 6, 'component' => [ 'type' => 'stat-card', 'title' => __( 'WAF Rules Active', 'ultraguard-security-suite' ), 'value' => $total, 'icon' => 'dashicons-filter',  'class' => 'secondary' ] ],
                    ],
                ],

                // ── Patches table (visible to all; free users see empty state) ─
                [
                    'type'  => 'card',
                    'title' => __( 'Active Virtual Patches', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-shield',
                    'data'  => [ [
                        'type'       => 'data-table',
                        'id'         => 'virtual-patches-table',
                        'columns'    => [
                            'cve_id'      => [ 'title' => __( 'CVE',        'ultraguard-security-suite' ), 'sortable' => true ],
                            'component'   => [ 'title' => __( 'Component',  'ultraguard-security-suite' ), 'sortable' => true ],
                            'versions'    => [ 'title' => __( 'Versions',   'ultraguard-security-suite' ) ],
                            'waf_rule_id' => [ 'title' => __( 'WAF Rule #', 'ultraguard-security-suite' ) ],
                            'applied_at'  => [ 'title' => __( 'Applied',    'ultraguard-security-suite' ), 'sortable' => true ],
                            'expiry'      => [ 'title' => __( 'Expires In', 'ultraguard-security-suite' ), 'sortable' => true ],
                        ],
                        'data'        => $rows,
                        'searchable'  => true,
                        'pagination'  => [ 'enabled' => count( $rows ) > 25, 'page_size' => 25 ],
                        'empty_state' => [
                            'title'       => __( 'No active virtual patches', 'ultraguard-security-suite' ),
                            'description' => $is_pro
                                ? __( 'Virtual patches are applied automatically for high/critical CVEs with no fix. You can also apply them manually from the Vulnerability Results page.', 'ultraguard-security-suite' )
                                : __( 'Upgrade to Pro to enable virtual patching — WAF rules that block CVE exploits before an official fix is available.', 'ultraguard-security-suite' ),
                        ],
                    ] ],
                ],

            ] ) ),
        ];
    }

    private function preview_patches(): array {
        return [
            [
                'id'                      => 81,
                'cve_id'                  => 'CVE-2026-1188',
                'component_slug'          => 'elementor',
                'component_version_range' => '<= 3.25.1',
                'waf_rule_id'             => 'VP-1134',
                'applied_at'              => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 2 ),
                'expires_at'              => gmdate( 'Y-m-d H:i:s', time() + DAY_IN_SECONDS * 12 ),
            ],
            [
                'id'                      => 82,
                'cve_id'                  => 'CVE-2026-0774',
                'component_slug'          => 'woocommerce-payments',
                'component_version_range' => '<= 8.4.0',
                'waf_rule_id'             => 'VP-1139',
                'applied_at'              => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 5 ),
                'expires_at'              => gmdate( 'Y-m-d H:i:s', time() + DAY_IN_SECONDS * 4 ),
            ],
        ];
    }
}
