<?php
/**
 * FluentC Support Report Class.
 *
 * Generates diagnostic information for support purposes
 *
 * @package FluentCPlugin
 * @author  FluentC <wp@fluentc.io>
 */

namespace FluentC\Services;

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

use FluentC\Services\Cache;
use FluentC\Utils\Language;

/**
 * Support_Report class for generating diagnostic information
 */
class Support_Report {
    /**
     * FluentC cache class
     *
     * @var Cache
     */
    protected $fluentc_cache;

    /**
     * FluentC language class
     *
     * @var Language
     */
    protected $fluentc_language;

    /**
     * Constructor.
     */
    public function __construct() {
        $this->fluentc_cache = new Cache();
        $this->fluentc_language = new Language();
    }

    /**
     * Generate a comprehensive support report
     *
     * @return array Report data
     */
    public function generate_report() {
        $report = array(
            'generated_at' => current_time('mysql'),
            'wordpress_info' => $this->get_wordpress_info(),
            'server_info' => $this->get_server_info(),
            'plugin_info' => $this->get_plugin_info(),
            'fluentc_info' => $this->get_fluentc_info(),
            'permalink_info' => $this->get_permalink_info(),
            'rewrite_rules' => $this->get_rewrite_rules(),
        );

        return $report;
    }

    /**
     * Get WordPress core information
     *
     * @return array WordPress information
     */
    protected function get_wordpress_info() {
        global $wp_version;

        return array(
            'version' => $wp_version,
            'site_url' => site_url(),
            'home_url' => home_url(),
            'is_multisite' => is_multisite(),
            'memory_limit' => WP_MEMORY_LIMIT,
            'debug_mode' => defined('WP_DEBUG') && WP_DEBUG,
            'locale' => get_locale(),
            'timezone' => wp_timezone_string(),
        );
    }

