<?php
/**
 * FirewallDashboard — Firewall overview with live stats, charts, recent blocks.
 *
 * @package UltraguardPro\modules\firewall\pages
 */

namespace UltraguardPro\modules\firewall\pages;

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

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

class FirewallDashboard extends BasePage {

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

    public function get_scheme( $context ): array {
        $db      = $this->plugin->modules->get_db_tables();
        $blocked = $db ? $db->get_table( 'blocked_requests' ) : null;
        $logs_t  = $db ? $db->get_table( 'firewall_logs' )    : null;
        $rules_t = $db ? $db->get_table( 'firewall_rules' )   : null;
        $bl_t    = $db ? $db->get_table( 'ip_blacklist' )     : null;
        $wl_t    = $db ? $db->get_table( 'ip_whitelist' )     : null;
        $rl_t    = $db ? $db->get_table( 'rate_limiting' )    : null;

        $today   = gmdate( 'Y-m-d 00:00:00' );
        $h24     = gmdate( 'Y-m-d H:i:s', strtotime( '-24 hours' ) );
        $h1      = gmdate( 'Y-m-d H:i:s', strtotime( '-1 hour' ) );
        $enabled = (bool) get_option( 'firewall_waf_enabled', true );
        $nonce   = $this->create_nonce( 'ultraguard_admin_nonce' );

        // ── Stats ─────────────────────────────────────────────────────────
        $blocked_today  = $blocked ? $blocked->count( [ 'created_at >='  => $today ] ) : 0;
        $blocked_24h    = $blocked ? $blocked->count( [ 'created_at >='  => $h24   ] ) : 0;
        $blocked_1h     = $blocked ? $blocked->count( [ 'created_at >='  => $h1    ] ) : 0;
        $requests_today = $logs_t  ? $logs_t->count(  [ 'created_at >='  => $today ] ) : 0;
        $active_rules   = $rules_t ? $rules_t->count( [ 'is_active' => 1 ] )            : 0;
        $blacklisted    = $bl_t    ? $bl_t->count(    [ 'is_active' => 1 ] )             : 0;
        $whitelisted    = $wl_t    ? $wl_t->count()                                       : 0;

        // ── Charts ────────────────────────────────────────────────────────
        $all_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' => [] ];

        // ── Recent blocked ────────────────────────────────────────────────
        $recent_blocked = $blocked ? $blocked->get_by( [], 8, 'created_at', 'DESC' ) : [];
        $recent_rows    = array_map( function( array $r ): array {
            return [
                'ip_address'  => esc_html( $r['ip_address']  ?? '' ),
                'request_uri' => esc_html( substr( $r['request_uri'] ?? '', 0, 55 ) ),
                'reason'      => esc_html( substr( $r['block_reason'] ?? '', 0, 40 ) ),
                'threat'      => [
                    'content' => ucfirst( $r['threat_level'] ?? 'medium' ),
                    'class'   => $this->threat_badge( $r['threat_level'] ?? 'medium' ),
                ],
                'time'        => esc_html( $this->format_time_ago( $r['created_at'] ?? '' ) ),
            ];
        }, $recent_blocked );

        // ── Top attacked URIs ─────────────────────────────────────────────
        $top_uris = $logs_t && method_exists( $logs_t, 'get_top_attacked_uris' )
            ? $logs_t->get_top_attacked_uris( 5, 24 )
            : [];
        $top_uri_items = array_map( function( array $r ): array {
            return [
                'icon'  => 'dashicons-admin-links',
                'text'  => esc_html( substr( (string) ( $r['request_uri'] ?? '' ), 0, 60 ) ),
                'badge' => [ 'text' => number_format_i18n( (int) ( $r['aggregate_value'] ?? $r['count'] ?? 0 ) ), 'badge_type' => 'danger' ],
            ];
        }, $top_uris );

        // ── Top blocked IPs ───────────────────────────────────────────────
        $top_ips = $blocked ? $blocked->get_top_blocked_ips( 5, 24 ) : [];
        $top_ip_items = array_map( function( array $r ): array {
            return [
                'icon'  => 'dashicons-dismiss',
                'text'  => esc_html( (string) ( $r['ip_address'] ?? '' ) ),
                'badge' => [ 'text' => number_format_i18n( (int) ( $r['aggregate_value'] ?? $r['count'] ?? 0 ) ) . ' ' . __( 'hits', 'ultraguard-security-suite' ), 'badge_type' => 'warning' ],
            ];
        }, $top_ips );

        // ── Threat breakdown by type ──────────────────────────────────────
        $threat_breakdown = [];
        if ( $logs_t ) {
            foreach ( [ 'critical', 'high', 'medium', 'low' ] as $level ) {
                $count = $logs_t->count( [ 'threat_level' => $level, 'created_at >=' => $h24 ] );
                if ( $count > 0 ) {
                    $threat_breakdown[] = [
                        'icon'  => $level === 'critical' ? 'dashicons-warning' : ( $level === 'high' ? 'dashicons-shield-alt' : 'dashicons-info' ),
                        'text'  => ucfirst( $level ) . ' ' . __( 'Severity', 'ultraguard-security-suite' ),
                        'badge' => [ 'text' => number_format_i18n( $count ), 'badge_type' => $this->threat_badge( $level ) ],
                    ];
                }
            }
        }
        if ( empty( $threat_breakdown ) ) {
            $threat_breakdown[] = [ 'icon' => 'dashicons-yes-alt', 'text' => __( 'No threats in last 24h', 'ultraguard-security-suite' ) ];
        }

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

            'header' => [
                'title'    => __( 'Firewall Dashboard', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Real-time WAF protection status, threat analytics and IP management', 'ultraguard-security-suite' ),
                'badge'    => [ 'text' => $enabled ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' ), 'badge_type' => $enabled ? 'success' : 'danger' ],
                'actions'  => [
                    $this->create_ajax_button( __( 'Refresh Stats',    'ultraguard-security-suite' ), 'ultraguard_refresh_firewall_stats', [], 'primary',   'dashicons-update'       ),
                    $this->create_ajax_button( __( 'Scan Threats',     'ultraguard-security-suite' ), 'ultraguard_scan_for_threats',       [], 'secondary', 'dashicons-search',     __( 'Run threat scan now?', 'ultraguard-security-suite' ) ),
                    $this->create_url_button(  __( 'Rules',            'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=firewall-rules' ),       'secondary', 'dashicons-filter'      ),
                    $this->create_url_button(  __( 'Logs',             'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=firewall-logs' ),        'secondary', 'dashicons-list-view'   ),
                ],
            ],

            'data' => [

                // ── Row 1: Stat cards ────────────────────────────────────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Blocked Today',   'ultraguard-security-suite' ), 'value' => $blocked_today,  'format' => 'number', 'icon' => 'dashicons-shield',        'class' => $blocked_today  > 0 ? 'danger'  : 'success', 'animated' => true ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Last 24 Hours',   'ultraguard-security-suite' ), 'value' => $blocked_24h,    'format' => 'number', 'icon' => 'dashicons-shield-alt',    'class' => $blocked_24h    > 0 ? 'warning' : 'success', 'animated' => true ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Last Hour',       'ultraguard-security-suite' ), 'value' => $blocked_1h,     'format' => 'number', 'icon' => 'dashicons-clock',         'class' => $blocked_1h     > 0 ? 'warning' : 'success' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Requests Today',  'ultraguard-security-suite' ), 'value' => $requests_today, 'format' => 'number', 'icon' => 'dashicons-admin-network', 'class' => 'info' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Active Rules',    'ultraguard-security-suite' ), 'value' => $active_rules,   'format' => 'number', 'icon' => 'dashicons-filter',        'class' => $active_rules   > 0 ? 'success' : 'secondary' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Blacklisted IPs', 'ultraguard-security-suite' ), 'value' => $blacklisted,    'format' => 'number', 'icon' => 'dashicons-dismiss',       'class' => $blacklisted    > 0 ? 'warning' : 'success' ] ],
                    ],
                ],

                // ── Row 2: Chart (span 8) + System status (span 4) ──────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 8,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Request Activity — Last 24 Hours', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-line',
                                'data'  => [ [
                                    'type'       => 'chart',
                                    'chart_type' => 'line',
                                    'height'     => '260px',
                                    'labels'     => $all_chart['labels'],
                                    'datasets'   => [
                                        [ 'label' => __( 'All Requests', 'ultraguard-security-suite' ), 'data' => $all_chart['data'],     'borderColor' => '#3b82f6', 'backgroundColor' => 'rgba(59,130,246,0.08)', 'tension' => 0.4, 'fill' => true ],
                                        [ 'label' => __( 'Blocked',      'ultraguard-security-suite' ), 'data' => $blocked_chart['data'], 'borderColor' => '#dc2626', 'backgroundColor' => 'rgba(220,38,38,0.08)',   'tension' => 0.4, 'fill' => true ],
                                    ],
                                    'security_theme' => true,
                                ] ],
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'    => 'card',
                                'title'   => __( 'System Status', 'ultraguard-security-suite' ),
                                'icon'    => 'dashicons-yes-alt',
                                'actions' => [ $this->create_url_button( __( 'Settings', 'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=firewall-settings' ), 'secondary', 'dashicons-admin-settings' ) ],
                                'data'    => [ [
                                    'type'  => 'list',
                                    'items' => [
                                        [ 'icon' => 'dashicons-shield',        'text' => __( 'WAF Engine',       'ultraguard-security-suite' ), 'badge' => [ 'text' => $enabled ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Off', 'ultraguard-security-suite' ), 'badge_type' => $enabled ? 'success' : 'danger' ] ],
                                        [ 'icon' => 'dashicons-dashboard',     'text' => __( 'Rate Limiting',    'ultraguard-security-suite' ), 'badge' => [ 'text' => get_option( 'firewall_rate_limiting', false ) ? __( 'On', 'ultraguard-security-suite' ) : __( 'Off', 'ultraguard-security-suite' ), 'badge_type' => get_option( 'firewall_rate_limiting', false ) ? 'success' : 'secondary' ] ],
                                        [ 'icon' => 'dashicons-location-alt',  'text' => __( 'Geo Blocking',     'ultraguard-security-suite' ), 'badge' => [ 'text' => \UltraguardPro\ultraguard_pro()->get_option( 'country_blocking_mode', 'none' ) !== 'none' ? __( 'On', 'ultraguard-security-suite' ) : __( 'Off', 'ultraguard-security-suite' ), 'badge_type' => \UltraguardPro\ultraguard_pro()->get_option( 'country_blocking_mode', 'none' ) !== 'none' ? 'success' : 'secondary' ] ],
                                        [ 'icon' => 'dashicons-admin-robots',  'text' => __( 'Bot Protection',   'ultraguard-security-suite' ), 'badge' => [ 'text' => get_option( 'firewall_bot_protection', true )  ? __( 'On', 'ultraguard-security-suite' ) : __( 'Off', 'ultraguard-security-suite' ), 'badge_type' => get_option( 'firewall_bot_protection', true )  ? 'success' : 'secondary' ] ],
                                        [ 'icon' => 'dashicons-dismiss',       'text' => __( 'Auto-Ban',         'ultraguard-security-suite' ), 'badge' => [ 'text' => get_option( 'firewall_auto_ban', true )         ? __( 'On', 'ultraguard-security-suite' ) : __( 'Off', 'ultraguard-security-suite' ), 'badge_type' => get_option( 'firewall_auto_ban', true )         ? 'success' : 'secondary' ] ],
                                        [ 'icon' => 'dashicons-lock',          'text' => __( 'Login Throttle',   'ultraguard-security-suite' ), 'badge' => [ 'text' => get_option( 'firewall_login_throttle', true )   ? __( 'On', 'ultraguard-security-suite' ) : __( 'Off', 'ultraguard-security-suite' ), 'badge_type' => get_option( 'firewall_login_throttle', true )   ? 'success' : 'secondary' ] ],
                                        [ 'icon' => 'dashicons-yes-alt',       'text' => __( 'Whitelisted IPs',  'ultraguard-security-suite' ), 'badge' => [ 'text' => $whitelisted, 'badge_type' => 'info' ] ],
                                    ],
                                ] ],
                            ],
                        ],
                    ],
                ],

