<?php

namespace UltraguardPro\modules\auto_updater;

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

use UltraguardPro\Plugin;

class AutoUpdaterDashboardContributor {

    private Plugin $plugin;

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

    public function register(): void {
        add_action( 'admin_init', [ $this, 'contribute' ], 20 );
    }

    public function contribute(): void {
        if ( ! \UltraguardPro\core\Admin::is_ultraguard_dashboard() ) { return; }

        $engine  = new UpdateEngine( $this->plugin );
        $pending = $engine->get_pending_updates();
        $log     = $this->plugin->modules->get_db_tables()->get_table( 'update_log' );
        $failed  = $log && method_exists( $log, 'count_by_status' ) ? (int) $log->count_by_status( 'failed' ) : 0;

        do_action( 'ultraguard_dashboard_register_stat', [
            'id'       => 'stat-auto-updater-pending',
            'title'    => __( 'Pending Updates', 'ultraguard-security-suite' ),
            'value'    => count( $pending ),
            'format'   => 'number',
            'icon'     => 'dashicons-update',
            'class'    => count( $pending ) > 0 ? 'warning' : 'success',
            'animated' => true,
            'hide_when_empty' => true,
            'priority' => 85,
            'span'     => 3,
        ] );

        do_action( 'ultraguard_dashboard_register_status', [
            'id'      => 'status-auto-updater',
            'icon'    => 'dashicons-update',
            'text'    => __( 'Auto Updater', 'ultraguard-security-suite' ),
            'badge'   => [
                'text'       => $failed > 0 ? __( 'Failures', 'ultraguard-security-suite' ) : __( 'Ready', 'ultraguard-security-suite' ),
                'badge_type' => $failed > 0 ? 'danger' : 'success',
            ],
            'actions' => [
                [
                    'type' => 'button',
                    'button_style' => 'secondary',
                    'size'  => 'small',
                    'text' => __( 'Manage', 'ultraguard-security-suite' ),
                    'url'  => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=auto-updater' ),
                ],
            ],
        ] );
    }
}
