<?php

namespace UltraguardPro\modules\ip_intelligence\pages;

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

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

class IpIntelligenceDashboard extends BasePage {

    private ?FeedSyncEngine $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();
        $preview_mode = $this->is_soft_gated_module_preview( 'ip_intelligence' );

        if ( $preview_mode ) {
            $stats = [
                'feed_total'   => 1834,
                'synced_today' => 264,
                'blocked_24h'  => 48,
                'categories'   => [
                    [ 'threat_category' => 'botnet', 'total' => 620 ],
                    [ 'threat_category' => 'credential_stuffing', 'total' => 418 ],
                    [ 'threat_category' => 'spam', 'total' => 357 ],
                    [ 'threat_category' => 'scanner', 'total' => 292 ],
                ],
                'blocks_30d'   => [
                    'Week 1' => 112,
                    'Week 2' => 138,
                    'Week 3' => 126,
                    'Week 4' => 149,
                ],
            ];
            $summary = [
                'abuseipdb'          => 97,
                'spamhaus'           => 84,
                'ultraguard_network' => 83,
            ];
            $rows = $this->preview_feed_rows();
            $last_sync = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS * 3 );
        } else {
            $stats     = $this->engine()->get_stats();
            $summary   = (array) get_option( 'ip_intelligence_last_sync_summary', [] );
            $feed      = $this->plugin->modules->get_db_tables()->get_table( 'threat_feed' );
            $rows      = $feed ? $feed->get_by( [], 100, 'updated_at', 'DESC' ) : [];
            $last_sync = (string) get_option( 'ip_intelligence_last_sync', '' );
        }

        $data = [
            ! $is_pro ? $this->pro_upsell_card( 'ip_intelligence' ) : [],
            $preview_mode ? $this->soft_gated_preview_data_notice(
                __( 'IP Reputation & Threat Intelligence', 'ultraguard-security-suite' ),
                __( 'The feed counts, reputation categories, and IP rows below are curated sample intelligence records. Upgrade to sync your own live threat feed and investigate real visitors.', 'ultraguard-security-suite' )
            ) : [],

            [ 'type' => 'grid', 'columns' => 12, 'gap' => '16px', 'items' => [
                [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Threat Feed IPs', 'ultraguard-security-suite' ), 'value' => $stats['feed_total'], 'format' => 'number', 'icon' => 'dashicons-shield-alt', 'class' => 'info' ] ],
                [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Synced Today', 'ultraguard-security-suite' ), 'value' => $stats['synced_today'], 'format' => 'number', 'icon' => 'dashicons-update', 'class' => 'success' ] ],
                [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Blocked by Intel (24h)', 'ultraguard-security-suite' ), 'value' => $stats['blocked_24h'], 'format' => 'number', 'icon' => 'dashicons-lock', 'class' => $stats['blocked_24h'] > 0 ? 'warning' : 'success' ] ],
                [ 'span' => 3, 'component' => [ 'type' => 'stat-card', 'title' => __( 'Last Sync', 'ultraguard-security-suite' ), 'value' => $last_sync ? $this->format_time_ago( $last_sync ) : __( 'Never', 'ultraguard-security-suite' ), 'format' => 'text', 'icon' => 'dashicons-clock', 'class' => 'secondary' ] ],
            ] ],
            [ 'type' => 'grid', 'columns' => 12, 'gap' => '16px', 'items' => [
                [ 'span' => 4, 'component' => $this->source_card( __( 'AbuseIPDB', 'ultraguard-security-suite' ), ! empty( $this->settings->get_option( 'ip_intelligence_abuseipdb_api_key', '' ) ) || $preview_mode, (string) ( $summary['abuseipdb'] ?? 0 ) ) ],
                [ 'span' => 4, 'component' => $this->source_card( __( 'Spamhaus', 'ultraguard-security-suite' ), (bool) $this->settings->get_option( 'ip_intelligence_enable_spamhaus', true ) || $preview_mode, (string) ( $summary['spamhaus'] ?? 0 ) ) ],
                [ 'span' => 4, 'component' => $this->source_card( __( 'UltraGuard Network', 'ultraguard-security-suite' ), true, (string) ( $summary['ultraguard_network'] ?? 0 ) ) ],
            ] ],
            [ 'type' => 'card', 'title' => __( 'IP Lookup Tool', 'ultraguard-security-suite' ), 'icon' => 'dashicons-search', 'data' => [
                [ 'type' => 'text', 'name' => 'ip-intelligence-lookup', 'label' => __( 'Enter an IP address', 'ultraguard-security-suite' ), 'value' => '' ],
                [ 'type' => 'button', 'text' => __( 'Look Up IP', 'ultraguard-security-suite' ), 'button_style' => 'primary', 'ajax' => [ 'action' => 'ultraguard_ip_intel_lookup_ip', 'nonce' => $this->create_nonce( 'ultraguard_admin_nonce' ), 'data' => [] ] ],
            ] ],
            [ 'type' => 'grid', 'columns' => 12, 'gap' => '20px', 'items' => [
                [ 'span' => 6, 'component' => [ 'type' => 'card', 'title' => __( 'Top Threat Categories', 'ultraguard-security-suite' ), 'data' => [ [ 'type' => 'chart', 'chart_type' => 'bar', 'height' => '250px', 'labels' => array_map( static fn( $r ) => $r['threat_category'], $stats['categories'] ), 'datasets' => [ [ 'label' => __( 'IPs', 'ultraguard-security-suite' ), 'data' => array_map( static fn( $r ) => (int) $r['total'], $stats['categories'] ), 'backgroundColor' => '#155eef' ] ] ] ] ] ],
                [ 'span' => 6, 'component' => [ 'type' => 'card', 'title' => __( 'Blocked Requests (30 Days)', 'ultraguard-security-suite' ), 'data' => [ [ 'type' => 'chart', 'chart_type' => 'line', 'height' => '250px', 'labels' => array_keys( $stats['blocks_30d'] ), 'datasets' => [ [ 'label' => __( 'Blocked', 'ultraguard-security-suite' ), 'data' => array_values( $stats['blocks_30d'] ), 'borderColor' => '#b42318', 'backgroundColor' => 'rgba(180,35,24,0.08)', 'fill' => true ] ] ] ] ] ],
            ] ],
            [ 'type' => 'card', 'title' => __( 'Threat Feed', 'ultraguard-security-suite' ), 'icon' => 'dashicons-list-view', 'data' => [ [
                'type'       => 'data-table',
                'id'         => 'ip-intelligence-feed-table',
                'columns'    => [
                    'ip'         => [ 'title' => __( 'IP', 'ultraguard-security-suite' ), 'sortable' => true ],
                    'category'   => [ 'title' => __( 'Category', 'ultraguard-security-suite' ) ],
                    'confidence' => [ 'title' => __( 'Confidence', 'ultraguard-security-suite' ) ],
                    'source'     => [ 'title' => __( 'Source', 'ultraguard-security-suite' ) ],
                    'country'    => [ 'title' => __( 'Country', 'ultraguard-security-suite' ) ],
                    'last_seen'  => [ 'title' => __( 'Last Seen', 'ultraguard-security-suite' ) ],
                    'actions'    => [ 'title' => __( 'Actions', 'ultraguard-security-suite' ) ],
                ],
                'data'       => $this->feed_rows( $rows ),
                'searchable' => true,
                'pagination' => [ 'enabled' => true, 'page_size' => 25 ],
            ] ] ],
        ];

        return [
            'type'      => 'page',
            'id'        => 'ip-intelligence-dashboard',
            'page_slug' => 'ip-intelligence',
            'header'    => [
                'title'    => __( 'IP Reputation & Threat Intelligence', 'ultraguard-security-suite' ),
                'subtitle' => __( 'Track hostile IPs from AbuseIPDB, Spamhaus, and the UltraGuard network, and auto-block malicious visitors.', 'ultraguard-security-suite' ),
                'actions'  => [
                    $this->create_ajax_button( __( 'Sync Now', 'ultraguard-security-suite' ), 'ultraguard_ip_intel_sync_now', [], 'primary', 'dashicons-update' ),
                    $this->create_url_button( __( 'Settings', 'ultraguard-security-suite' ), $this->get_page_url( 'ip-intelligence-settings' ), 'secondary', 'dashicons-admin-settings' ),
                ],
            ],
            'data'      => $this->prepend_soft_gated_module_notice( 'ip_intelligence', __( 'IP Reputation & Threat Intelligence', 'ultraguard-security-suite' ), array_values( array_filter( $data ) ) ),
            'form'      => [ 'enable' => false ],
        ];
    }

    private function source_card( string $title, bool $enabled, string $count ): array {
        return [
            'type'  => 'card',
            'title' => $title,
            'data'  => [
                [ 'type' => 'paragraph', 'content' => $enabled ? __( 'Enabled', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' ) ],
                /* translators: %s: string */
                [ 'type' => 'paragraph', 'content' => sprintf( __( 'Last sync additions: %s', 'ultraguard-security-suite' ), $count ) ],
            ],
        ];
    }

    private function feed_rows( array $rows ): array {
        $data = [];
        foreach ( $rows as $row ) {
            $data[] = [
                'id'         => 'intel-row-' . (int) ( $row['id'] ?? 0 ),
                'ip'         => esc_html( (string) ( $row['ip_address'] ?? '' ) ),
                'category'   => [ 'content' => esc_html( (string) ( $row['threat_category'] ?? '' ) ), 'class' => 'warning' ],
                'confidence' => [ 'content' => (int) ( $row['confidence'] ?? 0 ) . '%', 'class' => ( (int) ( $row['confidence'] ?? 0 ) ) >= 80 ? 'danger' : 'info' ],
                'source'     => esc_html( (string) ( $row['source'] ?? '' ) ),
                'country'    => esc_html( (string) ( $row['country_code'] ?? '' ) ),
                'last_seen'  => esc_html( ! empty( $row['last_seen_at'] ) ? $this->format_date_time( $row['last_seen_at'] ) : __( 'Unknown', 'ultraguard-security-suite' ) ),
                'actions'    => $this->row_actions( [
                    [ 'type' => 'button', 'text' => __( 'Remove', 'ultraguard-security-suite' ), 'button_style' => 'danger', 'ajax' => [ 'action' => 'ultraguard_ip_intel_remove_entry', 'nonce' => $this->create_nonce( 'ultraguard_admin_nonce' ), 'data' => [ 'id' => (int) $row['id'] ] ] ],
                    [ 'type' => 'button', 'text' => __( 'Look Up', 'ultraguard-security-suite' ), 'button_style' => 'secondary', 'ajax' => [ 'action' => 'ultraguard_ip_intel_lookup_ip', 'nonce' => $this->create_nonce( 'ultraguard_admin_nonce' ), 'data' => [ 'ip' => (string) ( $row['ip_address'] ?? '' ) ] ] ],
                ] ),
            ];
        }
        return $data;
    }

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

    private function preview_feed_rows(): array {
        return [
            [
                'id'              => 11,
                'ip_address'      => '185.143.223.41',
                'threat_category' => 'credential_stuffing',
                'confidence'      => 96,
                'source'          => 'AbuseIPDB',
                'country_code'    => 'RU',
                'last_seen_at'    => gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS * 2 ),
            ],
            [
                'id'              => 12,
                'ip_address'      => '103.87.212.9',
                'threat_category' => 'scanner',
                'confidence'      => 88,
                'source'          => 'Spamhaus',
                'country_code'    => 'SG',
                'last_seen_at'    => gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS * 5 ),
            ],
            [
                'id'              => 13,
                'ip_address'      => '34.210.18.72',
                'threat_category' => 'botnet',
                'confidence'      => 91,
                'source'          => 'UltraGuard Network',
                'country_code'    => 'US',
                'last_seen_at'    => gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS * 9 ),
            ],
        ];
    }
}
