<?php
/**
 * DashboardContributor — Registers the aggregate security-score stat card
 * into DashboardRegistry on behalf of the Dashboard module itself.
 *
 * Each feature module registers its OWN stats. This class only contributes
 * the top-level security score and the "all good" / "threats detected" alert.
 *
 * @package UltraguardPro\modules\dashboard
 */

namespace UltraguardPro\modules\dashboard;

use UltraguardPro\Plugin;

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

class DashboardContributor {

    private Plugin $plugin;

    public function __construct( Plugin $plugin ) {
        $this->plugin = $plugin;
    }

    /**
     * Register the contribution hook.
     * Uses `admin_init` priority 20 so all modules have booted first.
     * Guard inside contribute() ensures DB work only runs on the dashboard page.
     */
    public function register(): void {
        add_action( 'admin_init', [ $this, 'contribute' ], 20 );
    }

    /**
     * Fire all dashboard registration actions.
     * Called on `admin_init` priority 20 — gated so queries only run on the
     * dashboard page itself, not on Firewall, Antivirus, or any other page.
     */
    public function contribute(): void {
        if ( ! \UltraguardPro\core\Admin::is_ultraguard_dashboard() ) { return; }

        $handler = new DashboardDataHandler( $this->plugin );
        $score   = $handler->get_security_score();
        $value   = (int) ( $score['score'] ?? 0 );
        $level   = (string) ( $score['level'] ?? 'warning' );

        $class = match ( $level ) {
            'excellent' => 'success',
            'good'      => 'info',
            'warning'   => 'warning',
            default     => 'danger',
        };

        // ── Security score stat card (highest priority = leftmost) ────────
        do_action( 'ultraguard_dashboard_register_stat', [
            'id'       => 'stat-security-score',
            'title'    => __( 'Security Score', 'ultraguard-security-suite' ),
            'value'    => $value,
            'format'   => 'percentage',
            'icon'     => 'dashicons-shield-alt',
            'class'    => $class,
            'animated' => true,
            'hide_when_empty' => true,
            'priority' => 1,
            'span'     => 3,
        ] );

        // ── SSL status stat card ──────────────────────────────────────────
        do_action( 'ultraguard_dashboard_register_stat', [
            'id'       => 'stat-ssl-status',
            'title'    => __( 'HTTPS', 'ultraguard-security-suite' ),
            'value'    => is_ssl() ? __( 'Enabled', 'ultraguard-security-suite' ) : __( 'Disabled', 'ultraguard-security-suite' ),
            'format'   => 'text',
            'icon'     => is_ssl() ? 'dashicons-lock' : 'dashicons-unlock',
            'class'    => is_ssl() ? 'success' : 'danger',
            'animated' => false,
            'hide_when_empty' => true,
            'priority' => 2,
            'span'     => 3,
        ] );

        // ── WordPress version currency ────────────────────────────────────
        global $wp_version;
        $update  = get_transient( 'update_core' );
        $wp_ok   = true;
        $wp_val  = $wp_version ?? '—';
        if ( $update && ! empty( $update->updates[0]->version ) ) {
            $latest = $update->updates[0]->version;
            if ( version_compare( $wp_version, $latest, '<' ) ) {
                $wp_ok  = false;
                $wp_val = sprintf(
                    /* translators: %s: latest WP version */
                    __( 'Update to %s', 'ultraguard-security-suite' ),
                    $latest
                );
            }
        }

        do_action( 'ultraguard_dashboard_register_stat', [
            'id'       => 'stat-wp-version',
            'title'    => __( 'WordPress', 'ultraguard-security-suite' ),
            'value'    => $wp_val,
            'format'   => 'text',
            'icon'     => 'dashicons-wordpress',
            'class'    => $wp_ok ? 'success' : 'warning',
            'animated' => false,
            'hide_when_empty' => true,
            'priority' => 3,
            'span'     => 3,
        ] );

        // ── Active threats / malware stat — only shown when > 0 ──────────
        $scan_table = $this->plugin->modules->get_db_tables()
            ? $this->plugin->modules->get_db_tables()->get_table( 'scan_results' )
            : null;
        $malware_count = $scan_table ? (int) $scan_table->count( [ 'status' => 'infected' ] ) : 0;

        do_action( 'ultraguard_dashboard_register_stat', [
            'id'             => 'stat-malware-found',
            'title'          => __( 'Malware Found', 'ultraguard-security-suite' ),
            'value'          => $malware_count,
            'format'         => 'number',
            'icon'           => 'dashicons-warning',
            'class'          => $malware_count > 0 ? 'danger' : 'success',
            'animated'       => true,
            'priority'       => 10,
            'span'           => 3,
            'hide_when_empty'=> true,   // suppress this card entirely when value is 0
        ] );

        // ── PHP version currency ──────────────────────────────────────────
        $php_ver    = phpversion();
        $php_class  = version_compare( $php_ver, '8.1', '>=' ) ? 'success' : 'warning';

        do_action( 'ultraguard_dashboard_register_stat', [
            'id'       => 'stat-php-version',
            'title'    => __( 'PHP Version', 'ultraguard-security-suite' ),
            'value'    => $php_ver,
            'format'   => 'text',
            'icon'     => 'dashicons-code-standards',
            'class'    => $php_class,
            'animated' => false,
            'hide_when_empty' => true,
            'priority' => 4,
            'span'     => 3,
        ] );

        // ── Cloud threat intelligence stats ───────────────────────────────
        $threat_t     = $this->plugin->modules->get_db_tables()
                        ? $this->plugin->modules->get_db_tables()->get_table( 'threat_ips' )
                        : null;
        $threat_count = $threat_t ? (int) $threat_t->count( [ 'is_active' => 1 ] ) : 0;

        do_action( 'ultraguard_dashboard_register_stat', [
            'id'       => 'stat-threat-ips',
            'title'    => __( 'Cloud Threat IPs', 'ultraguard-security-suite' ),
            'value'    => $threat_count,
            'format'   => 'number',
            'icon'     => 'dashicons-cloud',
            'class'    => $threat_count > 0 ? 'info' : 'warning',
            'animated' => true,
            'priority' => 11,
            'span'     => 3,
            'link'     => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=server-intelligence' ),
            'tooltip'  => __( 'Global threat IPs synced from UltraGuard server. Click to manage.', 'ultraguard-security-suite' ),
            'hide_when_empty'=> true,
        ] );

        // ── Push queue depth ─────────────────────────────────────────────
        $queue_size = count( (array) get_option( 'ultraguard_push_queue', [] ) );

        if ( $queue_size > 0 ) {
            do_action( 'ultraguard_dashboard_register_stat', [
                'id'             => 'stat-push-queue',
                'title'          => __( 'Pending Push Events', 'ultraguard-security-suite' ),
                'value'          => $queue_size,
                'format'         => 'number',
                'icon'           => 'dashicons-upload',
                'class'          => $queue_size > 20 ? 'warning' : 'info',
                'animated'       => true,
                'priority'       => 12,
                'span'           => 3,
                'link'           => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=server-intelligence' ),
                'hide_when_empty'=> true,
            ] );
        }

        // ── Server Intelligence status item ───────────────────────────────
        $last_pull = (int) get_option( 'ultraguard_si_last_pull', 0 );
        $si_ok     = $last_pull > 0 && ( time() - $last_pull ) < 2 * DAY_IN_SECONDS;

        do_action( 'ultraguard_dashboard_register_status', [
            'id'       => 'status-server-intelligence',
            'label'    => __( 'Server Intelligence', 'ultraguard-security-suite' ),
            'status'   => $si_ok ? 'active' : 'warning',
            'detail'   => $last_pull
                /* translators: %s: string */
                ? sprintf( __( 'Last pull: %s', 'ultraguard-security-suite' ), human_time_diff( $last_pull ) . ' ago' )
                : __( 'Never synced', 'ultraguard-security-suite' ),
            'icon'     => 'dashicons-cloud',
            'priority' => 50,
            'button_style' => 'secondary',
            'size'  => 'small',
            'link'     => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=server-intelligence' ),
            'hide_when_empty'=> true,
        ] );

        // ── Upgrade recommendation (free users only) ──────────────────────
        if ( ! \UltraguardPro\support\LicenseInfo::instance()->isPro() ) {
            do_action( 'ultraguard_dashboard_register_recommendation', [
                'id'       => 'rec-upgrade-pro',
                'icon'     => 'dashicons-awards',
                'title'    => __( 'Upgrade to Pro for zero-day protection', 'ultraguard-security-suite' ),
                'detail'   => __( 'Pro users get malware signatures, IP blacklists, and firewall rules the moment they\'re published — zero delay. Free users receive updates within 24 hours.', 'ultraguard-security-suite' ),
                'action'   => [
                    'label' => __( 'Compare Free vs Pro →', 'ultraguard-security-suite' ),
                    'url'   => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=upgrade' ),
                ],
                'priority' => 1,
                'severity' => 'warning',
            ] );
        }
    }
}