<?php
/**
 * FirewallSettings — Comprehensive firewall configuration page.
 *
 * Tabs:
 *   WAF Core       — enable/disable each detection layer individually
 *   Rate Limiting  — sliding-window per-IP throttling
 *   Bot Protection — bad UA, empty UA, proxy/VPN/Tor blocking
 *   Auto-Ban       — threshold-based IP auto-banning
 *   Login Security — wp-login.php and XMLRPC throttling
 *   Hotlink        — media hotlink protection
 *   Reputation     — scheduled reputation feed sync
 *   Logging        — retention and verbosity
 *   Advanced       — performance tuning, export, reset
 *
 * @package UltraguardPro\modules\firewall\pages
 */

namespace UltraguardPro\modules\firewall\pages;

use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;

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

class FirewallSettings extends BasePage {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
    }

    public function get_scheme( $context ): array {
        $s     = fn( string $k, $d = '' ) => $this->get_setting( $k, $d );
        $nonce = $this->create_nonce( 'ultraguard_admin_nonce' );
        $waf   = (bool) $s( 'firewall_waf_enabled', true );

        return apply_filters( 'ultraguard_firewall_settings_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-firewall-settings',
            'page_slug' => 'firewall-settings',
            'class'     => 'ultraguard-firewall-settings-page',

            'header' => [
                'title'    => __( 'Firewall Settings', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Configure every layer of WAF protection, rate limiting, bot blocking, and more', 'ultraguard-security-suite' ),
                'badge'    => [ 'text' => $waf ? __( 'WAF Active', 'ultraguard-security-suite' ) : __( 'WAF Disabled', 'ultraguard-security-suite' ), 'badge_type' => $waf ? 'success' : 'danger' ],
                'actions'  => [
                    $this->create_ajax_button( __( 'Test Firewall',   'ultraguard-security-suite' ), 'ultraguard_test_firewall',    [], 'secondary', 'dashicons-yes'    ),
                    $this->create_url_button(  __( 'View Dashboard',  'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=firewall' ), 'secondary', 'dashicons-shield' ),
                ],
            ],

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

                    // ── Tab 1: WAF Core ──────────────────────────────────
                    [
                        'id'       => 'waf-core',
                        'title'    => __( 'WAF Core', 'ultraguard-security-suite' ),
                        'icon'     => 'dashicons-shield',
                        'data' => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [
                                    'span'      => 6,
                                    'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Core WAF Engine', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-shield',
                                        'data'  => [
                                            [ 'type' => 'toggle', 'name' => 'firewall_waf_enabled',         'label' => __( 'Enable WAF Engine',         'ultraguard-security-suite' ), 'description' => __( 'Master switch — disabling stops all WAF protection',   'ultraguard-security-suite' ), 'default' => $s( 'firewall_waf_enabled', true ) ],
                                            [ 'type' => 'select', 'name' => 'firewall_default_action',      'label' => __( 'Default Action',            'ultraguard-security-suite' ), 'description' => __( 'What to do when no rule matches but pattern detected', 'ultraguard-security-suite' ),
                                              'options' => [ 'block' => __( 'Block (403)', 'ultraguard-security-suite' ), 'log' => __( 'Log Only', 'ultraguard-security-suite' ) ],
                                              'default' => $s( 'firewall_default_action', 'block' ),
                                            ],
                                            [ 'type' => 'toggle', 'name' => 'firewall_scan_uploads',        'label' => __( 'Scan Upload Requests',      'ultraguard-security-suite' ), 'description' => __( 'Inspect upload payloads for malicious patterns',       'ultraguard-security-suite' ), 'default' => $s( 'firewall_scan_uploads', false ) ],
                                        ],
                                    ],
                                ],
                                [
                                    'span'      => 6,
                                    'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Attack Detection Layers', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-search',
                                        'data'  => [
                                            [ 'type' => 'toggle', 'name' => 'firewall_sql_injection_scan',  'label' => __( 'SQL Injection (SQLi)',       'ultraguard-security-suite' ), 'description' => __( 'UNION, SELECT, DROP, SLEEP, boolean blind patterns',  'ultraguard-security-suite' ), 'default' => $s( 'firewall_sql_injection_scan', true ) ],
                                            [ 'type' => 'toggle', 'name' => 'firewall_xss_scan',            'label' => __( 'Cross-Site Scripting (XSS)', 'ultraguard-security-suite' ), 'description' => __( 'Script tags, event handlers, javascript: URIs',       'ultraguard-security-suite' ), 'default' => $s( 'firewall_xss_scan', true ) ],
                                            [ 'type' => 'toggle', 'name' => 'firewall_directory_traversal', 'label' => __( 'Path / Directory Traversal', 'ultraguard-security-suite' ), 'description' => __( '../ sequences, /etc/passwd, /proc/self/environ',       'ultraguard-security-suite' ), 'default' => $s( 'firewall_directory_traversal', true ) ],
                                            [ 'type' => 'toggle', 'name' => 'firewall_rfi_protection',      'label' => __( 'Remote File Inclusion (RFI)', 'ultraguard-security-suite' ), 'description' => __( 'External URL inclusions in parameters',               'ultraguard-security-suite' ), 'default' => $s( 'firewall_rfi_protection', true ) ],
                                            [ 'type' => 'toggle', 'name' => 'firewall_rce_protection',      'label' => __( 'Remote Code Execution (RCE)', 'ultraguard-security-suite' ), 'description' => __( 'eval(), system(), shell_exec(), backtick operators', 'ultraguard-security-suite' ), 'default' => $s( 'firewall_rce_protection', true ) ],
                                            [ 'type' => 'toggle', 'name' => 'firewall_xxe_protection',      'label' => __( 'XML External Entity (XXE)',  'ultraguard-security-suite' ), 'description' => __( '<!ENTITY> and SYSTEM declarations in XML',            'ultraguard-security-suite' ), 'default' => $s( 'firewall_xxe_protection', true ) ],
                                            [ 'type' => 'toggle', 'name' => 'firewall_ssrf_protection',     'label' => __( 'Server-Side Request Forgery (SSRF)', 'ultraguard-security-suite' ), 'description' => __( 'Requests targeting internal IPs / metadata services', 'ultraguard-security-suite' ), 'default' => $s( 'firewall_ssrf_protection', true ) ],
                                            [ 'type' => 'toggle', 'name' => 'firewall_cmdi_protection',     'label' => __( 'Command Injection (CMDi)',   'ultraguard-security-suite' ), 'description' => __( 'Shell metacharacters, ; | & in request parameters',   'ultraguard-security-suite' ), 'default' => $s( 'firewall_cmdi_protection', true ) ],
                                            [ 'type' => 'toggle', 'name' => 'firewall_lfi_protection',      'label' => __( 'Local File Inclusion (LFI)', 'ultraguard-security-suite' ), 'description' => __( 'php:// wrappers, expect://, zip:// streams',          'ultraguard-security-suite' ), 'default' => $s( 'firewall_lfi_protection', true ) ],
                                        ],
                                    ],
                                ],
                            ],
                        ] ],
                    ],

                    // ── Tab 2: Rate Limiting ─────────────────────────────
                    [
                        'id'       => 'rate-limiting',
                        'title'    => __( 'Rate Limiting', 'ultraguard-security-suite' ),
                        'icon'     => 'dashicons-dashboard',
                        'data' => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [
                                    'span'      => 6,
                                    'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Global Rate Limit', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-clock',
                                        'data'  => [
                                            [ 'type' => 'toggle', 'name' => 'firewall_rate_limiting',          'label' => __( 'Enable Rate Limiting',        'ultraguard-security-suite' ), 'description' => __( 'Throttle IPs sending too many requests',            'ultraguard-security-suite' ), 'default' => $s( 'firewall_rate_limiting', false ) ],
                                            [ 'type' => 'number', 'name' => 'firewall_rate_limit_requests',    'label' => __( 'Max Requests per Window',     'ultraguard-security-suite' ), 'description' => __( 'Requests allowed before action is taken',          'ultraguard-security-suite' ), 'min' => 10, 'max' => 10000, 'default' => $s( 'firewall_rate_limit_requests', 200 ) ],
                                            [ 'type' => 'number', 'name' => 'firewall_rate_limit_window',      'label' => __( 'Window Size (seconds)',       'ultraguard-security-suite' ), 'description' => __( 'Sliding window duration for counting requests',    'ultraguard-security-suite' ), 'min' => 10, 'max' => 3600, 'default' => $s( 'firewall_rate_limit_window', 60 ) ],
                                            [ 'type' => 'select', 'name' => 'firewall_rate_limit_action',      'label' => __( 'Action When Limit Exceeded', 'ultraguard-security-suite' ), 'description' => __( 'What to do when an IP exceeds the rate limit',     'ultraguard-security-suite' ),
                                              'options' => [
                                                  'block'    => __( 'Block (403)',       'ultraguard-security-suite' ),
                                                  'throttle' => __( 'Slow Down (1s delay)', 'ultraguard-security-suite' ),
                                                  'log'      => __( 'Log Only',          'ultraguard-security-suite' ),
                                              ],
                                              'default' => $s( 'firewall_rate_limit_action', 'block' ),
                                            ],
                                        ],
                                    ],
                                ],
                                [
                                    'span'      => 6,
                                    'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Geo Blocking', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-location-alt',
                                        'data'  => [
                                            [ 'type' => 'toggle', 'name' => 'firewall_geo_blocking',          'label' => __( 'Enable Geo Blocking',  'ultraguard-security-suite' ), 'description' => __( 'Block or restrict traffic by country',                   'ultraguard-security-suite' ), 'default' => $s( 'firewall_geo_blocking', false ) ],
                                            [ 'type' => 'select', 'name' => 'firewall_geo_mode',              'label' => __( 'Blocking Mode',        'ultraguard-security-suite' ), 'description' => __( 'Blacklist = block listed; Whitelist = allow listed only', 'ultraguard-security-suite' ),
                                              'options' => [
                                                  'blacklist' => __( 'Blacklist (block countries)', 'ultraguard-security-suite' ),
                                                  'whitelist' => __( 'Whitelist (allow only)',      'ultraguard-security-suite' ),
                                              ],
                                              'default' => $s( 'firewall_geo_mode', 'blacklist' ),
                                            ],
                                        ],
                                        'footer' => [
                                            'type'      => 'button-group',
                                            'alignment' => 'right',
                                            'buttons'   => [
                                                $this->create_url_button( __( 'Manage Countries', 'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=firewall-country-blocking' ), 'secondary', 'dashicons-location-alt' ),
                                            ],
                                        ],
                                    ],
                                ],
                            ],
                        ] ],
                    ],

                    // ── Tab 3: Bot Protection ────────────────────────────
                    [
                        'id'       => 'bot-protection',
                        'title'    => __( 'Bot Protection', 'ultraguard-security-suite' ),
                        'icon'     => 'dashicons-admin-robots',
                        'data' => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [
                                    'span'      => 6,
                                    'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Bad Bot & Scanner Blocking', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-admin-robots',
                                        'data'  => [
                                            [ 'type' => 'toggle', 'name' => 'firewall_bot_protection',       'label' => __( 'Enable Bot Detection',       'ultraguard-security-suite' ), 'description' => __( 'Block sqlmap, nikto, nmap, dirbuster, scrapy, etc.',  'ultraguard-security-suite' ), 'default' => $s( 'firewall_bot_protection', true ) ],
                                            [ 'type' => 'toggle', 'name' => 'firewall_block_empty_ua',       'label' => __( 'Block Empty User-Agents',    'ultraguard-security-suite' ), 'description' => __( 'Block requests with no User-Agent header',             'ultraguard-security-suite' ), 'default' => $s( 'firewall_block_empty_ua', false ) ],
                                        ],
                                    ],
                                ],
                                [
                                    'span'      => 6,
                                    'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Proxy / VPN / Tor Blocking', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-networking',
                                        'data'  => [
                                            [ 'type' => 'toggle', 'name' => 'firewall_block_proxies',        'label' => __( 'Block Proxy / VPN IPs',      'ultraguard-security-suite' ), 'description' => __( 'Block IPs flagged as proxy/VPN in geo data',           'ultraguard-security-suite' ), 'default' => $s( 'firewall_block_proxies', false ) ],
                                        ],
                                    ],
                                ],
                            ],
                        ] ],
                    ],

                    // ── Tab 4: Auto-Ban ──────────────────────────────────
                    [
                        'id'       => 'auto-ban',
                        'title'    => __( 'Auto-Ban', 'ultraguard-security-suite' ),
                        'icon'     => 'dashicons-dismiss',
                        'data' => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [
                                    'span'      => 6,
                                    'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Auto-Ban Configuration', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-dismiss',
                                        'data'  => [
                                            [ 'type' => 'toggle', 'name' => 'firewall_auto_ban',             'label' => __( 'Enable Auto-Ban',                  'ultraguard-security-suite' ), 'description' => __( 'Automatically block IPs that trigger too many attacks', 'ultraguard-security-suite' ), 'default' => $s( 'firewall_auto_ban', true ) ],
                                            [ 'type' => 'number', 'name' => 'firewall_auto_ban_threshold',   'label' => __( 'Attack Threshold (per 10 min)',     'ultraguard-security-suite' ), 'description' => __( 'Number of attacks before auto-banning the IP',        'ultraguard-security-suite' ), 'min' => 2, 'max' => 100, 'default' => $s( 'firewall_auto_ban_threshold', 5 ) ],
                                            [ 'type' => 'number', 'name' => 'firewall_auto_ban_duration',    'label' => __( 'Ban Duration (seconds)',            'ultraguard-security-suite' ), 'description' => __( 'How long to keep the IP banned (3600 = 1 hour)',       'ultraguard-security-suite' ), 'min' => 60, 'max' => 2592000, 'default' => $s( 'firewall_auto_ban_duration', 3600 ) ],
                                        ],
                                    ],
                                ],
                                [
                                    'span'      => 6,
                                    'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Reputation Feed', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-rss',
                                        'data'  => [
                                            [ 'type' => 'toggle', 'name' => 'firewall_reputation_sync',      'label' => __( 'Enable Reputation Sync',           'ultraguard-security-suite' ), 'description' => __( 'Auto-import known bad IPs from FireHOL Level 1 feed', 'ultraguard-security-suite' ), 'default' => $s( 'firewall_reputation_sync', false ) ],
                                        ],
                                        'footer' => [
                                            'type'      => 'button-group',
                                            'alignment' => 'right',
                                            'buttons'   => [
                                                $this->create_ajax_button( __( 'Sync Now', 'ultraguard-security-suite' ), 'ultraguard_update_firewall_rules', [], 'secondary', 'dashicons-update' ),
                                            ],
                                        ],
                                    ],
                                ],
                            ],
                        ] ],
                    ],

                    // ── Tab 5: Login Security ────────────────────────────
                    [
                        'id'       => 'login-security',
                        'title'    => __( 'Login Security', 'ultraguard-security-suite' ),
                        'icon'     => 'dashicons-lock',
                        'data' => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [
                                    'span'      => 6,
                                    'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'wp-login.php Throttling', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-lock',
                                        'data'  => [
                                            [ 'type' => 'toggle', 'name' => 'firewall_login_throttle',       'label' => __( 'Enable Login Throttle',      'ultraguard-security-suite' ), 'description' => __( 'Rate-limit wp-login.php to prevent brute force',       'ultraguard-security-suite' ), 'default' => $s( 'firewall_login_throttle', true ) ],
                                            [ 'type' => 'number', 'name' => 'firewall_login_max_attempts',   'label' => __( 'Max Login Attempts',         'ultraguard-security-suite' ), 'description' => __( 'Attempts allowed per window before blocking the IP',   'ultraguard-security-suite' ), 'min' => 3, 'max' => 100, 'default' => $s( 'firewall_login_max_attempts', 10 ) ],
                                            [ 'type' => 'number', 'name' => 'firewall_login_window_seconds', 'label' => __( 'Window (seconds)',           'ultraguard-security-suite' ), 'description' => __( 'Counting window for login attempts',                  'ultraguard-security-suite' ), 'min' => 60, 'max' => 3600, 'default' => $s( 'firewall_login_window_seconds', 300 ) ],
                                        ],
                                    ],
                                ],
                                [
                                    'span'      => 6,
                                    'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Hotlink Protection', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-admin-links',
                                        'data'  => [
                                            [ 'type' => 'toggle', 'name' => 'firewall_hotlink_protection',   'label' => __( 'Enable Hotlink Protection',  'ultraguard-security-suite' ), 'description' => __( 'Block external sites from embedding your images/media', 'ultraguard-security-suite' ), 'default' => $s( 'firewall_hotlink_protection', false ) ],
                                        ],
                                        'footer' => [
                                            'type'      => 'alert-box',
                                            'alert_type'=> 'info',
                                            'message'   => __( 'Hotlink protection blocks requests for .jpg, .png, .gif, .webp, .svg, .mp4, .pdf where the Referer header is from a different domain.', 'ultraguard-security-suite' ),
                                        ],
                                    ],
                                ],
                            ],
                        ] ],
                    ],

                    // ── Tab 6: Logging ───────────────────────────────────
                    [
                        'id'       => 'logging',
                        'title'    => __( 'Logging', 'ultraguard-security-suite' ),
                        'icon'     => 'dashicons-text-page',
                        'data' => [ [
                            'type'    => 'grid',
                            'columns' => 12,
                            'gap'     => '20px',
                            'items'   => [
                                [
                                    'span'      => 6,
                                    'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Log Settings', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-list-view',
                                        'data'  => [
                                            [ 'type' => 'toggle', 'name' => 'firewall_log_blocked_only',     'label' => __( 'Log Blocked Requests Only',   'ultraguard-security-suite' ), 'description' => __( 'Reduce DB size by only logging blocked requests',     'ultraguard-security-suite' ), 'default' => $s( 'firewall_log_blocked_only', false ) ],
                                            [ 'type' => 'number', 'name' => 'firewall_log_retention_days',   'label' => __( 'Log Retention (days)',        'ultraguard-security-suite' ), 'description' => __( 'Auto-delete firewall logs older than N days',         'ultraguard-security-suite' ), 'min' => 1, 'max' => 365, 'default' => $s( 'firewall_log_retention_days', 30 ) ],
                                        ],
                                        'footer' => [
                                            'type'      => 'button-group',
                                            'alignment' => 'left',
                                            'buttons'   => [
                                                $this->create_ajax_button( __( 'Clear Cache',     'ultraguard-security-suite' ), 'ultraguard_clear_firewall_cache',    [], 'secondary', 'dashicons-trash'    ),
                                                $this->create_ajax_button( __( 'Export Logs',     'ultraguard-security-suite' ), 'ultraguard_export_firewall_logs',    [], 'secondary', 'dashicons-download' ),
                                                $this->create_ajax_button( __( 'Clear All Logs',  'ultraguard-security-suite' ), 'ultraguard_clear_firewall_logs',     [], 'danger',    'dashicons-trash',   __( 'Delete all firewall logs? This cannot be undone.', 'ultraguard-security-suite' ) ),
                                            ],
                                        ],
                                    ],
                                ],
                                [
                                    'span'      => 6,
                                    'component' => [
                                        'type'  => 'card',
                                        'title' => __( 'Export & Reset', 'ultraguard-security-suite' ),
                                        'icon'  => 'dashicons-admin-tools',
                                        'data'  => [
                                            [
                                                'type'      => 'button-group',
                                                'alignment' => 'center',
                                                'buttons'   => [
                                                    $this->create_ajax_button( __( 'Export Settings',  'ultraguard-security-suite' ), 'ultraguard_export_firewall_settings', [], 'secondary', 'dashicons-download' ),
                                                    $this->create_ajax_button( __( 'Refresh Rules',    'ultraguard-security-suite' ), 'ultraguard_update_firewall_rules',    [], 'secondary', 'dashicons-update'   ),
                                                ],
                                            ],
                                        ],
                                    ],
                                ],
                            ],
                        ] ],
                    ],

                ],
            ] ],

            'form' => [
                'enable' => true,
                'id'     => 'firewall-settings-form',
                'ajax'   => true,
                'action' => 'ultraguard_save_firewall_settings',
                'nonce'  => $nonce,
                'submit' => [ 'text' => __( 'Save All Settings', 'ultraguard-security-suite' ), 'button_style' => 'primary' ],
            ],
        ], $context );
    }
}
