<?php
/**
 * FilecheckerDashboardContributor — Registers File Checker data into the dashboard registry.
 *
 * Contributes:
 *   • stat-card  : "Files Monitored" with changed-files trend
 *   • status item: File Checker active/inactive badge
 *   • coverage   : File integrity coverage bar
 *   • tile       : Quick-access tile card
 *   • recommendation (when changes detected)
 *
 * Hooks into `init` (priority 20) so the DB tables are available.
 * Uses `do_action` only — no direct calls into other modules.
 *
 * @package UltraguardPro\modules\filechecker
 * @since   6.5.0
 */

namespace UltraguardPro\modules\filechecker;

use UltraguardPro\Plugin;

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

class FilecheckerDashboardContributor {

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

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

    /**
     * Register the `init` hook that feeds the dashboard registry.
     */
    public function register(): void {
        add_action( 'admin_init', [ $this, 'contribute' ], 20 );
    }

    /**
     * Build and dispatch all dashboard contributions via do_action.
     *
     * Called on `init` — tables and settings are already available.
     */
    public function contribute(): void {
        if ( ! \UltraguardPro\core\Admin::is_ultraguard_dashboard() ) { return; }


        $db      = $this->plugin->modules->get_db_tables();
        $fi      = $db ? $db->get_table( 'file_integrity' ) : null;
        $enabled = (bool) $this->plugin->settings->get_option( 'filechecker_enabled', true );

        // ── Counts (batched in two queries via count()) ────────────────────────
        $total_files   = $fi ? $fi->count()                               : 0;
        $changed_files = $fi ? $fi->count( [ 'status' => 'modified' ] )  : 0;
        $suspicious    = $fi ? $fi->count( [ 'status' => 'suspicious' ] ) : 0;
        $quarantined   = $fi ? $fi->count( [ 'status' => 'quarantined' ] ): 0;

        $is_healthy = $enabled && $changed_files === 0 && $suspicious === 0;

        // ── Stat-card ──────────────────────────────────────────────────────────
        do_action( 'ultraguard_dashboard_register_stat', [
            'id'       => 'stat-files-monitored',
            'title'    => __( 'Files Monitored', 'ultraguard-security-suite' ),
            'value'    => $total_files,
            'format'   => 'number',
            'icon'     => 'dashicons-media-document',
            'class'    => $changed_files > 0 ? 'warning' : ( $enabled ? 'success' : 'secondary' ),
            'animated' => true,
            'trend'    => $changed_files > 0
                ? [ 'direction' => 'up', 'value' => $changed_files, 'text' => __( 'changed', 'ultraguard-security-suite' ) ]
                : [],
            'priority' => 40,
            'span'     => 3,
            'hide_when_empty' => true,

        ] );

        // ── Status item ────────────────────────────────────────────────────────
        do_action( 'ultraguard_dashboard_register_status', [
            'id'       => 'status-filechecker',
            'icon'     => 'dashicons-media-code',
            'text'     => __( 'File Checker', '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' ),
                    'size'         => 'small',
                    'button_style' => 'secondary',
                    'url'          => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=filechecker' ),
                ],
            ],
            'priority' => 40,
        ] );

        // ── Coverage bar ───────────────────────────────────────────────────────
        $coverage_value = match ( true ) {
            ! $enabled           => 0,
            $suspicious > 0      => 40,
            $changed_files > 0   => 70,
            default              => 100,
        };

        $coverage_label = match ( true ) {
            ! $enabled           => __( 'Monitoring disabled', 'ultraguard-security-suite' ),
            /* translators: %d: number */
            $suspicious > 0      => sprintf( _n( '%d suspicious file', '%d suspicious files', $suspicious, 'ultraguard-security-suite' ), $suspicious ),
            /* translators: %d: number */
            $changed_files > 0   => sprintf( _n( '%d file changed', '%d files changed', $changed_files, 'ultraguard-security-suite' ), $changed_files ),
            /* translators: %d: number */
            $quarantined > 0     => sprintf( _n( '%d file quarantined', '%d files quarantined', $quarantined, 'ultraguard-security-suite' ), $quarantined ),
            /* translators: %d: number */
            default              => sprintf( _n( '%d file monitored', '%d files monitored', $total_files, 'ultraguard-security-suite' ), $total_files ),
        };

        do_action( 'ultraguard_dashboard_register_coverage', [
            'id'       => 'coverage-files',
            'title'    => __( 'File Integrity', 'ultraguard-security-suite' ),
            'value'    => $coverage_value,
            'max'      => 100,
            'status'   => match ( true ) {
                $suspicious > 0    => 'danger',
                $changed_files > 0 => 'warning',
                $enabled           => 'success',
                default            => 'secondary',
            },
            'label'    => $coverage_label,
            'priority' => 40,
        ] );

        // ── Quick tile ─────────────────────────────────────────────────────────
        do_action( 'ultraguard_dashboard_register_tile', [
            'title'    => __( 'File Checker', 'ultraguard-security-suite' ),
            'icon'     => 'dashicons-media-code',
            'content'  => $enabled
                ? ( $is_healthy ? __( 'All files clean', 'ultraguard-security-suite' ) : __( 'Changes detected', 'ultraguard-security-suite' ) )
                : __( 'Inactive', 'ultraguard-security-suite' ),
            'badge'    => $changed_files > 0
                ? [ 'text' => (string) $changed_files, '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=filechecker' ),
            ],
            'priority' => 40,
        ] );

        // ── Recommendations ────────────────────────────────────────────────────
        if ( $suspicious > 0 ) {
            do_action( 'ultraguard_dashboard_register_recommendation', [
                'title'    => sprintf(
                    /* translators: %d: number of suspicious files. */
                    _n(
                        '%d suspicious file detected — review the File Checker quarantine.',
                        '%d suspicious files detected — review the File Checker quarantine.',
                        $suspicious,
                        'ultraguard-security-suite'
                    ),
                    $suspicious
                ),
                'priority' => 'critical',
                'url'      => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=filechecker-quarantine' ),
            ] );
        } elseif ( $changed_files > 0 ) {
            do_action( 'ultraguard_dashboard_register_recommendation', [
                'title'    => sprintf(
                    /* translators: %d: number of modified files. */
                    _n(
                        '%d file has been modified since the last baseline scan.',
                        '%d files have been modified since the last baseline scan.',
                        $changed_files,
                        'ultraguard-security-suite'
                    ),
                    $changed_files
                ),
                'priority' => $changed_files > 5 ? 'high' : 'medium',
                'url'      => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=filechecker-changes' ),
            ] );
        }
    }
}
