<?php
/**
 * FirewallRules — Rules management subpage.
 * @package UltraguardPro\modules\firewall\pages
 */
namespace UltraguardPro\modules\firewall\pages;
use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;
if ( ! defined( 'ABSPATH' ) ) { exit; }

class FirewallRules extends BasePage {

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

    private function import_rules_modal(): array {
        return [
            'id'      => 'fw-import-rules',
            'title'   => __( 'Import Firewall Rules', 'ultraguard-security-suite' ),
            'size'    => 'large',
            'content' => $this->modal_content( [
                [
                    'type'        => 'textarea',
                    'name'        => 'rules_json',
                    'label'       => __( 'Rules JSON', 'ultraguard-security-suite' ),
                    'rows'        => 14,
                    'required'    => true,
                    'placeholder' => "[\n  {\n    \"name\": \"Block XML-RPC\",\n    \"match_field\": \"uri\",\n    \"match_operator\": \"contains\",\n    \"match_value\": \"/xmlrpc.php\",\n    \"action\": \"block\",\n    \"priority\": 10,\n    \"is_active\": 1\n  }\n]",
                    'description' => __( 'Paste the exported firewall rules JSON here.', 'ultraguard-security-suite' ),
                ],
            ] ),
            'footer'  => $this->modal_footer_save( 'ultraguard_import_firewall_rules' ),
        ];
    }

    // ── Select options (reused by view and edit modals) ───────────────────────

    private function match_field_options(): array {
        return [
            'ip'     => __( 'IP Address',  'ultraguard-security-suite' ),
            'uri'    => __( 'Request URI', 'ultraguard-security-suite' ),
            'ua'     => __( 'User-Agent',  'ultraguard-security-suite' ),
            'method' => __( 'HTTP Method', 'ultraguard-security-suite' ),
            'host'   => __( 'HTTP Host',   'ultraguard-security-suite' ),
        ];
    }

    private function match_operator_options(): array {
        return [
            'equals'       => __( 'Equals',       'ultraguard-security-suite' ),
            'not_equals'   => __( 'Not Equals',   'ultraguard-security-suite' ),
            'contains'     => __( 'Contains',     'ultraguard-security-suite' ),
            'not_contains' => __( 'Not Contains', 'ultraguard-security-suite' ),
            'starts_with'  => __( 'Starts With',  'ultraguard-security-suite' ),
            'ends_with'    => __( 'Ends With',    'ultraguard-security-suite' ),
            'regex'        => __( 'Regex',        'ultraguard-security-suite' ),
        ];
    }

    private function action_options(): array {
        return [
            'block' => __( 'Block (403)',       'ultraguard-security-suite' ),
            'log'   => __( 'Log Only',          'ultraguard-security-suite' ),
            'allow' => __( 'Allow (whitelist)', 'ultraguard-security-suite' ),
        ];
    }

    // ── Per-row modal builders ────────────────────────────────────────────────