    /**
     * Get server information
     *
     * @return array Server information
     */
    protected function get_server_info() {
        $server_info = array(
            'php_version' => phpversion(),
            'server_software' => isset($_SERVER['SERVER_SOFTWARE']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'])) : '',
            'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '',
        );

        // Get PHP modules if function exists
        if (function_exists('get_loaded_extensions')) {
            $server_info['php_extensions'] = get_loaded_extensions();
        }

        // Get MySQL version if possible
        global $wpdb;
        if (isset($wpdb) && is_object($wpdb)) {
            $server_info['mysql_version'] = $wpdb->db_version();
        }

        // Get max execution time
        $server_info['max_execution_time'] = ini_get('max_execution_time');
        
        // Get post max size
        $server_info['post_max_size'] = ini_get('post_max_size');
        
        // Get upload max filesize
        $server_info['upload_max_filesize'] = ini_get('upload_max_filesize');

        return $server_info;
    }

    /**
     * Get information about installed plugins
     *
     * @return array Plugin information
     */
    protected function get_plugin_info() {
        // Include plugin functions if necessary
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $all_plugins = get_plugins();
        $active_plugins = get_option('active_plugins', array());

        $plugin_info = array();
        foreach ($all_plugins as $path => $plugin) {
            $plugin_info[] = array(
                'name' => isset($plugin['Name']) ? $plugin['Name'] : '',
                'version' => isset($plugin['Version']) ? $plugin['Version'] : '',
                'active' => in_array($path, $active_plugins),
                'author' => isset($plugin['Author']) ? $plugin['Author'] : '',
                'plugin_uri' => isset($plugin['PluginURI']) ? $plugin['PluginURI'] : '',
            );
        }

        return $plugin_info;
    }

    /**
     * Get FluentC-specific information
     *
     * @return array FluentC information
     */
    protected function get_fluentc_info() {
        $api_key = get_option('fluentc_api_key', '');
        $has_key = !empty($api_key);
        
        $fluentc_info = array(
            'version' => FLUENTC_TRANSLATION_VERSION,
            'api_key' => $this->mask_api_key($api_key),
            'key_status' => $has_key ? 'present' : 'missing',
            'site_language' => $this->fluentc_language->fluentc_site_language(),
            'current_language' => $this->fluentc_language->get_fluentc_language(),
            'available_languages' => $this->fluentc_language->get_available_languages(),
        );
        
        // Get plugin activation time if available
        $activation_time = get_option('fluentc_activation_time', '');
        if (!empty($activation_time)) {
            $fluentc_info['activation_time'] = $activation_time;
        }
        
        // Check for last scan time
        $last_scan_time = get_transient('fluentc_last_scan_time');
        if ($last_scan_time) {
            $fluentc_info['last_scan_time'] = $last_scan_time;
            $fluentc_info['last_scan_time_formatted'] = date('Y-m-d H:i:s', $last_scan_time);
            $fluentc_info['time_since_scan'] = human_time_diff($last_scan_time, current_time('timestamp'));
        }
        
        // Check if translation is cancelled
        $translation_cancelled = get_option('fluentc_translation_cancelled', false);
        if ($translation_cancelled) {
            $fluentc_info['translation_cancelled'] = true;
        }
        
        // Check for API calls count
        $api_calls = $this->fluentc_cache->get('apicalls', 'settings');
        if ($api_calls !== false) {
            $fluentc_info['api_calls_count'] = $api_calls;
        }
        
        // Get widget options if available
        if ($has_key) {
            try {
                // Only include this if we have a connect service available
                if (class_exists('FluentC\\Services\\Connect')) {
                    $connect = new \FluentC\Services\Connect();
                    if (method_exists($connect, 'fetch_widget_options')) {
                        $widget_options = $connect->fetch_widget_options($api_key);
                        if ($widget_options) {
                            $fluentc_info['widget_options'] = $widget_options;
                        }
                    }
                }
            } catch (\Exception $e) {
                $fluentc_info['widget_options_error'] = $e->getMessage();
            }
        }
        
        // Add the cache settings and URLs data to the response
        $fluentc_info['cache_settings'] = $this->get_cache_settings();
        $fluentc_info['urls_settings'] = $this->get_urls_settings();
        
        return $fluentc_info;
    }

    /**
     * Get permalink structure information
     *
     * @return array Permalink information
     */
    protected function get_permalink_info() {
        $permalink_structure = get_option('permalink_structure');
        
        return array(
            'structure' => $permalink_structure,
            'category_base' => get_option('category_base'),
            'tag_base' => get_option('tag_base'),
            'using_index_php' => strpos($permalink_structure, 'index.php') !== false,
            'using_trailing_slash' => substr($permalink_structure, -1) === '/',
        );
    }

    /**
     * Get rewrite rules information
     *
     * @return array Rewrite rules
     */
    protected function get_rewrite_rules() {
        global $wp_rewrite;
        
        $rewrite_info = array(
            'permalink_structure' => get_option('permalink_structure'),
            'category_base' => get_option('category_base'),
            'tag_base' => get_option('tag_base'),
            'rules' => array()
        );
        
        // First try to get rules from global wp_rewrite object
        if (isset($wp_rewrite) && is_object($wp_rewrite)) {
            // Collect basic rewrite configuration
            if (method_exists($wp_rewrite, 'using_permalinks')) {
                $rewrite_info['using_permalinks'] = $wp_rewrite->using_permalinks();
            }
            if (method_exists($wp_rewrite, 'using_index_permalinks')) {
                $rewrite_info['using_index_permalinks'] = $wp_rewrite->using_index_permalinks();
            }
            if (method_exists($wp_rewrite, 'using_mod_rewrite_permalinks')) {
                $rewrite_info['using_mod_rewrite_permalinks'] = $wp_rewrite->using_mod_rewrite_permalinks();
            }
            
            // Gather important rewrite properties
            $properties_to_collect = array(
                'author_base', 'search_base', 'comments_base', 
                'pagination_base', 'comments_pagination_base', 'feed_base',
                'front', 'root', 'index', 'use_trailing_slashes'
            );
            
            foreach ($properties_to_collect as $property) {
                if (isset($wp_rewrite->$property)) {
                    $rewrite_info[$property] = $wp_rewrite->$property;
                }
            }
            
            // Get actual rewrite rules
            if (isset($wp_rewrite->rules) && is_array($wp_rewrite->rules)) {
                $rewrite_info['rules'] = $wp_rewrite->rules;
            }
            
            // Get extra rules
            if (isset($wp_rewrite->extra_rules) && is_array($wp_rewrite->extra_rules)) {
                $rewrite_info['extra_rules'] = $wp_rewrite->extra_rules;
            }
            
            if (isset($wp_rewrite->extra_rules_top) && is_array($wp_rewrite->extra_rules_top)) {
                $rewrite_info['extra_rules_top'] = $wp_rewrite->extra_rules_top;
            }
            
            // Get non-WP rules
            if (isset($wp_rewrite->non_wp_rules) && is_array($wp_rewrite->non_wp_rules)) {
                $rewrite_info['non_wp_rules'] = $wp_rewrite->non_wp_rules;
            }
            
            // Get endpoints
            if (isset($wp_rewrite->endpoints) && is_array($wp_rewrite->endpoints)) {
                $rewrite_info['endpoints'] = $wp_rewrite->endpoints;
            }
        }
        
        // If no rules found in wp_rewrite, try getting them from options
        if (empty($rewrite_info['rules'])) {
            $stored_rules = get_option('rewrite_rules');
            if ($stored_rules && is_array($stored_rules)) {
                $rewrite_info['rules'] = $stored_rules;
                $rewrite_info['source'] = 'option';
            } else {
                $rewrite_info['rules_error'] = 'No rewrite rules found';
            }
        } else {
            $rewrite_info['source'] = 'wp_rewrite';
        }
        
        // Get counts of rules
        if (!empty($rewrite_info['rules'])) {
            $rewrite_info['rules_count'] = count($rewrite_info['rules']);
        }
        
        return $rewrite_info;
    }

    /**
     * Get cached settings data
     *
     * @return array Cached settings
     */
    protected function get_cache_settings() {
        global $wpdb;
        
        $cache_data = array();
        
        // Query transients that match our settings group - no limit to ensure we get all data
        $results = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT option_name, option_value FROM {$wpdb->options} 
                WHERE option_name LIKE %s",
                $wpdb->esc_like('_transient_fluentc_') . '%_settings_%'
            )
        );
        
