<?php
if (!defined('ABSPATH')) exit;
/**
 * Elementor Integration for Text to Speech TTS
 * 
 * Handles special positioning for Elementor-built pages
 * 
 * @package    TTSWP
 * @subpackage Mementor_TTS/includes
 * @since      1.5.0
 */

class Mementor_TTS_Elementor_Integration {
    
    /**
     * Instance of this class
     */
    private static $instance = null;
    
    /**
     * Player position manager
     */
    private $position_manager;
    
    /**
     * Get single instance
     */
    public static function get_instance($position_manager = null) {
        if (null === self::$instance) {
            self::$instance = new self($position_manager);
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct($position_manager) {
        $this->position_manager = $position_manager;
        
        // Only run if Elementor is active
        if (!defined('ELEMENTOR_VERSION')) {
            return;
        }
        
        // Disabled for now - using JavaScript helper instead
        // add_filter('elementor/widget/render_content', array($this, 'maybe_inject_player'), 1, 2);
        // add_action('elementor/frontend/widget/before_render', array($this, 'before_widget_render'));
        // add_action('elementor/frontend/widget/after_render', array($this, 'after_widget_render'));

        // Excerpt placement for Elementor: inject player before/after the Post Excerpt widget
        $excerpt_position = get_option('mementor_tts_player_position', 'after_content');
        if ($excerpt_position === 'before_excerpt' || $excerpt_position === 'after_excerpt') {
            add_filter('elementor/widget/render_content', array($this, 'maybe_inject_player_excerpt'), 10, 2);
        }

        // Add our CSS for Elementor pages
        add_action('wp_enqueue_scripts', array($this, 'enqueue_elementor_styles'));
    }
    
    /**
     * Maybe inject player into Elementor widget
     */
    public function maybe_inject_player($content, $widget) {
        // Only process on frontend
        if (\Elementor\Plugin::$instance->editor->is_edit_mode()) {
            return $content;
        }
        
        // Only process post title widgets
        $widget_name = $widget->get_name();
        if ($widget_name !== 'theme-post-title' && $widget_name !== 'heading') {
            return $content;
        }
        
        // Check if we should display player
        if (!is_singular() || !in_the_loop() || !is_main_query()) {
            return $content;
        }
        
        // Get player position setting
        $position = get_option('mementor_tts_player_position', 'after_content');
        if ($position !== 'before_title') {
            return $content;
        }
        
        // Get post ID
        $post_id = get_the_ID();
        if (!$post_id) {
            return $content;
        }
        
        // Check if player already added
        if (strpos($content, 'mementor-tts-player-container') !== false) {
            return $content;
        }
        
        // Check post type
        $enabled_post_types = get_option('mementor_tts_post_types', array('post', 'page'));
        if (!in_array(get_post_type($post_id), $enabled_post_types)) {
            return $content;
        }
        
        // Check if player is disabled
        $player_disabled = get_post_meta($post_id, '_mementor_tts_disable_player', true);
        if ($player_disabled === '1' || $player_disabled === 'yes') {
            return $content;
        }
        
        // Get player HTML
        $public_instance = new Mementor_TTS_Public('text-to-speech-tts', MEMENTOR_TTS_VERSION);
        $audio_url = $public_instance->get_audio_url($post_id);
        
        // Check if audio exists or auto-add is enabled
        $auto_add = get_option('mementor_tts_auto_add_player', '1') === '1';
        if (!$audio_url && !$auto_add) {
            return $content;
        }
        
        // Get player HTML
        $player_html = $public_instance->get_player_html($post_id, 'before_title');
        
        if ($player_html) {
            // For heading widgets, check if this is actually the post title
            if ($widget_name === 'heading') {
                // Only inject if the heading contains the post title
                $post_title = get_the_title($post_id);
                if (stripos($content, $post_title) === false) {
                    return $content;
                }
            }
            
            // Wrap player for Elementor
            $wrapped_player = '<div class="mementor-tts-elementor-player-wrapper">' . $player_html . '</div>';
            
            // Insert player before the content
            $content = $wrapped_player . $content;
        }
        
        return $content;
    }
    
    /**
     * Track if excerpt player has been added
     *
     * @var bool
     */
    private $excerpt_player_added = false;

    /**
     * Inject player before/after Elementor Post Excerpt widget
     *
     * @param string $content Widget content.
     * @param \Elementor\Widget_Base $widget Widget instance.
     * @return string Modified content.
     */
    public function maybe_inject_player_excerpt($content, $widget) {
        // Only process theme-post-excerpt widgets
        if ($widget->get_name() !== 'theme-post-excerpt') {
            return $content;
        }

        // Only process on frontend
        if (\Elementor\Plugin::$instance->editor->is_edit_mode()) {
            return $content;
        }

        // Prevent duplicate injection
        if ($this->excerpt_player_added) {
            return $content;
        }

        // Only on singular posts/pages
        if (!is_singular()) {
            return $content;
        }

        $post_id = get_the_ID();
        if (!$post_id) {
            return $content;
        }

        // Check post type
        $enabled_post_types = get_option('mementor_tts_post_types', array('post', 'page'));
        if (!in_array(get_post_type($post_id), $enabled_post_types)) {
            return $content;
        }

        // Check if player is disabled for this post
        $player_disabled = get_post_meta($post_id, '_mementor_tts_disable_player', true);
        if ($player_disabled === '1' || $player_disabled === 'yes') {
            return $content;
        }

        // Get player HTML
        $public_instance = new Mementor_TTS_Public('text-to-speech-tts', MEMENTOR_TTS_VERSION);
        $audio_url = $public_instance->get_audio_url($post_id);

        if (!$audio_url) {
            $auto_add = get_option('mementor_tts_auto_add_player', '1') === '1';
            $is_pro = ttswp_has_paid_plan();
            if (!$auto_add || !$is_pro) {
                return $content;
            }
        }

        $position = get_option('mementor_tts_player_position', 'after_content');
        $player_html = $public_instance->get_player_html($post_id, $position);

        if ($player_html) {
            $this->excerpt_player_added = true;
            $wrapped_player = '<div class="mementor-tts-elementor-player-wrapper">' . $player_html . '</div>';

            if ($position === 'before_excerpt') {
                $content = $wrapped_player . $content;
            } else {
                $content = $content . $wrapped_player;
            }
        }

        return $content;
    }

    /**
     * Track if we should inject player
     */
    private $should_inject = false;
    private $player_html = '';
    
    /**
     * Before widget render
     */
    public function before_widget_render($widget) {
        // Only process on frontend
        if (\Elementor\Plugin::$instance->editor->is_edit_mode()) {
            return;
        }
        
        $widget_name = $widget->get_name();
        if ($widget_name !== 'theme-post-title') {
            return;
        }
        
        // Check position setting
        $position = get_option('mementor_tts_player_position', 'after_content');
        if ($position !== 'before_title') {
            return;
        }
        
        // Get player HTML
        $post_id = get_the_ID();
        if (!$post_id) {
            return;
        }
        
        // Check if we should display
        $enabled_post_types = get_option('mementor_tts_post_types', array('post', 'page'));
        if (!in_array(get_post_type($post_id), $enabled_post_types)) {
            return;
        }
        
        $player_disabled = get_post_meta($post_id, '_mementor_tts_disable_player', true);
        if ($player_disabled === '1' || $player_disabled === 'yes') {
            return;
        }
        
        // Get player HTML
        $public_instance = new Mementor_TTS_Public('text-to-speech-tts', MEMENTOR_TTS_VERSION);
        $audio_url = $public_instance->get_audio_url($post_id);
        
        $auto_add = get_option('mementor_tts_auto_add_player', '1') === '1';
        if (!$audio_url && !$auto_add) {
            return;
        }
        
        $this->player_html = $public_instance->get_player_html($post_id, 'before_title');
        if ($this->player_html) {
            $this->should_inject = true;
            // Output player before widget
            echo '<div class="mementor-tts-elementor-player-wrapper">' . $this->player_html . '</div>';
        }
    }
    
    /**
     * After widget render
     */
    public function after_widget_render($widget) {
        // Reset
        $this->should_inject = false;
        $this->player_html = '';
    }
    
    /**
     * Enqueue Elementor-specific styles
     */
    public function enqueue_elementor_styles() {
        if (!is_singular()) {
            return;
        }
        
        // Check if this is an Elementor page
        $post_id = get_the_ID();
        if (!$post_id || !get_post_meta($post_id, '_elementor_edit_mode', true)) {
            return;
        }
        
        wp_enqueue_style(
            'mementor-tts-elementor',
            plugin_dir_url(dirname(__FILE__)) . 'public/css/mementor-tts-elementor.css',
            array('mementor-tts-public'),
            MEMENTOR_TTS_VERSION
        );
    }
}