<?php

namespace UltraguardPro\modules\server_intelligence\pages;

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

use UltraguardPro\support\LicenseInfo;
use UltraguardPro\support\ServerCommunication;

class ServerIntelligenceDashboard extends ServerIntelligencePage {

    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' );
        $sync_config = $this->server_communication()->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 && method_exists( $threat_t, 'get_threat_summary' ) ? $threat_t->get_threat_summary() : [];

        return [
            'type'      => 'page',
            'id'        => 'ultraguard-server-intelligence-dashboard',
            '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' )
                    : __( 'Free: Updates delivered within 24 hours. Push events always real-time.', 'ultraguard-security-suite' ),
                '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_url_button( __( 'Settings', 'ultraguard-security-suite' ), $this->get_page_url( 'server-intelligence-settings' ), 'secondary', 'dashicons-admin-settings' ),
                    $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( [
                ! $is_pro ? [
                    'type'       => 'alert-box',
                    'alert_type' => 'info',
                    'title'      => __( '⏱ Free Tier: Intelligence updates delivered within 24 hours', 'ultraguard-security-suite' ),
                    'message'    => __( 'Your site is protected — all threat signatures, IP blocklists, and firewall rules are updated within 24 hours of publication. Pro users receive updates in real time (within minutes). Push events and emergency alerts are always instant on all tiers.', 'ultraguard-security-suite' ),
                    'actions'    => [
                        [
                            'type'         => 'button',
                            'text'         => __( 'Upgrade to Pro for Real-Time Updates →', 'ultraguard-security-suite' ),
                            'button_style' => 'secondary',
                            'url'          => \UltraguardPro\support\UpgradeManager::upgrade_page_url(),
                        ],
                    ],
                ] : null,
                [
                    'type'       => 'alert-box',
                    'alert_type' => 'info',
                    'title'      => __( 'Sync controls moved to Settings', 'ultraguard-security-suite' ),
                    'message'    => __( 'Automatic fetch intervals now live on the dedicated Server Intelligence settings page, while this dashboard focuses on live status, queues, and cloud data health.', 'ultraguard-security-suite' ),
                    'actions'    => [
                        [
                            'type'         => 'button',
                            'text'         => __( 'Open Settings', 'ultraguard-security-suite' ),
                            'button_style' => 'secondary',
                            'url'          => $this->get_page_url( 'server-intelligence-settings' ),
                        ],
                    ],
                ],
                [
                    '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' => ( (int) ( $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' ] ],
                    ],
                ],
                [
                    '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' ) ),
                                ],
                            ],
                        ],
                    ],
                ],
                [
                    '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' => false ],
        ];
    }
}
