<?php
/**
 * LoginLimiterDashboardContributor — Registers Login Limiter data into the main dashboard.
 *
 * Contributes:
 *   • stat-card  : "Failed Logins" with trend
 *   • stat-card  : "Active Lockouts"
 *   • status item: Login Limiter active/inactive
 *   • coverage   : Login security coverage bar
 *   • tile       : Quick-access tile
 *   • recommendation (when lockouts are stacking)
 *
 * @package UltraguardPro\modules\loginlimiter
 * @since   6.5.0
 */

namespace UltraguardPro\modules\loginlimiter;

use UltraguardPro\Plugin;

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

class LoginLimiterDashboardContributor {

    /** @var Plugin */
    private Plugin $plugin;

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

    /**
     * Hook into `init` (priority 20) so tables are available.
     */
    public function register(): void {
        add_action( 'admin_init', [ $this, 'contribute' ], 20 );
    }

    /**
     * Fire all dashboard registration actions.
     */
    public function contribute(): void {
        if ( ! \UltraguardPro\core\Admin::is_ultraguard_dashboard() ) { return; }


        $db      = $this->plugin->modules->get_db_tables();
        $att_t   = $db ? $db->get_table( 'login_attempts' )         : null;
        $lo_t    = $db ? $db->get_table( 'login_limiter_lockouts' )  : null;
        $bl_t    = $db ? $db->get_table( 'll_blocked_ips' )          : null;
        $enabled = (bool) $this->plugin->settings->get_option( 'loginlimiter_enabled', true );

        $today         = gmdate( 'Y-m-d 00:00:00' );
        $failed_logins = $att_t ? $att_t->count( [ 'status' => 'failed' ] )                               : 0;
        $failed_today  = $att_t ? $att_t->count( [ 'status' => 'failed', 'created_at >=' => $today ] )   : 0;
        $lockouts      = $lo_t  ? $lo_t->count( [ 'is_active' => 1 ] )                                    : 0;
        $blocked       = $bl_t  ? $bl_t->count( [ 'is_active' => 1 ] )                                    : 0;

        $two_fa = (bool) $this->plugin->settings->get_option( 'loginlimiter_two_factor_enabled', false );

        // ── Stat: Failed logins ────────────────────────────────────────────────
        do_action( 'ultraguard_dashboard_register_stat', [
            'id'             => 'stat-failed-logins',
            'title'          => __( 'Failed Logins', 'ultraguard-security-suite' ),
            'value'          => $failed_logins,
            'format'         => 'number',
            'icon'           => 'dashicons-admin-users',
            'class'          => $failed_logins > 50 ? 'danger' : ( $failed_logins > 10 ? 'warning' : 'success' ),
            'animated'       => true,
            'trend'          => $failed_today > 0
                ? [ 'direction' => 'up', 'value' => $failed_today, 'text' => __( 'today', 'ultraguard-security-suite' ) ]
                : [],
            'priority'       => 20,
            'span'           => 3,
            'hide_when_empty'=> true,
        ] );

        // ── Stat: Active lockouts ──────────────────────────────────────────────
        do_action( 'ultraguard_dashboard_register_stat', [
            'id'             => 'stat-active-lockouts',
            'title'          => __( 'Active Lockouts', 'ultraguard-security-suite' ),
            'value'          => $lockouts,
            'format'         => 'number',
            'icon'           => 'dashicons-dismiss',
            'class'          => $lockouts > 0 ? 'warning' : 'success',
            'animated'       => true,
            'priority'       => 30,
            'span'           => 3,
            'hide_when_empty'=> true,
        ] );

        // ── Status item ────────────────────────────────────────────────────────
        do_action( 'ultraguard_dashboard_register_status', [
            'id'       => 'status-login-limiter',
            'icon'     => 'dashicons-lock',
            'text'     => __( 'Login Limiter', 'ultraguard-security-suite' ),
            'badge'    => [
                'text'       => $enabled ? __( 'Active', 'ultraguard-security-suite' ) : __( 'Off', 'ultraguard-security-suite' ),
                'badge_type' => $enabled ? 'success' : 'secondary',
            ],
            'actions'  => [
                [
                    'type'         => 'button',
                    'text'         => __( 'Manage', 'ultraguard-security-suite' ),
                    'button_style' => 'secondary',
                    'size'=> 'small',
                    'url'          => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=login-limiter' ),
                ],
            ],
            'priority' => 20,
        ] );

        // ── Coverage bar ───────────────────────────────────────────────────────
        $coverage_value = match ( true ) {
            ! $enabled       => 0,
            $lockouts > 20   => 60,
            $lockouts > 0    => 80,
            $two_fa          => 100,
            default          => 85,
        };

        do_action( 'ultraguard_dashboard_register_coverage', [
            'id'       => 'coverage-login',
            'title'    => __( 'Login Security', 'ultraguard-security-suite' ),
            'value'    => $coverage_value,
            'max'      => 100,
            'status'   => match ( true ) {
                ! $enabled     => 'secondary',
                $lockouts > 20 => 'warning',
                default        => 'success',
            },
            'label'    => $lockouts > 0
                /* translators: %d: number */
                ? sprintf( _n( '%d active lockout', '%d active lockouts', $lockouts, 'ultraguard-security-suite' ), $lockouts )
                : ( $blocked > 0
                    /* translators: %d: number */
                    ? sprintf( _n( '%d IP blocked', '%d IPs blocked', $blocked, 'ultraguard-security-suite' ), $blocked )
                    : __( 'No active threats', 'ultraguard-security-suite' ) ),
            'priority' => 20,
        ] );

        // ── Quick tile ─────────────────────────────────────────────────────────
        do_action( 'ultraguard_dashboard_register_tile', [
            'title'    => __( 'Login', 'ultraguard-security-suite' ),
            'icon'     => 'dashicons-lock',
            'content'  => $enabled
                /* translators: %d: number of locked out users */
                ? ( $lockouts > 0 ? sprintf( _n( '%1$d locked out', '%1$d locked out', $lockouts, 'ultraguard-security-suite' ), $lockouts ) : __( 'Protected', 'ultraguard-security-suite' ) )
                : __( 'Inactive', 'ultraguard-security-suite' ),
            'badge'    => $lockouts > 0
                ? [ 'text' => (string) $lockouts, 'badge_type' => 'warning' ]
                : [],
            'footer'   => [
                'type'         => 'button',
                'text'         => __( 'Open', 'ultraguard-security-suite' ),
                'button_style' => 'secondary',
                'url'          => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=login-limiter' ),
            ],
            'priority' => 20,
        ] );

        // ── Recommendations ────────────────────────────────────────────────────
        if ( $lockouts > 20 ) {
            do_action( 'ultraguard_dashboard_register_recommendation', [
                'title'    => sprintf(
                    /* translators: Placeholder values are inserted into this string. */
                    __( '%d IPs are currently locked out — consider reviewing and clearing expired lockouts.', 'ultraguard-security-suite' ),
                    $lockouts
                ),
                'priority' => 'medium',
                'url'      => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=lockouts' ),
            ] );
        }

        if ( ! $two_fa && $enabled ) {
            do_action( 'ultraguard_dashboard_register_recommendation', [
                'title'    => __( 'Two-factor authentication is not enabled — consider enabling it for admin accounts.', 'ultraguard-security-suite' ),
                'priority' => 'low',
                'url'      => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=login-limiter-settings' ),
            ] );
        }
    }
}
