<?php

declare(strict_types=1);

namespace WPUltimateSecurity\UltimateSecurity\Modules\TestMode;

use WPUltimateSecurity\UltimateSecurity\Modules\Base\AbstractModule;

class TestModeModule extends AbstractModule
{
    public const MODULE_ID = 'system.test_mode';

    protected const VERSION = '2.0.0';

    /**
     * Get unique module identifier.
     */
    public static function getId(): string
    {
        return self::MODULE_ID;
    }

    /**
     * Get human-readable module name.
     */
    public static function getName(): string
    {
        return __('Test Mode', 'ultimate-security');
    }

    /**
     * Get module domain.
     */
    public static function getDomain(): string
    {
        return 'system';
    }

    /**
     * Boot the module after registration.
     */
    public static function boot(): void
    {
        add_action('admin_notices', [self::class, 'displayTestModeNotice']);
        add_action('wp_dashboard_setup', [self::class, 'registerDashboardWidget']);
        add_action('update_option_ultimate_security_options', [TestModeService::class, 'resetCache']);
        //display test mode admin bar if enabled
        if (TestModeService::isEnabled()) {
            add_action('wp_before_admin_bar_render', [self::class, 'displayTestModeAdminBar']);
        }
    }

    /**
     * Display test mode admin bar if enabled
     */
    public static function displayTestModeAdminBar(): void
    {
        if (!is_admin_bar_showing()) {
            return;
        }

        global $wp_admin_bar;

        if (!current_user_can('manage_options')) {
            return;
        }

        $args = [
            'id' => 'ultimate_security_test_mode',
            'title' => '<span class="ab-icon"></span>' . __('Test Mode is Active for Ultimate Security', 'ultimate-security'),
            'href' => admin_url('admin.php?page=ultimate-security#/settings/monitoring/test-mode'),
            'meta' => [
                'class' => 'ultimate-security-test-mode-admin-bar',
                'title' => __('Test Mode is currently active. Click to configure.', 'ultimate-security'),
            ],
        ];

        $wp_admin_bar->add_node($args);
    }

    /**
     * Display admin notice when test mode is active
     */
    public static function displayTestModeNotice(): void
    {
        if (!TestModeService::isEnabled()) {
            return;
        }

        if (!current_user_can('manage_options')) {
            return;
        }

        $settings = TestModeService::getSettings();
        if (!($settings['show_dashboard_notice'] ?? true)) {
            return;
        }

        $affectedRoles = $settings['affected_roles'] ?? [];
        if (empty($affectedRoles)) {
            $rolesText = __('no roles selected', 'ultimate-security');
        } else {
            $roleNames = array_map(function ($role) {
                return ucfirst(str_replace('_', ' ', $role));
            }, $affectedRoles);
            $rolesText = implode(', ', $roleNames);
        }

        $todayCount = TestModeService::getSimulationCount('today');

        printf(
            '<div class="notice notice-warning is-dismissible"><p><strong>%s</strong> %s <a href="%s">%s</a></p></div>',
            esc_html__('Ultimate Security Test Mode Active:', 'ultimate-security'),
            sprintf(
                /* translators: 1: list of roles, 2: count of simulated blocks */
                esc_html__('Security features are simulated for roles: %1$s. Simulated blocks today: %2$d.', 'ultimate-security'),
                esc_html($rolesText),
                (int) $todayCount
            ),
            esc_url(admin_url('admin.php?page=ultimate-security#/settings/monitoring/test-mode')),
            esc_html__('Configure', 'ultimate-security')
        );
    }

    /**
     * Register the dashboard widget
     */
    public static function registerDashboardWidget(): void
    {
        if (!TestModeService::isEnabled()) {
            return;
        }

        if (!current_user_can('manage_options')) {
            return;
        }

        wp_add_dashboard_widget(
            'ultimate_security_test_mode_widget',
            __('Ultimate Security - Test Mode Activity', 'ultimate-security'),
            [self::class, 'renderDashboardWidget']
        );
    }

    /**
     * Render the dashboard widget content
     */
    public static function renderDashboardWidget(): void
    {
        $todayCount = TestModeService::getSimulationCount('today');
        $weekCount = TestModeService::getSimulationCount('week');
        $monthCount = TestModeService::getSimulationCount('month');
        $byModule = TestModeService::getSimulationsByModule('today');

        echo '<div class="ultimate-security-test-mode-widget">';

        echo '<p><strong>' . esc_html__('Simulated Blocks:', 'ultimate-security') . '</strong></p>';
        echo '<ul style="margin-left: 20px;">';
        echo '<li>' . sprintf(esc_html__('Today: %d', 'ultimate-security'), absint($todayCount)) . '</li>';
        echo '<li>' . sprintf(esc_html__('This Week: %d', 'ultimate-security'), absint($weekCount)) . '</li>';
        echo '<li>' . sprintf(esc_html__('This Month: %d', 'ultimate-security'), absint($monthCount)) . '</li>';

        echo '</ul>';

        if (!empty($byModule)) {
            echo '<p><strong>' . esc_html__('By Module (Today):', 'ultimate-security') . '</strong></p>';
            echo '<ul style="margin-left: 20px;">';
            foreach ($byModule as $module => $count) {
                $moduleName = ucwords(str_replace('_', ' ', $module));
                echo '<li>' . esc_html($moduleName) . ': ' . esc_html((string) $count) . '</li>';
            }
            echo '</ul>';
        }

        echo '<p style="margin-top: 15px;">';
        echo '<a href="' . esc_url(admin_url('admin.php?page=ultimate-security#/settings/more/test-mode')) . '" class="button button-primary">';
        echo esc_html__('View Details', 'ultimate-security');
        echo '</a>';
        echo '</p>';

        echo '</div>';
    }
}