        if ($results) {
            foreach ($results as $result) {
                $transient_name = str_replace('_transient_', '', $result->option_name);
                
                // Try to decode JSON values for better readability
                $value = $result->option_value;
                $decoded = @json_decode($value, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $cache_data[$transient_name] = $decoded;
                } else {
                    // If it's not JSON, just include the raw value
                    $cache_data[$transient_name] = $value;
                }
            }
        }
        
        // Add cache statistics
        $cache_data['_meta'] = array(
            'count' => count($results),
            'collected_at' => current_time('mysql')
        );
        
        return $cache_data;
    }

    /**
     * Get cached URLs data
     *
     * @return array Cached URLs
     */
    protected function get_urls_settings() {
        global $wpdb;
        
        $urls_data = array();
        
        // Query transients that match our URLs group - no limit to ensure we get all data
        $results = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT option_name, option_value FROM {$wpdb->options} 
                WHERE option_name LIKE %s",
                $wpdb->esc_like('_transient_fluentc_') . '%_urls_%'
            )
        );
        
        // Also query fluentc_site_scan and fluentc_translated_urls options
        $scan_data = get_option('fluentc_site_scan', array());
        $translated_urls = get_option('fluentc_translated_urls', array());
        
        if ($results) {
            foreach ($results as $result) {
                $transient_name = str_replace('_transient_', '', $result->option_name);
                
                // Try to decode JSON values for better readability
                $value = $result->option_value;
                $decoded = @json_decode($value, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $urls_data[$transient_name] = $decoded;
                } else {
                    // If it's not JSON, just include the raw value
                    $urls_data[$transient_name] = $value;
                }
            }
        }
        
        // Add site scan data and translated URLs
        $urls_data['site_scan'] = $scan_data;
        $urls_data['translated_urls'] = $translated_urls;
        
        // Add batch translation information if available
        $batch_request = get_option('fluentc_batch_request', '');
        if (!empty($batch_request)) {
            $urls_data['batch_request'] = $batch_request;
        }
        
        // Add URLs statistics
        $urls_data['_meta'] = array(
            'transients_count' => count($results),
            'site_scan_count' => is_array($scan_data) ? count($scan_data) : 0,
            'translated_urls_count' => is_array($translated_urls) ? count($translated_urls) : 0,
            'collected_at' => current_time('mysql')
        );
        
        return $urls_data;
    }

    /**
     * Mask API key for security
     *
     * @param string $api_key The API key to mask
     * @return string Masked API key
     */
    protected function mask_api_key($api_key) {
        if (empty($api_key)) {
            return '';
        }
        
        // Show only first 4 and last 4 characters
        $length = strlen($api_key);
        if ($length <= 8) {
            return str_repeat('*', $length);
        }
        
        return substr($api_key, 0, 4) . str_repeat('*', $length - 8) . substr($api_key, -4);
    }
}