<?php
/**
 * AntivirusFileScanner — File scanner page with full scan control UI.
 * @package UltraguardPro\modules\antivirus\pages
 */
namespace UltraguardPro\modules\antivirus\pages;
use UltraguardPro\Plugin;
use UltraguardPro\modules\antivirus\AntivirusEngine;
use UltraguardPro\modules\core\BasePage;
if ( ! defined( 'ABSPATH' ) ) { exit; }

class AntivirusFileScanner extends BasePage {

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

    /**
     * @param  array<string,mixed> $r
     * @return array<string,string>
     */
    private function detection_view_data( array $r ): array {
        $meta = AntivirusEngine::get_detection_metadata( $r );

        return [
            'details'       => $meta['details_text'],
            'match_label'   => $meta['match_label'] ?: __( 'Exact Match', 'ultraguard-security-suite' ),
            'matched_code'  => $meta['matched_code'] ?: __( 'No exact code match could be reconstructed for this detection.', 'ultraguard-security-suite' ),
            'match_context' => $meta['match_context'],
        ];
    }

    /**
     * @param  array<string,mixed> $r
     * @return array<int,array<string,mixed>>
     */
    private function detection_modal_footer( array $r ): array {
        $id       = (int) ( $r['id'] ?? 0 );
        $modal_id = 'fs-view-result-' . $id;
        $buttons  = [];

        if ( ( $r['status'] ?? '' ) === 'infected' ) {
            $buttons[] = $this->create_ajax_button(
                __( 'Quarantine', 'ultraguard-security-suite' ),
                'ultraguard_antivirus_quarantine_file',
                [ 'result_id' => $id, 'modal_id' => $modal_id ],
                'warning',
                'dashicons-lock',
                __( 'Move this file to quarantine?', 'ultraguard-security-suite' )
            );
            $buttons[] = $this->create_ajax_button(
                __( 'Mark False Positive', 'ultraguard-security-suite' ),
                'ultraguard_antivirus_mark_false_positive',
                [ 'result_id' => $id, 'modal_id' => $modal_id ],
                'secondary',
                'dashicons-yes-alt',
                __( 'Mark this detection as a false positive?', 'ultraguard-security-suite' )
            );
        }

        $buttons[] = $this->create_ajax_button(
            __( 'Delete Result', 'ultraguard-security-suite' ),
            'ultraguard_antivirus_delete_scan_result',
            [ 'result_id' => $id, 'modal_id' => $modal_id ],
            'danger',
            'dashicons-trash',
            __( 'Delete this scan result log entry?', 'ultraguard-security-suite' )
        );

        return [ [
            'type'      => 'button-group',
            'alignment' => 'right',
            'size'      => 'medium',
            'buttons'   => $buttons,
        ] ];
    }

    /**
     * Render a read-only code block inside the modal body.
     *
     * @param string $label
     * @param string $content
     * @return array<string,mixed>
     */
    private function modal_code_block( string $label, string $content ): array {
        $display = trim( $content ) !== '' ? $content : '—';

        return [
            'type'    => 'html',
            'content' => sprintf(
                '<div><p><strong>%s</strong></p><pre><code>%s</code></pre></div>',
                esc_html( $label ),
                esc_html( $display )
            ),
        ];
    }

