<?php
declare(strict_types=1);

namespace WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\SiteHealth;

use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;
use WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\SiteHealth\Services\HealthCheckService;
use WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\SiteHealth\Collectors\WordPressCollector;
use WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\SiteHealth\Collectors\ServerCollector;
use WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\SiteHealth\Collectors\DatabaseCollector;
use WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\SiteHealth\Collectors\ConstantsCollector;
use WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\SiteHealth\Collectors\FileSystemCollector;
use WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\SiteHealth\Collectors\MediaCollector;
use WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\SiteHealth\Collectors\PluginCollector;
use WPUltimateSecurity\UltimateSecurity\Modules\Monitoring\SiteHealth\Collectors\ThemeCollector;
use WPUltimateSecurity\UltimateSecurity\Modules\Base\AbstractModule;

use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use Exception;

class SiteHealthInfo extends AbstractModule
{
    /**
     * Module identifier.
     */
    public const MODULE_ID = 'monitoring.site_health';

    /**
     * Module version.
     */
    protected const VERSION = '2.0.0';

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

    /**
     * Get the human-readable module name.
     *
     * @return string
     */
    public static function getName(): string
    {
        return __('Site Health Info', 'ultimate-security');
    }

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

    /**
     * Boot the module (registers hooks and handlers).
     *
     * @return void
     */
    public static function boot(): void
    {
        add_action('rest_api_init', array(self::class, 'register_routes'));
    }
    /**
     * Health Check Service instance
     *
     * @var HealthCheckService|null
     */
    private static ?HealthCheckService $healthCheckService = null;


    /**
     * Get the HealthCheckService instance with all collectors registered
     *
     * @return HealthCheckService
     */
    public static function getHealthCheckService(): HealthCheckService
    {
        if (self::$healthCheckService === null) {
            self::$healthCheckService = new HealthCheckService();
            self::registerCollectors();
        }

        return self::$healthCheckService;
    }

    /**
     * Register all collectors with the HealthCheckService
     */
    private static function registerCollectors(): void
    {
        self::$healthCheckService
            ->addCollector(new WordPressCollector())
            ->addCollector(new ServerCollector())
            ->addCollector(new DatabaseCollector())
            ->addCollector(new ConstantsCollector())
            ->addCollector(new FileSystemCollector())
            ->addCollector(new MediaCollector())
            ->addCollector(new PluginCollector())
            ->addCollector(new ThemeCollector());
    }

