<?php
/**
 * WP dashboard widget — at-a-glance security overview with actionable findings.
 *
 * Layout (top → bottom):
 *   1. Threat header (score, label, color-coded background, mini bar)
 *   2. Action items (max 3) — concrete things the admin should look at
 *   3. 24h stat grid (4 numbers + trend arrow vs. 7-day avg)
 *   4. System-status strip — green/red dots for each protection layer
 *   5. Top attacker IPs (3)
 *   6. Top targeted usernames (3) — reveals what credentials are being guessed
 *   7. Recent events (3, severity-colored)
 *   8. Open-Brainwerk Security Suite CTA
 *
 * @package Brainwerk Security Suite
 */

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

class Shieldforge_Dashboard_Widget {

    public static function register( Shieldforge_Loader $loader ) {
        $loader->add_action( 'wp_dashboard_setup', __CLASS__, 'add_widget' );
        $loader->add_action( 'wp_network_dashboard_setup', __CLASS__, 'add_widget' );
    }

    public static function add_widget() {
        if ( ! current_user_can( 'manage_options' ) && ! current_user_can( 'manage_network_options' ) ) {
            return;
        }
        wp_add_dashboard_widget(
            'shieldforge_overview',
            __( 'Brainwerk Security Suite — Security Overview', 'brainwerk-security-suite' ),
            array( __CLASS__, 'render' )
        );
    }