    public function get_scheme( $context ): array {
        $nonce       = $this->create_nonce( 'ultraguard_admin_nonce' );
        $scan_t      = $this->plugin->modules->get_db_tables()->get_table( 'scan_results' );
        $total_files = $scan_t ? $scan_t->count() : 0;
        $threats     = $scan_t ? $scan_t->count( [ 'status' => 'infected' ] ) : 0;
        $clean       = $scan_t ? $scan_t->count( [ 'status' => 'clean' ] ) : 0;
        $quarantined = $scan_t ? $scan_t->count( [ 'status' => 'quarantined' ] ) : 0;
        $active_scan = get_option( 'ultraguard_active_scan', [] );
        // Treat stale scans as idle in the initial page render.
        // JS will confirm via AJAX and cancel them server-side on first poll.
        if ( ( $active_scan['status'] ?? '' ) === 'running' ) {
            $started = isset( $active_scan['started_at'] )
                ? strtotime( $active_scan['started_at'] ) : 0;
            $elapsed = $started ? ( time() - $started ) : 9999;
            $prog    = (int) ( $active_scan['progress'] ?? 0 );
            if ( ( $elapsed > 600 && $prog <= 5 ) || $elapsed > 1200 ) {
                $active_scan['status'] = 'cancelled'; // treat as idle for render
            }
        }
        $is_running  = ( $active_scan['status'] ?? '' ) === 'running';

        // Build results rows
        $infected_rows = $scan_t ? $scan_t->get_by( [ 'status' => 'infected' ], 100, 'created_at', 'DESC' ) : [];
        $result_rows   = array_map( function( $r ) use ( $nonce ) {
            $id          = (int) ( $r['id'] ?? 0 );
            $level_class = match ( $r['threat_level'] ?? '' ) { 'critical' => 'danger', 'high' => 'warning', 'medium' => 'warning', default => 'info' };
            $view        = $this->detection_view_data( $r );

            // View modal: full details read-only
            $view_modal = [
                'id'      => 'fs-view-result-' . $id,
                /* translators: %s: string */
                'title'   => sprintf( __( 'Scan Result: %s', 'ultraguard-security-suite' ), esc_html( basename( $r['file_path'] ?? '' ) ) ),
                'size'    => 'large',
                'content' => $this->modal_content( [
                    [ 'type' => 'text',     'name' => 'fvr_file',    'label' => __( 'File Path',    'ultraguard-security-suite' ), 'value' => esc_html( $r['file_path']    ?? '' ),                           'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'fvr_threat',  'label' => __( 'Threat Type',  'ultraguard-security-suite' ), 'value' => esc_html( $r['threat_type']  ?? '—' ),                          'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'fvr_level',   'label' => __( 'Threat Level', 'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $r['threat_level'] ?? 'none' ) ),             'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'fvr_status',  'label' => __( 'Status',       'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $r['status']       ?? '' ) ),                 'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'fvr_size',    'label' => __( 'File Size',    'ultraguard-security-suite' ), 'value' => esc_html( size_format( (int) ( $r['file_size'] ?? 0 ) ) ),       'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'fvr_hash',    'label' => __( 'File Hash',    'ultraguard-security-suite' ), 'value' => esc_html( $r['file_hash']    ?? '—' ),                           'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'fvr_scan',    'label' => __( 'Scan ID',      'ultraguard-security-suite' ), 'value' => esc_html( $r['scan_id']      ?? '' ),                            'readonly' => true ],
                    [ 'type' => 'text',     'name' => 'fvr_found',   'label' => __( 'Detected',     'ultraguard-security-suite' ), 'value' => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),  'readonly' => true ],
                    [ 'type' => 'textarea', 'name' => 'fvr_details', 'label' => __( 'Details',      'ultraguard-security-suite' ), 'value' => $view['details'], 'rows' => 4, 'readonly' => true ],
                    $this->modal_code_block( $view['match_label'], $view['matched_code'] ),
                    $this->modal_code_block( __( 'Match Context', 'ultraguard-security-suite' ), $view['match_context'] ),
                ] ),
                'footer'  => $this->detection_modal_footer( $r ),
            ];

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

            if ( ( $r['status'] ?? '' ) === 'infected' ) {
                $btns[] = [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-lock',
                    'button_style' => 'warning',
                    'title'        => __( 'Quarantine', 'ultraguard-security-suite' ),
                    'ajax'         => [
                        'action'  => 'ultraguard_antivirus_quarantine_file',
                        'nonce'   => $nonce,
                        'data'    => [ 'result_id' => $id ],
                        'confirm' => __( 'Move this file to quarantine?', 'ultraguard-security-suite' ),
                    ],
                ];
                $btns[] = [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-yes-alt',
                    'button_style' => 'secondary',
                    'title'        => __( 'Mark as false positive', 'ultraguard-security-suite' ),
                    'ajax'         => [
                        'action'  => 'ultraguard_antivirus_mark_false_positive',
                        'nonce'   => $nonce,
                        'data'    => [ 'result_id' => $id ],
                        'confirm' => __( 'Mark this detection as a false positive?', 'ultraguard-security-suite' ),
                    ],
                ];
            }

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

            return [
                'id'          => 'ug-row-' . $id,
                'file'        => esc_html( basename( $r['file_path'] ) ),
                'full_path'   => esc_html( $r['file_path'] ),
                'threat_type' => esc_html( $r['threat_type'] ?? __( 'Unknown', 'ultraguard-security-suite' ) ),
                'severity'    => [ 'content' => ucfirst( $r['threat_level'] ?? 'unknown' ), 'class' => $level_class ],
                'status'      => [ 'content' => ucfirst( $r['status'] ?? 'unknown' ), 'class' => $r['status'] === 'clean' ? 'success' : ( $r['status'] === 'infected' ? 'danger' : 'warning' ) ],
                'size'        => esc_html( size_format( (int) $r['file_size'] ) ),
                'scanned_at'  => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),
                'actions'     => $this->row_actions( $btns ),
            ];
        }, $infected_rows );

        return [
            'type'      => 'page',
            'id'        => 'ultraguard-file-scanner',
            'page_slug' => 'file-scanner',
            'class'     => 'ultraguard-file-scanner-page ultraguard-page-no-sidebar',
            'header'    => [
                'title'    => __( 'File Scanner', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Deep file scanning with heuristic and signature-based detection', 'ultraguard-security-suite' ),
                'icon'     => 'dashicons-search',
                /* translators: %d: integer */
                'badge'    => [ 'text' => $threats > 0 ? sprintf( __( '%d threats', 'ultraguard-security-suite' ), $threats ) : __( 'Clean', 'ultraguard-security-suite' ), 'badge_type' => $threats > 0 ? 'danger' : 'success' ],
                'actions'  => [
                    $this->create_ajax_button( __( 'Quick Scan', 'ultraguard-security-suite' ), 'ultraguard_antivirus_start_scan', [ 'scan_type' => 'quick', 'nonce' => $nonce ], 'primary',   'dashicons-search' ),
                    $this->create_ajax_button( __( 'Full Scan',  'ultraguard-security-suite' ), 'ultraguard_antivirus_start_scan', [ 'scan_type' => 'full',  'nonce' => $nonce ], 'secondary', 'dashicons-shield' ),
                    $this->create_ajax_button( __( 'Export Report', 'ultraguard-security-suite' ), 'ultraguard_antivirus_export_report', [ 'nonce' => $nonce ], 'secondary', 'dashicons-download' ),
                ],
            ],
            'data' => [
                // Stats
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'id' => 'ug-av-file-scanner-total', 'title' => __( 'Total Scanned', 'ultraguard-security-suite' ), 'value' => $total_files,  'icon' => 'dashicons-media-code',  'class' => 'info'    ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'id' => 'ug-av-file-scanner-threats', 'title' => __( 'Threats',       'ultraguard-security-suite' ), 'value' => $threats,       'icon' => 'dashicons-warning',     'class' => $threats > 0 ? 'warning' : 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'id' => 'ug-av-file-scanner-clean', 'title' => __( 'Clean Files',   'ultraguard-security-suite' ), 'value' => $clean,         'icon' => 'dashicons-yes-alt',     'class' => 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'id' => 'ug-av-file-scanner-quarantined', 'title' => __( 'Quarantined',   'ultraguard-security-suite' ), 'value' => $quarantined,   'icon' => 'dashicons-lock',        'class' => 'warning' ] ],
                    ],
                ],

