<?php
/**
 * Caching Plugin Conflict Detector
 *
 * Detects active third-party caching plugins that may cause conflicts
 * with Mamba Cache. Prevents double-caching issues and ensures optimal performance.
 *
 * @package Mamba\Lifecycle
 * @since   1.0.0
 */

namespace Mamba\Lifecycle;

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

/**
 * Class ConflictDetector
 *
 * Identifies active caching plugins and displays admin notices
 * prompting users to deactivate them before using Mamba Cache.
 *
 * @since 1.0.0
 */
final class ConflictDetector {
    
    /**
     * Option name for tracking dismissed conflicts
     */
    private const DISMISSED_OPTION = 'mamba_conflicts_dismissed';
    
    /**
     * List of known caching plugins to detect
     * Format: 'plugin_file' => 'Plugin Display Name'
     */
    private const CACHING_PLUGINS = [
        // Page Caching Plugins
        'wp-rocket/wp-rocket.php' => 'WP Rocket',
        'wp-super-cache/wp-cache.php' => 'WP Super Cache',
        'w3-total-cache/w3-total-cache.php' => 'W3 Total Cache',
        'litespeed-cache/litespeed-cache.php' => 'LiteSpeed Cache',
        'wp-fastest-cache/wpFastestCache.php' => 'WP Fastest Cache',
        'cache-enabler/cache-enabler.php' => 'Cache Enabler',
        'comet-cache/comet-cache.php' => 'Comet Cache',
        'hummingbird-performance/wp-hummingbird.php' => 'Hummingbird',
        'breeze/breeze.php' => 'Breeze',
        'sg-cachepress/sg-cachepress.php' => 'SG Optimizer',
        'nitropack/nitropack.php' => 'NitroPack',
        'flying-press/flying-press.php' => 'FlyingPress',
        'powered-cache/powered-cache.php' => 'Powered Cache',
        'swift-performance-lite/performance.php' => 'Swift Performance Lite',
        'swift-performance/performance.php' => 'Swift Performance',
        'autoptimize/autoptimize.php' => 'Autoptimize',
        'wp-optimize/wp-optimize.php' => 'WP-Optimize',
        'perfmatters/perfmatters.php' => 'Perfmatters',
        'flying-scripts/flying-scripts.php' => 'Flying Scripts',
        'async-javascript/async-javascript.php' => 'Async JavaScript',
        'fast-velocity-minify/fvm.php' => 'Fast Velocity Minify',
        'hyper-cache/plugin.php' => 'Hyper Cache',
        'cachify/cachify.php' => 'Cachify',
        'simple-cache/simple-cache.php' => 'Simple Cache',
        'starter-starter/starter-starter.php' => 'starter starter',
        'starter starter/starter starter.php' => 'starter starter',
        
        // Object Cache Plugins (that may conflict)
        'redis-cache/redis-cache.php' => 'Redis Object Cache',
        'object-cache-pro/object-cache-pro.php' => 'Object Cache Pro',
        'docket-cache/docket-cache.php' => 'Docket Cache',
        'memcached/memcached.php' => 'Memcached Object Cache',
    ];
    
    /**
     * Register conflict detection hooks
     */
    public static function register(): void {
        // Show admin notice for conflicts
        add_action('admin_notices', [__CLASS__, 'showConflictNotice']);
        
        // AJAX handler to dismiss notice
        add_action('wp_ajax_mamba_dismiss_conflict', [__CLASS__, 'dismissConflict']);
    }
    
