<?php

namespace UltraguardPro\modules\traffic_monitor\pages;

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

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

class TrafficMonitorDashboard extends BasePage {

    private ?TrafficCaptureEngine $engine = null;

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

    public function get_scheme( $context ): array {
        $is_pro = \UltraguardPro\support\LicenseInfo::instance()->isPro();
        $engine = $this->engine();
        $stats  = $engine->get_overview_stats( 24 );
        $charts = $engine->get_traffic_stats( 24 );
        $logs   = $engine->get_live_traffic( [ 'page' => 1 ], 25 );
        $nonce  = $this->create_nonce( 'ultraguard_admin_nonce' );

        // Build header actions — hide export for free users
        $header_actions = [
            $this->create_url_button( __( 'Settings', 'ultraguard-security-suite' ), $this->get_page_url( 'traffic-monitor-settings' ), 'secondary', 'dashicons-admin-settings' ),
        ];
        if ( $is_pro ) {
            $header_actions[] = $this->create_ajax_button( __( 'Export CSV', 'ultraguard-security-suite' ), 'ultraguard_traffic_export', [], 'secondary', 'dashicons-download' );
        }
        $header_actions[] = $this->create_ajax_button( __( 'Clear Logs', 'ultraguard-security-suite' ), 'ultraguard_traffic_clear_logs', [], 'danger', 'dashicons-trash', __( 'Clear all traffic logs?', 'ultraguard-security-suite' ) );

        // ── Pre-build chart labels/data to avoid arrow fn nesting inside array_filter ──
        $timeline_labels = array_map( static function( $row ) {
            return gmdate( 'H:i', strtotime( $row['bucket'] ) );
        }, $charts['timeline'] );

        $timeline_clean = array_map( static function( $row ) {
            return (int) $row['clean_count'];
        }, $charts['timeline'] );

        $timeline_threat = array_map( static function( $row ) {
            return (int) $row['threat_count'];
        }, $charts['timeline'] );

        $threat_labels = array_map( static function( $row ) {
            return $row['threat_type'];
        }, $charts['threats'] );

        $threat_values = array_map( static function( $row ) {
            return (int) $row['total'];
        }, $charts['threats'] );

        $top_country_total  = max( 1, ...array_map( static fn( $row ) => (int) ( $row['total'] ?? 0 ), $charts['countries'] ?: [ [ 'total' => 1 ] ] ) );
        $country_hit_total  = max( 1, array_sum( array_map( static fn( $row ) => (int) ( $row['total'] ?? 0 ), $charts['countries'] ) ) );
        $country_bars = array_map( function( $row ) use ( $top_country_total, $country_hit_total ) {
            $code         = strtoupper( trim( (string) ( $row['ip_country'] ?? '' ) ) );
            $country_name = trim( (string) ( $row['ip_country_name'] ?? '' ) );
            $count        = (int) ( $row['total'] ?? 0 );
            $share        = $count > 0 ? round( ( $count / $country_hit_total ) * 100, 1 ) : 0;
            $label_parts  = [];

            if ( '' !== $country_name ) {
                $label_parts[] = trim( $this->country_flag( $code ) . ' ' . $country_name . ( '' !== $code ? ' (' . $code . ')' : '' ) );
            } elseif ( '' !== $code ) {
                $label_parts[] = trim( $this->country_flag( $code ) . ' ' . $code );
            } else {
                $label_parts[] = __( 'Unknown', 'ultraguard-security-suite' );
            }

            $label_parts[] = sprintf(
                /* translators: %s: text */
                _n( '%s request', '%s requests', $count, 'ultraguard-security-suite' ),
                number_format_i18n( $count )
            );
            $label_parts[] = $share . '%';

            return [
                'type'          => 'progress',
                'progress_type' => 'bar',
                'columns' => 6,
                'label'         => implode( ' · ', $label_parts ),
                'value'         => $count,
                'max'           => $top_country_total,
                'show_value'    => false,
                'status'        => 'info',
                'animated'      => false,
            ];
        }, $charts['countries'] );

        // ── Build data sections as a plain array, then filter empty entries ──
        $data_sections = [];

        // Retention / upsell hint for free users
        if ( ! $is_pro ) {
            $hint = $this->pro_retention_hint(
                __( 'You are viewing the last 200 requests (24-hour window). Upgrade to Pro for unlimited traffic history, date-range filtering, and CSV export for incident response.', 'ultraguard-security-suite' ),
                'traffic_history'
            );
            if ( ! empty( $hint ) ) {
                $data_sections[] = $hint;
            }
        }

        // Stat cards
        $data_sections[] = [
            'type'    => 'grid',
            'columns' => 12,
            'gap'     => '16px',
            'items'   => [
                [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Requests (24h)', 'ultraguard-security-suite' ), 'value' => $stats['total_requests'], 'format' => 'number', 'icon' => 'dashicons-chart-area', 'class' => 'info' ] ],
                [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Threats (24h)',  'ultraguard-security-suite' ), 'value' => $stats['threats'],        'format' => 'number', 'icon' => 'dashicons-warning',    'class' => $stats['threats'] > 0 ? 'warning' : 'success' ] ],
                [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Blocked (24h)', 'ultraguard-security-suite' ), 'value' => $stats['blocked'],        'format' => 'number', 'icon' => 'dashicons-shield',     'class' => $stats['blocked'] > 0 ? 'success' : 'secondary' ] ],
                [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Unique IPs (24h)', 'ultraguard-security-suite' ), 'value' => $stats['unique_ips'], 'format' => 'number', 'icon' => 'dashicons-networking', 'class' => 'info' ] ],
            ],
        ];

        // Live controls / filter bar
        $data_sections[] = [
            'type'  => 'card',
            'title' => __( 'Live Controls', 'ultraguard-security-suite' ),
            'icon'  => 'dashicons-update',
            'data'  => [
                [ 'type' => 'toggle', 'name' => 'traffic-monitor-live-refresh', 'label' => __( 'Auto-refresh every 10 seconds', 'ultraguard-security-suite' ), 'value' => true ],
                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '12px',
                    'items'   => [
                        [ 'span' => 3, 'component' => [ 'type' => 'text',   'name' => 'traffic-filter-ip',        'label' => __( 'IP address',  'ultraguard-security-suite' ), 'value' => '' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'select', 'name' => 'traffic-filter-threat',    'label' => __( 'Threat type', 'ultraguard-security-suite' ), 'options' => [
                            [ 'value' => '',            'label' => __( 'All',         'ultraguard-security-suite' ) ],
                            [ 'value' => 'clean',       'label' => __( 'Clean',       'ultraguard-security-suite' ) ],
                            [ 'value' => 'brute_force', 'label' => __( 'Brute Force', 'ultraguard-security-suite' ) ],
                            [ 'value' => 'sqli',        'label' => __( 'SQLi',        'ultraguard-security-suite' ) ],
                            [ 'value' => 'xss',         'label' => __( 'XSS',         'ultraguard-security-suite' ) ],
                            [ 'value' => 'scanner',     'label' => __( 'Scanner',     'ultraguard-security-suite' ) ],
                            [ 'value' => 'spam',        'label' => __( 'Spam',        'ultraguard-security-suite' ) ],
                        ] ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'text', 'name' => 'traffic-filter-date-from', 'label' => __( 'Date from', 'ultraguard-security-suite' ), 'value' => '' ] ],
                        [ 'span' => 3, 'component' => [ 'type' => 'text', 'name' => 'traffic-filter-date-to',   'label' => __( 'Date to',   'ultraguard-security-suite' ), 'value' => '' ] ],
                    ],
                ],
                [ 'type' => 'toggle', 'name' => 'traffic-filter-blocked-only', 'label' => __( 'Blocked only', 'ultraguard-security-suite' ), 'value' => false ],
            ],
        ];

        // Timeline + threat type charts
        $data_sections[] = [
            'type'    => 'grid',
            'columns' => 12,
            'gap'     => '20px',
            'items'   => [
                [
                    'span'      => 7,
                    'component' => [
                        'type'  => 'card',
                        'title' => __( 'Requests over 24 Hours', 'ultraguard-security-suite' ),
                        'data'  => [ [
                            'type'       => 'chart',
                            'chart_type' => 'line',
                            'height'     => '250px',
                            'labels'     => $timeline_labels,
                            'datasets'   => [
                                [ 'label' => __( 'Clean',      'ultraguard-security-suite' ), 'data' => $timeline_clean,  'borderColor' => '#157347', 'backgroundColor' => 'rgba(21,115,71,0.1)',  'fill' => true ],
                                [ 'label' => __( 'Threatened', 'ultraguard-security-suite' ), 'data' => $timeline_threat, 'borderColor' => '#b42318', 'backgroundColor' => 'rgba(180,35,24,0.08)', 'fill' => true ],
                            ],
                        ] ],
                    ],
                ],
                [
                    'span'      => 5,
                    'component' => [
                        'type'  => 'card',
                        'title' => __( 'Top Threat Types', 'ultraguard-security-suite' ),
                        'data'  => [ [
                            'type'       => 'chart',
                            'chart_type' => 'pie',
                            'height'     => '250px',
                            'labels'     => $threat_labels,
                            'datasets'   => [ [
                                'data'            => $threat_values,
                                'backgroundColor' => [ '#b42318', '#f79009', '#155eef', '#7a5af8', '#079455', '#344054' ],
                            ] ],
                        ] ],
                    ],
                ],
            ],
        ];

        // Country bars
        $data_sections[] = [
            'type'  => 'card',
            'span'      => 5,
            'title' => __( 'Top Source Countries', 'ultraguard-security-suite' ),
            'icon'  => 'dashicons-location-alt',

            'data'  => $country_bars,
        ];

        // Live requests table
        $data_sections[] = [
            'type'  => 'card',
            'title' => __( 'Live Requests', 'ultraguard-security-suite' ),
            'icon'  => 'dashicons-list-view',
            'data'  => [ [
                'type'       => 'data-table',
                'id'         => 'traffic-monitor-table',
                'columns'    => [
                    'time'     => [ 'title' => __( 'Time',     'ultraguard-security-suite' ), 'sortable' => true ],
                    'ip'       => [ 'title' => __( 'IP',       'ultraguard-security-suite' ), 'sortable' => true ],
                    'country'  => [ 'title' => __( 'Country',  'ultraguard-security-suite' ) ],
                    'method'   => [ 'title' => __( 'Method',   'ultraguard-security-suite' ) ],
                    'uri'      => [ 'title' => __( 'URI',      'ultraguard-security-suite' ) ],
                    'threat'   => [ 'title' => __( 'Threat',   'ultraguard-security-suite' ) ],
                    'response' => [ 'title' => __( 'Response', 'ultraguard-security-suite' ) ],
                    'actions'  => [ 'title' => __( 'Actions',  'ultraguard-security-suite' ) ],
                ],
                'data'       => $this->build_rows( $logs['rows'], $nonce ),
                'searchable' => false,
                'pagination' => [ 'enabled' => true, 'page_size' => 25 ],
            ] ],
        ];

        return [
            'type'      => 'page',
            'id'        => 'traffic-monitor-dashboard',
            'page_slug' => 'traffic-monitor',
            'header'    => [
                'title'    => __( 'Live Traffic Monitor', 'ultraguard-security-suite' ),
                'subtitle' => $is_pro
                    ? __( 'Watch requests hit your site in real time, inspect threats, and block suspicious IPs instantly.', 'ultraguard-security-suite' )
                    : __( 'Live traffic monitor — last 200 requests displayed. Upgrade to Pro for full history and export.', 'ultraguard-security-suite' ),
                'actions'  => $header_actions,
            ],
            'data'      => $data_sections,
            'form'      => [ 'enable' => false ],
        ];
    }

    private function build_rows( array $rows, string $nonce ): array {
        $data = [];

        foreach ( $rows as $row ) {
            $data[] = [
                'id'       => 'tm-log-' . (int) ( $row['id'] ?? 0 ),
                'time'     => esc_html( $this->format_date_time( (string) ( $row['created_at'] ?? '' ) ) ),
                'ip'       => esc_html( (string) ( $row['ip_address'] ?? '' ) ),
                'country'  => esc_html( $this->format_country( $row ) ),
                'method'   => esc_html( (string) ( $row['request_method'] ?? '' ) ),
                'uri'      => esc_html( mb_strimwidth( (string) ( $row['request_uri'] ?? '' ), 0, 80, '...' ) ),
                'threat'   => [
                    'content' => esc_html( (string) ( $row['threat_type'] ?? 'clean' ) ),
                    'class'   => $this->threat_badge( (string) ( $row['threat_level'] ?? 'none' ) ),
                ],
                'response' => (int) ( $row['response_code'] ?? 0 ),
                'actions'  => $this->row_actions( [
                    [ 'type' => 'button', 'text' => __( 'Block', 'ultraguard-security-suite' ), 'button_style' => 'danger', 'ajax' => [ 'action' => 'ultraguard_traffic_block_ip', 'nonce' => $nonce, 'data' => [ 'ip' => $row['ip_address'] ?? '' ] ] ],
                    [ 'type' => 'button', 'text' => __( 'Whitelist', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'ajax' => [ 'action' => 'ultraguard_traffic_whitelist_ip', 'nonce' => $nonce, 'data' => [ 'ip' => $row['ip_address'] ?? '' ] ] ],
                ] ),
            ];
        }

        return $data;
    }

    private function format_country( array $row ): string {
        $country_code = strtoupper( trim( (string) ( $row['ip_country'] ?? '' ) ) );
        $country_name = trim( (string) ( $row['ip_country_name'] ?? '' ) );
        $flag         = $this->country_flag( $country_code );

        if ( '' !== $country_name && '' !== $country_code ) {
            return trim( $flag . ' ' . $country_name . ' (' . $country_code . ')' );
        }

        if ( '' !== $country_name ) {
            return trim( $flag . ' ' . $country_name );
        }

        if ( '' !== $country_code ) {
            return trim( $flag . ' ' . $country_code );
        }

        return 'Unknown';
    }

    private function threat_badge( string $level ): string {
        switch ( $level ) {
            case 'critical':
                return 'danger';
            case 'high':
                return 'warning';
            case 'medium':
                return 'info';
            case 'low':
                return 'secondary';
            default:
                return 'success';
        }
    }

    private function country_flag( string $code ): string {
        $code = strtoupper( preg_replace( '/[^A-Z]/', '', $code ) );
        if ( strlen( $code ) !== 2 ) {
            return '';
        }

        return mb_chr( 127397 + ord( $code[0] ) ) . mb_chr( 127397 + ord( $code[1] ) );
    }

    private function engine(): TrafficCaptureEngine {
        if ( null === $this->engine ) {
            $this->engine = new TrafficCaptureEngine( $this->plugin );
        }

        return $this->engine;
    }
}
