<?php
/**
 * AntivirusSettings — Scanner settings page.
 *
 * Tabs:
 *   Scanning       — scan targets, depth, file types, auto-quarantine
 *   Schedule       — scheduled scan frequency and next-run info
 *   Notifications  — email alerts per event type
 *   Integrations   — API keys, signature counts, signature updates
 *
 * @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 AntivirusSettings extends BasePage {

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

    public function get_scheme( $context ): array {
        $s         = fn( string $k, $d = '' ) => $this->get_setting( $k, $d );
        $nonce     = $this->create_nonce( 'ultraguard_admin_nonce' );
        $sig_t     = $this->plugin->modules->get_db_tables()->get_table( 'malware_signatures' );
        $sig_count = $sig_t  ? $sig_t->count( [ 'is_active' => 1 ] ) : 0;
        $last_seed = get_option( 'ultraguard_antivirus_signatures_seeded', 0 );
        $next_cron = wp_next_scheduled( 'ultraguard_antivirus_scheduled_scan' );

        $last_seed_str = $last_seed
            ? get_date_from_gmt( gmdate( 'Y-m-d H:i:s', (int) $last_seed ), 'Y-m-d H:i:s' )
            : __( 'Never', 'ultraguard-security-suite' );

        $next_cron_str = $next_cron
            ? get_date_from_gmt( gmdate( 'Y-m-d H:i:s', $next_cron ), 'Y-m-d H:i:s' )
            : __( 'Not scheduled', 'ultraguard-security-suite' );

        $is_enabled = (bool) $s( 'antivirus_enabled', true );
        $internal_allowlist = array_map(
            static fn( string $reason, string $path ): array => [
                'icon' => 'dashicons-shield-alt',
                'text' => sprintf( '%s — %s', $path, $reason ),
            ],
            AntivirusEngine::get_internal_allowlisted_files(),
            array_keys( AntivirusEngine::get_internal_allowlisted_files() )
        );

        return apply_filters( 'ultraguard_antivirus_settings_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-scanner-settings',
            'page_slug' => 'scanner-settings',
            'class'     => 'ultraguard-scanner-settings-page ultraguard-page-no-sidebar',

            'header' => [
                'title'    => __( 'Antivirus Settings', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Configure scanning behaviour, scheduling, notifications and integrations.', 'ultraguard-security-suite' ),
                'icon'     => 'dashicons-admin-settings',
                'badge'    => [
                    'text'       => $is_enabled ? __( 'Enabled', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' ),
                    'badge_type' => $is_enabled ? 'success' : 'secondary',
                ],
            ],

            'data' => [ [
                'type' => 'tabs',
                'id'   => 'antivirus-settings-tabs',
                'tabs' => [

                    // ── Tab 1: Scanning ──────────────────────────────────
                    [
                        'id'    => 'scanning',
                        'title' => __( 'Scanning', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-admin-settings',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'General', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-admin-settings',
                                    'data'  => [
                                        [ 'type' => 'toggle',   'name' => 'antivirus_enabled',          'label' => __( 'Enable Antivirus Module',     'ultraguard-security-suite' ), 'description' => __( 'Master switch for the entire antivirus system.',           'ultraguard-security-suite' ), 'default' => $is_enabled ],
                                        [ 'type' => 'toggle',   'name' => 'antivirus_scan_php',          'label' => __( 'Scan PHP Files',              'ultraguard-security-suite' ), 'description' => __( 'Inspect PHP files for malicious code and web shells.',     'ultraguard-security-suite' ), 'default' => (bool) $s( 'antivirus_scan_php',   true ) ],
                                        [ 'type' => 'toggle',   'name' => 'antivirus_scan_js',           'label' => __( 'Scan JavaScript Files',       'ultraguard-security-suite' ), 'description' => __( 'Inspect JS for obfuscated code, miners and skimmers.',    'ultraguard-security-suite' ), 'default' => (bool) $s( 'antivirus_scan_js',    true ) ],
                                        [ 'type' => 'toggle',   'name' => 'antivirus_scan_html',         'label' => __( 'Scan HTML Files',             'ultraguard-security-suite' ), 'description' => __( 'Inspect HTML for iframe and script injections.',           'ultraguard-security-suite' ), 'default' => (bool) $s( 'antivirus_scan_html',  true ) ],
                                        [ 'type' => 'toggle',   'name' => 'antivirus_scan_uploads',      'label' => __( 'Scan Uploads Directory',      'ultraguard-security-suite' ), 'description' => __( 'Also scan wp-content/uploads for executables (slow).',     'ultraguard-security-suite' ), 'default' => (bool) $s( 'antivirus_scan_uploads', false ) ],
                                        [ 'type' => 'toggle',   'name' => 'antivirus_auto_quarantine',   'label' => __( 'Auto-Quarantine Critical',    'ultraguard-security-suite' ), 'description' => __( 'Automatically isolate files rated Critical after scan.',   'ultraguard-security-suite' ), 'default' => (bool) $s( 'antivirus_auto_quarantine', false ) ],
                                        [ 'type' => 'select',   'name' => 'antivirus_scan_depth',        'label' => __( 'Scan Depth',                  'ultraguard-security-suite' ),
                                          'options' => [
                                              'shallow' => __( 'Shallow — faster, plugins & themes root only', 'ultraguard-security-suite' ),
                                              'normal'  => __( 'Normal — recommended', 'ultraguard-security-suite' ),
                                              'deep'    => __( 'Deep — full recursive scan', 'ultraguard-security-suite' ),
                                          ],
                                          'default' => $s( 'antivirus_scan_depth', 'normal' ),
                                        ],
                                        [ 'type' => 'number',   'name' => 'antivirus_max_file_size_mb',  'label' => __( 'Max File Size to Scan (MB)', 'ultraguard-security-suite' ), 'min' => 1, 'max' => 100, 'description' => __( 'Files larger than this limit are skipped.', 'ultraguard-security-suite' ), 'default' => (int) $s( 'antivirus_max_file_size_mb', 10 ) ],
                                        [ 'type' => 'textarea', 'name' => 'antivirus_exclude_paths',     'label' => __( 'Excluded Paths',             'ultraguard-security-suite' ), 'rows' => 4, 'placeholder' => "wp-content/uploads\nwp-content/cache", 'description' => __( 'One path per line, relative to ABSPATH. These directories will be skipped. UltraGuard also auto-skips its own internal signature and cleaner files to prevent self-detection.', 'ultraguard-security-suite' ), 'default' => $s( 'antivirus_exclude_paths', '' ) ],
                                        [
                                            'type'       => 'alert-box',
                                            'alert_type' => 'info',
                                            'title'      => __( 'Automatic Internal Allowlist', 'ultraguard-security-suite' ),
                                            'message'    => __( 'UltraGuard automatically skips its own antivirus engine, signature seeder, and malware cleaner source files because they intentionally contain detection patterns and malicious-code references used by the scanner.', 'ultraguard-security-suite' ),
                                        ],
                                        [
                                            'type'  => 'list',
                                            'items' => $internal_allowlist,
                                        ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 2: Schedule ──────────────────────────────────
                    [
                        'id'    => 'schedule',
                        'title' => __( 'Schedule', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-clock',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Scheduled Scanning', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-clock',
                                    'data'  => [
                                        [ 'type' => 'toggle', 'name' => 'antivirus_scheduled_scan',  'label' => __( 'Enable Scheduled Scans', 'ultraguard-security-suite' ), 'description' => __( 'Automatically run scans at the configured interval.', 'ultraguard-security-suite' ), 'default' => (bool) $s( 'antivirus_scheduled_scan', true ) ],
                                        [ 'type' => 'select', 'name' => 'antivirus_scan_frequency',  'label' => __( 'Scan Frequency',         'ultraguard-security-suite' ),
                                          'options' => [
                                              'daily'       => __( 'Daily',       'ultraguard-security-suite' ),
                                              'twicedaily'  => __( 'Twice Daily', 'ultraguard-security-suite' ),
                                              'weekly'      => __( 'Weekly',      'ultraguard-security-suite' ),
                                          ],
                                          'default' => $s( 'antivirus_scan_frequency', 'daily' ),
                                        ],
                                        [
                                            'type'    => 'paragraph',
                                            'content' => sprintf(
                                                /* translators: Placeholder values are inserted into this string. */
                                                __( 'Next scheduled scan: %s', 'ultraguard-security-suite' ),
                                                '<strong>' . esc_html( $next_cron_str ) . '</strong>'
                                            ),
                                        ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 3: Notifications ─────────────────────────────
                    [
                        'id'    => 'notifications',
                        'title' => __( 'Notifications', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-email',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Email Notifications', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-email',
                                    'data'  => [
                                        [ 'type' => 'toggle', 'name' => 'antivirus_notify_on_threat',        'label' => __( 'Email on Threat Detected',       'ultraguard-security-suite' ), 'description' => __( 'Send an email alert when a scan finds malware.',         'ultraguard-security-suite' ), 'default' => (bool) $s( 'antivirus_notify_on_threat', true ) ],
                                        [ 'type' => 'toggle', 'name' => 'antivirus_notify_on_quarantine',    'label' => __( 'Email on File Quarantined',       'ultraguard-security-suite' ), 'description' => __( 'Send an email when a file is moved to quarantine.',     'ultraguard-security-suite' ), 'default' => (bool) $s( 'antivirus_notify_on_quarantine', true ) ],
                                        [ 'type' => 'toggle', 'name' => 'antivirus_notify_on_vulnerability', 'label' => __( 'Email on Critical Vulnerability', 'ultraguard-security-suite' ), 'description' => __( 'Send an email when a critical CVE is discovered.',       'ultraguard-security-suite' ), 'default' => (bool) $s( 'antivirus_notify_on_vulnerability', true ) ],
                                        [ 'type' => 'text',   'name' => 'antivirus_notify_email',            'label' => __( 'Alert Email Address',            'ultraguard-security-suite' ), 'placeholder' => get_option( 'admin_email' ), 'description' => __( 'Leave blank to use the site admin email.', 'ultraguard-security-suite' ), 'default' => $s( 'antivirus_notify_email', '' ) ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                    // ── Tab 4: Integrations ──────────────────────────────
                    [
                        'id'    => 'integrations',
                        'title' => __( 'Integrations', 'ultraguard-security-suite' ),
                        'icon'  => 'dashicons-admin-network',
                        'data'  => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [ 'span' => 12, 'component' => [
                                    'type'  => 'card',
                                    'title' => __( 'Integrations & Signatures', 'ultraguard-security-suite' ),
                                    'icon'  => 'dashicons-admin-network',
                                    'data'  => [
                                        [ 'type' => 'text', 'name' => 'antivirus_wpvulndb_api_key',
                                          'label'       => __( 'WPVulnDB / WPScan API Key', 'ultraguard-security-suite' ),
                                          'placeholder' => __( 'Optional — for live CVE data', 'ultraguard-security-suite' ),
                                          'description' => __( 'Get a free key at wpvulndb.com. Enables real-time vulnerability data for plugins and themes.', 'ultraguard-security-suite' ),
                                          'default'     => $s( 'antivirus_wpvulndb_api_key', '' ),
                                        ],
                                        [
                                            'type'    => 'paragraph',
                                            'content' => sprintf(
                                                /* translators: Placeholder values are inserted into this string. */
                                                __( 'Active signatures: <strong>%1$d</strong> &nbsp;·&nbsp; Last updated: <strong>%2$s</strong>', 'ultraguard-security-suite' ),
                                                $sig_count,
                                                esc_html( $last_seed_str )
                                            ),
                                        ],
                                    ],
                                    'footer' => [
                                        'type'      => 'button-group',
                                        'alignment' => 'left',
                                        'buttons'   => [
                                            $this->create_ajax_button(
                                                __( 'Update Signatures Now', 'ultraguard-security-suite' ),
                                                'ultraguard_antivirus_update_signatures',
                                                [ 'nonce' => $nonce ],
                                                'secondary',
                                                'dashicons-update'
                                            ),
                                        ],
                                    ],
                                ] ],
                            ],
                        ] ],
                    ],

                ],
            ] ],

            'form' => [
                'enable' => true,
                'id'     => 'antivirus-settings-form',
                'ajax'   => true,
                'action' => 'ultraguard_save_antivirus_settings',
                'nonce'  => $nonce,
                'submit' => [
                    'text'         => __( 'Save Settings', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                ],
            ],

        ], $context );
    }
}
