<?php
/**
 * DatabaseScannerDashboard — Rich admin page for the Database Scanner module.
 *
 * Free-user philosophy: full UI visible with inline_hint() nudge. Action
 * buttons and settings are gated behind $is_pro. AJAX handlers use
 * UpgradeManager::soft_gate_response() instead of hard 403s.
 *
 * @package UltraguardPro\modules\database_scanner\pages
 */

namespace UltraguardPro\modules\database_scanner\pages;

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

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

class DatabaseScannerDashboard extends BasePage {

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

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

        $table   = $this->plugin->modules->get_db_tables()->get_table( 'db_scan_results' );
        $summary = $preview_mode
            ? [ 'total' => 16, 'pending' => 7, 'cleaned' => 6, 'ignored' => 3, 'critical' => 2, 'high' => 3, 'medium' => 1, 'low' => 1 ]
            : ( $table ? $table->get_summary() : [
                'total' => 0, 'pending' => 0, 'cleaned' => 0, 'ignored' => 0, 'critical' => 0, 'high' => 0,
            ] );

        // ── Chart data ────────────────────────────────────────────────────────
        // Threats grouped by type (spam_links / pharma_hack / eval_injection / etc.)
        $threat_type_chart = $preview_mode
            ? [ 'labels' => [ 'spam_links', 'pharma_hack', 'eval_injection' ], 'data' => [ 3, 2, 2 ], 'colors' => [ '#dc2626', '#f97316', '#155eef' ] ]
            : ( $table
                ? $table->get_pie_chart_data( 'threat_type', 'id', 'COUNT', [ 'status' => 'pending' ], 8 )
                : [ 'labels' => [], 'data' => [], 'colors' => [] ] );

        // Threats grouped by severity level
        $severity_chart = [
            'labels' => [ __( 'Critical', 'ultraguard-security-suite' ), __( 'High', 'ultraguard-security-suite' ), __( 'Medium', 'ultraguard-security-suite' ), __( 'Low', 'ultraguard-security-suite' ) ],
            'data'   => [
                (int) $summary['critical'],
                (int) $summary['high'],
                (int) ( $summary['medium'] ?? 0 ),
                (int) ( $summary['low'] ?? 0 ),
            ],
            'colors' => [ '#dc2626', '#f97316', '#eab308', '#22c55e' ],
        ];

        // DB table distribution (which tables have findings)
        $table_dist_chart = $preview_mode
            ? [ 'labels' => [ 'wp_posts', 'wp_options', 'wp_postmeta' ], 'data' => [ 4, 2, 1 ], 'colors' => [ '#dc2626', '#f97316', '#22c55e' ] ]
            : ( $table
                ? $table->get_pie_chart_data( 'db_table', 'id', 'COUNT', [ 'status' => 'pending' ], 8 )
                : [ 'labels' => [], 'data' => [], 'colors' => [] ] );

        // ── Scan status transient ──────────────────────────────────────────────
        $scan_status = get_transient( 'ultraguard_db_scan_status' ) ?: [
            'status' => 'idle', 'progress' => 0, 'scan_id' => '',
        ];

        // Stale-check on render
        $is_running = in_array( $scan_status['status'] ?? '', [ 'running', 'queued' ], true );
        if ( $is_running ) {
            $started = isset( $scan_status['started'] ) ? strtotime( $scan_status['started'] ) : 0;
            $elapsed = $started ? ( time() - $started ) : 9999;
            if ( ( $elapsed > 600 && (int) ( $scan_status['progress'] ?? 0 ) <= 5 ) || $elapsed > 1200 ) {
                $is_running = false;
            }
        }

        // ── Results rows (read-only, visible to all users) ─────────────────────
        $items = $preview_mode
            ? [ 'records' => $this->preview_results() ]
            : ( $table
                ? $table->paginate( 1, 100, [ 'status' => 'pending' ], 'threat_level', 'DESC' )
                : [ 'records' => [] ] );