    private function rule_view_modal( array $r ): array {
        $id = (int) ( $r['id'] ?? 0 );
        return [
            'id'      => 'fw-view-rule-' . $id,
            /* translators: %s: string */
            'title'   => sprintf( __( 'Rule: %s', 'ultraguard-security-suite' ), esc_html( $r['name'] ?? '' ) ),
            'size'    => 'medium',
            'content' => $this->modal_content( [
                [ 'type' => 'text',     'name' => 'vrn',  'label' => __( 'Name',           'ultraguard-security-suite' ), 'value' => esc_html( $r['name']           ?? '' ),                              'readonly' => true ],
                [ 'type' => 'textarea', 'name' => 'vrd',  'label' => __( 'Description',    'ultraguard-security-suite' ), 'value' => esc_html( $r['description']    ?? '—' ), 'rows' => 2,               'readonly' => true ],
                [ 'type' => 'select',   'name' => 'vrmf', 'label' => __( 'Match Field',    'ultraguard-security-suite' ), 'value' => esc_attr( $r['match_field']    ?? 'uri' ), 'options' => $this->match_field_options(),    'readonly' => true ],
                [ 'type' => 'select',   'name' => 'vrmo', 'label' => __( 'Match Operator', 'ultraguard-security-suite' ), 'value' => esc_attr( $r['match_operator'] ?? 'contains' ), 'options' => $this->match_operator_options(), 'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vrmv', 'label' => __( 'Match Value',    'ultraguard-security-suite' ), 'value' => esc_html( $r['match_value']    ?? '' ),                              'readonly' => true ],
                [ 'type' => 'select',   'name' => 'vra',  'label' => __( 'Action',         'ultraguard-security-suite' ), 'value' => esc_attr( $r['action']         ?? 'block' ), 'options' => $this->action_options(),         'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vrp',  'label' => __( 'Priority',       'ultraguard-security-suite' ), 'value' => (string) (int) ( $r['priority']   ?? 100 ),                          'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vrs',  'label' => __( 'Status',         'ultraguard-security-suite' ), 'value' => (bool) ( $r['is_active'] ?? 1 ) ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Inactive', 'ultraguard-security-suite' ), 'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vrh',  'label' => __( 'Total Hits',     'ultraguard-security-suite' ), 'value' => number_format_i18n( (int) ( $r['hit_count'] ?? $r['hits_count'] ?? 0 ) ), 'readonly' => true ],
            ] ),
        ];
    }

    private function rule_edit_modal( array $r ): array {
        $id = (int) ( $r['id'] ?? 0 );
        return [
            'id'      => 'fw-edit-rule-' . $id,
            /* translators: %s: string */
            'title'   => sprintf( __( 'Edit Rule: %s', 'ultraguard-security-suite' ), esc_html( $r['name'] ?? '' ) ),
            'size'    => 'medium',
            'content' => $this->modal_content( [
                [ 'type' => 'text',     'name' => 'name',           'label' => __( 'Rule Name',      'ultraguard-security-suite' ), 'value' => esc_html( $r['name']           ?? '' ),         'required' => true ],
                [ 'type' => 'textarea', 'name' => 'description',    'label' => __( 'Description',    'ultraguard-security-suite' ), 'value' => esc_html( $r['description']    ?? '' ), 'rows' => 2, 'placeholder' => __( 'What does this rule protect against?', 'ultraguard-security-suite' ) ],
                [ 'type' => 'select',   'name' => 'match_field',    'label' => __( 'Match Field',    'ultraguard-security-suite' ), 'value' => esc_attr( $r['match_field']    ?? 'uri' ),     'options' => $this->match_field_options() ],
                [ 'type' => 'select',   'name' => 'match_operator', 'label' => __( 'Match Operator', 'ultraguard-security-suite' ), 'value' => esc_attr( $r['match_operator'] ?? 'contains' ),'options' => $this->match_operator_options() ],
                [ 'type' => 'text',     'name' => 'match_value',    'label' => __( 'Match Value',    'ultraguard-security-suite' ), 'value' => esc_html( $r['match_value']    ?? '' ),         'required' => true, 'placeholder' => __( 'e.g. /xmlrpc.php or 1.2.3.4', 'ultraguard-security-suite' ) ],
                [ 'type' => 'select',   'name' => 'action',         'label' => __( 'Action',         'ultraguard-security-suite' ), 'value' => esc_attr( $r['action']         ?? 'block' ),   'options' => $this->action_options() ],
                [ 'type' => 'number',   'name' => 'priority',       'label' => __( 'Priority',       'ultraguard-security-suite' ), 'value' => (string) (int) ( $r['priority'] ?? 100 ), 'min' => 1, 'max' => 1000 ],
                [ 'type' => 'toggle',   'name' => 'is_active',      'label' => __( 'Enable Rule',    'ultraguard-security-suite' ), 'value' => (bool) ( $r['is_active'] ?? 1 ) ? '1' : '0',  'description' => __( 'Rule fires on every request when enabled.', 'ultraguard-security-suite' ) ],
            ] ),
            'footer' => $this->modal_footer_save( 'ultraguard_firewall_edit_rule', [ 'rule_id' => $id ] ),
        ];
    }

    private function rule_actions( array $r ): array {
        $id     = (int) ( $r['id'] ?? 0 );
        $active = (bool) ( $r['is_active'] ?? 1 );
        return $this->row_actions( [
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-visibility',
                'button_style' => 'secondary',
                'title'        => __( 'View details', 'ultraguard-security-suite' ),
                'modal'        => $this->rule_view_modal( $r ),
            ],
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-edit',
                'button_style' => 'primary',
                'title'        => __( 'Edit rule', 'ultraguard-security-suite' ),
                'modal'        => $this->rule_edit_modal( $r ),
            ],
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => $active ? 'dashicons-controls-pause' : 'dashicons-controls-play',
                'button_style' => $active ? 'warning' : 'success',
                'title'        => $active ? __( 'Disable rule', 'ultraguard-security-suite' ) : __( 'Enable rule', 'ultraguard-security-suite' ),
                'ajax'         => [
                    'action' => 'ultraguard_firewall_toggle_rule',
                    'data'   => [ 'rule_id' => $id ],
                ],
            ],
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-trash',
                'button_style' => 'danger',
                'title'        => __( 'Delete rule', 'ultraguard-security-suite' ),
                'ajax'         => [
                    'action'  => 'ultraguard_firewall_delete_rule',
                    'data'    => [ 'rule_id' => $id ],
                    /* translators: %s: string */
                    'confirm' => sprintf( __( 'Delete rule "%s"?', 'ultraguard-security-suite' ), esc_js( $r['name'] ?? '' ) ),
                ],
            ],
        ] );
    }

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

    public function get_scheme( $context ): array {
        $db      = $this->plugin->modules->get_db_tables();
        $rules_t = $db ? $db->get_table( 'firewall_rules' ) : null;
        $total   = $rules_t ? $rules_t->count() : 0;
        $active  = $rules_t ? $rules_t->count( [ 'is_active' => 1 ] ) : 0;

        $rows = $rules_t ? $rules_t->get_by( [], 500, 'priority', 'ASC' ) : [];
        $data = array_map( function( array $r ): array {
            $action = $r['action'] ?? '';
            return [
                'id'             => 'rule-row-' . (int) ( $r['id'] ?? 0 ),
                'id'             => 'ug-fw-rule-row-' . (int) ( $r['id'] ?? 0 ),
                'data-rule-id'   => (int) ( $r['id'] ?? 0 ),
                'name'           => esc_html( $r['name'] ?? '' ),
                'match_field'    => esc_html( ucfirst( $r['match_field'] ?? '' ) ),
                'match_operator' => esc_html( $r['match_operator'] ?? '' ),
                'match_value'    => esc_html( substr( $r['match_value'] ?? '', 0, 50 ) ),
                'action'         => [ 'content' => ucfirst( $action ), 'class' => $action === 'block' ? 'danger' : ( $action === 'log' ? 'info' : 'secondary' ) ],
                'priority'       => (int) ( $r['priority'] ?? 0 ),
                'status'         => [ 'content' => $r['is_active'] ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Inactive', 'ultraguard-security-suite' ), 'class' => $r['is_active'] ? 'success' : 'secondary' ],
                'hits'           => (int) ( $r['hit_count'] ?? $r['hits_count'] ?? 0 ),
                'actions'        => $this->rule_actions( $r ),
            ];
        }, $rows );

        return apply_filters( 'ultraguard_firewall_rules_scheme', [
            'type'      => 'page',
            'id'        => 'ultraguard-firewall-rules',
            'page_slug' => 'firewall-rules',
            'class'     => 'ultraguard-firewall-rules-page',
            'header'    => [
                'title'    => __( 'Firewall Rules', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Manage custom firewall rules and IP-based access control', 'ultraguard-security-suite' ),
                /* translators: %d: integer */
                'badge'    => [ 'text' => sprintf( __( '%d Active Rules', 'ultraguard-security-suite' ), $active ), 'badge_type' => 'info' ],
                'actions'  => [
                    $this->create_url_button(  __( 'Add New Rule', 'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=firewall-add-rules' ), 'primary',   'dashicons-plus-alt'  ),
                    [ 'type' => 'button', 'text' => __( 'Import Rules', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'icon' => 'dashicons-upload', 'modal' => $this->import_rules_modal() ],
                    $this->create_ajax_button( __( 'Export Rules', 'ultraguard-security-suite' ), 'ultraguard_export_firewall_rules', [], 'secondary', 'dashicons-download' ),
                ],
            ],
            'data' => [
                [
                    'type' => 'grid', 'columns' => 12, 'gap' => '16px',
                    'items' => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Rules',    'ultraguard-security-suite' ), 'value' => $total,                                        'format' => 'number', 'icon' => 'dashicons-filter',    'class' => 'info'      ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Active Rules',   'ultraguard-security-suite' ), 'value' => $active,                                       'format' => 'number', 'icon' => 'dashicons-yes-alt',   'class' => 'success'   ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Inactive Rules', 'ultraguard-security-suite' ), 'value' => $total - $active,                              'format' => 'number', 'icon' => 'dashicons-minus',      'class' => 'secondary' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Hits',     'ultraguard-security-suite' ), 'value' => $rules_t ? array_sum( array_column( $rows, 'hit_count' ) ) : 0, 'format' => 'number', 'icon' => 'dashicons-chart-bar', 'class' => 'warning' ] ],
                    ],
                ],
                [
                    'type'         => 'data-table',
                    'id'           => 'firewall-rules-table',
                    'columns'      => [
                        'name'           => [ 'title' => __( 'Name',     'ultraguard-security-suite' ), 'sortable' => true ],
                        'match_field'    => [ 'title' => __( 'Field',    'ultraguard-security-suite' ) ],
                        'match_operator' => [ 'title' => __( 'Operator', 'ultraguard-security-suite' ) ],
                        'match_value'    => [ 'title' => __( 'Value',    'ultraguard-security-suite' ) ],
                        'action'         => [ 'title' => __( 'Action',   'ultraguard-security-suite' ) ],
                        'priority'       => [ 'title' => __( 'Priority', 'ultraguard-security-suite' ), 'sortable' => true ],
                        'status'         => [ 'title' => __( 'Status',   'ultraguard-security-suite' ) ],
                        'hits'           => [ 'title' => __( 'Hits',     'ultraguard-security-suite' ), 'sortable' => true ],
                        'actions'        => [ 'title' => __( 'Actions',  'ultraguard-security-suite' ), 'width' => '150px' ],
                    ],
                    'data'         => $data,
                    'searchable'   => true,
                    'bulk_actions' => [
                        'enable'  => __( 'Enable Selected',  'ultraguard-security-suite' ),
                        'disable' => __( 'Disable Selected', 'ultraguard-security-suite' ),
                        'delete'  => __( 'Delete Selected',  'ultraguard-security-suite' ),
                    ],
                    'pagination'  => [ 'enabled' => true, 'page_size' => 25 ],
                    'empty_state' => [ 'title' => __( 'No firewall rules yet', 'ultraguard-security-suite' ), 'description' => __( 'Add your first rule or apply a protection preset.', 'ultraguard-security-suite' ) ],
                ],
                [
                    'type'  => 'card',
                    'title' => __( 'Protection Presets', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-admin-tools',
                    'data'  => [ [
                        'type'      => 'button-group',
                        'alignment' => 'center',
                        'buttons'   => [
                            $this->create_ajax_button( __( 'Add Threat Protection', 'ultraguard-security-suite' ), 'ultraguard_add_threat_protection', [], 'primary',   'dashicons-shield',    __( 'Add SQL injection, XSS and traversal protection rules?',  'ultraguard-security-suite' ) ),
                            $this->create_ajax_button( __( 'Add WP Protection',     'ultraguard-security-suite' ), 'ultraguard_add_wp_protection',     [], 'secondary', 'dashicons-wordpress', __( 'Add WordPress-specific protection rules?',                 'ultraguard-security-suite' ) ),
                            $this->create_ajax_button( __( 'Enable Rate Limiting',  'ultraguard-security-suite' ), 'ultraguard_enable_rate_limiting',  [], 'secondary', 'dashicons-dashboard', __( 'Enable request rate limiting?',                            'ultraguard-security-suite' ) ),
                            $this->create_ajax_button( __( 'Clear All Rules',       'ultraguard-security-suite' ), 'ultraguard_clear_all_rules',       [], 'danger',    'dashicons-trash',     __( 'Delete ALL firewall rules? This cannot be undone.',        'ultraguard-security-suite' ) ),
                        ],
                    ] ],
                ],
            ],
            'form' => [ 'enable' => false ],
        ], $context );
    }
}