    /**
     * Build a list of "do this now" items by walking the snapshot for
     * conditions that suggest concrete admin action.
     */
    public static function action_items( array $snap, array $score, array $top_ips, array $top_users ) {
        $items = array();

        // Healthcheck findings (most authoritative — proxy / anonymization / BF off)
        $hc = Shieldforge_Healthcheck::run();
        foreach ( $hc as $f ) {
            $items[] = array(
                'severity' => $f['severity'],
                'title'    => $f['title'],
                'href'     => admin_url( 'admin.php?page=brainwerk-security-suite' ),
            );
        }

        // Critical threat-score
        if ( $score['score'] >= 70 ) {
            $items[] = array(
                'severity' => 'critical',
                'title'    => sprintf(
                    /* translators: %d: threat score */
                    __( 'Threat level CRITICAL (%d/100) — review attacker activity.', 'brainwerk-security-suite' ),
                    $score['score']
                ),
                'href'     => admin_url( 'admin.php?page=brainwerk-security-suite&tab=logs' ),
            );
        } elseif ( $score['score'] >= 40 ) {
            $items[] = array(
                'severity' => 'warning',
                'title'    => sprintf(
                    __( 'Threat level HIGH (%d/100) — review the activity log.', 'brainwerk-security-suite' ),
                    $score['score']
                ),
                'href'     => admin_url( 'admin.php?page=brainwerk-security-suite&tab=logs' ),
            );
        }

        // Lockouts in 24h
        if ( ( $snap['lockouts'] ?? 0 ) >= 3 ) {
            $items[] = array(
                'severity' => 'warning',
                'title'    => sprintf(
                    /* translators: %d: lockout count */
                    __( '%d brute-force lockouts in 24h — check the firewall list.', 'brainwerk-security-suite' ),
                    (int) $snap['lockouts']
                ),
                'href'     => admin_url( 'admin.php?page=brainwerk-security-suite&tab=firewall' ),
            );
        }

        // High failed-login volume
        if ( ( $snap['logins_fail'] ?? 0 ) >= 50 ) {
            $items[] = array(
                'severity' => 'warning',
                'title'    => sprintf(
                    /* translators: %d: failed login count */
                    __( '%d failed logins in 24h — consider tightening the brute-force threshold.', 'brainwerk-security-suite' ),
                    (int) $snap['logins_fail']
                ),
                'href'     => admin_url( 'admin.php?page=brainwerk-security-suite&tab=login' ),
            );
        }

        // Vulnerable active components — highest-impact recurring nag.
        // Only counts vulns on currently-active plugins/themes/core (inactive
        // ones are still listed on the tab but don't shout from the dashboard).
        if ( class_exists( 'Shieldforge_VulnScanner' ) ) {
            $vc_active = Shieldforge_VulnScanner::active_critical_count();
            if ( $vc_active > 0 ) {
                $items[] = array(
                    'severity' => 'critical',
                    'title'    => sprintf(
                        /* translators: %d: vulnerability count on active components */
                        _n( '%d known vulnerability on an active plugin/theme/core. Update or replace ASAP.', '%d known vulnerabilities on active plugins/themes/core. Update or replace ASAP.', $vc_active, 'brainwerk-security-suite' ),
                        $vc_active
                    ),
                    'href'     => admin_url( 'admin.php?page=brainwerk-security-suite&tab=vulnerabilities' ),
                );
            }
        }

        // Suspicious-pattern hits — highest priority among scanner findings.
        if ( ( $snap['malware_suspect'] ?? 0 ) >= 1 ) {
            $items[] = array(
                'severity' => 'critical',
                'title'    => sprintf(
                    /* translators: %d: malware-suspect hit count */
                    _n( '%d suspicious code pattern detected by the scanner — investigate immediately.', '%d suspicious code patterns detected by the scanner — investigate immediately.', (int) $snap['malware_suspect'], 'brainwerk-security-suite' ),
                    (int) $snap['malware_suspect']
                ),
                'href'     => admin_url( 'admin.php?page=brainwerk-security-suite&tab=scanner' ),
            );
        }

        // File changes (warn at 1+, critical at 5+)
        if ( ( $snap['file_changed'] ?? 0 ) >= 5 || ( $snap['file_missing'] ?? 0 ) >= 5 ) {
            $items[] = array(
                'severity' => 'critical',
                'title'    => sprintf(
                    /* translators: 1: changed count, 2: missing count */
                    __( '%1$d files changed and %2$d missing in 24h — verify against intentional updates.', 'brainwerk-security-suite' ),
                    (int) ( $snap['file_changed'] ?? 0 ),
                    (int) ( $snap['file_missing'] ?? 0 )
                ),
                'href'     => admin_url( 'admin.php?page=brainwerk-security-suite&tab=scanner' ),
            );
        } elseif ( ( $snap['file_changed'] ?? 0 ) >= 1 ) {
            $items[] = array(
                'severity' => 'warning',
                'title'    => sprintf(
                    /* translators: %d: changed file count */
                    _n( '%d file changed since the last scan — review on the Scanner tab.', '%d files changed since the last scan — review on the Scanner tab.', (int) $snap['file_changed'], 'brainwerk-security-suite' ),
                    (int) $snap['file_changed']
                ),
                'href'     => admin_url( 'admin.php?page=brainwerk-security-suite&tab=scanner' ),
            );
        }

        // Anomalous logins
        if ( ( $snap['anomalies'] ?? 0 ) >= 1 ) {
            $items[] = array(
                'severity' => 'warning',
                'title'    => sprintf(
                    /* translators: %d: anomaly count */
                    _n( '%d anomalous login flagged — verify it is legitimate.', '%d anomalous logins flagged — verify they are legitimate.', (int) $snap['anomalies'], 'brainwerk-security-suite' ),
                    (int) $snap['anomalies']
                ),
                'href'     => admin_url( 'admin.php?page=brainwerk-security-suite&tab=anomaly' ),
            );
        }

        // Current admin doesn't have 2FA enabled — nudge them. Highest-leverage
        // single change against credential-stuffing, so worth surfacing on
        // every dashboard load until they enroll.
        if ( Shieldforge_TwoFactor::is_module_enabled() ) {
            $cur_uid = get_current_user_id();
            if ( $cur_uid && ! Shieldforge_TwoFactor::is_enabled_for_user( $cur_uid ) ) {
                $items[] = array(
                    'severity' => 'warning',
                    'title'    => __( 'You do not have 2FA enabled. Set it up on your profile — single biggest defense against password attacks.', 'brainwerk-security-suite' ),
                    'href'     => admin_url( 'profile.php#shieldforge-2fa' ),
                );
            }
        }

        // Real admin username being targeted
        $admin_user = wp_get_current_user();
        $admin_login = $admin_user ? $admin_user->user_login : '';
        if ( $admin_login && ! empty( $top_users ) ) {
            foreach ( $top_users as $u ) {
                if ( strcasecmp( $u->username, $admin_login ) === 0 && $u->hits >= 5 ) {
                    $items[] = array(
                        'severity' => 'critical',
                        'title'    => sprintf(
                            /* translators: 1: admin username, 2: hit count */
                            __( 'Your own admin username "%1$s" is being targeted (%2$d attempts in 24h).', 'brainwerk-security-suite' ),
                            $admin_login,
                            (int) $u->hits
                        ),
                        'href'     => admin_url( 'admin.php?page=brainwerk-security-suite&tab=login' ),
                    );
                    break;
                }
            }
        }

        return array_slice( $items, 0, 4 );
    }

