<?php
/**
 * FirewallLogs — Full firewall log viewer with filters, charts and bulk actions.
 * @package UltraguardPro\modules\firewall\pages
 */
namespace UltraguardPro\modules\firewall\pages;
use UltraguardPro\Plugin;
use UltraguardPro\modules\core\BasePage;
if ( ! defined( 'ABSPATH' ) ) { exit; }

class FirewallLogs extends BasePage {

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

    // ── Per-row modal & action builders ───────────────────────────────────────

    private function log_view_modal( array $r ): array {
        $id = (int) ( $r['id'] ?? 0 );
        return [
            'id'      => 'fw-view-log-' . $id,
            /* translators: %d: integer */
            'title'   => sprintf( __( 'Log Entry #%d', 'ultraguard-security-suite' ), $id ),
            'size'    => 'medium',
            'content' => $this->modal_content( [
                [ 'type' => 'text',     'name' => 'vli',   'label' => __( 'IP Address',     'ultraguard-security-suite' ), 'value' => esc_html( $r['ip_address']     ?? '' ),                             'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vlm',   'label' => __( 'Method',         'ultraguard-security-suite' ), 'value' => esc_html( $r['request_method'] ?? 'GET' ),                          'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vlu',   'label' => __( 'Request URI',    'ultraguard-security-suite' ), 'value' => esc_html( $r['request_uri']    ?? '' ),                             'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vla',   'label' => __( 'Action',         'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $r['action'] ?? 'allowed' ) ),                   'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vlt',   'label' => __( 'Threat Level',   'ultraguard-security-suite' ), 'value' => esc_html( ucfirst( $r['threat_level']  ?? 'none' ) ),               'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vlc',   'label' => __( 'Country',        'ultraguard-security-suite' ), 'value' => esc_html( $r['country_code']    ?? '—' ),                           'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vlr',   'label' => __( 'Matched Rule ID','ultraguard-security-suite' ), 'value' => esc_html( (string) ( $r['rule_id'] ?? '—' ) ),                      'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vlrc',  'label' => __( 'Response Code',  'ultraguard-security-suite' ), 'value' => esc_html( (string) ( $r['response_code'] ?? '—' ) ),                'readonly' => true ],
                [ 'type' => 'text',     'name' => 'vlw',   'label' => __( 'Time',           'ultraguard-security-suite' ), 'value' => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),      'readonly' => true ],
                [ 'type' => 'textarea', 'name' => 'vlua',  'label' => __( 'User Agent',     'ultraguard-security-suite' ), 'value' => esc_html( $r['user_agent']     ?? '—' ), 'rows' => 3,               'readonly' => true ],
            ] ),
        ];
    }

    private function log_actions( array $r ): array {
        $id = (int) ( $r['id'] ?? 0 );
        $ip = esc_html( $r['ip_address'] ?? '' );
        return $this->row_actions( [
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-visibility',
                'button_style' => 'secondary',
                'title'        => __( 'View full details', 'ultraguard-security-suite' ),
                'modal'        => $this->log_view_modal( $r ),
            ],
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-dismiss',
                'button_style' => 'warning',
                'title'        => __( 'Block this IP', 'ultraguard-security-suite' ),
                'ajax'         => [
                    'action'  => 'ultraguard_block_ip_from_log',
                    'data'    => [ 'log_id' => $id ],
                    /* translators: %s: string */
                    'confirm' => sprintf( __( 'Block IP %s?', 'ultraguard-security-suite' ), $ip ),
                ],
            ],
            [
                'type'         => 'button',
                'text'         => '',
                'icon'         => 'dashicons-trash',
                'button_style' => 'danger',
                'title'        => __( 'Delete log entry', 'ultraguard-security-suite' ),
                'ajax'         => [
                    'action'  => 'ultraguard_firewall_delete_log',
                    'data'    => [ 'log_id' => $id ],
                    'confirm' => __( 'Delete this log entry?', 'ultraguard-security-suite' ),
                ],
            ],
        ] );
    }

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

    public function get_scheme( $context ): array {
        $db     = $this->plugin->modules->get_db_tables();
        $logs_t = $db ? $db->get_table( 'firewall_logs' ) : null;
        $today  = gmdate( 'Y-m-d 00:00:00' );
        $h24    = gmdate( 'Y-m-d H:i:s', strtotime( '-24 hours' ) );

        $total          = $logs_t ? $logs_t->count() : 0;
        $today_count    = $logs_t ? $logs_t->count( [ 'created_at >=' => $today ] ) : 0;
        $blocked_count  = $logs_t ? $logs_t->count( [ 'action' => 'blocked' ] ) : 0;
        $critical_count = $logs_t ? $logs_t->count( [ 'threat_level' => 'critical', 'created_at >=' => $h24 ] ) : 0;

        $chart         = $logs_t ? $logs_t->get_chart_data( 'created_at', 'id', 'hour', [],                    24 ) : [ 'labels' => [], 'data' => [] ];
        $blocked_chart = $logs_t ? $logs_t->get_chart_data( 'created_at', 'id', 'hour', [ 'action' => 'blocked' ], 24 ) : [ 'labels' => [], 'data' => [] ];

        $rows = $logs_t ? $logs_t->get_by( [], 200, 'created_at', 'DESC' ) : [];
        $data = array_map( function( array $r ): array {
            return [
                'id'          => 'ug-fw-log-row-' . (int) ( $r['id'] ?? 0 ),
                'data-log-id' => (int) ( $r['id'] ?? 0 ),
                'ip_address'  => esc_html( $r['ip_address']    ?? '' ),
                'method'      => [ 'content' => esc_html( $r['request_method'] ?? 'GET' ), 'class' => 'info' ],
                'request_uri' => esc_html( substr( $r['request_uri'] ?? '', 0, 70 ) ),
                'action'      => [ 'content' => ucfirst( $r['action'] ?? 'allowed' ), 'class' => $r['action'] === 'blocked' ? 'danger' : ( $r['action'] === 'logged' ? 'info' : 'success' ) ],
                'threat'      => [ 'content' => ucfirst( $r['threat_level'] ?? 'none' ), 'class' => $this->threat_badge( $r['threat_level'] ?? 'none' ) ],
                'country'     => esc_html( $r['country_code'] ?? '—' ),
                'created_at'  => esc_html( $this->format_date_time( $r['created_at'] ?? '' ) ),
                'actions'     => $this->log_actions( $r ),
            ];
        }, $rows );

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

            'header' => [
                'title'    => __( 'Firewall Logs', 'ultraguard-security-suite' ),
                'subtitle' => __( 'View, filter and analyse all firewall events and blocked requests', 'ultraguard-security-suite' ),
                'badge'    => [ 'text' => number_format_i18n( $total ) . ' ' . __( 'Events', 'ultraguard-security-suite' ), 'badge_type' => $critical_count > 0 ? 'danger' : ( $blocked_count > 0 ? 'warning' : 'success' ) ],
                'actions'  => [
                    $this->create_ajax_button( __( 'Export CSV', 'ultraguard-security-suite' ), 'ultraguard_export_firewall_logs', [], 'secondary', 'dashicons-download' ),
                    $this->create_ajax_button( __( 'Clear Logs', 'ultraguard-security-suite' ), 'ultraguard_clear_firewall_logs',  [], 'danger',    'dashicons-trash',   __( 'Delete all firewall logs? This cannot be undone.', 'ultraguard-security-suite' ) ),
                ],
            ],

            'data' => [
                [
                    'type' => 'grid', 'columns' => 12, 'gap' => '16px',
                    'items' => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Total Events',   'ultraguard-security-suite' ), 'value' => $total,          'format' => 'number', 'icon' => 'dashicons-list-view', 'class' => 'info'    ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Events Today',   'ultraguard-security-suite' ), 'value' => $today_count,    'format' => 'number', 'icon' => 'dashicons-clock',     'class' => 'warning' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Blocked',        'ultraguard-security-suite' ), 'value' => $blocked_count,  'format' => 'number', 'icon' => 'dashicons-shield',    'class' => 'danger'  ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Critical (24h)','ultraguard-security-suite' ), 'value' => $critical_count, 'format' => 'number', 'icon' => 'dashicons-warning',   'class' => $critical_count > 0 ? 'danger' : 'success' ] ],
                    ],
                ],
                [
                    'type' => 'grid', 'columns' => 12, 'gap' => '20px',
                    'items' => [ [
                        'span'      => 12,
                        'component' => [
                            'type'  => 'card',
                            'title' => __( 'Event Activity — Last 24 Hours', 'ultraguard-security-suite' ),
                            'icon'  => 'dashicons-chart-line',
                            'data'  => [ [
                                'type'           => 'chart',
                                'chart_type'     => 'bar',
                                'height'         => '200px',
                                'labels'         => $chart['labels'],
                                'datasets'       => [
                                    [ 'label' => __( 'All Events', 'ultraguard-security-suite' ), 'data' => $chart['data'],         'backgroundColor' => 'rgba(59,130,246,0.6)', 'borderColor' => '#3b82f6', 'borderWidth' => 1 ],
                                    [ 'label' => __( 'Blocked',    'ultraguard-security-suite' ), 'data' => $blocked_chart['data'], 'backgroundColor' => 'rgba(220,38,38,0.7)',  'borderColor' => '#dc2626', 'borderWidth' => 1 ],
                                ],
                                'security_theme' => true,
                            ] ],
                        ],
                    ] ],
                ],
                [
                    'type'         => 'data-table',
                    'id'           => 'firewall-logs-table',
                    'columns'      => [
                        'ip_address'  => [ 'title' => __( 'IP Address', 'ultraguard-security-suite' ), 'sortable' => true ],
                        'method'      => [ 'title' => __( 'Method',     'ultraguard-security-suite' ) ],
                        'request_uri' => [ 'title' => __( 'URI',        'ultraguard-security-suite' ) ],
                        'action'      => [ 'title' => __( 'Action',     'ultraguard-security-suite' ) ],
                        'threat'      => [ 'title' => __( 'Threat',     'ultraguard-security-suite' ) ],
                        'country'     => [ 'title' => __( 'Country',    'ultraguard-security-suite' ) ],
                        'created_at'  => [ 'title' => __( 'Time',       'ultraguard-security-suite' ), 'sortable' => true ],
                        'actions'     => [ 'title' => __( 'Actions',    'ultraguard-security-suite' ), 'width' => '110px' ],
                    ],
                    'data'         => $data,
                    'searchable'   => true,
                    'bulk_actions' => [
                        'block_ip'     => __( 'Block IP',     'ultraguard-security-suite' ),
                        'whitelist_ip' => __( 'Whitelist IP', 'ultraguard-security-suite' ),
                        'delete'       => __( 'Delete',       'ultraguard-security-suite' ),
                    ],
                    'pagination'   => [ 'enabled' => true, 'page_size' => 50 ],
                    'empty_state'  => [ 'title' => __( 'No log entries', 'ultraguard-security-suite' ), 'description' => __( 'Firewall events will appear here as the WAF processes requests.', 'ultraguard-security-suite' ) ],
                ],
            ],

            'form' => [ 'enable' => false ],
        ], $context );
    }

    private function threat_badge( string $level ): string {
        return match ( strtolower( $level ) ) {
            'critical', 'high' => 'danger',
            'medium'           => 'warning',
            'low', 'none'      => 'secondary',
            default            => 'info',
        };
    }
}
