<?php
/**
 * Compatibility fixes for Text to Speech TTS plugin
 * 
 * This file contains fixes to prevent conflicts with other plugins,
 * particularly TutorLMS, Elementor, and other quiz/tooltip plugins.
 * 
 * @package TTSWP
 * @since 1.4.1
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Class Mementor_TTS_Compatibility_Fixes
 * 
 * Handles compatibility fixes for the plugin to work well with others
 */
class Mementor_TTS_Compatibility_Fixes {
    
    /**
     * Instance of this class
     */
    private static $instance = null;
    
    /**
     * Get single instance of this class
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        // Initialize compatibility fixes
        add_action('init', array($this, 'init_compatibility_fixes'), 5);
        
        // Prevent loading our assets on other plugin pages
        add_action('admin_enqueue_scripts', array($this, 'prevent_asset_conflicts'), 1);
        add_action('wp_enqueue_scripts', array($this, 'prevent_frontend_conflicts'), 1);
        
        // Fix tooltip conflicts
        add_action('wp_enqueue_scripts', array($this, 'fix_tooltip_conflicts'), 999);
        add_action('admin_enqueue_scripts', array($this, 'fix_admin_tooltip_conflicts'), 999);
        
        // Fix event propagation issues
        add_filter('mementor_tts_stop_propagation', array($this, 'should_stop_propagation'), 10, 2);
        
        // Add filter to control admin notice hiding
        add_filter('mementor_tts_hide_admin_notices', array($this, 'should_hide_admin_notices'));
    }
    
    /**
     * Initialize compatibility fixes
     */
    public function init_compatibility_fixes() {
        // Check if we're on a page where conflicts might occur
        if ($this->is_conflict_prone_page()) {
            // Disable aggressive notice hiding on non-TTS pages
            remove_action('admin_print_styles', array($this, 'hide_third_party_notices'));
            remove_action('admin_print_footer_scripts', array($this, 'hide_notices_js'));
        }
    }
    
    /**
     * Prevent loading our CSS/JS on other plugin admin pages
     */
    public function prevent_asset_conflicts($hook) {
        // Only apply if compatibility mode is enabled
        if (get_option('mementor_tts_compatibility_mode', '0') !== '1') {
            return;
        }
        
        // Check if we're on another plugin's admin page
        if ($this->is_other_plugin_admin_page($hook)) {
            // Dequeue all our admin scripts
            wp_dequeue_script('mementor-tts-tooltip');
            wp_dequeue_script('mementor-tts-admin');
            wp_dequeue_script('mementor-tts-generator');
            wp_dequeue_script('mementor-tts-notifications');
            wp_dequeue_script('mementor-tts-modal-utils');
            
            // Dequeue all our admin styles
            wp_dequeue_style('mementor-tts-admin');
            wp_dequeue_style('mementor-tts-generator');
            wp_dequeue_style('mementor-tts-notifications');
            wp_dequeue_style('mementor-tts-shared');
            
            // Remove our admin notice hiding styles
            remove_action('admin_print_styles', array($this, 'hide_third_party_notices'));
            remove_action('admin_print_footer_scripts', array($this, 'hide_notices_js'));
        }
    }
    
    /**
     * Prevent loading our frontend assets on quiz/learning pages
     */
    public function prevent_frontend_conflicts() {
        // Only apply if compatibility mode is enabled
        if (get_option('mementor_tts_compatibility_mode', '0') !== '1') {
            return;
        }
        
        if ($this->is_quiz_or_learning_page()) {
            // Dequeue our public scripts that might interfere
            wp_dequeue_script('mementor-tts-public');
            wp_dequeue_script('mementor-tts-shortcode');
            
            // Only keep essential styles for the player itself
            // but remove any that might interfere with forms
            wp_dequeue_style('mementor-tts-public');
            
            // Re-enqueue only minimal player styles if audio exists on page
            if ($this->has_tts_player_on_page()) {
                wp_enqueue_style('mementor-tts-player-minimal', 
                    MEMENTOR_TTS_PLUGIN_URL . 'public/css/mementor-tts-player-minimal.css',
                    array(),
                    MEMENTOR_TTS_VERSION
                );
            }
        }
    }
    