        $rows = array_map( function ( $r ) use ( $nonce, $is_pro ) {
            $r           = (array) $r;
            $id          = (int) ( $r['id'] ?? 0 );
            $status      = $r['status'] ?? '';
            $level_class = match ( $r['threat_level'] ?? '' ) {
                'critical' => 'danger', 'high' => 'warning', 'medium' => 'info', default => 'secondary',
            };

            // ── View modal ─────────────────────────────────────────────────────
            $view_modal = [
                'id'      => 'dbs-view-result-' . $id,
                /* translators: %1$d: integer, %2$s: string */
                'title'   => sprintf( __( 'DB Threat #%1$d — %2$s', 'ultraguard-security-suite' ), $id, esc_html( $r['db_table'] ?? '' ) ),
                'size'    => 'medium',
                'content' => $this->modal_content( [
                    [ 'type' => 'text',     'name' => 'vdr_tbl',  'label' => __( 'DB Table',        'ultraguard-security-suite' ), 'value' => esc_html( $r['db_table']        ?? '' ),                                'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vdr_col',  'label' => __( 'Column',          'ultraguard-security-suite' ), 'value' => esc_html( $r['column_name']     ?? '' ),                                'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vdr_row',  'label' => __( 'Row ID',          'ultraguard-security-suite' ), 'value' => (string) (int) ( $r['row_id']   ?? 0 ),                                 'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vdr_type', 'label' => __( 'Threat Type',     'ultraguard-security-suite' ), 'value' => esc_html( str_replace( '_', ' ', ucfirst( $r['threat_type'] ?? '' ) ) ), 'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vdr_lvl',  'label' => __( 'Severity',        'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $r['threat_level'] ?? '' ) ),                         'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vdr_sts',  'label' => __( 'Status',          'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $status ) ),                                          'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vdr_scan', 'label' => __( 'Scan ID',         'ultraguard-security-suite' ), 'value' => esc_html( $r['scan_id']         ?? '' ),                                'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vdr_dt',   'label' => __( 'Detected',        'ultraguard-security-suite' ), 'value' => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),          'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'vdr_cln',  'label' => __( 'Cleaned At',      'ultraguard-security-suite' ), 'value' => $r['cleaned_at'] ? esc_html( $this->format_date_time( $r['cleaned_at'] ) ) : __( '—', 'ultraguard-security-suite' ), 'readonly' => true ],
                    [ 'type' => 'textarea', 'name' => 'vdr_ptn',  'label' => __( 'Matched Pattern', 'ultraguard-security-suite' ), 'value' => esc_html( $r['matched_pattern'] ?? '—' ), 'rows' => 3,                  'readonly' => true ],
                    [ 'type' => 'textarea', 'name' => 'vdr_exc',  'label' => __( 'Content Excerpt', 'ultraguard-security-suite' ), 'value' => esc_html( $r['content_excerpt'] ?? '—' ), 'rows' => 4,                  'readonly' => true ],
                ] ),
            ];

            // ── Action buttons ─────────────────────────────────────────────────
            $btns = [
                [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-visibility',
                    'button_style' => 'secondary',
                    'title'        => __( 'View full details', 'ultraguard-security-suite' ),
                    'modal'        => $view_modal,
                ],
            ];

            if ( $status === 'pending' ) {
                $btns[] = [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-shield-alt',
                    'button_style' => 'primary',
                    'title'        => __( 'Clean injection', 'ultraguard-security-suite' ),
                    'ajax'         => [
                        'action'  => 'ultraguard_db_scanner_clean_injection',
                        'nonce'   => $nonce,
                        'data'    => [ 'result_id' => $id, 'clean_value' => '' ],
                        'confirm' => __( 'Remove this injection from the database?', 'ultraguard-security-suite' ),
                    ],
                ];
            }

            if ( $status === 'pending' ) {
                $btns[] = [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-hidden',
                    'button_style' => 'secondary',
                    'title'        => __( 'Mark as false positive', 'ultraguard-security-suite' ),
                    'ajax'         => [
                        'action'  => 'ultraguard_db_scanner_ignore_result',
                        'nonce'   => $nonce,
                        'data'    => [ 'result_id' => $id ],
                        'confirm' => __( 'Mark as false positive and hide from results?', 'ultraguard-security-suite' ),
                    ],
                ];
            }

            $btns[] = [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-trash',
                'button_style' => 'danger',
                'title'        => __( 'Delete result', 'ultraguard-security-suite' ),
                'ajax'         => [
                    'action'  => 'ultraguard_db_scanner_delete_result',
                    'nonce'   => $nonce,
                    'data'    => [ 'result_id' => $id ],
                    'confirm' => __( 'Delete this scan result log entry?', 'ultraguard-security-suite' ),
                ],
            ];

            return [
                'id'          => 'ug-db-row-' . $id,
                'db_table'    => esc_html( $r['db_table']    ?? '' ),
                'column'      => esc_html( $r['column_name'] ?? '' ),
                'row_id'      => esc_html( (string) ( $r['row_id'] ?? '' ) ),
                'threat_type' => esc_html( str_replace( '_', ' ', ucfirst( $r['threat_type'] ?? '' ) ) ),
                'severity'    => [ 'content' => esc_html( ucfirst( $r['threat_level'] ?? '' ) ), 'class' => $level_class ],
                'excerpt'     => wp_kses_post( mb_substr( $r['content_excerpt'] ?? '', 0, 120 ) . '…' ),
                'status'      => [ 'content' => esc_html( ucfirst( $status ) ), 'class' => 'secondary' ],
                'found_at'    => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),
                'actions'     => $this->row_actions( $btns ),
            ];
        }, $items['records'] ?? [] );

        $settings = $this->plugin->settings->get_module_settings( 'database_scanner' );

        return [
            'type'      => 'page',
            'id'        => 'ultraguard-db-scanner',
            'page_slug' => 'database-scanner',
            'class'     => 'ultraguard-db-scanner-page ultraguard-page-no-sidebar',
            'header'    => [
                'title'    => __( 'Database Scanner', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Scan WordPress database tables for injected malicious content, SEO spam, and hidden backdoors.', 'ultraguard-security-suite' ),
                'icon'     => 'dashicons-database',
                'badge'    => [
                    'text'       => $is_pro
                        /* translators: %d: integer */
                        ? sprintf( __( '%d threats', 'ultraguard-security-suite' ), (int) $summary['pending'] )
                        : __( 'Pro', 'ultraguard-security-suite' ),
                    'badge_type' => $is_pro
                        ? ( $summary['pending'] > 0 ? 'danger' : 'success' )
                        : 'warning',
                ],
                // BUG FIX: ternary now has proper else branch
                'actions'  => ! $is_running ? [
                    $this->create_ajax_button(
                        __( 'Scan Database', 'ultraguard-security-suite' ),
                        'ultraguard_db_scanner_start_scan', [],
                        'primary', 'dashicons-search',
                        __( 'Start a full database scan? This may take a moment on large sites.', 'ultraguard-security-suite' )
                    ),
                    $this->create_ajax_button(
                        __( 'Export CSV', 'ultraguard-security-suite' ),
                        'ultraguard_db_scanner_export_results', [],
                        'secondary', 'dashicons-download'
                    ),
                ] : [],
            ],

            // ── Page-level form — only shown to Pro users ──────────────────────
            'form' => [
                'enable' => true,
                'id'     => 'db-scanner-settings-form',
                'ajax'   => true,
                'action' => 'ultraguard_save_db_scanner_settings',
                'nonce'  => $nonce,
                'submit' => [
                    'text'         => __( 'Save Settings', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                ],
            ],

            'data' => array_values( array_filter( [
                $preview_mode ? $this->soft_gated_preview_data_notice(
                    __( 'Database Scanner', 'ultraguard-security-suite' ),
                    __( 'These malicious SQL findings, table hotspots, and cleanup actions are sample database-scan results. Upgrade to scan your live WordPress tables and remediate real injections safely.', 'ultraguard-security-suite' )
                ) : null,

                // ── Soft nudge for free users (non-blocking) ───────────────────
                UpgradeManager::should_show_nudge()
                    ? UpgradeManager::inline_hint(
                        'database_scan',
                        __( 'Scan your WordPress database to detect injected malware, SEO spam, and hidden backdoors — then remove them with one click.', 'ultraguard-security-suite' )
                    )
                    : null,

                // ── Live scan panel — rendered via RenderEngine ────────────────
                $this->build_db_scan_panel_scheme( $scan_status, $is_running, $is_pro, $nonce ),

                // ── Stat cards ─────────────────────────────────────────────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total',    'ultraguard-security-suite' ), 'value' => $summary['total'],    'icon' => 'dashicons-database', 'class' => 'info' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Pending',  'ultraguard-security-suite' ), 'value' => $summary['pending'],  'icon' => 'dashicons-flag',     'class' => $summary['pending']  > 0 ? 'warning' : 'success' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Critical', 'ultraguard-security-suite' ), 'value' => $summary['critical'], 'icon' => 'dashicons-warning',  'class' => $summary['critical'] > 0 ? 'danger'  : 'success' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'High',     'ultraguard-security-suite' ), 'value' => $summary['high'],     'icon' => 'dashicons-shield',   'class' => $summary['high']     > 0 ? 'warning' : 'success' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Cleaned',  'ultraguard-security-suite' ), 'value' => $summary['cleaned'],  'icon' => 'dashicons-yes-alt',  'class' => 'success' ] ],
                        [ 'span' => 2, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Ignored',  'ultraguard-security-suite' ), 'value' => $summary['ignored'],  'icon' => 'dashicons-hidden',   'class' => 'secondary' ] ],
                    ],
                ],

                // ── Teaser card for free users ─────────────────────────────────
                UpgradeManager::should_show_nudge()
                    ? UpgradeManager::teaser_card( 'database_scan' )
                    : null,

                // ── Charts: Threat types (doughnut) + Severity (bar) ──────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 5,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Threat Types Found', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-pie',
                                'data'  => empty( $threat_type_chart['data'] ) ? [
                                    [ 'type' => 'paragraph', 'content' => __( 'No pending threats. Run a scan to populate this chart.', 'ultraguard-security-suite' ) ],
                                ] : [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'doughnut',
                                        'height'         => '230px',
                                        'labels'         => $threat_type_chart['labels'],
                                        'datasets'       => [
                                            [
                                                'data'            => $threat_type_chart['data'],
                                                'backgroundColor' => $threat_type_chart['colors'],
                                                'borderWidth'     => 2,
                                            ],
                                        ],
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Threats by Severity', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-bar',
                                'data'  => array_sum( $severity_chart['data'] ) === 0 ? [
                                    [ 'type' => 'paragraph', 'content' => __( 'No severity data yet.', 'ultraguard-security-suite' ) ],
                                ] : [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'bar',
                                        'height'         => '230px',
                                        'labels'         => $severity_chart['labels'],
                                        'datasets'       => [
                                            [
                                                'label'           => __( 'Threats', 'ultraguard-security-suite' ),
                                                'data'            => $severity_chart['data'],
                                                'backgroundColor' => $severity_chart['colors'],
                                                'borderWidth'     => 1,
                                            ],
                                        ],
                                        'x_axis_title'   => __( 'Severity', 'ultraguard-security-suite' ),
                                        'y_axis_title'   => __( 'Count', 'ultraguard-security-suite' ),
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                        [
                            'span'      => 3,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Affected Tables', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-database',
                                'data'  => empty( $table_dist_chart['data'] ) ? [
                                    [ 'type' => 'paragraph', 'content' => __( 'No table data yet.', 'ultraguard-security-suite' ) ],
                                ] : [
                                    [
                                        'type'           => 'chart',
                                        'chart_type'     => 'pie',
                                        'height'         => '230px',
                                        'labels'         => $table_dist_chart['labels'],
                                        'datasets'       => [
                                            [
                                                'data'            => $table_dist_chart['data'],
                                                'backgroundColor' => $table_dist_chart['colors'],
                                                'borderWidth'     => 2,
                                            ],
                                        ],
                                        'security_theme' => true,
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Database Scan Results', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-warning',
                    'data'  => [ [
                        'type'       => 'data-table',
                        'id'         => 'db-scan-results-table',
                        'columns'    => [
                            'db_table'    => [ 'title' => __( 'Table',    'ultraguard-security-suite' ), 'sortable' => true ],
                            'column'      => [ 'title' => __( 'Column',   'ultraguard-security-suite' ) ],
                            'row_id'      => [ 'title' => __( 'Row ID',   'ultraguard-security-suite' ) ],
                            'threat_type' => [ 'title' => __( 'Threat',   'ultraguard-security-suite' ), 'sortable' => true ],
                            'severity'    => [ 'title' => __( 'Severity', 'ultraguard-security-suite' ), 'sortable' => true ],
                            'excerpt'     => [ 'title' => __( 'Excerpt',  'ultraguard-security-suite' ) ],
                            'status'      => [ 'title' => __( 'Status',   'ultraguard-security-suite' ) ],
                            'found_at'    => [ 'title' => __( 'Found',    'ultraguard-security-suite' ), 'sortable' => true ],
                            'actions'     => [ 'title' => __( 'Actions',  'ultraguard-security-suite' ), 'width' => '130px' ],
                        ],
                        'data'        => $rows,
                        'searchable'  => true,
                        'pagination'  => [ 'enabled' => count( $rows ) > 25, 'page_size' => 25 ],
                        'empty_state' => [
                            'title'       => __( 'No threats found', 'ultraguard-security-suite' ),
                            'description' => $is_pro
                                ? __( 'No database injections detected. Run a scan to check your database.', 'ultraguard-security-suite' )
                                : __( 'Upgrade to Pro and run your first scan to see results here.', 'ultraguard-security-suite' ),
                        ],
                    ] ],
                ],

                // ── Settings — Pro users only ──────────────────────────────────
                [
                    'type'  => 'card',
                    'title' => __( 'Scanner Settings', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-admin-settings',
                    'data'  => array_values( array_filter( [
                        ! $is_pro ? [
                            'type'       => 'paragraph',
                            'class'      => 'ug-upgrade-preview-hint',
                            'content'    => __( 'Preview mode: scheduled scans become available after upgrading to Pro.', 'ultraguard-security-suite' ),
                        ] : null,
                        [
                            'type'        => 'toggle',
                            'name'        => 'database_scanner_scheduled',
                            'label'       => __( 'Scheduled Daily Scan', 'ultraguard-security-suite' ),
                            'description' => __( "Automatically run a database scan as part of UltraGuard's daily cron sweep.", 'ultraguard-security-suite' ),
                            'default'     => (bool) ( $settings['database_scanner_scheduled'] ?? false ),
                        ],
                    ] ) ),
                ],

            ] ) ),
        ];
    }

    // ── Scan panel scheme ──────────────────────────────────────────────────────

    /**
     * Build the DB scanner status card as a pure RenderEngine scheme.
     *
     * Replaces the former ob_start() / ob_get_clean() HTML template with:
     *   • 'progress'      — WidgetRenderer::render_progress()  (animated bar)
     *   • 'list'          — WidgetRenderer::render_list()       (per-table phase rows)
     *   • 'button-group'  — ActionRenderer                      (Scan / Stop buttons)
     *
     * The Pro gate is expressed by conditionally including or omitting children
     * from the 'data' array, keeping logic in PHP rather than mixed into HTML.
     */
    private function build_db_scan_panel_scheme(
        array  $scan,
        bool   $running,
        bool   $is_pro,
        string $nonce
    ): array {
        $progress = (int) ( $scan['progress'] ?? 0 );
        $scan_id  = esc_attr( $scan['scan_id'] ?? '' );
        $status   = $scan['status'] ?? 'idle';

        $data = [];

        $phase = (string) ( $scan['phase'] ?? '' );

        $data[] = [
            'type'          => 'progress',
            'id'            => 'db-scan-progress-bar',
            'class'         => $running ? '' : 'ultraguard-hidden',
            'value'         => $progress,
            'max'           => 100,
            'progress_type' => 'bar',
            'status'        => $running ? 'primary' : 'secondary',
            'animated'      => $running,
            'striped'       => $running,
            'label'         => $running
                /* translators: %d: integer */
                ? sprintf( __( 'Scanning… %d%%', 'ultraguard-security-suite' ), $progress )
                : __( 'Scanning… 0%', 'ultraguard-security-suite' ),
            'show_value'    => true,
        ];

        $data[] = [
            'type'       => 'paragraph',
            'id'         => 'db-scan-phase',
            'class'      => $running ? 'ug-db-scan-phase' : 'ug-db-scan-phase ultraguard-hidden',
            'content'    => $phase !== '' ? esc_html( $phase ) : __( 'Preparing scan…', 'ultraguard-security-suite' ),
            'attributes' => [ 'data-db-phase' => '1' ],
        ];

        $data[] = [
            'type'       => 'alert-box',
            'id'         => 'db-scan-error-box',
            'class'      => $status === 'error' ? '' : 'ultraguard-hidden',
            'alert_type' => 'danger',
            'icon'       => 'dashicons-warning',
            'message'    => esc_html( (string) ( $scan['error'] ?? '' ) ),
        ];

        // ── Stats table (shown when pro) ──────────────────────────────────────
        if ( $is_pro ) {
            $threats_found  = (int) ( $scan['threats_found'] ?? 0 );
            $total_checked  = (int) ( $scan['total_checked'] ?? 0 );

            $data[] = [
                'type'  => 'list',
                'id'    => 'db-scan-live-stats',
                'class' => 'ug-db-scan-stats',
                'items' => [
                    [
                        'icon'  => 'dashicons-database',
                        'text'  => __( 'Rows Checked', 'ultraguard-security-suite' ),
                        'badge' => [
                            'text'       => number_format_i18n( $total_checked ),
                            'badge_type' => 'info',
                        ],
                    ],
                    [
                        'icon'  => 'dashicons-warning',
                        'text'  => __( 'Threats Found', 'ultraguard-security-suite' ),
                        'badge' => [
                            'text'       => number_format_i18n( $threats_found ),
                            'badge_type' => $threats_found > 0 ? 'danger' : 'success',
                        ],
                    ],
                    [
                        'icon'  => 'dashicons-admin-post',
                        'text'  => __( 'Posts / Pages', 'ultraguard-security-suite' ),
                        'badge' => [
                            'text'       => __( 'Pending', 'ultraguard-security-suite' ),
                            'badge_type' => 'secondary',
                        ],
                    ],
                    [
                        'icon'  => 'dashicons-admin-settings',
                        'text'  => __( 'Site Options', 'ultraguard-security-suite' ),
                        'badge' => [
                            'text'       => __( 'Pending', 'ultraguard-security-suite' ),
                            'badge_type' => 'secondary',
                        ],
                    ],
                    [
                        'icon'  => 'dashicons-admin-users',
                        'text'  => __( 'User Records', 'ultraguard-security-suite' ),
                        'badge' => [
                            'text'       => __( 'Pending', 'ultraguard-security-suite' ),
                            'badge_type' => 'secondary',
                        ],
                    ],
                    [
                        'icon'  => 'dashicons-id-alt',
                        'text'  => __( 'User Metadata', 'ultraguard-security-suite' ),
                        'badge' => [
                            'text'       => __( 'Pending', 'ultraguard-security-suite' ),
                            'badge_type' => 'secondary',
                        ],
                    ],
                ],
            ];

            $data[] = [
                'type'       => 'alert-box',
                'id'         => 'db-scan-complete-summary',
                'class'      => $status === 'complete' ? '' : 'ultraguard-hidden',
                'alert_type' => 'success',
                'icon'       => 'dashicons-yes-alt',
                'message'    => sprintf(
                    /* translators: Placeholder values are inserted into this string. */
                    __( 'Scan complete. %d threats found.', 'ultraguard-security-suite' ),
                    (int) ( $scan['threats_found'] ?? 0 )
                ),
            ];
            $data[] = [
                'type'    => 'paragraph',
                'id'      => 'db-scan-complete-detail',
                'class'   => $status === 'complete' ? 'ug-complete-detail' : 'ug-complete-detail ultraguard-hidden',
                'content' => esc_html(
                    sprintf(
                        /* translators: Placeholder values are inserted into this string. */
                        __( '%d threats found.', 'ultraguard-security-suite' ),
                        (int) ( $scan['threats_found'] ?? 0 )
                    )
                ),
            ];
        }

        // ── Action buttons ────────────────────────────────────────────────────
        $buttons = [];
        if ( $is_pro ) {
            if ( $running ) {
                $buttons[] = [
                    'type'         => 'button',
                    'text'         => __( 'Stop', 'ultraguard-security-suite' ),
                    'button_style' => 'secondary',
                    'icon'         => 'dashicons-no-alt',
                    'id'           => 'ug-db-stop-btn',
                    'attributes'   => [ 'data-rt' => 'db-stop-btn' ],
                    'ajax'         => [
                        'action' => 'ultraguard_db_scanner_stop_scan',
                        'nonce'  => $nonce,
                        'data'   => [ 'scan_id' => $scan_id ],
                    ],
                ];
            } else {
                $buttons[] = [
                    'type'         => 'button',
                    'text'         => __( 'Scan Database', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                    'icon'         => 'dashicons-search',
                    'id'           => 'ug-db-scan-btn',
                    'attributes'   => [ 'data-rt' => 'db-scan-btn' ],
                    'ajax'         => [
                        'action'  => 'ultraguard_db_scanner_start_scan',
                        'nonce'   => $nonce,
                        'confirm' => __( 'Start a full database scan? This may take a moment on large sites.', 'ultraguard-security-suite' ),
                    ],
                ];
            }
        } else {
            // Free user — keep the action visible and let AJAX return the upgrade gate.
            $buttons[] = [
                'type'         => 'button',
                'text'         => __( 'Scan Database', 'ultraguard-security-suite' ),
                'button_style' => 'primary',
                'icon'         => 'dashicons-search',
                'id'           => 'ug-db-scan-btn',
                'attributes'   => [ 'data-rt' => 'db-scan-btn' ],
                'ajax'         => [
                    'action'  => 'ultraguard_db_scanner_start_scan',
                    'nonce'   => $nonce,
                    'confirm' => __( 'Start a full database scan? This may take a moment on large sites.', 'ultraguard-security-suite' ),
                ],
            ];
        }

        $data[] = [
            'type'      => 'button-group',
            'alignment' => 'left',
            'id'        => 'ug-db-scan-actions',
            'buttons'   => $buttons,
        ];

        return [
            'type'       => 'card',
            'id'         => 'ug-db-scan-panel',
            'title'      => __( 'Scan Status', 'ultraguard-security-suite' ),
            'icon'       => 'dashicons-database',
            'badge'      => [
                'text'       => $running ? __( 'Running', 'ultraguard-security-suite' ) : ucfirst( $status ),
                'badge_type' => $running ? 'warning' : ( $status === 'error' ? 'danger' : 'info' ),
            ],
            'attributes' => [
                'data-scan-id'    => $scan_id,
                'data-nonce'      => $nonce,
                'data-running'    => $running ? '1' : '0',
                'data-poll-action'=> 'ultraguard_db_scanner_scan_status',
                'data-stop-action'=> 'ultraguard_db_scanner_stop_scan',
            ],
            'data' => $data,
        ];
    }

    private function preview_results(): array {
        return [
            [
                'id'              => 301,
                'db_table'        => 'wp_posts',
                'column_name'     => 'post_content',
                'row_id'          => 928,
                'threat_type'     => 'spam_links',
                'threat_level'    => 'critical',
                'content_excerpt' => '<a href="https://malicious-example.tld">Cheap meds</a>',
                'matched_pattern' => 'Injected anchor farm',
                'status'          => 'pending',
                'created_at'      => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS ),
                'cleaned_at'      => '',
            ],
            [
                'id'              => 302,
                'db_table'        => 'wp_options',
                'column_name'     => 'option_value',
                'row_id'          => 144,
                'threat_type'     => 'eval_injection',
                'threat_level'    => 'high',
                'content_excerpt' => 'eval(base64_decode(...))',
                'matched_pattern' => 'Obfuscated PHP payload',
                'status'          => 'pending',
                'created_at'      => gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 2 ),
                'cleaned_at'      => '',
            ],
        ];
    }
}
