<?php
/**
 * ServerIntelligencePage — Admin UI for the Server Communication / Intelligence Sync feature.
 *
 * All render component types are verified against WidgetRenderer:
 *   stat-card, data-table, alert-box, card, list, grid
 *
 * @package UltraguardPro\support
 * @since   6.6.0
 */

namespace UltraguardPro\support;

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

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

class ServerIntelligencePage extends BasePage {

    protected string $ajax_nonce_action = 'ultraguard_admin_nonce';

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

    public function get_scheme( $context ): array {
        $is_pro      = LicenseInfo::instance()->isPro();
        $free_delay  = LicenseInfo::instance()->getUpdateDelay();
        $queue       = (array) get_option( 'ultraguard_push_queue', [] );
        $queue_size  = count( $queue );
        $last_pull   = (int) get_option( 'ultraguard_si_last_pull', 0 );
        $sig_ver     = (string) get_option( 'ultraguard_si_sig_version',  '' );
        $vuln_ver    = (string) get_option( 'ultraguard_si_vuln_version', '' );
        $nonce       = $this->create_nonce( 'ultraguard_admin_nonce' );
        $si          = new ServerCommunication( $this->plugin );
        $sync_config = $si->get_schedule_snapshot();

        $db_tables = $this->plugin->modules->get_db_tables();
        $threat_t  = $db_tables ? $db_tables->get_table( 'threat_ips' ) : null;
        $threat_s  = $threat_t ? $threat_t->get_threat_summary() : [];

        return [
            'type'      => 'page',
            'id'        => 'ultraguard-server-intelligence',
            'page_slug' => 'server-intelligence',

            'header' => [
                'title'    => __( 'Server Intelligence', 'ultraguard-security-suite' ),
                'subtitle' => $is_pro
                    ? __( 'Pro: All threat data synced immediately. Push events delivered in real-time.', 'ultraguard-security-suite' )
                    : sprintf(
                        /* translators: Placeholder values are inserted into this string. */
                        __( 'Free: Pull updates delayed %d days. Push events always real-time.', 'ultraguard-security-suite' ),
                        $free_delay
                      ),
                'badge' => [
                    'text'       => $is_pro
                        ? __( 'Pro — Immediate Sync', 'ultraguard-security-suite' )
                        : __( 'Free — Within 24 Hours', 'ultraguard-security-suite' ),
                    'badge_type' => $is_pro ? 'success' : 'warning',
                ],
                'actions' => [
                    $this->create_ajax_button(
                        __( 'Pull All Now', 'ultraguard-security-suite' ),
                        'ultraguard_si_pull_all', [], 'primary', 'dashicons-update',
                        __( 'Force-sync all intelligence sources from the server?', 'ultraguard-security-suite' )
                    ),
                    $this->create_ajax_button(
                        __( 'Test Connection', 'ultraguard-security-suite' ),
                        'ultraguard_si_test_pull', [], 'secondary', 'dashicons-networking'
                    ),
                    $this->create_ajax_button(
                        __( 'Test Push', 'ultraguard-security-suite' ),
                        'ultraguard_si_test_push', [], 'secondary', 'dashicons-upload'
                    ),
                ],
            ],

            'data' => array_values( array_filter( [

                // Free-tier notice
                ! $is_pro ? [
                    'type'       => 'alert-box',
                    'alert_type' => 'warning',
                    'title'      => sprintf(
                        /* translators: Placeholder values are inserted into this string. */
                        __( 'Free Tier: Intelligence updates delayed %d days', 'ultraguard-security-suite' ),
                        $free_delay
                    ),
                    'message' => __( 'Push events (hack attempts, malware, brute force) are always sent to the server instantly. However, pull updates — threat IPs, signatures, vulnerability DB, firewall rules, .htaccess templates — are available within 24 hours of server release. Upgrade to Pro for real-time sync.', 'ultraguard-security-suite' ),
                    'actions' => [ [
                        'type'         => 'button',
                        'text'         => __( 'Upgrade to Pro', 'ultraguard-security-suite' ),
                        'button_style' => 'primary',
                        'url'          => 'https://ultraguard.net/pricing',
                        'target'       => '_blank',
                    ] ],
                ] : null,

                // Stat row
                [
                    'type'  => 'card',
                    'title' => __( 'Automatic Fetch Controls', 'ultraguard-security-suite' ),
                    'icon'  => 'dashicons-controls-repeat',
                    'data'  => array_merge(
                        [
                            [
                                'type'       => 'alert-box',
                                'alert_type' => 'info',
                                'title'      => __( 'Granular sync timing', 'ultraguard-security-suite' ),
                                'message'    => $is_pro
                                    ? __( 'Each intelligence feed can now be enabled and scheduled independently. Faster intervals mean fresher cloud data but more frequent remote checks.', 'ultraguard-security-suite' )
                                    : sprintf(
                                        __( 'You can tune how often each feed checks for updates. Free tier updates arrive within 24 hours of server publication.', 'ultraguard-security-suite' ),
                                        $free_delay
                                    ),
                            ],
                        ],
                        $this->build_sync_control_fields( $sync_config )
                    ),
                ],

                [
                    'type'    => 'grid',
                    'columns' => 12,
                    'gap'     => '16px',
                    'items'   => [
                        [
                            'span' => 3, 'responsive' => [ 'md' => 6, 'sm' => 12 ],
                            'component' => [
                                'type' => 'stat-card',
                                'title' => __( 'Push Queue', 'ultraguard-security-suite' ),
                                'value' => $queue_size, 'format' => 'number',
                                'icon' => 'dashicons-upload',
                                'class' => $queue_size > 20 ? 'warning' : ( $queue_size > 0 ? 'info' : 'success' ),
                            ],
                        ],
                        [
                            'span' => 3, 'responsive' => [ 'md' => 6, 'sm' => 12 ],
                            'component' => [
                                'type' => 'stat-card',
                                'title' => __( 'Cloud Threat IPs', 'ultraguard-security-suite' ),
                                'value' => (int) ( $threat_s['active'] ?? 0 ), 'format' => 'number',
                                'icon' => 'dashicons-shield-alt',
                                'class' => ( $threat_s['active'] ?? 0 ) > 0 ? 'info' : 'warning',
                            ],
                        ],
                        [
                            'span' => 3, 'responsive' => [ 'md' => 6, 'sm' => 12 ],
                            'component' => [
                                'type' => 'stat-card',
                                'title' => __( 'Signature Version', 'ultraguard-security-suite' ),
                                'value' => $sig_ver ?: __( 'Not synced', 'ultraguard-security-suite' ), 'format' => 'string',
                                'icon' => 'dashicons-search',
                                'class' => $sig_ver ? 'success' : 'warning',
                            ],
                        ],
                        [
                            'span' => 3, 'responsive' => [ 'md' => 6, 'sm' => 12 ],
                            'component' => [
                                'type' => 'stat-card',
                                'title' => __( 'Vuln DB Version', 'ultraguard-security-suite' ),
                                'value' => $vuln_ver ?: __( 'Not synced', 'ultraguard-security-suite' ), 'format' => 'string',
                                'icon' => 'dashicons-warning',
                                'class' => $vuln_ver ? 'success' : 'warning',
                            ],
                        ],
                    ],
                ],

                // Pull schedule + Push queue
                [
                    'type' => 'grid', 'columns' => 12, 'gap' => '20px',
                    'items' => [
                        [
                            'span' => 7, 'responsive' => [ 'lg' => 12 ],
                            'component' => [
                                'type' => 'card',
                                'title' => __( 'Pull Schedule', 'ultraguard-security-suite' ),
                                'icon' => 'dashicons-calendar-alt',
                                'data' => [ [
                                    'type'       => 'data-table',
                                    'id'         => 'si-schedule-table',
                                    'columns'    => [
                                        'resource' => [ 'title' => __( 'Resource',  'ultraguard-security-suite' ) ],
                                        'enabled'  => [ 'title' => __( 'Auto Fetch', 'ultraguard-security-suite' ), 'width' => '120px' ],
                                        'interval' => [ 'title' => __( 'Frequency', 'ultraguard-security-suite' ) ],
                                        'next_run' => [ 'title' => __( 'Next Run',  'ultraguard-security-suite' ) ],
                                        'status'   => [ 'title' => __( 'Status',    'ultraguard-security-suite' ) ],
                                        'sync_now' => [ 'title' => '', 'width' => '100px' ],
                                    ],
                                    'data'       => $this->build_schedule_rows( $nonce, $sync_config ),
                                    'searchable' => false,
                                    'pagination' => [ 'enabled' => false ],
                                    'empty_state' => [ 'title' => '', 'message' => __( 'Cron events not yet registered.', 'ultraguard-security-suite' ) ],
                                ] ],
                            ],
                        ],
                        [
                            'span' => 5, 'responsive' => [ 'lg' => 12 ],
                            'component' => [
                                'type' => 'card',
                                'title' => __( 'Push Queue', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-cloud-upload',
                                'data'  => $this->build_queue_panel( $queue ),
                                'footer_actions' => [
                                    $this->create_ajax_button(
                                        __( 'Flush Queue', 'ultraguard-security-suite' ),
                                        'ultraguard_si_flush_queue', [], 'primary', 'dashicons-upload'
                                    ),
                                    $this->create_ajax_button(
                                        __( 'Discard All', 'ultraguard-security-suite' ),
                                        'ultraguard_si_clear_queue', [], 'danger', 'dashicons-trash',
                                        __( 'Permanently discard all queued push events?', 'ultraguard-security-suite' )
                                    ),
                                ],
                            ],
                        ],
                    ],
                ],

                // Threat breakdown + Tier card
                [
                    'type' => 'grid', 'columns' => 12, 'gap' => '20px',
                    'items' => [
                        [
                            'span' => 7, 'responsive' => [ 'lg' => 12 ],
                            'component' => [
                                'type'  => 'card',
                                'title' => __( 'Threat Intelligence Breakdown', 'ultraguard-security-suite' ),
                                'icon'  => 'dashicons-shield-alt',
                                'data'  => $this->build_threat_panel( $threat_s ),
                                'footer_actions' => [
                                    $this->create_ajax_button(
                                        __( 'Purge Expired', 'ultraguard-security-suite' ),
                                        'ultraguard_si_purge_old_ips', [], 'secondary', 'dashicons-trash'
                                    ),
                                    $this->create_ajax_button(
                                        __( 'Sync Blacklist Now', 'ultraguard-security-suite' ),
                                        'ultraguard_si_pull_now', [ 'resource' => 'blacklist' ], 'primary', 'dashicons-update'
                                    ),
                                ],
                            ],
                        ],
                        [
                            'span' => 5, 'responsive' => [ 'lg' => 12 ],
                            'component' => $this->build_tier_card( $is_pro, $last_pull ),
                        ],
                    ],
                ],

            ] ) ),
            'form' => [
                'enable' => true,
                'id'     => 'server-intelligence-settings-form',
                'ajax'   => true,
                'action' => 'ultraguard_si_save_settings',
                'nonce'  => $nonce,
                'submit' => [
                    'text'         => __( 'Save Sync Settings', 'ultraguard-security-suite' ),
                    'button_style' => 'primary',
                    'icon'         => 'dashicons-saved',
                ],
            ],
        ];
    }

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

    private 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 < 86400 ) {
                /* translators: %1$d: integer, %2$d: integer */
                $next_str = sprintf( __( '%1$dh %2$dm', 'ultraguard-security-suite' ), floor( $diff / 3600 ), floor( ( $diff % 3600 ) / 60 ) );
            } 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;
    }

    private 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;
    }

    private 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' ),
        ];
    }

    private function build_queue_panel( array $queue ): array {
        $count = count( $queue );
        if ( $count === 0 ) {
            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 ) {
            $t = $item['event_type'] ?? 'unknown';
            $by_type[ $t ] = ( $by_type[ $t ] ?? 0 ) + 1;
        }
        arsort( $by_type );

        $oldest  = min( array_column( $queue, '_queued_at' ) + [ time() ] );
        $age_sec = time() - (int) $oldest;

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

        return [
            [
                'type' => 'alert-box',
                'alert_type' => $age_sec > 3600 ? '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 ],
        ];
    }

    private function build_threat_panel( array $summary ): array {
        $active = (int) ( $summary['active'] ?? 0 );
        if ( $active === 0 ) {
            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    = fn( $n ) => $active > 0 ? round( $n / $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' => '' ],
        ] ];
    }

    private 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',
                ],
            ],
        ];
    }
}
