<?php

namespace UltraguardPro\modules\server_intelligence\pages;

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

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

abstract class ServerIntelligencePage extends BasePage {

    private ?ServerCommunication $server_communication = null;

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

    protected function server_communication(): ServerCommunication {
        if ( null === $this->server_communication ) {
            $this->server_communication = new ServerCommunication( $this->plugin );
        }

        return $this->server_communication;
    }

    protected function get_resource_labels(): array {
        return [
            'blacklist'  => __( 'Global Threat IPs', 'ultraguard-security-suite' ),
            'signatures' => __( 'Malware Signatures', 'ultraguard-security-suite' ),
            'vulndb'     => __( 'Vulnerability DB', 'ultraguard-security-suite' ),
            'fw_rules'   => __( 'Firewall Rules', 'ultraguard-security-suite' ),
            'htaccess'   => __( '.htaccess Templates', 'ultraguard-security-suite' ),
        ];
    }

    protected function build_schedule_rows( string $nonce, array $sync_config ): array {
        $rows = [];

        foreach ( $this->get_resource_labels() as $key => $label ) {
            $config  = $sync_config[ $key ] ?? [];
            $next_ts = isset( $config['next_run'] ) ? (int) $config['next_run'] : 0;
            $diff    = $next_ts ? max( 0, $next_ts - time() ) : 0;

            if ( ! $next_ts ) {
                $next_str = '-';
            } elseif ( $diff < 60 ) {
                $next_str = __( '< 1 min', 'ultraguard-security-suite' );
            } elseif ( $diff < 3600 ) {
                /* translators: %d: integer */
                $next_str = sprintf( __( '%d min', 'ultraguard-security-suite' ), floor( $diff / 60 ) );
            } elseif ( $diff < DAY_IN_SECONDS ) {
                $next_str = sprintf(
                    /* translators: %1$d: hours, %2$d: minutes */
__( '                        %1$dh %2$dm', 'ultraguard-security-suite' ),
                    floor( $diff / HOUR_IN_SECONDS ),
                    floor( ( $diff % HOUR_IN_SECONDS ) / MINUTE_IN_SECONDS )
                );
            } else {
                $next_str = date_i18n( 'M j g:i A', $next_ts );
            }

            $rows[] = [
                'resource' => esc_html( $label ),
                'enabled'  => [
                    'content'    => ! empty( $config['enabled'] ) ? __( 'Enabled', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' ),
                    'badge_type' => ! empty( $config['enabled'] ) ? 'success' : 'secondary',
                ],
                'interval' => esc_html( (string) ( $config['label'] ?? __( 'Custom', 'ultraguard-security-suite' ) ) ),
                'next_run' => esc_html( $next_str ),
                'status'   => [
                    'content'    => ! empty( $config['enabled'] ) && $next_ts ? __( 'Scheduled', 'ultraguard-security-suite' ) : __( 'Paused', 'ultraguard-security-suite' ),
                    'badge_type' => ! empty( $config['enabled'] ) && $next_ts ? 'success' : 'warning',
                ],
                'sync_now' => [
                    'type' => 'button',
                    'text' => __( 'Sync Now', 'ultraguard-security-suite' ),
                    'button_style' => 'secondary',
                    'size' => 'small',
                    'ajax' => [
                        'action' => 'ultraguard_si_pull_now',
                        'nonce'  => $nonce,
                        'data'   => [ 'resource' => $key ],
                    ],
                ],
            ];
        }

        return $rows;
    }

    protected function build_sync_control_fields( array $sync_config ): array {
        $interval_options = [];

        foreach ( ServerCommunication::get_interval_labels() as $value => $label ) {
            if ( ! isset( wp_get_schedules()[ $value ] ) ) {
                continue;
            }

            $interval_options[] = [
                'value' => $value,
                'label' => $label,
            ];
        }

        $fields = [];

        foreach ( $this->get_resource_labels() as $key => $label ) {
            $config = $sync_config[ $key ] ?? [];

            $fields[] = [
                'type'  => 'toggle',
                'name'  => 'ultraguard_si_' . $key . '_enabled',
                /* translators: %s: string */
                'label' => sprintf( __( 'Auto-fetch %s', 'ultraguard-security-suite' ), $label ),
                'value' => ! empty( $config['enabled'] ),
            ];

            $fields[] = [
                'type'      => 'select',
                'name'      => 'ultraguard_si_' . $key . '_interval',
                /* translators: %s: string */
                'label'     => sprintf( __( '%s fetch interval', 'ultraguard-security-suite' ), $label ),
                'value'     => (string) ( $config['interval'] ?? 'daily' ),
                'options'   => $interval_options,
                'help_text' => __( 'Controls how often UltraGuard checks the cloud for fresh data for this feed.', 'ultraguard-security-suite' ),
            ];
        }

        return $fields;
    }

    protected function build_queue_panel( array $queue ): array {
        $count = count( $queue );

        if ( 0 === $count ) {
            return [
                [
                    'type'       => 'alert-box',
                    'alert_type' => 'success',
                    'title'      => __( 'Queue Empty', 'ultraguard-security-suite' ),
                    'message'    => __( 'All security events have been delivered to the UltraGuard server.', 'ultraguard-security-suite' ),
                ],
            ];
        }

        $by_type = [];
        foreach ( $queue as $item ) {
            $type             = $item['event_type'] ?? 'unknown';
            $by_type[ $type ] = ( $by_type[ $type ] ?? 0 ) + 1;
        }

        arsort( $by_type );

        $timestamps = array_filter( array_map( 'intval', array_column( $queue, '_queued_at' ) ) );
        $oldest     = ! empty( $timestamps ) ? min( $timestamps ) : time();
        $age_sec    = time() - $oldest;
        $items      = [];

        foreach ( $by_type as $type => $count_by_type ) {
            $items[] = [
                'icon'  => 'dashicons-warning',
                'text'  => esc_html( ucwords( str_replace( '_', ' ', $type ) ) ),
                'badge' => [ 'text' => $count_by_type, 'badge_type' => 'info' ],
            ];
        }

        return [
            [
                'type'       => 'alert-box',
                'alert_type' => $age_sec > HOUR_IN_SECONDS ? 'warning' : 'info',
                /* translators: %d: number */
                'title'      => sprintf( _n( '%d event pending', '%d events pending', $count, 'ultraguard-security-suite' ), $count ),
                /* translators: %s: string */
                'message'    => sprintf( __( 'Oldest: %s ago. Events flush automatically on shutdown.', 'ultraguard-security-suite' ), human_time_diff( $oldest ) ),
            ],
            [
                'type'  => 'list',
                'items' => $items,
            ],
        ];
    }

    protected function build_threat_panel( array $summary ): array {
        $active = (int) ( $summary['active'] ?? 0 );

        if ( 0 === $active ) {
            return [
                [
                    'type'       => 'alert-box',
                    'alert_type' => 'warning',
                    'title'      => __( 'No threat IPs loaded', 'ultraguard-security-suite' ),
                    'message'    => __( 'Click "Sync Blacklist Now" to download global threat intelligence.', 'ultraguard-security-suite' ),
                ],
            ];
        }

        $cloud  = (int) ( $summary['cloud'] ?? 0 );
        $crowd  = (int) ( $summary['crowd'] ?? 0 );
        $manual = (int) ( $summary['manual'] ?? 0 );
        $pct    = static function ( int $count ) use ( $active ): string {
            return $active > 0 ? round( ( $count / $active ) * 100, 1 ) . '%' : '0%';
        };

        return [
            [
                'type'       => 'data-table',
                'id'         => 'si-threat-table',
                'columns'    => [
                    'source' => [ 'title' => __( 'Source', 'ultraguard-security-suite' ) ],
                    'count'  => [ 'title' => __( 'IPs', 'ultraguard-security-suite' ), 'width' => '110px' ],
                    'pct'    => [ 'title' => __( 'Share', 'ultraguard-security-suite' ), 'width' => '80px' ],
                ],
                'data'       => [
                    [ 'source' => __( 'Cloud Blacklist (server-synced)', 'ultraguard-security-suite' ), 'count' => number_format_i18n( $cloud ), 'pct' => $pct( $cloud ) ],
                    [ 'source' => __( 'Crowd Reports (other sites)', 'ultraguard-security-suite' ), 'count' => number_format_i18n( $crowd ), 'pct' => $pct( $crowd ) ],
                    [ 'source' => __( 'Manual (admin-added)', 'ultraguard-security-suite' ), 'count' => number_format_i18n( $manual ), 'pct' => $pct( $manual ) ],
                    [ 'source' => '<strong>' . __( 'Total Active', 'ultraguard-security-suite' ) . '</strong>', 'count' => '<strong>' . number_format_i18n( $active ) . '</strong>', 'pct' => '<strong>100%</strong>' ],
                ],
                'searchable' => false,
                'pagination' => [ 'enabled' => false ],
                'empty_state'=> [ 'title' => '', 'message' => '' ],
            ],
        ];
    }

    protected function build_tier_card( bool $is_pro, int $last_pull ): array {
        /* translators: %s: string */
        $last_str = $last_pull ? sprintf( __( 'Last pull: %s ago', 'ultraguard-security-suite' ), human_time_diff( $last_pull ) ) : __( 'Never synced', 'ultraguard-security-suite' );

        if ( $is_pro ) {
            return [
                'type'  => 'card',
                'title' => __( 'Pro - Immediate Sync', 'ultraguard-security-suite' ),
                'icon'  => 'dashicons-awards',
                'data'  => [
                    [ 'type' => 'alert-box', 'alert_type' => 'success', 'title' => __( 'Pro license active', 'ultraguard-security-suite' ), 'message' => $last_str ],
                    [
                        'type'  => 'list',
                        'items' => [
                            [ 'icon' => 'dashicons-yes', 'text' => __( 'Threat IP blacklist: hourly', 'ultraguard-security-suite' ) ],
                            [ 'icon' => 'dashicons-yes', 'text' => __( 'Malware signatures: 0-day', 'ultraguard-security-suite' ) ],
                            [ 'icon' => 'dashicons-yes', 'text' => __( 'Vulnerability DB: 0-day', 'ultraguard-security-suite' ) ],
                            [ 'icon' => 'dashicons-yes', 'text' => __( 'Cloud firewall rules: instant', 'ultraguard-security-suite' ) ],
                            [ 'icon' => 'dashicons-yes', 'text' => __( 'Push events: real-time', 'ultraguard-security-suite' ) ],
                        ],
                    ],
                ],
            ];
        }

        return [
            'type'  => 'card',
            'title' => __( 'Free — 24-Hour Delay', 'ultraguard-security-suite' ),
            'icon'  => 'dashicons-clock',
            'data'  => [
                [ 'type' => 'alert-box', 'alert_type' => 'warning', 'title' => __( 'Pull updates delivered within 24 hours', 'ultraguard-security-suite' ), 'message' => $last_str ],
                [
                    'type'  => 'list',
                    'items' => [
                        [ 'icon' => 'dashicons-yes', 'text' => __( 'Push events: real-time', 'ultraguard-security-suite' ) ],
                        [ 'icon' => 'dashicons-clock', 'text' => __( 'Threat blacklist: within 24h', 'ultraguard-security-suite' ) ],
                        [ 'icon' => 'dashicons-clock', 'text' => __( 'Malware signatures: within 24h', 'ultraguard-security-suite' ) ],
                        [ 'icon' => 'dashicons-clock', 'text' => __( 'Vulnerability DB: within 24h', 'ultraguard-security-suite' ) ],
                        [ 'icon' => 'dashicons-clock', 'text' => __( 'Firewall rules: within 24h', 'ultraguard-security-suite' ) ],
                    ],
                ],
                [
                    'type'         => 'button',
                    'text'         => __( 'Upgrade to Pro', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                    'icon'         => 'dashicons-awards',
                                    'url'          => 'https://ultraguard.net/pricing',
                    'target'       => '_blank',
                ],
            ],
        ];
    }
}
