<?php
/**
 * Data Collector Class
 * 
 * Collects technical data from WordPress installation
 * - WordPress & WooCommerce versions
 * - Theme information
 * - Active plugins
 * - Server environment
 * - Performance metrics
 * 
 * @package InPost_Paczkomaty
 * @subpackage Activator
 * @version 1.0.0
 */

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

class Parcselect_Data_Collector {
    
    /**
     * Collect all data in one call
     * 
     * @return array Complete diagnostic data
     */
    public function collect_all() {
        return [
            'environment' => $this->collect_environment(),
            'wordpress' => $this->collect_wordpress_info(),
            'woocommerce' => $this->collect_woocommerce_info(),
            'theme' => $this->collect_theme_info(),
            'plugins' => $this->collect_plugins_info(),
            'server' => $this->collect_server_info(),
            'performance' => $this->collect_performance_metrics(),
        ];
    }
    
    /**
     * Collect environment data
     * 
     * @return array Environment information
     */
    private function collect_environment() {
        global $wpdb;
        
        return [
            'php_version' => phpversion(),
            'mysql_version' => $wpdb->db_version(),
            'server_software' => sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ?? 'unknown' ) ),
            'web_server' => $this->detect_web_server(),
            'https_enabled' => is_ssl(),
            'memory_limit' => WP_MEMORY_LIMIT,
            'max_execution_time' => ini_get('max_execution_time'),
            'max_upload_size' => size_format(wp_max_upload_size()),
            'max_post_size' => ini_get('post_max_size'),
            'php_extensions' => [
                'curl' => extension_loaded('curl'),
                'mbstring' => extension_loaded('mbstring'),
                'gd' => extension_loaded('gd'),
                'zip' => extension_loaded('zip'),
                'openssl' => extension_loaded('openssl'),
                'json' => extension_loaded('json'),
                'xml' => extension_loaded('xml'),
            ],
        ];
    }
    
    /**
     * Collect WordPress information
     * 
     * @return array WordPress config
     */
    private function collect_wordpress_info() {
        return [
            'version' => get_bloginfo('version'),
            'is_multisite' => is_multisite(),
            'site_language' => get_locale(),
            'timezone' => get_option('timezone_string') ?: 'UTC+' . get_option('gmt_offset'),
            'permalink_structure' => get_option('permalink_structure'),
            'home_url' => wp_parse_url(home_url(), PHP_URL_HOST),
            'site_url' => wp_parse_url(site_url(), PHP_URL_HOST),
            'wp_debug' => defined('WP_DEBUG') && WP_DEBUG,
            'wp_debug_log' => defined('WP_DEBUG_LOG') && WP_DEBUG_LOG,
            'wp_debug_display' => defined('WP_DEBUG_DISPLAY') && WP_DEBUG_DISPLAY,
        ];
    }
    
    /**
     * Collect WooCommerce information
     * 
     * @return array WooCommerce config
     */
    private function collect_woocommerce_info() {
        if (!class_exists('WooCommerce')) {
            return ['installed' => false];
        }
        
        return [
            'installed' => true,
            'version' => WC_VERSION,
            'currency' => get_woocommerce_currency(),
            'currency_symbol' => get_woocommerce_currency_symbol(),
            'country' => WC()->countries->get_base_country(),
            'shipping_enabled' => wc_shipping_enabled(),
            'tax_enabled' => wc_tax_enabled(),
            'payment_gateways' => $this->get_active_payment_gateways(),
            'shipping_methods' => $this->get_active_shipping_methods(),
            'orders_count' => $this->get_orders_count(),
            'last_order_id' => $this->get_last_order_id(),
        ];
    }
    
    /**
     * Collect theme information
     * 
     * @return array Theme details
     */
    private function collect_theme_info() {
        $theme = wp_get_theme();
        
        return [
            'name' => $theme->get('Name'),
            'slug' => $theme->get('Stylesheet'),
            'version' => $theme->get('Version'),
            'author' => $theme->get('Author'),
            'author_uri' => $theme->get('AuthorURI'),
            'is_child_theme' => is_child_theme(),
            'parent_name' => is_child_theme() ? $theme->parent()->get('Name') : null,
            'parent_version' => is_child_theme() ? $theme->parent()->get('Version') : null,
            'woocommerce_support' => current_theme_supports('woocommerce'),
        ];
    }
    
    /**
     * Collect active plugins information
     * 
     * @return array Plugins list
     */
    private function collect_plugins_info() {
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        
        $active_plugins = [];
        
        foreach (get_option('active_plugins', []) as $plugin_path) {
            $plugin_file = WP_PLUGIN_DIR . '/' . $plugin_path;
            
            if (!file_exists($plugin_file)) {
                continue;
            }
            
            $plugin_data = get_plugin_data($plugin_file, false, false);
            
            $active_plugins[] = [
                'name' => $plugin_data['Name'],
                'version' => $plugin_data['Version'],
                'slug' => dirname($plugin_path),
            ];
        }
        
        return [
            'count' => count($active_plugins),
            'list' => $active_plugins,
        ];
    }
    
    /**
     * Collect server information
     * 
     * @return array Server details
     */
    private function collect_server_info() {
        return [
            'server_ip' => sanitize_text_field( wp_unslash( $_SERVER['SERVER_ADDR'] ?? 'unknown' ) ),
            'client_ip' => $this->get_client_ip(),
            'hostname' => gethostname(),
            'os' => PHP_OS,
            'architecture' => php_uname('m'),
        ];
    }
    
    /**
     * Collect performance metrics
     * 
     * @return array Performance data
     */
    private function collect_performance_metrics() {
        global $wpdb;
        
        return [
            'db_queries' => $wpdb->num_queries,
            'page_load_time' => timer_stop(0, 3),
            'memory_usage' => size_format(memory_get_usage(true)),
            'memory_peak' => size_format(memory_get_peak_usage(true)),
        ];
    }
    
    /**
     * Detect web server type
     * 
     * @return string Server type
     */
    private function detect_web_server() {
        $server = sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ?? '' ) );
        
        if (stripos($server, 'apache') !== false) {
            return 'Apache';
        } elseif (stripos($server, 'nginx') !== false) {
            return 'Nginx';
        } elseif (stripos($server, 'litespeed') !== false) {
            return 'LiteSpeed';
        } elseif (stripos($server, 'microsoft-iis') !== false) {
            return 'IIS';
        }
        
        return 'Unknown';
    }
    
    /**
     * Get active payment gateways
     * 
     * @return array Gateway IDs
     */
    private function get_active_payment_gateways() {
        if (!class_exists('WC_Payment_Gateways')) {
            return [];
        }
        
        $gateways = WC()->payment_gateways()->payment_gateways();
        $active = [];
        
        foreach ($gateways as $gateway) {
            if ($gateway->enabled === 'yes') {
                $active[] = $gateway->id;
            }
        }
        
        return $active;
    }
    
    /**
     * Get active shipping methods
     * 
     * @return array Shipping method IDs
     */
    private function get_active_shipping_methods() {
        if (!class_exists('WC_Shipping')) {
            return [];
        }
        
        $methods = WC()->shipping()->get_shipping_methods();
        $active = [];
        
        foreach ($methods as $method) {
            if ($method->enabled === 'yes') {
                $active[] = $method->id;
            }
        }
        
        return $active;
    }
    
    /**
     * Get total orders count
     * 
     * @return int Orders count
     */
    private function get_orders_count() {
        global $wpdb;
        
        if (!function_exists('wc_get_orders')) {
            return 0;
        }
        
        // Use direct COUNT query instead of loading ALL order IDs into memory
        // wc_get_orders(['limit' => -1]) would crash shops with 100k+ orders
        if (class_exists('Automattic\WooCommerce\Utilities\OrderUtil') 
            && \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled()) {
            // HPOS (High-Performance Order Storage)
            $count = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}wc_orders WHERE type = 'shop_order'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- HPOS table has no WP API; caching would skew the quota counter.
        } else {
            // Legacy post-based orders
            $count = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- legacy order count; no WC API returns this without loading all orders; caching would skew the quota counter.
                $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = %s", 'shop_order' )
            );
        }
        
        return (int) $count;
    }
    
    /**
     * Get last order ID
     * 
     * @return int Last order ID
     */
    private function get_last_order_id() {
        if (!function_exists('wc_get_orders')) {
            return 0;
        }
        
        $orders = wc_get_orders([
            'limit' => 1,
            'orderby' => 'date',
            'order' => 'DESC',
            'return' => 'ids',
        ]);
        
        return !empty($orders) ? $orders[0] : 0;
    }
    
    /**
     * Get client IP address (real IP behind proxies)
     * 
     * @return string IP address
     */
    private function get_client_ip() {
        $ip_keys = [
            'HTTP_CF_CONNECTING_IP',  // CloudFlare
            'HTTP_X_REAL_IP',          // Nginx proxy
            'HTTP_X_FORWARDED_FOR',   // Proxy
            'HTTP_CLIENT_IP',
            'REMOTE_ADDR',
        ];
        
        foreach ($ip_keys as $key) {
            if (isset($_SERVER[$key]) && filter_var(wp_unslash($_SERVER[$key]), FILTER_VALIDATE_IP)) {
                return sanitize_text_field( wp_unslash( $_SERVER[$key] ) );
            }
        }
        
        return 'unknown';
    }
}
