<?php
/**
 * AntivirusMalwareDetection — Malware detection results page.
 *
 * Per-row actions use BasePage::modal_content(), modal_footer_save(),
 * and row_actions() helpers (defined in BasePage, available to all pages).
 *
 * @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 AntivirusMalwareDetection extends BasePage {

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

    // ── Threat-level options (shared by view & edit modals) ───────────────────

    private function threat_options(): array {
        return [
            'none'     => __( 'None',     'ultraguard-security-suite' ),
            'low'      => __( 'Low',      'ultraguard-security-suite' ),
            'medium'   => __( 'Medium',   'ultraguard-security-suite' ),
            'high'     => __( 'High',     'ultraguard-security-suite' ),
            'critical' => __( 'Critical', 'ultraguard-security-suite' ),
        ];
    }

    // ── Scan result modals ────────────────────────────────────────────────────

    /**
     * @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 = 'av-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 )
            ),
        ];
    }

    private function scan_result_view_modal( array $r ): array {
        $id   = (int) ( $r['id'] ?? 0 );
        $view = $this->detection_view_data( $r );

        return [
            'id'      => 'av-view-result-' . $id,
            /* translators: %d: integer */
            'title'   => sprintf( __( 'Scan Result #%d', 'ultraguard-security-suite' ), $id ),
            'size'    => 'large',
            'content' => $this->modal_content( [
                [ 'type' => 'text',     'name' => 'vsr_file',    'label' => __( 'File Path',    'ultraguard-security-suite' ), 'value' => esc_html( $r['file_path']    ?? '' ),                             'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vsr_threat',  'label' => __( 'Threat Type',  'ultraguard-security-suite' ), 'value' => esc_html( $r['threat_type']  ?? '—' ),                            'readonly' => true ],
                [ 'type' => 'select',   'name' => 'vsr_level',   'label' => __( 'Threat Level', 'ultraguard-security-suite' ), 'value' => esc_attr( $r['threat_level'] ?? 'none' ), 'options' => $this->threat_options(), 'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vsr_status',  'label' => __( 'Status',       'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $r['status'] ?? '' ) ),                        'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vsr_hash',    'label' => __( 'File Hash',    'ultraguard-security-suite' ), 'value' => esc_html( $r['file_hash']    ?? '—' ),                            'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vsr_size',    'label' => __( 'File Size',    'ultraguard-security-suite' ), 'value' => esc_html( size_format( (int) ( $r['file_size'] ?? 0 ) ) ),        'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vsr_scan',    'label' => __( 'Scan ID',      'ultraguard-security-suite' ), 'value' => esc_html( $r['scan_id']      ?? '' ),                             'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vsr_found',   'label' => __( 'Detected',     'ultraguard-security-suite' ), 'value' => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),   'readonly' => true ],
                [ 'type' => 'textarea', 'name' => 'vsr_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 ),
        ];
    }

    private function scan_result_actions( array $r, string $nonce ): array {
        $id      = (int) ( $r['id'] ?? 0 );
        $status  = $r['status'] ?? '';
        $btns    = [
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-visibility',
                'button_style' => 'secondary',
                'title'        => __( 'View details', 'ultraguard-security-suite' ),
                'modal'        => $this->scan_result_view_modal( $r ),
            ],
        ];
        if ( $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 $this->row_actions( $btns );
    }

    // ── Signature modals ──────────────────────────────────────────────────────

    private function sig_view_modal( array $s ): array {
        $id = (int) ( $s['id'] ?? 0 );
        return [
            'id'      => 'av-view-sig-' . $id,
            /* translators: %s: string */
            'title'   => sprintf( __( 'Signature: %s', 'ultraguard-security-suite' ), esc_html( $s['name'] ?? '' ) ),
            'size'    => 'medium',
            'content' => $this->modal_content( [
                [ 'type' => 'text',     'name' => 'vsg_name',   'label' => __( 'Name',          'ultraguard-security-suite' ), 'value' => esc_html( $s['name']           ?? '' ),                           'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vsg_hash',   'label' => __( 'Hash',          'ultraguard-security-suite' ), 'value' => esc_html( $s['signature_hash'] ?? '' ),                           'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vsg_type',   'label' => __( 'Type',          'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $s['type'] ?? 'hash' ) ),                      'readonly' => true ],
                [ 'type' => 'select',   'name' => 'vsg_level',  'label' => __( 'Threat Level',  'ultraguard-security-suite' ), 'value' => esc_attr( $s['threat_level'] ?? 'medium' ), 'options' => array_diff_key( $this->threat_options(), ['none' => ''] ), 'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vsg_source', 'label' => __( 'Source',        'ultraguard-security-suite' ), 'value' => esc_html( $s['source']         ?? 'ultraguard' ),                  'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vsg_hits',   'label' => __( 'Hits',          'ultraguard-security-suite' ), 'value' => number_format_i18n( (int) ( $s['hits_count'] ?? 0 ) ),             'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vsg_active', 'label' => __( 'Status',        'ultraguard-security-suite' ), 'value' => (bool) ( $s['is_active'] ?? 1 ) ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' ), 'readonly' => true ],
                [ 'type' => 'textarea', 'name' => 'vsg_pattern','label' => __( 'Pattern',       'ultraguard-security-suite' ), 'value' => esc_html( $s['pattern']        ?? '—' ), 'rows' => 3,              'readonly' => true ],
            ] ),
        ];
    }

    private function sig_edit_modal( array $s ): array {
        $id = (int) ( $s['id'] ?? 0 );
        $threat_opts = array_diff_key( $this->threat_options(), [ 'none' => '' ] );
        return [
            'id'      => 'av-edit-sig-' . $id,
            /* translators: %s: string */
            'title'   => sprintf( __( 'Edit Signature: %s', 'ultraguard-security-suite' ), esc_html( $s['name'] ?? '' ) ),
            'size'    => 'medium',
            'content' => $this->modal_content( [
                [ 'type' => 'text',   'name' => 'name',         'label' => __( 'Name',         'ultraguard-security-suite' ), 'value' => esc_html( $s['name']         ?? '' ) ],
                [ 'type' => 'select', 'name' => 'threat_level', 'label' => __( 'Threat Level', 'ultraguard-security-suite' ), 'value' => esc_attr( $s['threat_level'] ?? 'medium' ), 'options' => $threat_opts ],
                [ 'type' => 'toggle', 'name' => 'is_active',    'label' => __( 'Active',       'ultraguard-security-suite' ), 'value' => (bool) ( $s['is_active'] ?? 1 ) ? '1' : '0', 'description' => __( 'Disable to stop this signature matching during scans.', 'ultraguard-security-suite' ) ],
            ] ),
            'footer'  => [ [
                'type'      => 'button-group',
                'alignment' => 'right',
                'size'      => 'medium',
                'buttons'   => [
                    $this->create_ajax_button(
                        __( 'Save Changes', 'ultraguard-security-suite' ),
                        'ultraguard_antivirus_edit_signature',
                        [
                            'sig_id'   => $id,
                            'modal_id' => 'av-edit-sig-' . $id,
                        ],
                        'primary',
                        'dashicons-saved'
                    ),
                ],
            ] ],
        ];
    }

    private function sig_actions( array $s, string $nonce ): array {
        $id = (int) ( $s['id'] ?? 0 );
        return $this->row_actions( [
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-visibility',
                'button_style' => 'secondary',
                'title'        => __( 'View details', 'ultraguard-security-suite' ),
                'modal'        => $this->sig_view_modal( $s ),
            ],
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-edit',
                'button_style' => 'primary',
                'title'        => __( 'Edit', 'ultraguard-security-suite' ),
                'modal'        => $this->sig_edit_modal( $s ),
            ],
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-trash',
                'button_style' => 'danger',
                'title'        => __( 'Delete signature', 'ultraguard-security-suite' ),
                'ajax'         => [
                    'action'  => 'ultraguard_antivirus_delete_signature',
                    'nonce'   => $nonce,
                    'data'    => [ 'sig_id' => $id ],
                    /* translators: %s: string */
                    'confirm' => sprintf( __( 'Delete signature "%s"? This cannot be undone.', 'ultraguard-security-suite' ), esc_js( $s['name'] ?? '' ) ),
                ],
            ],
        ] );
    }

    // ── Page scheme ───────────────────────────────────────────────────────────

    public function get_scheme( $context ): array {
        $nonce      = $this->create_nonce( 'ultraguard_admin_nonce' );
        $db         = $this->plugin->modules->get_db_tables();
        $sig_table  = $db ? $db->get_table( 'malware_signatures' ) : null;
        $scan_table = $db ? $db->get_table( 'scan_results' )        : null;

        $sig_count  = $sig_table  ? $sig_table->count( [ 'is_active' => 1 ] )           : 0;
        $infected   = $scan_table ? $scan_table->count( [ 'status' => 'infected' ] )     : 0;
        $fp_count   = $scan_table ? $scan_table->count( [ 'is_false_positive' => 1 ] )   : 0;
        $detections = $scan_table ? $scan_table->get_by( [ 'status' => 'infected' ], 200, 'created_at', 'DESC' ) : [];
        $sigs       = $sig_table  ? $sig_table->get_active_signatures( 100 )             : [];

        $det_rows = array_map( function( $r ) use ( $nonce ) {
            $level_class = match ( $r['threat_level'] ?? '' ) { 'critical' => 'danger', 'high' => 'warning', default => 'info' };
            return [
                'id'       => 'ug-row-' . $r['id'],
                'file'     => esc_html( basename( $r['file_path'] ) ),
                'threat'   => esc_html( $r['threat_type'] ?? '—' ),
                'level'    => [ 'content' => ucfirst( $r['threat_level'] ?? 'unknown' ), 'class' => $level_class ],
                'status'   => [ 'content' => ucfirst( $r['status'] ?? '' ), 'class' => $r['status'] === 'infected' ? 'danger' : 'warning' ],
                'scan_id'  => esc_html( $r['scan_id'] ),
                'found_at' => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),
                'actions'  => $this->scan_result_actions( $r, $nonce ),
            ];
        }, $detections );

        $sig_rows = array_map( fn( $s ) => [
            'id'     => 'ug-sig-' . $s['id'],
            'name'   => esc_html( $s['name'] ),
            'type'   => esc_html( ucfirst( $s['type'] ?? 'hash' ) ),
            'level'  => [ 'content' => ucfirst( $s['threat_level'] ), 'class' => $s['threat_level'] === 'critical' ? 'danger' : 'warning' ],
            'source' => esc_html( $s['source'] ?? 'ultraguard' ),
            'hits'   => number_format_i18n( (int) $s['hits_count'] ),
            'active' => [ 'content' => $s['is_active'] ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' ), 'class' => $s['is_active'] ? 'success' : 'secondary' ],
            'actions'=> $this->sig_actions( $s, $nonce ),
        ], $sigs );

        return [
            'type'      => 'page',
            'id'        => 'ultraguard-malware-detection',
            'page_slug' => 'malware-detection',
            'class'     => 'ultraguard-malware-detection-page ultraguard-page-no-sidebar',
            'header'    => [
                'title'    => __( 'Malware Detection', 'ultraguard-security-suite' ),
                'subtitle' => __( 'All detected threats, false positives, and active malware signatures', 'ultraguard-security-suite' ),
                'icon'     => 'dashicons-warning',
                'actions'  => [
                    $this->create_ajax_button( __( 'Update Signatures', 'ultraguard-security-suite' ), 'ultraguard_antivirus_update_signatures', [], 'primary',   'dashicons-update'   ),
                    $this->create_ajax_button( __( 'Export Report',     'ultraguard-security-suite' ), 'ultraguard_antivirus_export_report',     [], 'secondary', 'dashicons-download' ),
                ],
            ],
            'data' => [
                [
                    'type' => 'grid', 'columns' => 12, 'gap' => '16px',
                    'items' => [
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'id' => 'ug-av-malware-detection-count', 'title' => __( 'Total Detections',  'ultraguard-security-suite' ), 'value' => $infected,  'icon' => 'dashicons-warning',       'class' => $infected  > 0 ? 'warning'   : 'success' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'id' => 'ug-av-active-signatures-count', 'title' => __( 'Active Signatures', 'ultraguard-security-suite' ), 'value' => $sig_count, 'icon' => 'dashicons-admin-network', 'class' => 'info' ] ],
                        [ 'span' => 4, 'component' => [ 'type' => 'stat-card', 'id' => 'ug-av-false-positive-count', 'title' => __( 'False Positives',   'ultraguard-security-suite' ), 'value' => $fp_count,  'icon' => 'dashicons-yes-alt',       'class' => 'secondary' ] ],
                    ],
                ],

                // Detections table
                [
                    'type'  => 'card',
                    'title' => __( 'All Detections', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-warning',
                    'data'  => [ [
                        'type'        => 'data-table',
                        'id'          => 'detections-table',
                        'columns'     => [
                            'file'     => [ 'title' => __( 'File',     'ultraguard-security-suite' ), 'sortable' => true ],
                            'threat'   => [ 'title' => __( 'Threat',   'ultraguard-security-suite' ), 'sortable' => true ],
                            'level'    => [ 'title' => __( 'Severity', 'ultraguard-security-suite' ), 'sortable' => true ],
                            'status'   => [ 'title' => __( 'Status',   'ultraguard-security-suite' ) ],
                            'found_at' => [ 'title' => __( 'Found',    'ultraguard-security-suite' ), 'sortable' => true ],
                            'actions'  => [ 'title' => __( 'Actions',  'ultraguard-security-suite' ), 'width' => '130px' ],
                        ],
                        'data'        => $det_rows,
                        'searchable'  => true,
                        'pagination'  => [ 'enabled' => count( $det_rows ) > 25, 'page_size' => 25 ],
                        'empty_state' => [ 'title' => __( 'No threats detected', 'ultraguard-security-suite' ) ],
                    ] ],
                ],

                // Signatures table
                [
                    'type'  => 'card',
                    'title' => __( 'Malware Signatures Database', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-admin-network',
                    'data'  => [ [
                        'type'        => 'data-table',
                        'id'          => 'signatures-table',
                        'columns'     => [
                            'name'    => [ 'title' => __( 'Name',     'ultraguard-security-suite' ), 'sortable' => true ],
                            'type'    => [ 'title' => __( 'Type',     'ultraguard-security-suite' ) ],
                            'level'   => [ 'title' => __( 'Severity', 'ultraguard-security-suite' ), 'sortable' => true ],
                            'source'  => [ 'title' => __( 'Source',   'ultraguard-security-suite' ) ],
                            'hits'    => [ 'title' => __( 'Hits',     'ultraguard-security-suite' ), 'sortable' => true ],
                            'active'  => [ 'title' => __( 'Status',   'ultraguard-security-suite' ) ],
                            'actions' => [ 'title' => __( 'Actions',  'ultraguard-security-suite' ), 'width' => '110px' ],
                        ],
                        'data'        => $sig_rows,
                        'searchable'  => true,
                        'pagination'  => [ 'enabled' => count( $sig_rows ) > 25, 'page_size' => 25 ],
                        'empty_state' => [ 'title' => __( 'No signatures loaded', 'ultraguard-security-suite' ), 'description' => __( 'Click "Update Signatures" to load the malware database.', 'ultraguard-security-suite' ) ],
                    ] ],
                ],
            ],
        ];
    }
}