                // ── Row 3: Recent Blocks + Top IPs + Threat breakdown ────
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 8,
                            'component' => [
                                'type'    => 'card',
                                'title'   => __( 'Recently Blocked Requests', 'ultraguard-security-suite' ),
                                'icon'    => 'dashicons-shield-alt',
                                'actions' => [ $this->create_url_button( __( 'View All Logs', 'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=firewall-logs' ), 'secondary', 'dashicons-external' ) ],
                                'data'    => [ [
                                    'type'       => 'data-table',
                                    'id'         => 'fw-recent-blocked',
                                    'columns'    => [
                                        'ip_address'  => [ 'title' => __( 'IP',     'ultraguard-security-suite' ) ],
                                        'request_uri' => [ 'title' => __( 'URI',    'ultraguard-security-suite' ) ],
                                        'reason'      => [ 'title' => __( 'Reason', 'ultraguard-security-suite' ) ],
                                        'threat'      => [ 'title' => __( 'Threat', 'ultraguard-security-suite' ) ],
                                        'time'        => [ 'title' => __( 'Time',   'ultraguard-security-suite' ) ],
                                    ],
                                    'data'        => $recent_rows,
                                    'pagination'  => [ 'enabled' => false ],
                                    'empty_state' => [ 'title' => __( 'No blocked requests yet', 'ultraguard-security-suite' ) ],
                                ] ],
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Top Blocked IPs (24h)', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-chart-bar',
                                'data'  => [ [ 'type' => 'list', 'list_type' => 'ul', 'items' => ! empty( $top_ip_items ) ? $top_ip_items : [ [ 'icon' => 'dashicons-yes-alt', 'text' => __( 'No blocked IPs in last 24h', 'ultraguard-security-suite' ) ] ] ] ],
                            ],
                        ],
                    ],
                ],

                // ── Row 4: Top attacked URIs + Threat breakdown + Quick actions
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '20px',
                    'items'   => [
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Top Attacked URIs (24h)', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-admin-links',
                                'data'  => [ [ 'type' => 'list', 'list_type' => 'ul', 'items' => ! empty( $top_uri_items ) ? $top_uri_items : [ [ 'icon' => 'dashicons-yes-alt', 'text' => __( 'No attacks in last 24h', 'ultraguard-security-suite' ) ] ] ] ],
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Threat Breakdown (24h)', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-warning',
                                'data'  => [ [ 'type' => 'list', 'list_type' => 'ul', 'items' => $threat_breakdown ] ],
                            ],
                        ],
                        [
                            'span'      => 4,
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Quick Actions', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-admin-tools',
                                'data'  => [ [
                                    'type'      => 'button-group',
                                    'alignment' => 'center',
                                    'buttons'   => [
                                        $this->create_url_button(  __( 'Manage Rules',      'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=firewall-rules' ),           'primary',   'dashicons-filter'       ),
                                        $this->create_url_button(  __( 'Add Rule',          'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=firewall-add-rules' ),        'secondary', 'dashicons-plus-alt'     ),
                                        $this->create_url_button(  __( 'IP Management',     'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=firewall-ip-management' ),   'secondary', 'dashicons-networking'   ),
                                        $this->create_url_button(  __( 'Country Blocking',  'ultraguard-security-suite' ), admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=firewall-country-blocking' ),'secondary', 'dashicons-location-alt' ),
                                        $this->create_ajax_button( __( 'Export Config',     'ultraguard-security-suite' ), 'ultraguard_export_firewall_settings', [],               'secondary', 'dashicons-download'     ),
                                    ],
                                ] ],
                            ],
                        ],
                    ],
                ],
            ],

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

    // ── Helpers ───────────────────────────────────────────────────────────────

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