    /**
     * Register the REST API routes.
     */
    public static function register_routes()
    {
        register_rest_route(
            'ultimate-security/v1',
            '/site-health-info',
            array(
                'methods' => 'GET',
                'callback' => array(self::class, 'get_site_health_info'),
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );

        register_rest_route(
            'ultimate-security/v1',
            '/site-health/mu-plugins',
            array(
                'methods' => 'GET',
                'callback' => array(self::class, 'get_mu_plugins_info'),
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );

        register_rest_route(
            'ultimate-security/v1',
            '/site-health/(?P<tab_id>[a-zA-Z0-9-_]+)',
            array(
                'methods' => 'GET',
                'callback' => array(self::class, 'get_tab_info'),
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
                'args' => array(
                    'tab_id' => array(
                        'required' => true,
                        'sanitize_callback' => 'sanitize_text_field',
                    ),
                ),
            )
        );

        // Health Check Service endpoints using collectors
        register_rest_route(
            'ultimate-security/v1',
            '/health-check',
            array(
                'methods' => 'GET',
                'callback' => array(self::class, 'get_health_check_data'),
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );

        register_rest_route(
            'ultimate-security/v1',
            '/health-check/(?P<collector>[a-zA-Z0-9-_]+)',
            array(
                'methods' => 'GET',
                'callback' => array(self::class, 'get_health_check_collector'),
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
                'args' => array(
                    'collector' => array(
                        'required' => true,
                        'sanitize_callback' => 'sanitize_text_field',
                    ),
                ),
            )
        );

        register_rest_route(
            'ultimate-security/v1',
            '/health-check/collectors',
            array(
                'methods' => 'GET',
                'callback' => array(self::class, 'get_available_collectors'),
                'permission_callback' => function () {
                    return current_user_can('manage_options');
                },
            )
        );
    }

    /**
     * Check if the current user has admin permissions.
     *
     * @return bool Whether the user has permission to access these endpoints.
     */
    public static function check_admin_permissions()
    {
        return current_user_can('manage_options');
    }

    /**
     * Cache key for health check data
     */
    private const HEALTH_CACHE_KEY = 'ultimate_security_health_check';

    /**
     * Cache expiry in seconds (5 minutes)
     */
    private const HEALTH_CACHE_EXPIRY = 300;

    /**
     * Get health check data from all collectors
     *
     * Performance: Results are cached for 5 minutes to prevent repeated expensive operations.
     * Use ?refresh=1 query parameter to force cache refresh.
     *
     * @return WP_REST_Response Health check data from all collectors
     */
    public static function get_health_check_data()
    {
        try {
            // Check for force refresh
            $force_refresh = isset($_GET['refresh']) && $_GET['refresh'] === '1';

            // Try to get cached data
            if (!$force_refresh) {
                $cached = get_transient(self::HEALTH_CACHE_KEY);
                if ($cached !== false) {
                    $cached['cached'] = true;
                    return rest_ensure_response($cached);
                }
            }

            $service = self::getHealthCheckService();
            $data = $service->collectAll();

            // Format the response with collector metadata
            $response = [];
            foreach ($service->getCollectors() as $name => $collector) {
                $response[$name] = [
                    'label' => $collector->getLabel(),
                    'data' => $data[$name] ?? [],
                ];
            }

            $result = [
                'success' => true,
                'collectors' => $response,
                'collector_count' => $service->count(),
                'cached' => false,
                'cache_expires' => time() + self::HEALTH_CACHE_EXPIRY,
            ];

            // Cache the result
            set_transient(self::HEALTH_CACHE_KEY, $result, self::HEALTH_CACHE_EXPIRY);

            return rest_ensure_response($result);
        } catch (Exception $e) {
            return new WP_Error(
                'health_check_error',
                $e->getMessage(),
                array('status' => 500)
            );
        }
    }

    /**
     * Get health check data from a specific collector
     *
     * @param WP_REST_Request $request Full details about the request
     * @return WP_REST_Response Health check data from specific collector
     */
    public static function get_health_check_collector(WP_REST_Request $request)
    {
        try {
            $collector_name = $request->get_param('collector');
            $service = self::getHealthCheckService();

            if (!$service->hasCollector($collector_name)) {
                return new WP_Error(
                    'collector_not_found',
                    sprintf(__('Collector "%s" not found.', 'ultimate-security'), $collector_name),
                    array('status' => 404)
                );
            }

            $collector = $service->getCollector($collector_name);
            $data = $service->collect($collector_name);

            return rest_ensure_response([
                'success' => true,
                'name' => $collector_name,
                'label' => $collector->getLabel(),
                'data' => $data,
            ]);
        } catch (Exception $e) {
            return new WP_Error(
                'health_check_collector_error',
                $e->getMessage(),
                array('status' => 500)
            );
        }
    }

    /**
     * Get list of available collectors
     *
     * @return WP_REST_Response List of available collectors
     */
    public static function get_available_collectors()
    {
        try {
            $service = self::getHealthCheckService();
            $collectors = [];

            foreach ($service->getCollectors() as $name => $collector) {
                $collectors[] = [
                    'name' => $name,
                    'label' => $collector->getLabel(),
                ];
            }

            return rest_ensure_response([
                'success' => true,
                'collectors' => $collectors,
                'count' => count($collectors),
            ]);
        } catch (Exception $e) {
            return new WP_Error(
                'available_collectors_error',
                $e->getMessage(),
                array('status' => 500)
            );
        }
    }

    /**
     * Get site health information
     *
     * @return WP_REST_Response Site health information and tabs list
     */
    public static function get_site_health_info()
    {
        try {
            // Manually create the data structure if WP_Debug_Data is not available
            $site_info = self::get_manual_debug_data();

            // Create tabs data
            $tabs = self::get_tabs_data();

            // Return the data
            return rest_ensure_response(array(
                'data' => $site_info,
                'tabs' => $tabs,
            ));
        } catch (Exception $e) {
            return new WP_Error(
                'site_health_info_error',
                $e->getMessage(),
                array('status' => 500)
            );
        }
    }

    /**
     * Get manually created debug data
     * 
     * @return array Site health information
     */
    private static function get_manual_debug_data()
    {
        global $wpdb;
        $site_info = array();

        // WordPress Information
        $site_info['wordpress'] = array(
            array(
                'label' => __('WordPress Version', 'ultimate-security'),
                'value' => get_bloginfo('version'),
            ),
            array(
                'label' => __('Site Language', 'ultimate-security'),
                'value' => get_bloginfo('language'),
            ),
            array(
                'label' => __('Home URL', 'ultimate-security'),
                'value' => get_home_url(),
            ),
            array(
                'label' => __('Site URL', 'ultimate-security'),
                'value' => get_site_url(),
            ),
            array(
                'label' => __('Permalink Structure', 'ultimate-security'),
                'value' => get_option('permalink_structure') ? get_option('permalink_structure') : __('Default', 'ultimate-security'),
            ),
            array(
                'label' => __('HTTPS Status', 'ultimate-security'),
                'value' => is_ssl() ? __('HTTPS is enabled', 'ultimate-security') : __('HTTPS is not enabled', 'ultimate-security'),
            ),
            array(
                'label' => __('Multisite', 'ultimate-security'),
                'value' => is_multisite() ? __('Yes', 'ultimate-security') : __('No', 'ultimate-security'),
            ),
        );

        // Server Information
        $site_info['server'] = array(
            array(
                'label' => __('PHP Version', 'ultimate-security'),
                'value' => phpversion(),
            ),
            array(
                'label' => __('MySQL Version', 'ultimate-security'),
                'value' => $wpdb->db_version(),
            ),
            array(
                'label' => __('Server Software', 'ultimate-security'),
                'value' => isset($_SERVER['SERVER_SOFTWARE'])
                    ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE']))
                    : __('Not available', 'ultimate-security'),
            ),
            array(
                'label' => __('User Agent', 'ultimate-security'),
                'value' => isset($_SERVER['HTTP_USER_AGENT'])
                    ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT']))
                    : __('Not available', 'ultimate-security'),
            ),
            array(
                'label' => __('PHP Memory Limit', 'ultimate-security'),
                'value' => ini_get('memory_limit'),
            ),
            array(
                'label' => __('PHP Max Execution Time', 'ultimate-security'),
                'value' => ini_get('max_execution_time') . ' ' . __('seconds', 'ultimate-security'),
            ),
            array(
                'label' => __('PHP Max Input Vars', 'ultimate-security'),
                'value' => ini_get('max_input_vars'),
            ),
            array(
                'label' => __('PHP Post Max Size', 'ultimate-security'),
                'value' => ini_get('post_max_size'),
            ),
            array(
                'label' => __('PHP Max Upload Size', 'ultimate-security'),
                'value' => ini_get('upload_max_filesize'),
            ),
        );

        // Database Information
        $site_info['database'] = array(
            array(
                'label' => __('Database Name', 'ultimate-security'),
                'value' => DB_NAME,
            ),
            array(
                'label' => __('Database Host', 'ultimate-security'),
                'value' => DB_HOST,
            ),
            array(
                'label' => __('Database Charset', 'ultimate-security'),
                'value' => $wpdb->charset,
            ),
            array(
                'label' => __('Database Collate', 'ultimate-security'),
                'value' => $wpdb->collate,
            ),
            array(
                'label' => __('Table Prefix', 'ultimate-security'),
                'value' => $wpdb->prefix,
            ),
            array(
                'label' => __('Ultimate Security DB Version', 'ultimate-security'),
                'value' => defined('ULTIMATE_SECURITY_DB_VERSION') ? ULTIMATE_SECURITY_DB_VERSION : __('Not defined', 'ultimate-security'),
            ),
        );

        // Add Pro DB version ONLY if defined
        if (defined('ULTIMATE_SECURITY_PRO_DB_VERSION')) {
            $site_info['database'][] = array(
                'label' => __('Ultimate Security Pro DB Version', 'ultimate-security'),
                'value' => ULTIMATE_SECURITY_PRO_DB_VERSION,
            );
        }


        // WordPress Constants
        $site_info['constants'] = array(
            array(
                'label' => 'ABSPATH',
                'value' => defined('ABSPATH') ? ABSPATH : __('Not defined', 'ultimate-security'),
            ),
            array(
                'label' => 'WP_DEBUG',
                'value' => defined('WP_DEBUG') && WP_DEBUG ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
            ),
            array(
                'label' => 'WP_DEBUG_LOG',
                'value' => defined('WP_DEBUG_LOG') && WP_DEBUG_LOG ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
            ),
            array(
                'label' => 'WP_DEBUG_DISPLAY',
                'value' => defined('WP_DEBUG_DISPLAY') && WP_DEBUG_DISPLAY ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
            ),
            array(
                'label' => 'SCRIPT_DEBUG',
                'value' => defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
            ),
            array(
                'label' => 'WP_CACHE',
                'value' => defined('WP_CACHE') && WP_CACHE ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
            ),
            array(
                'label' => 'CONCATENATE_SCRIPTS',
                'value' => defined('CONCATENATE_SCRIPTS') && CONCATENATE_SCRIPTS ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
            ),
            array(
                'label' => 'COMPRESS_SCRIPTS',
                'value' => defined('COMPRESS_SCRIPTS') && COMPRESS_SCRIPTS ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
            ),
            array(
                'label' => 'COMPRESS_CSS',
                'value' => defined('COMPRESS_CSS') && COMPRESS_CSS ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
            ),
        );

        // Media Handling
        $site_info['media'] = array(
            array(
                'label' => __('Image Editor', 'ultimate-security'),
                'value' => _wp_image_editor_choose() ? _wp_image_editor_choose() : __('No image editor available', 'ultimate-security'),
            ),
            array(
                'label' => __('Media Uploads', 'ultimate-security'),
                'value' => wp_is_writable(wp_upload_dir()['basedir']) ? __('Writeable', 'ultimate-security') : __('Not Writeable', 'ultimate-security'),
            ),
            array(
                'label' => __('Thumbnail Size Width', 'ultimate-security'),
                'value' => get_option('thumbnail_size_w') . ' ' . __('pixels', 'ultimate-security'),
            ),
            array(
                'label' => __('Thumbnail Size Height', 'ultimate-security'),
                'value' => get_option('thumbnail_size_h') . ' ' . __('pixels', 'ultimate-security'),
            ),
            array(
                'label' => __('Medium Size Width', 'ultimate-security'),
                'value' => get_option('medium_size_w') . ' ' . __('pixels', 'ultimate-security'),
            ),
            array(
                'label' => __('Medium Size Height', 'ultimate-security'),
                'value' => get_option('medium_size_h') . ' ' . __('pixels', 'ultimate-security'),
            ),
            array(
                'label' => __('Large Size Width', 'ultimate-security'),
                'value' => get_option('large_size_w') . ' ' . __('pixels', 'ultimate-security'),
            ),
            array(
                'label' => __('Large Size Height', 'ultimate-security'),
                'value' => get_option('large_size_h') . ' ' . __('pixels', 'ultimate-security'),
            ),
        );

        // Active Theme
        $theme = wp_get_theme();
        $site_info['theme'] = array(
            array(
                'label' => __('Theme Name', 'ultimate-security'),
                'value' => $theme->get('Name'),
            ),
            array(
                'label' => __('Theme Version', 'ultimate-security'),
                'value' => $theme->get('Version'),
            ),
            array(
                'label' => __('Theme Author', 'ultimate-security'),
                'value' => $theme->get('Author'),
            ),
            array(
                'label' => __('Theme Author URI', 'ultimate-security'),
                'value' => $theme->get('AuthorURI'),
            ),
            array(
                'label' => __('Theme Description', 'ultimate-security'),
                'value' => $theme->get('Description'),
            ),
            array(
                'label' => __('Theme Path', 'ultimate-security'),
                'value' => get_template_directory(),
            ),
        );

        // Create filesystem permissions data
        $site_info['filesystem'] = array(
            array(
                'label' => __('WordPress Root Directory', 'ultimate-security'),
                'value' => ABSPATH,
                'description' => self::get_file_permissions(ABSPATH),
            ),
            array(
                'label' => __('Content Directory', 'ultimate-security'),
                'value' => WP_CONTENT_DIR,
                'description' => self::get_file_permissions(WP_CONTENT_DIR),
            ),
            array(
                'label' => __('Plugins Directory', 'ultimate-security'),
                'value' => WP_PLUGIN_DIR,
                'description' => self::get_file_permissions(WP_PLUGIN_DIR),
            ),
            array(
                'label' => __('Uploads Directory', 'ultimate-security'),
                'value' => wp_upload_dir()['basedir'],
                'description' => self::get_file_permissions(wp_upload_dir()['basedir']),
            ),
            array(
                'label' => __('Themes Directory', 'ultimate-security'),
                'value' => get_theme_root(),
                'description' => self::get_file_permissions(get_theme_root()),
            ),
        );

        // For directories and sizes, inactive themes, active plugins, and inactive plugins,
        // we'll implement these fully when the endpoint is called

        return $site_info;
    }

    /**
     * Get file permissions
     * 
     * @param string $path File or directory path
     * @return string Formatted permissions
     */
    private static function get_file_permissions($path)
    {
        if (!file_exists($path)) {
            return __('Path does not exist', 'ultimate-security');
        }

        $perms = fileperms($path);

        if (($perms & 0xC000) == 0xC000) {
            // Socket
            $info = 's';
        } elseif (($perms & 0xA000) == 0xA000) {
            // Symbolic Link
            $info = 'l';
        } elseif (($perms & 0x8000) == 0x8000) {
            // Regular
            $info = '-';
        } elseif (($perms & 0x6000) == 0x6000) {
            // Block special
            $info = 'b';
        } elseif (($perms & 0x4000) == 0x4000) {
            // Directory
            $info = 'd';
        } elseif (($perms & 0x2000) == 0x2000) {
            // Character special
            $info = 'c';
        } elseif (($perms & 0x1000) == 0x1000) {
            // FIFO pipe
            $info = 'p';
        } else {
            // Unknown
            $info = 'u';
        }

        // Owner
        $info .= (($perms & 0x0100) ? 'r' : '-');
        $info .= (($perms & 0x0080) ? 'w' : '-');
        $info .= (($perms & 0x0040) ?
            (($perms & 0x0800) ? 's' : 'x') : (($perms & 0x0800) ? 'S' : '-'));

        // Group
        $info .= (($perms & 0x0020) ? 'r' : '-');
        $info .= (($perms & 0x0010) ? 'w' : '-');
        $info .= (($perms & 0x0008) ?
            (($perms & 0x0400) ? 's' : 'x') : (($perms & 0x0400) ? 'S' : '-'));

        // World
        $info .= (($perms & 0x0004) ? 'r' : '-');
        $info .= (($perms & 0x0002) ? 'w' : '-');
        $info .= (($perms & 0x0001) ?
            (($perms & 0x0200) ? 't' : 'x') : (($perms & 0x0200) ? 'T' : '-'));

        return $info;
    }

    /**
     * Get tabs data - Consolidated from 13 to 6 tabs
     *
     * @return array Tabs data
     */
    private static function get_tabs_data()
    {
        $tabs = array();

        // 1. WordPress
        $tabs[] = array(
            'id' => 'wordpress',
            'label' => __('WordPress', 'ultimate-security'),
        );

        // 2. Environment (merged: server + constants)
        $tabs[] = array(
            'id' => 'environment',
            'label' => __('Environment', 'ultimate-security'),
        );

        // 3. Database
        $tabs[] = array(
            'id' => 'database',
            'label' => __('Database', 'ultimate-security'),
        );

        // 4. Filesystem (merged: filesystem permissions + directories)
        $tabs[] = array(
            'id' => 'filesystem',
            'label' => __('Filesystem', 'ultimate-security'),
        );

        // 5. Themes (merged: active + inactive themes) - use cached version
        $all_themes = Utils::get_themes_cached();
        $tabs[] = array(
            'id' => 'themes',
            'label' => __('Themes', 'ultimate-security'),
            'count' => count($all_themes),
        );

        // 6. Plugins (merged: active + inactive + mu plugins) - use cached version
        $all_plugins = Utils::get_plugins_cached();
        $mu_plugins = get_mu_plugins();
        $tabs[] = array(
            'id' => 'plugins',
            'label' => __('Plugins', 'ultimate-security'),
            'count' => count($all_plugins) + count($mu_plugins),
        );

        return $tabs;
    }

    /**
     * Get Environment information (merged: server + constants)
     *
     * @return WP_REST_Response Environment information
     */
    private static function get_environment_info()
    {
        global $wpdb;

        $data = array();

        // Server Section
        $data[] = array(
            'label' => __('Server', 'ultimate-security'),
            'value' => '',
            'is_section_title' => true,
        );

        $data[] = array(
            'label' => __('PHP Version', 'ultimate-security'),
            'value' => phpversion(),
        );

        $data[] = array(
            'label' => __('MySQL Version', 'ultimate-security'),
            'value' => $wpdb->db_version(),
        );

        $data[] = array(
            'label' => __('Server Software', 'ultimate-security'),
            'value' => isset($_SERVER['SERVER_SOFTWARE'])
                ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE']))
                : __('Not available', 'ultimate-security'),
        );

        $data[] = array(
            'label' => __('PHP Memory Limit', 'ultimate-security'),
            'value' => ini_get('memory_limit'),
        );

        $data[] = array(
            'label' => __('PHP Max Execution Time', 'ultimate-security'),
            'value' => ini_get('max_execution_time') . ' ' . __('seconds', 'ultimate-security'),
        );

        $data[] = array(
            'label' => __('PHP Max Input Vars', 'ultimate-security'),
            'value' => ini_get('max_input_vars'),
        );

        $data[] = array(
            'label' => __('PHP Post Max Size', 'ultimate-security'),
            'value' => ini_get('post_max_size'),
        );

        $data[] = array(
            'label' => __('PHP Max Upload Size', 'ultimate-security'),
            'value' => ini_get('upload_max_filesize'),
        );

        // WordPress Constants Section
        $data[] = array(
            'label' => __('WordPress Constants', 'ultimate-security'),
            'value' => '',
            'is_section_title' => true,
        );

        $data[] = array(
            'label' => 'ABSPATH',
            'value' => defined('ABSPATH') ? ABSPATH : __('Not defined', 'ultimate-security'),
        );

        $data[] = array(
            'label' => 'WP_DEBUG',
            'value' => defined('WP_DEBUG') && WP_DEBUG ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
        );

        $data[] = array(
            'label' => 'WP_DEBUG_LOG',
            'value' => defined('WP_DEBUG_LOG') && WP_DEBUG_LOG ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
        );

        $data[] = array(
            'label' => 'WP_DEBUG_DISPLAY',
            'value' => defined('WP_DEBUG_DISPLAY') && WP_DEBUG_DISPLAY ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
        );

        $data[] = array(
            'label' => 'SCRIPT_DEBUG',
            'value' => defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
        );

        $data[] = array(
            'label' => 'WP_CACHE',
            'value' => defined('WP_CACHE') && WP_CACHE ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
        );

        $data[] = array(
            'label' => 'CONCATENATE_SCRIPTS',
            'value' => defined('CONCATENATE_SCRIPTS') && CONCATENATE_SCRIPTS ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
        );

        $data[] = array(
            'label' => 'COMPRESS_SCRIPTS',
            'value' => defined('COMPRESS_SCRIPTS') && COMPRESS_SCRIPTS ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
        );

        $data[] = array(
            'label' => 'COMPRESS_CSS',
            'value' => defined('COMPRESS_CSS') && COMPRESS_CSS ? __('Enabled', 'ultimate-security') : __('Disabled', 'ultimate-security'),
        );

        return rest_ensure_response(array(
            'id' => 'environment',
            'label' => __('Environment', 'ultimate-security'),
            'data' => $data,
        ));
    }

    /**
     * Get combined Filesystem information (merged: permissions + sizes)
     *
     * @return WP_REST_Response Filesystem information
     */
    private static function get_combined_filesystem_info()
    {
        $upload_dir = wp_upload_dir();

        $directories = array(
            array(
                'label' => __('WordPress Root', 'ultimate-security'),
                'path' => ABSPATH,
            ),
            array(
                'label' => __('Content Directory', 'ultimate-security'),
                'path' => WP_CONTENT_DIR,
            ),
            array(
                'label' => __('Plugins Directory', 'ultimate-security'),
                'path' => WP_PLUGIN_DIR,
            ),
            array(
                'label' => __('Uploads Directory', 'ultimate-security'),
                'path' => $upload_dir['basedir'],
            ),
            array(
                'label' => __('Themes Directory', 'ultimate-security'),
                'path' => get_theme_root(),
            ),
            array(
                'label' => __('Must-Use Plugins Directory', 'ultimate-security'),
                'path' => WPMU_PLUGIN_DIR,
            ),
        );

        $data = array();

        foreach ($directories as $dir) {
            $perms = self::get_file_permissions($dir['path']);
            $size = self::get_directory_size($dir['path']);

            $data[] = array(
                'label' => $dir['label'],
                'value' => $dir['path'],
                'permissions' => $perms,
                'size' => $size,
                'description' => sprintf(
                    // translators: %1$s is permissions, %2$s is size
                    __('Permissions: %1$s | Size: %2$s', 'ultimate-security'),
                    $perms,
                    $size
                ),
            );
        }

        return rest_ensure_response(array(
            'id' => 'filesystem',
            'label' => __('Filesystem', 'ultimate-security'),
            'data' => $data,
        ));
    }

    /**
     * Get all themes information (merged: active + inactive)
     *
     * @return WP_REST_Response Themes information
     */
    private static function get_all_themes_info()
    {
        $all_themes = Utils::get_themes_cached();
        $active_theme = wp_get_theme();
        $themes_data = array();

        foreach ($all_themes as $theme_slug => $theme) {
            $is_active = ($theme_slug === $active_theme->get_stylesheet());

            $themes_data[] = array(
                'name' => $theme->get('Name'),
                'version' => $theme->get('Version'),
                'author' => $theme->get('Author'),
                'description' => $theme->get('Description'),
                'path' => $theme->get_stylesheet_directory(),
                'status' => $is_active ? 'active' : 'inactive',
                'status_label' => $is_active
                    ? __('Active', 'ultimate-security')
                    : __('Inactive', 'ultimate-security'),
            );
        }

        // Sort: active theme first, then alphabetically
        usort($themes_data, function ($a, $b) {
            if ($a['status'] === 'active')
                return -1;
            if ($b['status'] === 'active')
                return 1;
            return strcasecmp($a['name'], $b['name']);
        });

        return rest_ensure_response(array(
            'id' => 'themes',
            'label' => __('Themes', 'ultimate-security'),
            'themes' => $themes_data,
            'counts' => array(
                'total' => count($all_themes),
                'active' => 1,
                'inactive' => count($all_themes) - 1,
            ),
        ));
    }

    /**
     * Get all plugins information (merged: active + inactive + mu)
     *
     * @return WP_REST_Response Plugins information
     */
    private static function get_all_plugins_info()
    {
        $active_plugins = get_option('active_plugins', array());
        $all_plugins = Utils::get_plugins_cached();
        $mu_plugins = get_mu_plugins();
        $plugins_data = array();

        // Regular plugins (active and inactive)
        foreach ($all_plugins as $plugin_path => $plugin) {
            $is_active = in_array($plugin_path, $active_plugins, true);

            $plugins_data[] = array(
                'name' => $plugin['Name'],
                'version' => $plugin['Version'],
                'author' => $plugin['Author'],
                'description' => $plugin['Description'],
                'path' => $plugin_path,
                'status' => $is_active ? 'active' : 'inactive',
                'status_label' => $is_active
                    ? __('Active', 'ultimate-security')
                    : __('Inactive', 'ultimate-security'),
                'type' => 'regular',
            );
        }

        // Must-Use plugins
        foreach ($mu_plugins as $plugin_path => $plugin) {
            $plugins_data[] = array(
                'name' => isset($plugin['Name']) ? $plugin['Name'] : basename($plugin_path),
                'version' => isset($plugin['Version']) ? $plugin['Version'] : __('Unknown', 'ultimate-security'),
                'author' => isset($plugin['Author']) ? $plugin['Author'] : '',
                'description' => isset($plugin['Description']) ? $plugin['Description'] : '',
                'path' => $plugin_path,
                'status' => 'mu',
                'status_label' => __('Must-Use', 'ultimate-security'),
                'type' => 'mu',
            );
        }

        // Sort: active first, then mu, then inactive, then alphabetically
        usort($plugins_data, function ($a, $b) {
            $order = array('active' => 0, 'mu' => 1, 'inactive' => 2);
            $orderA = $order[$a['status']] ?? 3;
            $orderB = $order[$b['status']] ?? 3;
            if ($orderA !== $orderB) {
                return $orderA - $orderB;
            }
            return strcasecmp($a['name'], $b['name']);
        });

        return rest_ensure_response(array(
            'id' => 'plugins',
            'label' => __('Plugins', 'ultimate-security'),
            'plugins' => $plugins_data,
            'counts' => array(
                'total' => count($plugins_data),
                'active' => count($active_plugins),
                'inactive' => count($all_plugins) - count($active_plugins),
                'mu' => count($mu_plugins),
            ),
        ));
    }

    /**
     * Get Must Use Plugins information
     *
     * @return WP_REST_Response Must Use Plugins information
     */
    public static function get_mu_plugins_info()
    {
        try {
            // Get must-use plugins
            $mu_plugins = get_mu_plugins();

            // Format the data
            $plugins_data = array();

            foreach ($mu_plugins as $plugin_path => $plugin_data) {
                $plugins_data[] = array(
                    'name' => isset($plugin_data['Name']) ? $plugin_data['Name'] : basename($plugin_path),
                    'version' => isset($plugin_data['Version']) ? $plugin_data['Version'] : __('Unknown', 'ultimate-security'),
                    'description' => isset($plugin_data['Description']) ? $plugin_data['Description'] : '',
                    'author' => isset($plugin_data['Author']) ? $plugin_data['Author'] : '',
                    'status' => 'Active', // Must-use plugins are always active
                    'path' => $plugin_path,
                );
            }

            // Return the data (empty array is valid - no mock data)
            return rest_ensure_response(array(
                'plugins' => $plugins_data,
                'count' => count($plugins_data),
            ));
        } catch (Exception $e) {
            return new WP_Error(
                'mu_plugins_info_error',
                $e->getMessage(),
                array('status' => 500)
            );
        }
    }

    /**
     * Get information for a specific tab
     *
     * @param WP_REST_Request $request Full details about the request.
     * @return WP_REST_Response Tab specific information
     */
    public static function get_tab_info($request)
    {
        try {
            $tab_id = $request->get_param('tab_id');

            // Handle consolidated tabs
            switch ($tab_id) {
                case 'wordpress':
                    $site_info = self::get_manual_debug_data();
                    return rest_ensure_response(array(
                        'id' => 'wordpress',
                        'label' => __('WordPress', 'ultimate-security'),
                        'data' => $site_info['wordpress'],
                    ));

                case 'environment':
                    return self::get_environment_info();

                case 'database':
                    $site_info = self::get_manual_debug_data();
                    return rest_ensure_response(array(
                        'id' => 'database',
                        'label' => __('Database', 'ultimate-security'),
                        'data' => $site_info['database'],
                    ));

                case 'filesystem':
                    return self::get_combined_filesystem_info();

                case 'themes':
                    return self::get_all_themes_info();

                case 'plugins':
                    return self::get_all_plugins_info();

                default:
                    return new WP_Error(
                        'site_health_info_error',
                        __('Information for this tab is not available.', 'ultimate-security'),
                        array('status' => 404)
                    );
            }
        } catch (Exception $e) {
            return new WP_Error(
                'tab_info_error',
                $e->getMessage(),
                array('status' => 500)
            );
        }
    }

    /**
     * Get tab label
     *
     * @param string $tab_id Tab ID
     * @return string Tab label
     */
    private static function get_tab_label($tab_id)
    {
        $labels = array(
            'wordpress' => __('WordPress', 'ultimate-security'),
            'environment' => __('Environment', 'ultimate-security'),
            'database' => __('Database', 'ultimate-security'),
            'filesystem' => __('Filesystem', 'ultimate-security'),
            'themes' => __('Themes', 'ultimate-security'),
            'plugins' => __('Plugins', 'ultimate-security'),
        );

        return isset($labels[$tab_id]) ? $labels[$tab_id] : $tab_id;
    }


    /**
     * Get directory size
     *
     * @param string $path Directory path
     * @return string Formatted size
     */
    private static function get_directory_size($path)
    {
        if (!is_dir($path)) {
            return __('Not a directory', 'ultimate-security');
        }

        // Check if we can get size from WordPress core function
        if (function_exists('get_dirsize')) {
            $size = get_dirsize($path);
            if ($size !== null && $size !== false) {
                return self::format_bytes($size);
            }
        }

        // Try to calculate size for smaller directories (limit to prevent timeout)
        $size = self::calculate_directory_size($path, 1000); // Max 1000 files

        if ($size === false) {
            return __('Size calculation skipped (large directory)', 'ultimate-security');
        }

        return self::format_bytes($size);
    }

    /**
     * Calculate directory size with file limit
     *
     * @param string $path Directory path
     * @param int $max_files Maximum files to count before aborting
     * @return int|false Size in bytes or false if too many files
     */
    private static function calculate_directory_size($path, $max_files = 1000)
    {
        $size = 0;
        $count = 0;

        try {
            $iterator = new \RecursiveIteratorIterator(
                new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS),
                \RecursiveIteratorIterator::LEAVES_ONLY
            );

            foreach ($iterator as $file) {
                if ($file->isFile()) {
                    $size += $file->getSize();
                    $count++;

                    if ($count > $max_files) {
                        return false; // Too many files, abort
                    }
                }
            }
        } catch (\Exception $e) {
            return false;
        }

        return $size;
    }

    /**
     * Format bytes to human readable format
     *
     * @param int $bytes Size in bytes
     * @return string Formatted size
     */
    private static function format_bytes($bytes)
    {
        if ($bytes < 1024) {
            return $bytes . ' B';
        } elseif ($bytes < 1048576) {
            return round($bytes / 1024, 2) . ' KB';
        } elseif ($bytes < 1073741824) {
            return round($bytes / 1048576, 2) . ' MB';
        } else {
            return round($bytes / 1073741824, 2) . ' GB';
        }
    }

}