    /**
     * Check if we're on another plugin's admin page
     */
    private function is_other_plugin_admin_page($hook) {
        // Our plugin pages
        if (strpos($hook, 'text-to-speech-tts') !== false) {
            return false;
        }
        
        // Check for known plugin admin pages
        $other_plugin_patterns = array(
            'tutor-lms',
            'tutor_',
            'elementor',
            'learndash',
            'learnpress',
            'sensei',
            'wpcw_',
            'sfwd-lms',
            'quiz',
            'exam',
            'assessment'
        );
        
        foreach ($other_plugin_patterns as $pattern) {
            if (strpos($hook, $pattern) !== false) {
                return true;
            }
        }
        
        // Check current screen
        $screen = get_current_screen();
        if ($screen) {
            // Check post type
            $quiz_post_types = array('tutor_quiz', 'sfwd-quiz', 'lesson', 'course');
            if (in_array($screen->post_type, $quiz_post_types)) {
                return true;
            }
            
            // Check screen ID
            foreach ($other_plugin_patterns as $pattern) {
                if (strpos($screen->id, $pattern) !== false) {
                    return true;
                }
            }
        }
        
        return false;
    }
    
    /**
     * Check if we should hide admin notices
     */
    public function should_hide_admin_notices($should_hide) {
        // Don't hide notices on other plugin pages
        if ($this->is_other_plugin_admin_page('')) {
            return false;
        }
        
        return $should_hide;
    }
    
    /**
     * Check if TTS player exists on current page
     */
    private function has_tts_player_on_page() {
        if (!is_singular()) {
            return false;
        }
        
        global $post;
        if (!$post) {
            return false;
        }
        
        // Check if post type is enabled
        $enabled_post_types = get_option('mementor_tts_post_types', array('post'));
        if (!in_array($post->post_type, $enabled_post_types)) {
            return false;
        }
        
        // Check if audio file exists
        $upload_dir = wp_upload_dir();
        $audio_file = $upload_dir['basedir'] . '/text-to-speech-tts/mementor-' . $post->ID . '-en.mp3';
        
        return file_exists($audio_file);
    }
    