                // Scan status panel — rendered via RenderEngine
                $this->build_scanner_panel_scheme( $active_scan, $is_running, $nonce ),

                // Results table
                [
                    'type'  => 'card',
                    'title' => __( 'Scan Results — Infected Files', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-warning',
                    'actions' => [
                        $this->create_ajax_button( __( 'Clear Clean Results', 'ultraguard-security-suite' ), 'ultraguard_antivirus_clear_results', [], 'secondary', 'dashicons-trash' ),
                    ],
                    'data' => [ [
                        'type'         => 'data-table',
                        'id'           => 'scan-results-table',
                        'columns'      => [
                            'file'        => [ 'title' => __( 'File',      'ultraguard-security-suite' ), 'sortable' => true ],
                            'threat_type' => [ 'title' => __( 'Threat',    'ultraguard-security-suite' ), 'sortable' => true ],
                            'severity'    => [ 'title' => __( 'Severity',  'ultraguard-security-suite' ), 'sortable' => true ],
                            'status'      => [ 'title' => __( 'Status',    'ultraguard-security-suite' ) ],
                            'size'        => [ 'title' => __( 'Size',      'ultraguard-security-suite' ) ],
                            'scanned_at'  => [ 'title' => __( 'Detected',  'ultraguard-security-suite' ), 'sortable' => true ],
                            'actions'     => [ 'title' => __( 'Actions',   'ultraguard-security-suite' ), 'width' => '150px' ],
                        ],
                        'data'         => $result_rows,
                        'searchable'   => true,
                        'search_placeholder' => __( 'Search by file name or threat type…', 'ultraguard-security-suite' ),
                        'pagination'   => [ 'enabled' => count( $result_rows ) > 25, 'page_size' => 25 ],
                        'empty_state'  => [ 'title' => __( 'No infected files found', 'ultraguard-security-suite' ), 'description' => __( 'Run a scan to check your site for malware.', 'ultraguard-security-suite' ) ],
                    ] ],
                ],
            ],
        ];
    }

    /**
     * Build the file scanner status card with table layout.
     */
    private function build_scanner_panel_scheme( array $scan, bool $running, string $nonce ): array {
        $progress  = (int) ( $scan['progress'] ?? 0 );
        $scan_id   = esc_attr( $scan['scan_id'] ?? '' );
        $scan_type = ! empty( $scan['scan_type'] ) ? ucfirst( (string) $scan['scan_type'] ) : '';

        $data = [
            [
                'type'          => 'progress',
                'id'            => 'ug-progress-fill',
                'class'         => $running ? '' : 'ug-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,
            ],
        ];

        if ( $running ) {
            $data[] = [
                'type'  => 'list',
                'class' => 'ug-scan-live-stats',
                'items' => [
                    [
                        'icon'  => 'dashicons-media-code',
                        'text'  => __( 'Files Scanned', 'ultraguard-security-suite' ),
                        'badge' => [
                            'text'       => number_format_i18n( (int) ( $scan['files_scanned'] ?? 0 ) ),
                            'badge_type' => 'info',
                        ],
                    ],
                    [
                        'icon'  => 'dashicons-warning',
                        'text'  => __( 'Threats Found', 'ultraguard-security-suite' ),
                        'badge' => [
                            'text'       => number_format_i18n( (int) ( $scan['threats_found'] ?? 0 ) ),
                            'badge_type' => ( (int) ( $scan['threats_found'] ?? 0 ) > 0 ) ? 'danger' : 'success',
                        ],
                    ],
                ],
            ];

            if ( ! empty( $scan['current_file'] ) ) {
                $data[] = [
                    'type'    => 'paragraph',
                    'class'   => 'ug-scan-current-file',
                    'content' => esc_html( '…' . substr( (string) $scan['current_file'], -60 ) ),
                ];
            }
        } else {
            $data[] = [
                'type'    => 'paragraph',
                'class'   => 'ug-scan-status-note',
                'content' => __( 'No scan in progress.', 'ultraguard-security-suite' ),
            ];
        }

        $buttons = [];
        if ( $running ) {
            $buttons[] = [ 'type' => 'button', 'text' => __( 'Stop', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'icon' => 'dashicons-no-alt', 'id' => 'ug-stop-scan-btn', 'class' => 'ug-stop-scan-btn', 'ajax' => [ 'action' => 'ultraguard_antivirus_stop_scan', 'nonce' => $nonce, 'data' => [ 'scan_id' => $scan_id ] ] ];
        } else {
            $buttons[] = [ 'type' => 'button', 'text' => __( 'Quick Scan', 'ultraguard-security-suite' ), 'button_style' => 'primary',  'icon' => 'dashicons-search', 'class' => 'ultraguard-start-scan-btn', 'attributes' => [ 'data-rt' => 'antivirus-scan-btn' ], 'ajax' => [ 'action' => 'ultraguard_antivirus_start_scan', 'nonce' => $nonce, 'data' => [ 'scan_type' => 'quick' ] ] ];
            $buttons[] = [ 'type' => 'button', 'text' => __( 'Full Scan',  'ultraguard-security-suite' ), 'button_style' => 'secondary', 'icon' => 'dashicons-shield', 'class' => 'ultraguard-start-scan-btn', 'ajax' => [ 'action' => 'ultraguard_antivirus_start_scan', 'nonce' => $nonce, 'data' => [ 'scan_type' => 'full' ] ] ];
            $buttons[] = [ 'type' => 'button', 'text' => __( 'Scan Path',  'ultraguard-security-suite' ), 'button_style' => 'secondary', 'icon' => 'dashicons-folder-open', 'class' => 'ultraguard-start-scan-btn', 'ajax' => [ 'action' => 'ultraguard_antivirus_start_scan', 'nonce' => $nonce, 'data' => [ 'scan_type' => 'custom' ] ], 'attributes' => [ 'data-custom-path-input' => 'ug-custom-path-input' ] ];
        }
        $data[] = [ 'type' => 'button-group', 'alignment' => 'left', 'id' => 'ug-scan-actions', 'buttons' => $buttons ];

        return [
            'type'       => 'card', 'id' => 'ug-scan-panel', 'title' => __( 'Scanner', 'ultraguard-security-suite' ), 'icon' => 'dashicons-search',
            'badge'      => [ 'text' => $running ? ( $scan_type ? $scan_type . ' — ' . __( 'Running', 'ultraguard-security-suite' ) : __( 'Running', 'ultraguard-security-suite' ) ) : __( 'Idle', 'ultraguard-security-suite' ), 'badge_type' => $running ? 'warning' : 'secondary' ],
            'attributes' => [ 'data-scan-id' => $scan_id, 'data-nonce' => $nonce, 'data-running' => $running ? '1' : '0' ],
            'data'       => $data,
        ];
    }
}
