<?php

namespace WPUltimateSecurity\UltimateSecurity\Presentation\API\Controllers;

use WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\IpHelper;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_Site_Health;
use Exception;
use Throwable;
use Error;
/**
 * System Controller
 *
 * Handles system information and health check endpoints
 */
class SystemController
{
    /**
     * Get plugin info
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public static function get_plugin_info(WP_REST_Request $request)
    {
        $ultimate_security_info = [
            'name' => esc_html(ULTIMATE_SECURITY_NAME),
            'version' => esc_html(ULTIMATE_SECURITY_VERSION),
        ];
        return new WP_REST_Response($ultimate_security_info, 200);
    }

    /**
     * Get visitor IP
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public static function get_ip(WP_REST_Request $request)
    {
        $ultimate_security_get_visitor_ip = IpHelper::getClientIp();

        $ultimate_security_ip_info = [
            'ip' => esc_html($ultimate_security_get_visitor_ip),
        ];

        return new WP_REST_Response($ultimate_security_ip_info, 200);
    }

    /**
     * Get post types
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public static function get_post_types(WP_REST_Request $request)
    {
        $post_types = get_post_types([], 'objects');
        $data = [];

        foreach ($post_types as $post_type) {
            $data[] = [
                'name' => $post_type->name,
                'label' => $post_type->label,
                'public' => $post_type->public,
                'hierarchical' => $post_type->hierarchical,
                'show_ui' => $post_type->show_ui,
                'show_in_rest' => $post_type->show_in_rest,
            ];
        }

        return new WP_REST_Response($data, 200);
    }

    // Add this method to your class (before or after get_site_health_data)
    public static function maybe_trigger_site_health_refresh()
    {
        $last_run = get_transient('health-check-site-status-result');

        // If never run or empty, trigger it now
        if (false === $last_run || empty($last_run)) {
            if (!class_exists('WP_Site_Health')) {
                require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php';
            }

            $site_health = WP_Site_Health::get_instance();

            // Get all tests
            $tests = $site_health->get_tests();

            // Run all direct tests and store results
            $results = [];

            if (isset($tests['direct'])) {
                foreach ($tests['direct'] as $test_id => $test) {
                    if (is_callable($test['test'])) {
                        try {
                            $result = call_user_func($test['test']);
                            $results[$test_id] = $result;
                        } catch (Exception $e) {
                            continue;
                        }
                    }
                }
            }

            // Store the results in the same transient WordPress uses
            set_transient('health-check-site-status-result', $results, DAY_IN_SECONDS);
        }
    }

    /**
     * Get site health data
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public static function get_site_health_data(WP_REST_Request $request)
    {
        // Force refresh parameter
        $force_refresh = isset($request['force_refresh']) ? (bool) $request['force_refresh'] : false;

        // Check cache
        if (!$force_refresh) {
            $cached_data = get_transient('ultimate_security_site_health');
            if ($cached_data !== false) {
                return new WP_REST_Response($cached_data, 200);
            }
        }

        // Initialize response arrays
        $issues = array();
        $critical_issues = array();
        $debug_info = array(
            'php_version' => PHP_VERSION,
            'wp_version' => get_bloginfo('version'),
        );

        try {
            // Load WP_Site_Health class
            if (!class_exists('WP_Site_Health')) {
                require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php';
            }

            $site_health = WP_Site_Health::get_instance();
            $tests = $site_health->get_tests();

            $debug_info['has_tests'] = !empty($tests);
            $debug_info['direct_tests_count'] = isset($tests['direct']) ? count($tests['direct']) : 0;
            $debug_info['async_tests_count'] = isset($tests['async']) ? count($tests['async']) : 0;

            // Run direct tests
            if (isset($tests['direct']) && is_array($tests['direct'])) {
                foreach ($tests['direct'] as $test_id => $test) {
                    if (!isset($test['test']) || !is_callable($test['test'])) {
                        continue;
                    }

                    try {
                        $result = call_user_func($test['test']);

                        if (!is_array($result)) {
                            continue;
                        }

                        $status = isset($result['status']) ? $result['status'] : 'good';
                        $label = isset($result['label']) ? $result['label'] : $test_id;
                        $description = isset($result['description']) ? wp_strip_all_tags($result['description']) : '';

                        if ($status === 'critical' || $status === 'recommended') {
                            $issue = array(
                                'label' => $label,
                                'status' => $status,
                                'description' => $description,
                                'test' => $test_id,
                            );

                            $issues[] = $issue;

                            if ($status === 'critical') {
                                $critical_issues[] = $issue;
                            }
                        }
                    } catch (Exception $e) {
                        // Skip failed tests
                        continue;
                    } catch (Error $e) {
                        // Skip failed tests
                        continue;
                    }
                }
            }

            // Check for debug.log in public location (most common critical issue)
            if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
                $log_path = (WP_DEBUG_LOG === true) ? WP_CONTENT_DIR . '/debug.log' : WP_DEBUG_LOG;

                // Check if it's potentially public
                if (strpos($log_path, ABSPATH) === 0 && file_exists($log_path)) {
                    $issue = array(
                        'label' => __('Your site is set to log errors to a potentially public file', 'ultimate-security'),
                        'status' => 'critical',
                        'description' => __('Your site is currently set to log errors to a file that may be publicly accessible. It is highly recommended to ensure this file is not accessible, or to disable error logging.', 'ultimate-security'),
                        'test' => 'debug_log_public',
                    );

                    $issues[] = $issue;
                    $critical_issues[] = $issue;
                }
            }

            // Check inactive plugins (use cached version for performance)
            $all_plugins = Utils::get_plugins_cached();
            $active_plugins = get_option('active_plugins', array());
            $inactive_count = count($all_plugins) - count($active_plugins);

            if ($inactive_count > 0) {
                $issue = array(
                    'label' => __('You should remove inactive plugins', 'ultimate-security'),
                    'status' => 'recommended',
                    'description' => sprintf(
                        __('You have %d inactive plugin(s). Inactive plugins can be a security risk.', 'ultimate-security'),
                        $inactive_count
                    ),
                    'test' => 'inactive_plugins',
                );
                $issues[] = $issue;
            }

            // Check inactive themes (use cached version for performance)
            $all_themes = Utils::get_themes_cached();
            $inactive_theme_count = count($all_themes) - 1;

            if ($inactive_theme_count > 0) {
                $issue = array(
                    'label' => __('You should remove inactive themes', 'ultimate-security'),
                    'status' => 'recommended',
                    'description' => sprintf(
                        __('You have %d inactive theme(s). Inactive themes can be a security risk.', 'ultimate-security'), 
                        $inactive_theme_count
                    ),
                    'test' => 'inactive_themes',
                );
                $issues[] = $issue;
            }

            // Check PHP version
            if (version_compare(PHP_VERSION, '8.0', '<')) {
                $php_version = PHP_VERSION;
                $issue = array(
                    'label' => __('Your site is running on an older version of PHP', 'ultimate-security'),
                    'status' => 'recommended',
                    'description' => sprintf(
                        __('Your site is running on PHP %s. Consider updating to PHP 8.0 or higher for better performance and security.', 'ultimate-security'), 
                        $php_version
                    ),
                    'test' => 'php_version',
                );
                $issues[] = $issue;
            }

            $debug_info['issues_found'] = count($issues);
            $debug_info['critical_found'] = count($critical_issues);

        } catch (Exception $e) {
            $debug_info['error'] = $e->getMessage();
        } catch (Error $e) {
            $debug_info['error'] = $e->getMessage();
        }

        $status = count($critical_issues) > 0 ? 'critical' : 'good';

        $response_data = array(
            'status' => $status,
            'total_issues' => count($issues),
            'critical_count' => count($critical_issues),
            'critical_issues' => $critical_issues,
            'all_issues' => $issues,
            // 'debug' => $debug_info,
        );

        // Cache for 6 hours
        set_transient('ultimate_security_site_health', $response_data, 6 * HOUR_IN_SECONDS);

        return new WP_REST_Response($response_data, 200);
    }

    /**
     * Setup complete callback
     *
     * @return WP_REST_Response
     */
    public static function setup_complete()
    {
        update_option('ultimate_security_setup', 0);
        return rest_ensure_response(['success' => true]);
    }