    /**
     * Check if we're on a page where conflicts might occur
     */
    private function is_conflict_prone_page() {
        // Check if TutorLMS is active
        if (defined('TUTOR_VERSION')) {
            return true;
        }
        
        // Check if Elementor is active and we're in editor
        if (defined('ELEMENTOR_VERSION') && \Elementor\Plugin::$instance->editor->is_edit_mode()) {
            return true;
        }
        
        // Check for other known quiz/LMS plugins
        $conflict_plugins = array(
            'learndash/learndash.php',
            'learnpress/learnpress.php',
            'sfwd-lms/sfwd_lms.php',
            'wp-courseware/wp-courseware.php',
            'sensei/sensei-lms.php'
        );
        
        foreach ($conflict_plugins as $plugin) {
            if (is_plugin_active($plugin)) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Fix tooltip conflicts
     */
    public function fix_tooltip_conflicts() {
        // Only apply if compatibility mode is enabled
        if (get_option('mementor_tts_compatibility_mode', '0') !== '1') {
            return;
        }
        
        // Only load our tooltip script if not on a quiz/learning page
        if ($this->is_quiz_or_learning_page()) {
            // Dequeue our tooltip script on quiz pages
            wp_dequeue_script('mementor-tts-tooltip');
            
            // Add inline script to prevent tooltip initialization and event issues
            wp_add_inline_script('jquery', '
                // Disable TTS tooltips on quiz pages
                if (typeof window.mementorTTSTooltip !== "undefined") {
                    window.mementorTTSTooltip.disabled = true;
                }
                
                // Set flag to prevent event propagation stopping
                window.mementorTTSCompatibilityMode = true;
                
                // Override any global click handlers from our plugin
                jQuery(document).ready(function($) {
                    // Remove our document-level handlers
                    $(document).off(".mementorTTS");
                    
                    // Ensure form elements work properly
                    $("form input, form select, form textarea, form button").off(".mementorTTS");
                });
            ');
        }
    }
    
    /**
     * Fix admin tooltip conflicts
     */
    public function fix_admin_tooltip_conflicts() {
        // Only apply if compatibility mode is enabled
        if (get_option('mementor_tts_compatibility_mode', '0') !== '1') {
            return;
        }
        
        // Add CSS to reduce our tooltip z-index
        wp_add_inline_style('mementor-tts-admin', '
            /* Reduce z-index to prevent conflicts */
            .mementor-tts-tooltip {
                z-index: 9999 !important; /* Reduced from 99999 */
            }
            
            /* Ensure our tooltips dont interfere with form elements */
            .mementor-tts-tooltip {
                pointer-events: none !important;
            }
            .mementor-tts-tooltip.active {
                pointer-events: auto !important;
            }
        ');
    }
    
    
    /**
     * Check if we're on a quiz or learning page
     */
    private function is_quiz_or_learning_page() {
        // Check for TutorLMS quiz pages
        if (function_exists('tutor') && (is_singular('tutor_quiz') || tutor_utils()->is_tutor_dashboard())) {
            return true;
        }
        
        // Check for LearnDash quiz pages
        if (function_exists('learndash_is_quiz') && learndash_is_quiz()) {
            return true;
        }
        
        // Check for common quiz URL patterns
        $current_url = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
        $quiz_patterns = array('/quiz/', '/test/', '/exam/', '/assessment/', '/question/');
        
        foreach ($quiz_patterns as $pattern) {
            if (strpos($current_url, $pattern) !== false) {
                return true;
            }
        }
        
        // Check for quiz-related classes in body
        if (is_singular()) {
            global $post;
            if ($post && (
                strpos($post->post_content, 'quiz') !== false ||
                strpos($post->post_content, 'tutor-quiz') !== false ||
                strpos($post->post_content, 'elementor-widget-form') !== false
            )) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Filter to determine if event propagation should be stopped
     */
    public function should_stop_propagation($should_stop, $context = '') {
        // Only apply if compatibility mode is enabled
        if (get_option('mementor_tts_compatibility_mode', '0') !== '1') {
            return $should_stop;
        }
        
        // Don't stop propagation on quiz/learning pages
        if ($this->is_quiz_or_learning_page()) {
            return false;
        }
        
        // Don't stop propagation if we detect form elements nearby
        if ($context === 'player_click' && $this->has_form_elements_nearby()) {
            return false;
        }
        
        return $should_stop;
    }
    
    /**
     * Check if there are form elements nearby
     */
    private function has_form_elements_nearby() {
        // This is a placeholder - in actual implementation,
        // we'd check via JavaScript if form elements are near the player
        return apply_filters('mementor_tts_has_form_elements_nearby', false);
    }
    
    /**
     * Add compatibility mode setting
     */
    public static function add_compatibility_settings($settings) {
        $settings['compatibility_mode'] = array(
            'type' => 'checkbox',
            'label' => __('Enable Compatibility Mode', 'text-to-speech-tts'),
            'description' => __('Enable this if you experience conflicts with tooltips, quizzes, or form submissions from other plugins.', 'text-to-speech-tts'),
            'default' => false
        );
        
        return $settings;
    }
}

// Initialize compatibility fixes
Mementor_TTS_Compatibility_Fixes::get_instance();

// Add filter for settings
add_filter('mementor_tts_advanced_settings', array('Mementor_TTS_Compatibility_Fixes', 'add_compatibility_settings'));