<?php
/**
 * CDN Conflict Detector
 * Detects other CDN plugins/services and shows warnings
 */

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

class USCDN_Conflict_Detector {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('admin_notices', [$this, 'show_action_notices']);
        add_action('admin_notices', [$this, 'show_conflict_notices']);
        add_action('admin_init', [$this, 'handle_disable_actions']);
    }
    
    /**
     * Detect conflicting CDN plugins/services
     */
    public function detect_conflicts() {
        $conflicts = [];
        
        // 1. Jetpack Photon/CDN
        if (class_exists('Jetpack') && method_exists('Jetpack', 'is_module_active')) {
            if (Jetpack::is_module_active('photon') || Jetpack::is_module_active('photon-cdn')) {
                $conflicts['jetpack'] = [
                    'name' => 'Jetpack CDN (Photon)',
                    'description' => 'Jetpack is wrapping your images with i0.wp.com CDN',
                    'can_disable' => true,
                    'disable_action' => 'disable_jetpack_cdn'
                ];
            }
        }
        
        // 2. WP Rocket CDN
        if (defined('WP_ROCKET_VERSION')) {
            $wp_rocket_settings = get_option('wp_rocket_settings', []);
            if (!empty($wp_rocket_settings['cdn']) && !empty($wp_rocket_settings['cdn_cnames'])) {
                $conflicts['wp_rocket'] = [
                    'name' => 'WP Rocket CDN',
                    'description' => 'WP Rocket CDN is enabled and may conflict',
                    'can_disable' => false,
                    'message' => 'Please disable CDN in WP Rocket settings manually'
                ];
            }
        }
        
        // 3. W3 Total Cache CDN
        if (defined('W3TC') && function_exists('w3tc_get_option')) {
            if (w3tc_get_option('cdn.enabled')) {
                $conflicts['w3tc'] = [
                    'name' => 'W3 Total Cache CDN',
                    'description' => 'W3 Total Cache CDN is enabled and may conflict',
                    'can_disable' => false,
                    'message' => 'Please disable CDN in W3 Total Cache settings manually'
                ];
            }
        }
        
        // 4. Cloudflare Plugin
        if (class_exists('CF\WordPress\Hooks')) {
            $conflicts['cloudflare'] = [
                'name' => 'Cloudflare Plugin',
                'description' => 'Cloudflare plugin detected. Ensure it\'s not conflicting with CDN URLs',
                'can_disable' => false,
                'message' => 'Check Cloudflare plugin settings to avoid conflicts'
            ];
        }
        
        // 5. Autoptimize CDN
        if (class_exists('autoptimizeConfig')) {
            $cdn_url = get_option('autoptimize_cdn_url', '');
            if (!empty($cdn_url)) {
                $conflicts['autoptimize'] = [
                    'name' => 'Autoptimize CDN',
                    'description' => 'Autoptimize CDN is configured',
                    'can_disable' => false,
                    'message' => 'Please disable CDN in Autoptimize settings manually'
                ];
            }
        }
        
        // 6. BunnyCDN Plugin
        if (class_exists('BunnyCDN')) {
            $conflicts['bunnycdn'] = [
                'name' => 'BunnyCDN Plugin',
                'description' => 'BunnyCDN plugin is active and may conflict',
                'can_disable' => false,
                'message' => 'Please disable or configure to avoid conflicts'
            ];
        }
        
        return $conflicts;
    }
    
    /**
     * Show admin notices for conflicts
     */
    public function show_conflict_notices() {
        // Only show on plugin pages
        $screen = get_current_screen();
        if (!$screen || strpos($screen->id, 'cdn-manager') === false) {
            return;
        }
        
        $conflicts = $this->detect_conflicts();
        
        if (empty($conflicts)) {
            // Show success message if no conflicts
            echo '<div class="notice notice-success is-dismissible">';
            echo '<p><strong>✅ No CDN Conflicts Detected</strong> - Your Utility Server CDN is the only active CDN.</p>';
            echo '</div>';
            return;
        }
        
        // Show warning for each conflict
        foreach ($conflicts as $key => $conflict) {
            echo '<div class="notice notice-warning">';
            echo '<p><strong>⚠️ CDN Conflict Detected: ' . esc_html($conflict['name']) . '</strong></p>';
            echo '<p>' . esc_html($conflict['description']) . '</p>';
            
            if ($conflict['can_disable']) {
                $nonce = wp_create_nonce('uscdn_disable_' . $key);
                $url = add_query_arg([
                    'action' => $conflict['disable_action'],
                    '_wpnonce' => $nonce
                ], admin_url('admin.php'));
                
                echo '<p>';
                echo '<a href="' . esc_url($url) . '" class="button button-primary">Disable ' . esc_html($conflict['name']) . '</a> ';
                echo '<span style="color: #d63638;">Recommended to avoid conflicts</span>';
                echo '</p>';
                
                // Manual disable instructions for Jetpack
                if ($key === 'jetpack') {
                    echo '<p><strong>Or disable manually:</strong></p>';
                    echo '<ol style="margin-left: 20px;">';
                    echo '<li>Go to <strong>Jetpack → Settings</strong></li>';
                    echo '<li>Click on the <strong>Performance</strong> tab</li>';
                    echo '<li>Find <strong>Image CDN</strong> or <strong>Site Accelerator</strong></li>';
                    echo '<li>Toggle it <strong>OFF</strong></li>';
                    echo '</ol>';
                }
            } else {
                echo '<p><em>' . esc_html($conflict['message']) . '</em></p>';
            }
            
            echo '</div>';
        }
    }
    
    /**
     * Handle disable actions
     */
    public function handle_disable_actions() {
        if (!isset($_GET['action'])) {
            return;
        }
        
        $action = sanitize_text_field($_GET['action']);
        
        // Disable Jetpack CDN
        if ($action === 'disable_jetpack_cdn') {
            // Check permissions
            if (!current_user_can('manage_options')) {
                wp_die('Sorry, you do not have permission to perform this action.');
            }
            
            // Verify nonce
            if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'uscdn_disable_jetpack')) {
                wp_die('Security check failed. Please try again.');
            }
            
            // Disable Jetpack modules
            if (class_exists('Jetpack') && method_exists('Jetpack', 'deactivate_module')) {
                Jetpack::deactivate_module('photon');
                Jetpack::deactivate_module('photon-cdn');
                
                // Set success message
                set_transient('uscdn_admin_notice', [
                    'type' => 'success',
                    'message' => 'Jetpack CDN has been disabled successfully.'
                ], 30);
            } else {
                set_transient('uscdn_admin_notice', [
                    'type' => 'error',
                    'message' => 'Could not disable Jetpack CDN. Please disable it manually in Jetpack settings.'
                ], 30);
            }
            
            // Redirect back
            wp_redirect(admin_url('admin.php?page=cdn-manager-settings'));
            exit;
        }
    }
    
    /**
     * Show action result notices
     */
    public function show_action_notices() {
        $notice = get_transient('uscdn_admin_notice');
        if ($notice) {
            delete_transient('uscdn_admin_notice');
            
            $class = $notice['type'] === 'success' ? 'notice-success' : 'notice-error';
            echo '<div class="notice ' . esc_attr($class) . ' is-dismissible">';
            echo '<p>' . esc_html($notice['message']) . '</p>';
            echo '</div>';
        }
    }
    
    /**
     * Get conflict summary for display
     */
    public function get_conflict_summary() {
        $conflicts = $this->detect_conflicts();
        
        if (empty($conflicts)) {
            return [
                'has_conflicts' => false,
                'message' => 'No conflicts detected'
            ];
        }
        
        return [
            'has_conflicts' => true,
            'count' => count($conflicts),
            'conflicts' => $conflicts
        ];
    }
}
