<?php
/**
 * AntivirusQuarantine — Quarantine management page.
 * @package UltraguardPro\modules\antivirus\pages
 */
namespace UltraguardPro\modules\antivirus\pages;
use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;
use UltraguardPro\support\UpgradeManager;
if ( ! defined( 'ABSPATH' ) ) { exit; }

class AntivirusQuarantine extends BasePage {

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

    // ── Quarantine modals ─────────────────────────────────────────────────────

    private function quarantine_view_modal( array $r ): array {
        $id = (int) ( $r['id'] ?? 0 );
        $status_class = match ( $r['status'] ?? '' ) {
            'active'   => 'warning',
            'cleaned',
            'restored' => 'success',
            'deleted'  => 'danger',
            default    => 'secondary',
        };
        return [
            'id'      => 'av-view-quar-' . $id,
            /* translators: %d: integer */
            'title'   => sprintf( __( 'Quarantine Record #%d', 'ultraguard-security-suite' ), $id ),
            'size'    => 'medium',
            'content' => $this->modal_content( [
                [ 'type' => 'text',     'name' => 'vq_orig',    'label' => __( 'Original Path',    'ultraguard-security-suite' ), 'value' => esc_html( $r['original_path']   ?? '' ),                            'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vq_qpath',   'label' => __( 'Quarantine Path',  'ultraguard-security-suite' ), 'value' => esc_html( $r['quarantine_path'] ?? '' ),                            'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vq_threat',  'label' => __( 'Threat Type',      'ultraguard-security-suite' ), 'value' => esc_html( $r['threat_type']     ?? '—' ),                           'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vq_level',   'label' => __( 'Threat Level',     'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $r['threat_level'] ?? '' ) ),                    'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vq_status',  'label' => __( 'Status',           'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $r['status']     ?? '' ) ),                      'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vq_method',  'label' => __( 'Clean Method',     'ultraguard-security-suite' ), 'value' => esc_html( $r['clean_method']     ?? '—' ),                          'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vq_size',    'label' => __( 'File Size',        'ultraguard-security-suite' ), 'value' => esc_html( size_format( (int) ( $r['file_size'] ?? 0 ) ) ),          'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vq_hash',    'label' => __( 'File Hash',        'ultraguard-security-suite' ), 'value' => esc_html( $r['file_hash']        ?? '—' ),                          'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vq_date',    'label' => __( 'Quarantined',      'ultraguard-security-suite' ), 'value' => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),       'readonly' => true ],
                [ 'type' => 'textarea', 'name' => 'vq_notes',   'label' => __( 'Notes',            'ultraguard-security-suite' ), 'value' => esc_html( $r['notes']           ?? '' ), 'rows' => 3,               'readonly' => true ],
            ] ),
        ];
    }

    private function quarantine_edit_modal( array $r ): array {
        $id = (int) ( $r['id'] ?? 0 );
        return [
            'id'      => 'av-edit-quar-' . $id,
            /* translators: %d: integer */
            'title'   => sprintf( __( 'Edit Quarantine Record #%d', 'ultraguard-security-suite' ), $id ),
            'size'    => 'small',
            'content' => $this->modal_content( [
                [ 'type' => 'text',     'name' => 'original_path', 'label' => __( 'Original Path', 'ultraguard-security-suite' ), 'value' => esc_html( $r['original_path'] ?? '' ), 'readonly' => true ],
                [ 'type' => 'textarea', 'name' => 'notes',         'label' => __( 'Notes',         'ultraguard-security-suite' ), 'value' => esc_html( $r['notes']         ?? '' ), 'rows' => 4, 'placeholder' => __( 'Admin notes about this quarantined file…', 'ultraguard-security-suite' ) ],
            ] ),
            'footer'  => $this->modal_footer_save( 'ultraguard_antivirus_edit_quarantine_notes', [ 'quarantine_id' => $id ] ),
        ];
    }

    private function quarantine_actions( array $r, string $nonce, bool $is_pro ): 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->quarantine_view_modal( $r ),
            ],
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-edit',
                'button_style' => 'secondary',
                'title'        => __( 'Add/edit notes', 'ultraguard-security-suite' ),
                'modal'        => $this->quarantine_edit_modal( $r ),
            ],
        ];

        if ( $status === 'active' ) {
            if ( $is_pro ) {
                $btns[] = [
                    'type'         => 'button',
                    'text'         => '',
                    'icon'         => 'dashicons-shield-alt',
                    'button_style' => 'primary',
                    'title'        => __( 'Clean & Restore', 'ultraguard-security-suite' ),
                    'ajax'         => [
                        'action'  => 'ultraguard_antivirus_clean_file',
                        'nonce'   => $nonce,
                        'data'    => [ 'quarantine_id' => $id ],
                        'confirm' => __( 'Attempt to automatically clean and restore this file?', 'ultraguard-security-suite' ),
                    ],
                ];
            }
            $btns[] = [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-undo',
                'button_style' => 'warning',
                'title'        => __( 'Restore file', 'ultraguard-security-suite' ),
                'ajax'         => [
                    'action'  => 'ultraguard_antivirus_restore_file',
                    'nonce'   => $nonce,
                    'data'    => [ 'quarantine_id' => $id ],
                    'confirm' => __( 'Restore this file to its original location? It may still be dangerous.', 'ultraguard-security-suite' ),
                ],
            ];
            $btns[] = [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-trash',
                'button_style' => 'danger',
                'title'        => __( 'Delete permanently', 'ultraguard-security-suite' ),
                'ajax'         => [
                    'action'  => 'ultraguard_antivirus_delete_quarantine',
                    'nonce'   => $nonce,
                    'data'    => [ 'quarantine_id' => $id ],
                    'confirm' => __( 'Permanently delete this file? This cannot be undone.', 'ultraguard-security-suite' ),
                ],
            ];
        }

        return $this->row_actions( $btns );
    }

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

    public function get_scheme( $context ): array {
        $nonce  = $this->create_nonce( 'ultraguard_admin_nonce' );
        $db     = $this->plugin->modules->get_db_tables();
        $table  = $db ? $db->get_table( 'quarantine' ) : null;
        $stats  = $table ? $table->get_quarantine_stats() : [ 'active' => 0, 'restored' => 0, 'deleted' => 0, 'total' => 0 ];
        $items  = $table ? $table->get_by( [], 200, 'created_at', 'DESC' ) : [];
        $is_pro = \UltraguardPro\support\LicenseInfo::instance()->isPro();

        $rows = array_map( function( $r ) use ( $nonce, $is_pro ) {
            $level_class  = match ( $r['threat_level'] ?? '' ) { 'critical' => 'danger', 'high' => 'warning', default => 'info' };
            $status_class = match ( $r['status'] ?? '' ) {
                'active'   => 'warning',
                'cleaned',
                'restored' => 'success',
                'deleted'  => 'danger',
                default    => 'secondary',
            };
            $method_label = match ( $r['clean_method'] ?? '' ) {
                'core'            => __( 'WP Core',         'ultraguard-security-suite' ),
                'plugin'          => __( 'Plugin',          'ultraguard-security-suite' ),
                'theme'           => __( 'Theme',           'ultraguard-security-suite' ),
                'injection_strip' => __( 'Injection Strip', 'ultraguard-security-suite' ),
                default           => '—',
            };
            return [
                'id'          => 'ug-row-' . $r['id'],
                'file'        => esc_html( basename( $r['original_path'] ) ),
                'original'    => esc_html( $r['original_path'] ),
                'threat_type' => esc_html( $r['threat_type'] ?: '—' ),
                'level'       => [ 'content' => ucfirst( $r['threat_level'] ?? '' ), 'class' => $level_class ],
                'status'      => [ 'content' => ucfirst( $r['status']      ?? '' ), 'class' => $status_class ],
                'method'      => [ 'content' => $method_label,                       'class' => 'info' ],
                'size'        => esc_html( size_format( (int) $r['file_size'] ) ),
                'quarantined' => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),
                'actions'     => $this->quarantine_actions( $r, $nonce, $is_pro ),
            ];
        }, $items );

        return [
            'type'      => 'page',
            'id'        => 'ultraguard-quarantine',
            'page_slug' => 'quarantine',
            'class'     => 'ultraguard-quarantine-page ultraguard-page-no-sidebar',
            'header'    => [
                'title'    => __( 'Quarantine', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Isolated files that have been flagged as threats. Files here cannot execute.', 'ultraguard-security-suite' ),
                'icon'     => 'dashicons-lock',
                /* translators: %d: integer */
                'badge'    => [ 'text' => sprintf( __( '%d active', 'ultraguard-security-suite' ), $stats['active'] ), 'badge_type' => $stats['active'] > 0 ? 'warning' : 'success' ],
            ],
            'data' => array_values( array_filter( [
                UpgradeManager::should_show_nudge()
                    ? UpgradeManager::inline_hint( 'file_quarantine', __( 'Pro users can automatically clean malware injections and restore files with one click.', 'ultraguard-security-suite' ) )
                    : null,
                [
                    'type' => 'grid', 'columns' => 12, 'gap' => '16px',
                    'items' => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Active',   'ultraguard-security-suite' ), 'value' => $stats['active'],   'icon' => 'dashicons-lock',      'class' => $stats['active'] > 0 ? 'warning' : 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Restored', 'ultraguard-security-suite' ), 'value' => $stats['restored'], 'icon' => 'dashicons-undo',      'class' => 'secondary' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Deleted',  'ultraguard-security-suite' ), 'value' => $stats['deleted'],  'icon' => 'dashicons-trash',     'class' => 'secondary' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total',    'ultraguard-security-suite' ), 'value' => $stats['total'],    'icon' => 'dashicons-portfolio', 'class' => 'info' ] ],
                    ],
                ],
                [
                    'type'       => 'alert-box',
                    'alert_type' => 'warning',
                    'title'      => __( 'Quarantine Protection', 'ultraguard-security-suite' ),
                    'message'    => __( 'Quarantined files have been renamed with a .quarantine extension and an .htaccess file prevents direct access. Restoring a file re-introduces it to its original location — only do this if you are certain it is safe.', 'ultraguard-security-suite' ),
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Quarantined Files', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-lock',
                    'data'  => [ [
                        'type'        => 'data-table',
                        'id'          => 'quarantine-table',
                        'columns'     => [
                            'file'        => [ 'title' => __( 'File',         'ultraguard-security-suite' ), 'sortable' => true ],
                            'threat_type' => [ 'title' => __( 'Threat',       'ultraguard-security-suite' ) ],
                            'level'       => [ 'title' => __( 'Severity',     'ultraguard-security-suite' ), 'sortable' => true ],
                            'status'      => [ 'title' => __( 'Status',       'ultraguard-security-suite' ) ],
                            'method'      => [ 'title' => __( 'Clean Method', 'ultraguard-security-suite' ) ],
                            'size'        => [ 'title' => __( 'Size',         'ultraguard-security-suite' ) ],
                            'quarantined' => [ 'title' => __( 'Quarantined',  'ultraguard-security-suite' ), 'sortable' => true ],
                            'actions'     => [ 'title' => __( 'Actions',      'ultraguard-security-suite' ), 'width' => '150px' ],
                        ],
                        'data'        => $rows,
                        'searchable'  => true,
                        'pagination'  => [ 'enabled' => count( $rows ) > 25, 'page_size' => 25 ],
                        'empty_state' => [ 'title' => __( 'No files in quarantine', 'ultraguard-security-suite' ), 'description' => __( 'Files identified as threats during scans will appear here.', 'ultraguard-security-suite' ) ],
                    ] ],
                ],
            ] ) ),
        ];
    }
}
