<?php
/**
 * CDN Dynamic Content Rewriter
 * Replaces URLs in content on-the-fly without modifying database
 */

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

class USCDN_Content_Rewriter {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        // Only run if dynamic rewriting is enabled
        if (USCDN_Settings::get('enable_dynamic_rewriting', 0)) {
            $this->init_filters();
        }
    }
    
    private function init_filters() {
        // Content filters - high priority to run after other plugins
        add_filter('the_content', [$this, 'rewrite_content'], 999);
        add_filter('the_excerpt', [$this, 'rewrite_content'], 999);
        add_filter('widget_text', [$this, 'rewrite_content'], 999);
        add_filter('widget_content', [$this, 'rewrite_content'], 999);
        
        // Post meta and custom fields
        add_filter('get_post_metadata', [$this, 'rewrite_meta'], 999, 4);
        
        // Options
        add_filter('option_blogdescription', [$this, 'rewrite_content'], 999);
        add_filter('option_blogname', [$this, 'rewrite_content'], 999);
        
        // WooCommerce specific
        add_filter('woocommerce_short_description', [$this, 'rewrite_content'], 999);
        add_filter('woocommerce_product_description', [$this, 'rewrite_content'], 999);
        
        // Page builders
        add_filter('elementor_widget_render_content', [$this, 'rewrite_content'], 999);
        add_filter('et_builder_render_layout', [$this, 'rewrite_content'], 999);
        
        // Final output buffer (catch-all)
        if (USCDN_Settings::get('dynamic_rewriting_aggressive', 0)) {
            add_action('template_redirect', [$this, 'start_output_buffer'], 1);
        }
    }
    
    /**
     * Rewrite content with configured rules
     */
    public function rewrite_content($content) {
        if (!is_string($content) || empty($content)) {
            return $content;
        }
        
        $rules = $this->get_rewrite_rules();
        
        if (empty($rules)) {
            return $content;
        }
        
        foreach ($rules as $rule) {
            if (empty($rule['find']) || empty($rule['replace'])) {
                continue;
            }
            
            // Simple string replace for exact matches
            $content = str_replace($rule['find'], $rule['replace'], $content);
            
            // Also handle protocol-relative URLs
            if (strpos($rule['find'], 'https://') === 0) {
                $protocol_relative = str_replace('https://', '//', $rule['find']);
                $replace_protocol_relative = str_replace('https://', '//', $rule['replace']);
                $content = str_replace($protocol_relative, $replace_protocol_relative, $content);
            }
        }
        
        return $content;
    }
    
    /**
     * Rewrite post meta on-the-fly
     */
    public function rewrite_meta($value, $object_id, $meta_key, $single) {
        // Only process if value is already retrieved
        if ($value === null) {
            return $value;
        }
        
        // Get the actual meta value
        $meta = get_metadata('post', $object_id, $meta_key, $single);
        
        if (is_string($meta)) {
            return $this->rewrite_content($meta);
        } elseif (is_array($meta)) {
            return $this->rewrite_array_recursive($meta);
        }
        
        return $meta;
    }
    
    /**
     * Recursively rewrite arrays
     */
    private function rewrite_array_recursive($data) {
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                if (is_string($value)) {
                    $data[$key] = $this->rewrite_content($value);
                } elseif (is_array($value)) {
                    $data[$key] = $this->rewrite_array_recursive($value);
                }
            }
        }
        return $data;
    }
    
    /**
     * Get rewrite rules from settings
     */
    private function get_rewrite_rules() {
        $rules = [];
        
        // Get custom rules from settings
        $custom_rules = USCDN_Settings::get('dynamic_rewrite_rules', '');
        
        if (!empty($custom_rules)) {
            $lines = explode("\n", $custom_rules);
            foreach ($lines as $line) {
                $line = trim($line);
                if (empty($line) || strpos($line, '|') === false) {
                    continue;
                }
                
                list($find, $replace) = explode('|', $line, 2);
                $rules[] = [
                    'find' => trim($find),
                    'replace' => trim($replace)
                ];
            }
        }
        
        // Auto-generate rules based on CDN settings
        if (USCDN_Settings::get('dynamic_rewriting_auto_rules', 1)) {
            $auto_rules = $this->get_auto_rules();
            $rules = array_merge($rules, $auto_rules);
        }
        
        return apply_filters('uscdn_dynamic_rewrite_rules', $rules);
    }
    
    /**
     * Generate automatic rewrite rules based on CDN configuration
     */
    private function get_auto_rules() {
        $rules = [];
        $current_url = home_url();
        
        // Rule 1: Origin URL
        if (USCDN_Settings::get('enable_origin_url') && USCDN_Settings::get('origin_url')) {
            $origin_url = USCDN_Settings::get('origin_url');
            if ($origin_url !== $current_url) {
                $rules[] = [
                    'find' => $current_url,
                    'replace' => $origin_url
                ];
            }
        }
        
        // Rule 2: Image CDN
        if (USCDN_Settings::get('enable_image_cdn') && USCDN_Settings::get('cdn_image_base')) {
            $rules[] = [
                'find' => $current_url . '/wp-content/uploads',
                'replace' => USCDN_Settings::get('cdn_image_base') . '/wp-content/uploads'
            ];
        }
        
        // Rule 3: Static CDN for themes
        if (USCDN_Settings::get('enable_static_cdn') && USCDN_Settings::get('cdn_static_base')) {
            $rules[] = [
                'find' => $current_url . '/wp-content/themes',
                'replace' => USCDN_Settings::get('cdn_static_base') . '/wp-content/themes'
            ];
            
            $rules[] = [
                'find' => $current_url . '/wp-content/plugins',
                'replace' => USCDN_Settings::get('cdn_static_base') . '/wp-content/plugins'
            ];
            
            $rules[] = [
                'find' => $current_url . '/wp-includes',
                'replace' => USCDN_Settings::get('cdn_static_base') . '/wp-includes'
            ];
        }
        
        return $rules;
    }
    
    /**
     * Start output buffer for aggressive mode
     */
    public function start_output_buffer() {
        if (!is_admin()) {
            ob_start([$this, 'rewrite_content']);
        }
    }
    
    /**
     * Get statistics about rewriting
     */
    public static function get_stats() {
        $rules = self::get_instance()->get_rewrite_rules();
        
        return [
            'enabled' => (bool) USCDN_Settings::get('enable_dynamic_rewriting', 0),
            'aggressive_mode' => (bool) USCDN_Settings::get('dynamic_rewriting_aggressive', 0),
            'auto_rules' => (bool) USCDN_Settings::get('dynamic_rewriting_auto_rules', 1),
            'total_rules' => count($rules),
            'custom_rules' => count(array_filter($rules, function($rule) {
                return !empty($rule['find']);
            }))
        ];
    }
}