    public static function system_status() {
        return array(
            array(
                'label'   => __( 'BF', 'brainwerk-security-suite' ),
                'on'      => (bool) Shieldforge_Settings::get( 'bruteforce_enabled', true ),
                'tooltip' => __( 'Brute-force protection (IP-based)', 'brainwerk-security-suite' ),
            ),
            array(
                'label'   => __( 'Account-lock', 'brainwerk-security-suite' ),
                'on'      => (bool) Shieldforge_Settings::get( 'bf_user_lockout_enabled', true ),
                'tooltip' => __( 'Account-based lockout', 'brainwerk-security-suite' ),
            ),
            array(
                'label'   => __( 'Hardening', 'brainwerk-security-suite' ),
                'on'      => (bool) Shieldforge_Settings::get( 'hardening_disable_xmlrpc', true ),
                'tooltip' => __( 'Hardening (XML-RPC, version, REST, headers)', 'brainwerk-security-suite' ),
            ),
            array(
                'label'   => __( 'Anomaly', 'brainwerk-security-suite' ),
                'on'      => (bool) Shieldforge_Settings::get( 'anomaly_enabled', false ),
                'tooltip' => __( 'Anomaly detection', 'brainwerk-security-suite' ),
            ),
            array(
                'label'   => __( 'Scanner', 'brainwerk-security-suite' ),
                'on'      => (bool) Shieldforge_Settings::get( 'scanner_enabled', true ),
                'tooltip' => __( 'File-integrity + malware-pattern scanner', 'brainwerk-security-suite' ),
            ),
            array(
                'label'   => __( '2FA', 'brainwerk-security-suite' ),
                'on'      => (bool) Shieldforge_Settings::get( 'twofactor_enabled', true ),
                'tooltip' => __( 'Two-factor authentication module', 'brainwerk-security-suite' ),
            ),
            array(
                'label'   => __( 'Vuln-DB', 'brainwerk-security-suite' ),
                'on'      => (bool) Shieldforge_Settings::get( 'vulnscan_enabled', false ),
                'tooltip' => __( 'Plugin/theme/core vulnerability scanner', 'brainwerk-security-suite' ),
            ),
            array(
                'label'   => __( 'Anonymize', 'brainwerk-security-suite' ),
                'on'      => (bool) Shieldforge_Settings::get( 'privacy_anonymize_ip', true ),
                'tooltip' => __( 'IP anonymization (GDPR)', 'brainwerk-security-suite' ),
            ),
            array(
                'label'   => __( 'Digest', 'brainwerk-security-suite' ),
                'on'      => (bool) Shieldforge_Settings::get( 'digest_enabled', true ),
                'tooltip' => __( 'Daily digest e-mail', 'brainwerk-security-suite' ),
            ),
        );
    }

    public static function render() {
        $data    = Shieldforge_Threat_Intel::build_digest();
        $score   = $data['score'];
        $label   = (string) $score['label'];
        $snap    = $data['snapshot_24h'];
        $trend   = $data['trend'];
        $top_ips = $data['top_attackers'];
        $since_24h = gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS );
        $top_users = Shieldforge_Threat_Intel::top_targeted_usernames( $since_24h, 3 );
        $recent  = Shieldforge_Logger::recent( array( 'min_severity' => Shieldforge_Logger::SEV_WARN ), 3, 0 );

        $items   = self::action_items( $snap, $score, $top_ips, $top_users );
        $sysrow  = self::system_status();

        $label_pretty = array(
            'calm'     => __( 'Calm', 'brainwerk-security-suite' ),
            'elevated' => __( 'Elevated', 'brainwerk-security-suite' ),
            'high'     => __( 'High', 'brainwerk-security-suite' ),
            'critical' => __( 'Critical', 'brainwerk-security-suite' ),
        );
        $label_text = isset( $label_pretty[ $label ] ) ? $label_pretty[ $label ] : ucfirst( $label );

        // Helper: trend arrow text per metric key
        $arrow = function( $key ) use ( $trend ) {
            return isset( $trend[ $key ]['arrow'] ) ? $trend[ $key ]['arrow'] : '';
        };
        ?>
        <div class="sf-widget">
            <div class="sf-widget-threat is-<?php echo esc_attr( $label ); ?>">
                <div class="score"><?php echo (int) $score['score']; ?></div>
                <div class="meta">
                    <strong><?php echo esc_html( $label_text ); ?></strong>
                    <span>
                        <?php
                        printf(
                            /* translators: 1: anomalies in 24h, 2: distinct attacker IPs in 24h */
                            esc_html__( '%1$d anomalies · %2$d distinct attackers (24h)', 'brainwerk-security-suite' ),
                            (int) ( $snap['anomalies'] ?? 0 ),
                            (int) ( $snap['distinct_ips'] ?? 0 )
                        );
                        ?>
                    </span>
                </div>
                <div class="bar"><span style="width: <?php echo (int) $score['score']; ?>%"></span></div>
            </div>

            <?php if ( ! empty( $items ) ) : ?>
                <h4 class="sf-widget-h4"><?php esc_html_e( 'Action items', 'brainwerk-security-suite' ); ?></h4>
                <ul class="sf-widget-actions">
                    <?php foreach ( $items as $it ) : ?>
                        <li class="<?php echo esc_attr( 'sev-' . $it['severity'] ); ?>">
                            <a href="<?php echo esc_url( $it['href'] ); ?>"><?php echo esc_html( $it['title'] ); ?></a>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>

