<?php
/**
 * Dashboard tab — overview with stats, top attackers, modules at-a-glance.
 *
 * @package Brainwerk Security Suite
 */

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

global $wpdb;

// ===== Hero data: live threat score + action items =====
$digest        = Shieldforge_Threat_Intel::build_digest();
$score_data    = $digest['score'];
$score_value   = (int) $score_data['score'];
$score_label   = (string) $score_data['label'];
$snap_24h      = $digest['snapshot_24h'];
$snap_top_ips  = $digest['top_attackers'];
$snap_top_users = $digest['top_usernames'];
// Re-use the dashboard-widget's action-item builder (same logic / same nags).
$hero_actions  = array();
if ( class_exists( 'Shieldforge_Dashboard_Widget' ) ) {
    $hero_actions = Shieldforge_Dashboard_Widget::action_items( $snap_24h, $score_data, $snap_top_ips, $snap_top_users );
}

$score_pretty = array(
    'calm'     => __( 'All systems calm', 'brainwerk-security-suite' ),
    'elevated' => __( 'Slightly elevated activity', 'brainwerk-security-suite' ),
    'high'     => __( 'High threat level — review now', 'brainwerk-security-suite' ),
    'critical' => __( 'CRITICAL — investigate immediately', 'brainwerk-security-suite' ),
);
$score_emoji = array(
    'calm' => '✓', 'elevated' => '⚠', 'high' => '⚠', 'critical' => '⚡',
);

$since_24h = gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS );
$since_7d  = gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS * 7 );

$stats_24h = array(
    'logins_ok'   => Shieldforge_Logger::count_since( $since_24h, array( 'event_type' => Shieldforge_Logger::EVT_LOGIN_OK ) ),
    'logins_fail' => Shieldforge_Logger::count_since( $since_24h, array( 'event_type' => Shieldforge_Logger::EVT_LOGIN_FAIL ) ),
    'lockouts'    => Shieldforge_Logger::count_since( $since_24h, array( 'event_type' => Shieldforge_Logger::EVT_BF_LOCKOUT ) ),
    'probing'     => Shieldforge_Logger::count_since( $since_24h, array( 'event_type' => Shieldforge_Logger::EVT_PROBING_404 ) ),
);
$top_ips      = Shieldforge_Logger::top_attacker_ips( 24, 5 );
$active_blocks = Shieldforge_Bruteforce::active_blocks();