    /**
     * Check if any conflicting caching plugins are active
     *
     * @return array List of active conflicting plugins ['file' => 'name']
     */
    public static function getActiveConflicts(): array {
        if (!function_exists('is_plugin_active')) {
            include_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        
        $conflicts = [];
        
        foreach (self::CACHING_PLUGINS as $pluginFile => $pluginName) {
            if (is_plugin_active($pluginFile)) {
                $conflicts[$pluginFile] = $pluginName;
            }
        }
        
        return $conflicts;
    }
    
    /**
     * Check if there are any active conflicts
     *
     * @return bool True if conflicts exist
     */
    public static function hasConflicts(): bool {
        return !empty(self::getActiveConflicts());
    }
    
    /**
     * Check if Mamba caching should be blocked due to conflicts
     * This is used to prevent enabling caching when conflicts exist
     *
     * @return bool True if caching should be blocked
     */
    public static function shouldBlockCaching(): bool {
        return self::hasConflicts();
    }
    
    /**
     * Display admin notice for conflicting plugins
     */
    public static function showConflictNotice(): void {
        // Only show on admin pages
        if (!is_admin()) {
            return;
        }
        
        // Don't show on network admin for now
        if (is_network_admin()) {
            return;
        }
        
        // Check for conflicts
        $conflicts = self::getActiveConflicts();
        if (empty($conflicts)) {
            return;
        }
        
        // Check if dismissed
        $dismissed = get_option(self::DISMISSED_OPTION, []);
        $conflictHash = md5(serialize(array_keys($conflicts)));
        if (in_array($conflictHash, $dismissed, true)) {
            return;
        }
        
        // Get current screen
        $screen = get_current_screen();
        $isMambaPage = $screen && strpos($screen->id, 'mamba') !== false;
        
        // Build plugin list
        $pluginList = array_values($conflicts);
        $pluginCount = count($pluginList);
        
        if ($pluginCount === 1) {
            $pluginText = '<strong>' . esc_html($pluginList[0]) . '</strong>';
        } elseif ($pluginCount === 2) {
            $pluginText = '<strong>' . esc_html($pluginList[0]) . '</strong> and <strong>' . esc_html($pluginList[1]) . '</strong>';
        } else {
            $lastPlugin = array_pop($pluginList);
            $pluginText = '<strong>' . implode('</strong>, <strong>', array_map('esc_html', $pluginList)) . '</strong>, and <strong>' . esc_html($lastPlugin) . '</strong>';
        }
        
        // Nonce for dismiss action
        $nonce = wp_create_nonce('mamba_dismiss_conflict');
        
        ?>
        <div class="notice mamba-conflict-notice" data-conflict-hash="<?php echo esc_attr($conflictHash); ?>" data-nonce="<?php echo esc_attr($nonce); ?>">
            <div class="mamba-conflict-content">
                <div class="mamba-conflict-icon">
                    <span class="dashicons dashicons-warning"></span>
                </div>
                <div class="mamba-conflict-message">
                    <h4><?php echo esc_html__('Caching Plugin Conflict Detected', 'mamba-cache-for-woocommerce'); ?></h4>
                    <p>
                        <?php
                        printf(
                            /* translators: %s: list of conflicting plugin names */
                            esc_html__('Mamba Cache has detected that %s is currently active. Running multiple caching plugins simultaneously can cause conflicts, double-caching issues, and degraded performance.', 'mamba-cache-for-woocommerce'),
                            $pluginText
                        );
                        ?>
                    </p>
                    <p class="mamba-conflict-recommendation">
                        <strong><?php echo esc_html__('Recommendation:', 'mamba-cache-for-woocommerce'); ?></strong>
                        <?php echo esc_html__('Please deactivate the conflicting plugin(s) before enabling Mamba Cache to ensure optimal performance and avoid caching conflicts.', 'mamba-cache-for-woocommerce'); ?>
                    </p>
                    <div class="mamba-conflict-actions">
                        <a href="<?php echo esc_url(admin_url('plugins.php')); ?>" class="button button-primary mamba-conflict-btn-primary">
                            <span class="dashicons dashicons-admin-plugins"></span>
                            <?php echo esc_html__('Go to Plugins', 'mamba-cache-for-woocommerce'); ?>
                        </a>
                        <button type="button" class="button mamba-conflict-dismiss">
                            <?php echo esc_html__('Dismiss', 'mamba-cache-for-woocommerce'); ?>
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <?php
        $conflict_css = '.mamba-conflict-notice{background:linear-gradient(135deg,#fef3c7 0%,#fde68a 100%);border:1px solid #f59e0b;border-left:4px solid #f59e0b;border-radius:8px;padding:0;margin:15px 0;box-shadow:0 2px 8px rgba(245,158,11,0.15)}.mamba-conflict-content{display:flex;align-items:flex-start;gap:16px;padding:16px 20px}.mamba-conflict-icon{display:flex;align-items:center;justify-content:center;width:48px;height:48px;background:linear-gradient(135deg,#f59e0b 0%,#d97706 100%);border-radius:10px;flex-shrink:0;box-shadow:0 2px 8px rgba(245,158,11,0.3)}.mamba-conflict-icon .dashicons{font-size:24px;width:24px;height:24px;color:#ffffff}.mamba-conflict-message{flex:1}.mamba-conflict-message h4{margin:0 0 8px 0;font-size:15px;font-weight:600;color:#92400e}.mamba-conflict-message p{margin:0 0 10px 0;font-size:13px;line-height:1.5;color:#78350f}.mamba-conflict-recommendation{background:rgba(255,255,255,0.5);padding:10px 12px;border-radius:6px;border:1px solid rgba(245,158,11,0.3)}.mamba-conflict-actions{display:flex;align-items:center;gap:10px;margin-top:12px}.mamba-conflict-btn-primary{display:inline-flex;align-items:center;gap:6px;background:linear-gradient(135deg,#f59e0b 0%,#d97706 100%) !important;border:none !important;color:#ffffff !important;font-weight:500;padding:8px 16px;border-radius:6px;text-decoration:none;transition:all 0.2s ease}.mamba-conflict-btn-primary:hover{transform:translateY(-1px);box-shadow:0 4px 12px rgba(245,158,11,0.4);color:#ffffff !important}.mamba-conflict-btn-primary .dashicons{font-size:16px;width:16px;height:16px}.mamba-conflict-dismiss{background:transparent !important;border:1px solid #d97706 !important;color:#92400e !important;font-weight:500;padding:7px 14px;border-radius:6px;cursor:pointer;transition:all 0.2s ease}.mamba-conflict-dismiss:hover{background:rgba(217,119,6,0.1) !important}[data-mamba-theme="dark"] .mamba-conflict-notice{background:linear-gradient(135deg,rgba(245,158,11,0.15) 0%,rgba(217,119,6,0.1) 100%);border-color:rgba(245,158,11,0.4)}[data-mamba-theme="dark"] .mamba-conflict-message h4{color:#fbbf24}[data-mamba-theme="dark"] .mamba-conflict-message p{color:#fcd34d}[data-mamba-theme="dark"] .mamba-conflict-recommendation{background:rgba(0,0,0,0.2);border-color:rgba(245,158,11,0.3)}[data-mamba-theme="dark"] .mamba-conflict-dismiss{border-color:#fbbf24 !important;color:#fbbf24 !important}';
        wp_register_style('mamba-conflict-notice-inline', false);
        wp_enqueue_style('mamba-conflict-notice-inline');
        wp_add_inline_style('mamba-conflict-notice-inline', $conflict_css);
        wp_print_styles(['mamba-conflict-notice-inline']);

        $conflict_js = '(function(){document.addEventListener("DOMContentLoaded",function(){var notice=document.querySelector(".mamba-conflict-notice");if(!notice)return;var dismissBtn=notice.querySelector(".mamba-conflict-dismiss");if(!dismissBtn)return;dismissBtn.addEventListener("click",function(){var hash=notice.getAttribute("data-conflict-hash");var nonce=notice.getAttribute("data-nonce");notice.style.display="none";var xhr=new XMLHttpRequest();xhr.open("POST",ajaxurl,true);xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.send("action=mamba_dismiss_conflict&hash="+encodeURIComponent(hash)+"&nonce="+encodeURIComponent(nonce));});});})();';
        wp_add_inline_script('mamba-admin', $conflict_js);
        ?>
        <?php
    }
    
    /**
     * AJAX handler to dismiss conflict notice
     */
    public static function dismissConflict(): void {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'mamba_dismiss_conflict')) {
            wp_send_json_error('Invalid nonce');
            return;
        }
        
        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Permission denied');
            return;
        }
        
        // Get hash
        $hash = isset($_POST['hash']) ? sanitize_text_field(wp_unslash($_POST['hash'])) : '';
        if (empty($hash)) {
            wp_send_json_error('Invalid hash');
            return;
        }
        
        // Save dismissal
        $dismissed = get_option(self::DISMISSED_OPTION, []);
        if (!in_array($hash, $dismissed, true)) {
            $dismissed[] = $hash;
            update_option(self::DISMISSED_OPTION, $dismissed, false);
        }
        
        wp_send_json_success();
    }
    
    /**
     * Reset dismissed conflicts (useful when conflicts change)
     */
    public static function resetDismissed(): void {
        delete_option(self::DISMISSED_OPTION);
    }
    
    /**
     * Get a formatted message about conflicts for use in other contexts
     *
     * @return string|null Message about conflicts or null if none
     */
    public static function getConflictMessage(): ?string {
        $conflicts = self::getActiveConflicts();
        if (empty($conflicts)) {
            return null;
        }
        
        $pluginNames = array_values($conflicts);
        $count = count($pluginNames);
        
        if ($count === 1) {
            return sprintf(
                __('%s is currently active. Please deactivate it to avoid caching conflicts.', 'mamba-cache-for-woocommerce'),
                $pluginNames[0]
            );
        }
        
        return sprintf(
            __('%d caching plugins are currently active (%s). Please deactivate them to avoid conflicts.', 'mamba-cache-for-woocommerce'),
            $count,
            implode(', ', $pluginNames)
        );
    }
}