            <ul class="sf-widget-stats">
                <li>
                    <span class="num"><?php echo (int) ( $snap['logins_ok'] ?? 0 ); ?></span>
                    <span class="lbl"><?php esc_html_e( 'Logins', 'brainwerk-security-suite' ); ?> <em><?php echo esc_html( $arrow( 'logins_ok' ) ); ?></em></span>
                </li>
                <li class="<?php echo ( ($snap['logins_fail'] ?? 0) > 10 ) ? 'warn' : ''; ?>">
                    <span class="num"><?php echo (int) ( $snap['logins_fail'] ?? 0 ); ?></span>
                    <span class="lbl"><?php esc_html_e( 'Failed', 'brainwerk-security-suite' ); ?> <em><?php echo esc_html( $arrow( 'logins_fail' ) ); ?></em></span>
                </li>
                <li class="<?php echo ( ($snap['lockouts'] ?? 0) > 0 ) ? 'high' : ''; ?>">
                    <span class="num"><?php echo (int) ( $snap['lockouts'] ?? 0 ); ?></span>
                    <span class="lbl"><?php esc_html_e( 'Lockouts', 'brainwerk-security-suite' ); ?> <em><?php echo esc_html( $arrow( 'lockouts' ) ); ?></em></span>
                </li>
                <li class="<?php echo ( ($snap['probing_404s'] ?? 0) > 5 ) ? 'warn' : ''; ?>">
                    <span class="num"><?php echo (int) ( $snap['probing_404s'] ?? 0 ); ?></span>
                    <span class="lbl"><?php esc_html_e( 'Probes', 'brainwerk-security-suite' ); ?> <em><?php echo esc_html( $arrow( 'probing_404s' ) ); ?></em></span>
                </li>
            </ul>

            <div class="sf-widget-sysrow">
                <?php foreach ( $sysrow as $s ) : ?>
                    <span class="<?php echo $s['on'] ? 'on' : 'off'; ?>" title="<?php echo esc_attr( $s['tooltip'] ); ?>">
                        <span class="dot"></span><?php echo esc_html( $s['label'] ); ?>
                    </span>
                <?php endforeach; ?>
            </div>

            <?php if ( ! empty( $top_ips ) || ! empty( $top_users ) ) : ?>
                <div class="sf-widget-cols">
                    <?php if ( ! empty( $top_ips ) ) : ?>
                        <div>
                            <h4 class="sf-widget-h4"><?php esc_html_e( 'Top attackers (24h)', 'brainwerk-security-suite' ); ?></h4>
                            <ul class="sf-widget-ips">
                                <?php foreach ( array_slice( $top_ips, 0, 3 ) as $row ) : ?>
                                    <li>
                                        <code><?php echo esc_html( $row->ip ); ?></code>
                                        <span class="hits"><?php echo (int) $row->hits; ?></span>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>
                    <?php if ( ! empty( $top_users ) ) : ?>
                        <div>
                            <h4 class="sf-widget-h4"><?php esc_html_e( 'Targeted users (24h)', 'brainwerk-security-suite' ); ?></h4>
                            <ul class="sf-widget-ips">
                                <?php foreach ( $top_users as $u ) : ?>
                                    <li>
                                        <code><?php echo esc_html( $u->username ); ?></code>
                                        <span class="hits"><?php echo (int) $u->hits; ?></span>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

            <?php if ( ! empty( $recent ) ) : ?>
                <h4 class="sf-widget-h4"><?php esc_html_e( 'Recent events', 'brainwerk-security-suite' ); ?></h4>
                <ul class="sf-widget-events">
                    <?php foreach ( $recent as $row ) :
                        $sev_class = '';
                        if ( (int) $row->severity >= Shieldforge_Logger::SEV_HIGH ) { $sev_class = 'sev-high'; }
                        elseif ( (int) $row->severity >= Shieldforge_Logger::SEV_WARN ) { $sev_class = 'sev-warn'; }
                    ?>
                        <li class="<?php echo esc_attr( $sev_class ); ?>">
                            <code><?php echo esc_html( $row->event_type ); ?></code>
                            <?php if ( $row->ip ) : ?>
                                <span class="ip"><?php echo esc_html( $row->ip ); ?></span>
                            <?php endif; ?>
                            <span class="ago"><?php echo esc_html( human_time_diff( strtotime( $row->created_at . ' UTC' ), time() ) ); ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>

            <p class="sf-widget-foot">
                <a href="<?php echo esc_url( admin_url( 'admin.php?page=brainwerk-security-suite' ) ); ?>" class="button button-primary">
                    <?php esc_html_e( 'Open Brainwerk Security Suite', 'brainwerk-security-suite' ); ?>
                </a>
            </p>
        </div>
        <?php
    }
}