    /**
     * Get system information for the dashboard
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public static function get_system_info(WP_REST_Request $request)
    {
        global $wpdb;

        // Get WordPress version
        $wp_version = get_bloginfo('version');

        // Get PHP version
        $php_version = PHP_VERSION;

        // Get active plugins count
        $active_plugins = get_option('active_plugins', array());
        $active_plugins_count = count($active_plugins);

        // For multisite, also count network-active plugins
        if (is_multisite()) {
            $network_plugins = get_site_option('active_sitewide_plugins', array());
            $active_plugins_count += count($network_plugins);
        }

        // Get active theme
        $active_theme = wp_get_theme();
        $active_theme_name = $active_theme->get('Name');

        // Get MySQL version
        $db_version = $wpdb->db_version();

        // Get memory limit
        $memory_limit = ini_get('memory_limit');

        // Get server software
        $server_software = isset($_SERVER['SERVER_SOFTWARE']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'])) : 'Unknown';

        // Get max execution time
        $max_execution_time = ini_get('max_execution_time');

        // Get upload max filesize
        $upload_max_filesize = ini_get('upload_max_filesize');

        // Get post max size
        $post_max_size = ini_get('post_max_size');

        // Check if HTTPS is enabled
        $https_enabled = is_ssl();

        // Check if debug mode is enabled
        $debug_mode = defined('WP_DEBUG') && WP_DEBUG;

        // Get database prefix
        $db_prefix = $wpdb->prefix;

        // Get total users count
        $total_users = count_users();

        // Get site URL info
        $site_url = get_site_url();
        $home_url = get_home_url();

        $response_data = array(
            'wp_version' => esc_html($wp_version),
            'php_version' => esc_html($php_version),
            'active_plugins' => $active_plugins_count,
            'active_theme' => esc_html($active_theme_name),
            'db_version' => esc_html($db_version),
            'memory_limit' => esc_html($memory_limit),
            'server_software' => esc_html($server_software),
            'max_execution_time' => esc_html($max_execution_time) . 's',
            'upload_max_filesize' => esc_html($upload_max_filesize),
            'post_max_size' => esc_html($post_max_size),
            'https_enabled' => $https_enabled,
            'debug_mode' => $debug_mode,
            'db_prefix' => esc_html($db_prefix),
            'total_users' => isset($total_users['total_users']) ? $total_users['total_users'] : 0,
            'site_url' => esc_url($site_url),
            'home_url' => esc_url($home_url),
            'is_multisite' => is_multisite(),
        );

        return new WP_REST_Response($response_data, 200);
    }
}