// Build 24h hourly buckets for the failed-login sparkline.
$buckets = array_fill( 0, 24, 0 );
$log_table = Shieldforge_Utils::table( 'log' );
$rows_h = $wpdb->get_results( $wpdb->prepare( 'SELECT HOUR(created_at) AS h, COUNT(*) AS c FROM ' . $log_table . ' WHERE event_type = %s AND created_at >= %s GROUP BY HOUR(created_at)', Shieldforge_Logger::EVT_LOGIN_FAIL, $since_24h ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $log_table is a trusted internal table name ($wpdb->prefix), never user input; %s placeholders used for actual values; custom security table, direct live read by design, not cacheable.
foreach ( (array) $rows_h as $r ) {
    $idx = (int) $r->h;
    if ( $idx >= 0 && $idx < 24 ) {
        $buckets[ $idx ] = (int) $r->c;
    }
}
$max = max( 1, max( $buckets ) );
$pts = array();
foreach ( $buckets as $i => $v ) {
    $x = (int) ( ( $i / 23 ) * 200 );
    $y = (int) ( 40 - ( $v / $max ) * 36 );
    $pts[] = $x . ',' . $y;
}
$sparkline_points = implode( ' ', $pts );

$module_status = array(
    __( 'Login Logging', 'brainwerk-security-suite' )       => Shieldforge_Settings::get( 'login_log_enabled' ),
    __( 'Brute-Force Protection', 'brainwerk-security-suite' ) => Shieldforge_Settings::get( 'bruteforce_enabled' ),
    __( 'Hardening', 'brainwerk-security-suite' )           => Shieldforge_Settings::get( 'hardening_security_headers' ),
    __( '404 Probing Tracking', 'brainwerk-security-suite' ) => Shieldforge_Settings::get( 'probing_track_enabled' ),
    __( 'Email Notifications', 'brainwerk-security-suite' ) => Shieldforge_Settings::get( 'notify_email_enabled' ),
    __( 'Daily Digest', 'brainwerk-security-suite' )        => Shieldforge_Settings::get( 'digest_enabled' ),
    __( 'IP Anonymization (GDPR)', 'brainwerk-security-suite' ) => Shieldforge_Settings::get( 'privacy_anonymize_ip' ),
    __( 'Anomaly Detection', 'brainwerk-security-suite' )   => Shieldforge_Settings::get( 'anomaly_enabled' ),
);
?>

<!-- ============ Quick-Setup banner (only if not dismissed) ============ -->
<?php Shieldforge_Quick_Setup::render_banner(); ?>

<!-- ============ Hero status banner ============ -->
<div class="sf-hero is-<?php echo esc_attr( $score_label ); ?>">
    <div class="sf-hero-score">
        <div class="sf-hero-score-num"><?php echo (int) $score_value; ?></div>
        <div class="sf-hero-score-max"><?php esc_html_e( '/ 100', 'brainwerk-security-suite' ); ?></div>
    </div>
    <div class="sf-hero-text">
        <div class="sf-hero-headline">
            <span class="sf-hero-emoji"><?php echo esc_html( $score_emoji[ $score_label ] ?? '·' ); ?></span>
            <?php echo esc_html( $score_pretty[ $score_label ] ?? ucfirst( $score_label ) ); ?>
        </div>
        <div class="sf-hero-sub">
            <?php
            printf(
                /* translators: 1: failed-login count 24h, 2: lockouts, 3: distinct-attacker-IPs */
                esc_html__( 'Last 24h: %1$d failed logins, %2$d lockouts, %3$d distinct attacker IPs.', 'brainwerk-security-suite' ),
                (int) ( $snap_24h['logins_fail'] ?? 0 ),
                (int) ( $snap_24h['lockouts'] ?? 0 ),
                (int) ( $snap_24h['distinct_ips'] ?? 0 )
            );
            ?>
        </div>
    </div>
    <div class="sf-hero-bar"><span style="width: <?php echo (int) $score_value; ?>%"></span></div>
</div>

<!-- ============ Action items (only shown when there ARE any) ============ -->
<?php if ( ! empty( $hero_actions ) ) : ?>
    <div class="sf-action-items">
        <h2 class="sf-action-items-title"><?php
            /* translators: %d: action item count */
            printf( esc_html( _n( '%d thing needs your attention', '%d things need your attention', count( $hero_actions ), 'brainwerk-security-suite' ) ), count( $hero_actions ) );
        ?></h2>
        <div class="sf-action-grid">
            <?php foreach ( $hero_actions as $a ) : ?>
                <a class="sf-action-card sf-action-<?php echo esc_attr( $a['severity'] ); ?>" href="<?php echo esc_url( $a['href'] ); ?>">
                    <span class="sf-action-icon"><?php
                        echo esc_html( 'critical' === $a['severity'] ? '⚡' : ( 'warning' === $a['severity'] ? '⚠' : 'ℹ' ) );
                    ?></span>
                    <span class="sf-action-text"><?php echo esc_html( $a['title'] ); ?></span>
                    <span class="sf-action-arrow">→</span>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
<?php else : ?>
    <div class="sf-action-items sf-action-items-empty">
        <?php esc_html_e( '✓ No outstanding action items. Everything that should be on is on, and no recent activity is noisy enough to act on.', 'brainwerk-security-suite' ); ?>
    </div>
<?php endif; ?>

<!-- ============ Detail grid (existing data, now below the hero) ============ -->
<div class="shieldforge-grid">

    <div class="shieldforge-card shieldforge-card--stats">
        <h2><?php esc_html_e( 'Last 24 hours', 'brainwerk-security-suite' ); ?></h2>
        <ul class="shieldforge-stats shieldforge-stats--lg">
            <li>
                <span class="num"><?php echo esc_html( $stats_24h['logins_ok'] ); ?></span>
                <span class="lbl"><?php esc_html_e( 'Successful logins', 'brainwerk-security-suite' ); ?></span>
            </li>
            <li class="<?php echo $stats_24h['logins_fail'] > 10 ? 'warn' : ''; ?>">
                <span class="num"><?php echo esc_html( $stats_24h['logins_fail'] ); ?></span>
                <span class="lbl"><?php esc_html_e( 'Failed logins', 'brainwerk-security-suite' ); ?></span>
                <svg class="sf-sparkline" viewBox="0 0 200 42" preserveAspectRatio="none" aria-hidden="true">
                    <polyline points="<?php echo esc_attr( $sparkline_points ); ?>" fill="none" stroke="#1d6fa5" stroke-width="2"/>
                </svg>
            </li>
            <li class="<?php echo $stats_24h['lockouts'] > 0 ? 'high' : ''; ?>">
                <span class="num"><?php echo esc_html( $stats_24h['lockouts'] ); ?></span>
                <span class="lbl"><?php esc_html_e( 'Lockouts triggered', 'brainwerk-security-suite' ); ?></span>
            </li>
            <li class="<?php echo $stats_24h['probing'] > 5 ? 'warn' : ''; ?>">
                <span class="num"><?php echo esc_html( $stats_24h['probing'] ); ?></span>
                <span class="lbl"><?php esc_html_e( 'Probing 404s', 'brainwerk-security-suite' ); ?></span>
            </li>
        </ul>
    </div>

    <div class="shieldforge-card">
        <h2><?php esc_html_e( 'Module status', 'brainwerk-security-suite' ); ?></h2>
        <ul class="shieldforge-module-list">
            <?php foreach ( $module_status as $label => $on ) : ?>
                <li>
                    <span class="pill <?php echo $on ? 'pill--on' : 'pill--off'; ?>">
                        <?php echo $on ? esc_html__( 'On', 'brainwerk-security-suite' ) : esc_html__( 'Off', 'brainwerk-security-suite' ); ?>
                    </span>
                    <?php echo esc_html( $label ); ?>
                </li>
            <?php endforeach; ?>
        </ul>
    </div>

    <div class="shieldforge-card">
        <h2><?php esc_html_e( 'Top attacker IPs (24h)', 'brainwerk-security-suite' ); ?></h2>
        <?php if ( empty( $top_ips ) ) : ?>
            <p class="muted"><?php esc_html_e( 'Quiet day — nothing to flag.', 'brainwerk-security-suite' ); ?></p>
        <?php else : ?>
            <table class="widefat striped">
                <thead><tr>
                    <th><?php esc_html_e( 'IP', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Hits', 'brainwerk-security-suite' ); ?></th>
                </tr></thead>
                <tbody>
                <?php foreach ( $top_ips as $row ) : ?>
                    <tr>
                        <td><code><?php echo esc_html( $row->ip ?: '—' ); ?></code></td>
                        <td><?php echo esc_html( (int) $row->hits ); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <div class="shieldforge-card">
        <h2><span class="dashicons dashicons-translation"></span> <?php esc_html_e( 'Plugin language', 'brainwerk-security-suite' ); ?></h2>
        <p class="description">
            <?php esc_html_e( 'Language of the Brainwerk Security Suite admin pages. "WordPress default" follows your site / profile language; picking a language overrides it for this plugin only.', 'brainwerk-security-suite' ); ?>
        </p>
        <form method="post" action="">
            <?php wp_nonce_field( 'shieldforge_set_language' ); ?>
            <input type="hidden" name="shieldforge_action" value="set_language" />
            <?php $sf_current_lang = Shieldforge_I18n::admin_language(); ?>
            <select name="shieldforge_language">
                <?php foreach ( Shieldforge_I18n::choices() as $code => $label ) : ?>
                    <option value="<?php echo esc_attr( $code ); ?>" <?php selected( $sf_current_lang, $code ); ?>>
                        <?php echo esc_html( $label ); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <button type="submit" class="button button-secondary"><?php esc_html_e( 'Apply', 'brainwerk-security-suite' ); ?></button>
        </form>
    </div>

    <div class="shieldforge-card">
        <h2><?php esc_html_e( 'Active blocks', 'brainwerk-security-suite' ); ?></h2>
        <?php if ( empty( $active_blocks ) ) : ?>
            <p class="muted"><?php esc_html_e( 'No IPs are currently blocked.', 'brainwerk-security-suite' ); ?></p>
        <?php else : ?>
            <table class="widefat striped">
                <thead><tr>
                    <th><?php esc_html_e( 'IP', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Reason', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Until', 'brainwerk-security-suite' ); ?></th>
                </tr></thead>
                <tbody>
                <?php foreach ( $active_blocks as $row ) : ?>
                    <tr>
                        <td><code><?php echo esc_html( $row->ip ); ?></code></td>
                        <td><?php echo esc_html( $row->reason ); ?></td>
                        <td><?php echo esc_html( $row->blocked_until ); ?> UTC</td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

</div>
