<?php
/**
 * Plugin Name: Launchmind Blog
 * Description: Display AI-powered Launchmind blog content on your WordPress site.
 * Version: 2.6.0
 * Author: Launchmind.io
 * Author URI: https://launchmind.io
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: launchmind-blog
 * Requires at least: 5.8
 * Requires PHP: 7.4
 * Tested up to: 6.9
 */

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

// Define plugin constants
define('LAUNCHMIND_BLOG_VERSION', '2.5.0');
define('LAUNCHMIND_BLOG_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('LAUNCHMIND_BLOG_PLUGIN_URL', plugin_dir_url(__FILE__));
define('LAUNCHMIND_BLOG_PLUGIN_BASENAME', plugin_basename(__FILE__));

// Default API base URL
define('LAUNCHMIND_API_DEFAULT_BASE', 'https://launchmind.io/api');

// Default cache TTL (10 minutes)
define('LAUNCHMIND_CACHE_DEFAULT_TTL', 600);

/**
 * Main Plugin Class
 */
class Launchmind_Blog_Connector {
    
    /**
     * Singleton instance
     */
    private static $instance = null;
    
    /**
     * Get singleton instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        $this->load_dependencies();
        $this->init_hooks();
    }
    
    /**
     * Load required files
     */
    private function load_dependencies() {
        require_once LAUNCHMIND_BLOG_PLUGIN_DIR . 'includes/class-launchmind-api.php';
        require_once LAUNCHMIND_BLOG_PLUGIN_DIR . 'includes/class-launchmind-cache.php';
        require_once LAUNCHMIND_BLOG_PLUGIN_DIR . 'includes/class-launchmind-shortcodes.php';
        // Admin
        if (is_admin()) {
            require_once LAUNCHMIND_BLOG_PLUGIN_DIR . 'admin/class-launchmind-admin.php';
            require_once LAUNCHMIND_BLOG_PLUGIN_DIR . 'admin/class-launchmind-dashboard.php';
        }
        // Blocks
        require_once LAUNCHMIND_BLOG_PLUGIN_DIR . 'blocks/index.php';
    }
    
    /**
     * Initialize hooks
     */
    private function init_hooks() {
        // Activation/Deactivation
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));
        
        // Initialize components
        add_action('init', array($this, 'init'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_public_assets'));
        
        // Add rewrite rules for single blog posts
        add_action('init', array($this, 'add_rewrite_rules'));
        add_filter('query_vars', array($this, 'add_query_vars'));
        add_action('template_redirect', array($this, 'handle_single_post_template'));
        
        // STRUCTURAL FIX: Process shortcodes BEFORE theme renders content
        // This ensures shortcodes work even if theme bypasses WordPress filters
        add_filter('the_posts', array($this, 'process_shortcodes_in_posts'), 10);
        
        // ACF COMPATIBILITY: Process shortcodes in ACF fields
        // Many custom themes (like Stay Awake) use ACF for page content
        add_filter('acf/format_value/type=textarea', 'do_shortcode', 10);
        add_filter('acf/format_value/type=wysiwyg', 'do_shortcode', 10);
        add_filter('acf/format_value', 'do_shortcode', 10);
        
        // Load translations
        add_action('plugins_loaded', array($this, 'load_textdomain'));
    }
    
    /**
     * Plugin activation
     */
    public function activate() {
        // Set default options if not exists
        if (false === get_option('launchmind_blog_api_base')) {
            update_option('launchmind_blog_api_base', LAUNCHMIND_API_DEFAULT_BASE);
        }
        if (false === get_option('launchmind_blog_cache_ttl')) {
            update_option('launchmind_blog_cache_ttl', LAUNCHMIND_CACHE_DEFAULT_TTL);
        }
        
        // Clear any existing cache (with safety check)
        if (class_exists('Launchmind_Cache')) {
        Launchmind_Cache::clear_all();
        }

        // Auto-create a clean Blog page (idempotent, won't overwrite existing /blog)
        $this->ensure_blog_page();
        
        // Register rewrite rules
        $this->add_rewrite_rules();
        
        // Flush rewrite rules for custom endpoints
        flush_rewrite_rules();
    }
    
    /**
     * Plugin deactivation
     */
    public function deactivate() {
        // Clear cache (with safety check)
        if (class_exists('Launchmind_Cache')) {
        Launchmind_Cache::clear_all();
        }
        
        // Flush rewrite rules
        flush_rewrite_rules();
    }
    
    /**
     * Initialize plugin
     */
    public function init() {
        // Initialize shortcodes (with safety check)
        if (class_exists('Launchmind_Shortcodes')) {
        Launchmind_Shortcodes::init();
        }
        
        // Initialize admin
        if (is_admin() && class_exists('Launchmind_Admin')) {
            Launchmind_Admin::init();
        }
    }
    
    /**
     * Enqueue public assets
     */
    public function enqueue_public_assets() {
        wp_enqueue_style(
            'launchmind-blog',
            LAUNCHMIND_BLOG_PLUGIN_URL . 'public/css/launchmind-blog.css',
            array(),
            LAUNCHMIND_BLOG_VERSION
        );
    }
    
    /**
     * Load plugin textdomain
     * Note: When hosted on WordPress.org, translations are loaded automatically.
     * This method is kept for standalone installations.
     */
    public function load_textdomain() {
        // WordPress.org handles translations automatically since WP 4.6
        // No manual loading needed for plugins hosted on wordpress.org
    }
    
    /**
     * Get plugin option with default
     */
    public static function get_option($key, $default = '') {
        $option = get_option('launchmind_blog_' . $key, $default);
        return $option !== false ? $option : $default;
    }
    
    /**
     * Update plugin option
     */
    public static function update_option($key, $value) {
        return update_option('launchmind_blog_' . $key, $value);
    }
    
    /**
     * Process shortcodes in post content BEFORE theme renders
     * This is the structural solution for themes that bypass WordPress content filters
     */
    public function process_shortcodes_in_posts($posts) {
        if (empty($posts) || is_admin()) {
            return $posts;
        }
        
        foreach ($posts as &$post) {
            // Only process if post contains our shortcodes
            if (isset($post->post_content) && 
                (strpos($post->post_content, '[launchmind_blog') !== false || 
                 strpos($post->post_content, '[launchmind_post') !== false ||
                 strpos($post->post_content, '[launchmind_test') !== false)) {
                // Execute shortcodes and replace in post content
                $post->post_content = do_shortcode($post->post_content);
            }
        }
        
        return $posts;
    }

    /**
     * Ensure a Blog page exists (creates /blog once, stores its ID).
     * Does NOT overwrite an existing page with slug 'blog'.
     */
    private function ensure_blog_page() {
        // Allow disabling via option if needed
        $enabled = self::get_option('auto_create_blog_page', true);
        if (!$enabled) {
            return;
        }

        $existing_id = (int) self::get_option('blog_page_id', 0);
        if ($existing_id > 0) {
            $existing_post = get_post($existing_id);
            if ($existing_post && $existing_post->post_type === 'page') {
                return;
            }
        }

        // If a /blog page already exists, just store it (don't overwrite content)
        $blog_page = get_page_by_path('blog', OBJECT, 'page');
        if ($blog_page && !empty($blog_page->ID)) {
            self::update_option('blog_page_id', (int) $blog_page->ID);
            // Ensure base path is consistent
            if (!self::get_option('base_path', '')) {
                self::update_option('base_path', '/blog/');
            }
            return;
        }

        // Create a clean page: title "Blog" and only the shortcode in content
        $content = "[launchmind_blog limit=\"12\" columns=\"4\"]";

        $new_id = wp_insert_post(array(
            'post_title' => 'Blog',
            'post_name' => 'blog',
            'post_content' => $content,
            'post_status' => 'publish',
            'post_type' => 'page',
            'comment_status' => 'closed',
            'ping_status' => 'closed',
        ), true);

        if (!is_wp_error($new_id) && $new_id) {
            self::update_option('blog_page_id', (int) $new_id);
            // Set base path for links
            self::update_option('base_path', '/blog/');
        }
    }
    
    /**
     * Add rewrite rules for blog posts
     */
    public function add_rewrite_rules() {
        add_rewrite_rule(
            '^blog/([^/]+)/?$',
            'index.php?launchmind_post=$matches[1]',
            'top'
        );
    }
    
    /**
     * Add query vars
     */
    public function add_query_vars($vars) {
        $vars[] = 'launchmind_post';
        return $vars;
    }
    
    /**
     * Handle single post rendering
     */
    public function handle_single_post_template() {
        $slug = get_query_var('launchmind_post');
        
        if (!$slug) {
            return;
        }
        
        // Safety check: ensure required classes are available
        if (!class_exists('Launchmind_API') || !class_exists('Launchmind_Cache')) {
            return;
        }
        
        // Get language from URL parameter or use WordPress locale
        $lang = isset($_GET['lang']) ? sanitize_text_field($_GET['lang']) : substr(get_locale(), 0, 2);
        $lang = in_array($lang, array('en', 'nl', 'de', 'fr', 'es', 'it', 'hi')) ? $lang : substr(get_locale(), 0, 2);
        
        // Wrap in try-catch to prevent fatal errors
        try {
            // Get the post from API
            $post = Launchmind_API::get_post($slug, $lang);
            
            // Get available languages for this post (pass post data to avoid extra API calls)
            $available_languages = Launchmind_API::get_post_languages($slug, $post);
        } catch (Exception $e) {
            // Log error but don't crash the site
            error_log('Launchmind Blog: Error fetching post - ' . $e->getMessage());
            return;
        }
        
        if (is_wp_error($post) || empty($post)) {
            global $wp_query;
            $wp_query->set_404();
            status_header(404);
            get_template_part('404');
            exit;
        }
        
        // CRITICAL: Start output buffering IMMEDIATELY, before ANY other output
        // This ensures we can catch and fix canonical URLs and meta tags added by themes/plugins
        $post_url = home_url('/blog/' . $slug);
        $meta_description = !empty($post['seo']['description']) ? $post['seo']['description'] : (!empty($post['excerpt']) ? wp_strip_all_tags($post['excerpt']) : '');
        
        // Get cover image - ensure absolute URL
        $cover_image = '';
        if (!empty($post['coverImage'])) {
            $cover_image = $post['coverImage'];
            if (strpos($cover_image, 'http') !== 0) {
                $cover_image = home_url($cover_image);
            }
            $cover_image = esc_url($cover_image);
        }
        
        // Fallback: Try to extract first image from content if no coverImage
        if (empty($cover_image) && !empty($post['html'])) {
            if (preg_match('/<img[^>]+src=["\']([^"\']+)["\']/i', $post['html'], $matches)) {
                $first_image = $matches[1];
                if (strpos($first_image, 'http') !== 0) {
                    $first_image = home_url($first_image);
                }
                $cover_image = esc_url($first_image);
            }
        }
        
        // Final fallback: Use site icon
        if (empty($cover_image)) {
            $site_icon = get_site_icon_url(512);
            if ($site_icon) {
                $cover_image = esc_url($site_icon);
            }
        }
        
        // Store post data globally for output buffer callback
        $GLOBALS['launchmind_blog_post_data'] = array(
            'url' => $post_url,
            'title' => esc_attr($post['title']),
            'description' => esc_attr($meta_description),
            'image' => $cover_image,
            'site_name' => esc_attr(get_bloginfo('name'))
        );
        
        // Start output buffering with aggressive HTML filtering
        // Use ob_start early priority to catch everything
        if (ob_get_level() === 0) {
            ob_start(function($html) {
                // Safety check: only process Launchmind blog posts
                if (!isset($GLOBALS['launchmind_blog_post_data']) || !is_string($html)) {
                    return $html;
                }
                
                try {
                    $data = $GLOBALS['launchmind_blog_post_data'];
                    
                    // Safety: ensure we have valid data
                    if (empty($data['url']) || empty($data['title'])) {
                        return $html;
                    }
                    
                    // Find </head> position - if not found, return unchanged (safety)
                    $head_pos = stripos($html, '</head>');
                    if ($head_pos === false) {
                        return $html;
                    }
                    
                    // Extract head section for processing
                    $head_section = substr($html, 0, $head_pos);
                    $body_section = substr($html, $head_pos);
                    
                    // Remove ALL existing canonical URLs (multiple patterns to catch all variants)
                    $head_section = preg_replace('/<link\s+[^>]*rel\s*=\s*["\']canonical["\'][^>]*>/i', '', $head_section);
                    $head_section = preg_replace('/<link\s+rel\s*=\s*["\']canonical["\'][^>]*>/i', '', $head_section);
                    
                    // Remove ALL existing og:title tags
                    $head_section = preg_replace('/<meta\s+[^>]*property\s*=\s*["\']og:title["\'][^>]*>/i', '', $head_section);
                    $head_section = preg_replace('/<meta\s+property\s*=\s*["\']og:title["\'][^>]*>/i', '', $head_section);
                    
                    // Remove ALL existing og:url tags
                    $head_section = preg_replace('/<meta\s+[^>]*property\s*=\s*["\']og:url["\'][^>]*>/i', '', $head_section);
                    $head_section = preg_replace('/<meta\s+property\s*=\s*["\']og:url["\'][^>]*>/i', '', $head_section);
                    
                    // Remove ALL existing og:description tags
                    if (!empty($data['description'])) {
                        $head_section = preg_replace('/<meta\s+[^>]*property\s*=\s*["\']og:description["\'][^>]*>/i', '', $head_section);
                        $head_section = preg_replace('/<meta\s+property\s*=\s*["\']og:description["\'][^>]*>/i', '', $head_section);
                    }
                    
                    // Remove ALL existing og:image tags and related
                    if (!empty($data['image'])) {
                        $head_section = preg_replace('/<meta\s+[^>]*property\s*=\s*["\']og:image["\'][^>]*>/i', '', $head_section);
                        $head_section = preg_replace('/<meta\s+property\s*=\s*["\']og:image["\'][^>]*>/i', '', $head_section);
                        $head_section = preg_replace('/<meta\s+[^>]*property\s*=\s*["\']og:image:width["\'][^>]*>/i', '', $head_section);
                        $head_section = preg_replace('/<meta\s+[^>]*property\s*=\s*["\']og:image:height["\'][^>]*>/i', '', $head_section);
                        $head_section = preg_replace('/<meta\s+[^>]*property\s*=\s*["\']og:image:alt["\'][^>]*>/i', '', $head_section);
                    }
                    
                    // Remove incorrect <title> tags that might say "Kennisbank"
                    // Only remove if they contain "Kennisbank" or don't contain our article title
                    $head_section = preg_replace_callback('/<title[^>]*>([^<]+)<\/title>/i', function($matches) use ($data) {
                        $title_content = $matches[1];
                        // If title is "Kennisbank" or doesn't contain our article title, remove it
                        if (stripos($title_content, 'Kennisbank') !== false || stripos($title_content, $data['title']) === false) {
                            return ''; // Remove this title tag
                        }
                        return $matches[0]; // Keep original if it's correct
                    }, $head_section);
                    
                    // Build correct meta tags to inject
                    $correct_tags = "\n";
                    $correct_tags .= '<link rel="canonical" href="' . esc_url($data['url']) . '">' . "\n";
                    $correct_tags .= '<meta property="og:type" content="article">' . "\n";
                    $correct_tags .= '<meta property="og:title" content="' . $data['title'] . '">' . "\n";
                    if (!empty($data['description'])) {
                        $correct_tags .= '<meta property="og:description" content="' . $data['description'] . '">' . "\n";
                    }
                    $correct_tags .= '<meta property="og:url" content="' . esc_url($data['url']) . '">' . "\n";
                    if (!empty($data['image'])) {
                        $correct_tags .= '<meta property="og:image" content="' . $data['image'] . '">' . "\n";
                        $correct_tags .= '<meta property="og:image:width" content="1200">' . "\n";
                        $correct_tags .= '<meta property="og:image:height" content="630">' . "\n";
                        $correct_tags .= '<meta property="og:image:alt" content="' . $data['title'] . '">' . "\n";
                    }
                    $correct_tags .= '<meta property="og:site_name" content="' . $data['site_name'] . '">' . "\n";
                    $correct_tags .= '<title>' . esc_html($data['title'] . ' - ' . $data['site_name']) . '</title>' . "\n";
                    
                    // Insert correct tags just before </head>
                    $head_section .= $correct_tags;
                    
                    // Reconstruct HTML
                    $html = $head_section . $body_section;
                    
                } catch (Exception $e) {
                    error_log('Launchmind Blog: Error filtering HTML - ' . $e->getMessage());
                }
                
                // Clean up global variable
                unset($GLOBALS['launchmind_blog_post_data']);
                
                return $html;
            });
        }
        
        // Set page title with high priority to override theme/plugin titles
        add_filter('wp_title', function($title) use ($post) {
            return $post['title'] . ' - ' . get_bloginfo('name');
        }, 999);
        add_filter('document_title_parts', function($parts) use ($post) {
            $parts['title'] = $post['title'];
            $parts['site'] = get_bloginfo('name');
            return $parts;
        }, 999);
        
        // Also set the page title directly in head to ensure it's used
        add_action('wp_head', function() use ($post) {
            echo '<title>' . esc_html($post['title'] . ' - ' . get_bloginfo('name')) . '</title>' . "\n";
        }, 1);
        
        // Remove existing Open Graph tags and canonical URLs from SEO plugins/themes that might override ours
        add_action('wp_head', function() {
            // Remove Yoast SEO Open Graph tags and canonical
            remove_action('wp_head', 'wpseo_opengraph', 30);
            remove_action('wp_head', 'wpseo_canonical', 20);
            // Remove Rank Math Open Graph tags and canonical
            remove_action('wp_head', 'rank_math_opengraph_tags', 20);
            remove_action('wp_head', 'rank_math_canonical', 20);
            // Remove All in One SEO Open Graph tags and canonical
            remove_action('wp_head', 'aioseo_opengraph_tags', 10);
            remove_action('wp_head', 'aioseo_canonical', 10);
            // Remove theme Open Graph tags (common theme functions)
            remove_action('wp_head', 'the_theme_opengraph_tags', 10);
            // Remove any other canonical URLs
            remove_action('wp_head', 'rel_canonical');
        }, 1);
        
        // Force correct canonical URL with high priority (backup in case output buffering fails)
        add_action('wp_head', function() use ($post_url) {
            echo '<link rel="canonical" href="' . esc_url($post_url) . '">' . "\n";
        }, 9998);
        
        // Add SEO meta tags and structured data for Google & AI engines
        // Use priority 9999 to ensure our tags are added VERY LAST, after ALL other plugins/themes
        // Note: Output buffering will catch and fix any incorrect tags added after this
        add_action('wp_head', function() use ($post, $slug, $lang, $post_url, $cover_image, $meta_description) {
            $this->add_seo_meta_tags($post, $slug, $lang, $post_url, $cover_image, $meta_description);
        }, 9999);
        
        // Language names mapping
        $language_names = array(
            'en' => 'English',
            'nl' => 'Nederlands',
            'de' => 'Deutsch',
            'fr' => 'Français',
            'es' => 'Español',
            'it' => 'Italiano',
            'hi' => 'हिन्दी',
        );
        
        // Language flags mapping
        $language_flags = array(
            'en' => '🇬🇧',
            'nl' => '🇳🇱',
            'de' => '🇩🇪',
            'fr' => '🇫🇷',
            'es' => '🇪🇸',
            'it' => '🇮🇹',
            'hi' => '🇮🇳',
        );
        
        // Render template
        get_header();
        ?>
        <main class="launchmind-single-wrapper" style="max-width:1200px;margin:0 auto;padding:2rem 1rem;">
            <article class="launchmind-post-single">
                <?php if (!empty($post['coverImage'])): ?>
                    <div class="launchmind-post-featured-image">
                        <img src="<?php echo esc_url($post['coverImage']); ?>" alt="<?php echo esc_attr($post['title']); ?>">
                    </div>
                <?php endif; ?>
                
                <h1 class="launchmind-post-title"><?php echo esc_html($post['title']); ?></h1>
                
                <div class="launchmind-post-meta">
                    <?php if (!empty($post['publishedAt'])): ?>
                        <span class="launchmind-post-date">
                            <?php echo esc_html(date_i18n(get_option('date_format'), strtotime($post['publishedAt']))); ?>
                        </span>
                    <?php endif; ?>
                    
                    <?php if (!empty($post['author'])): ?>
                        <span class="launchmind-post-author">
                            <?php echo esc_html($post['author']); ?>
                        </span>
                    <?php endif; ?>
                </div>
                
                <div class="launchmind-post-body">
                    <?php 
                    // Inject language switcher after first paragraph(s) if available
                    $html_content = wp_kses_post($post['html']);
                    
                    // Only show language switcher if more than 1 language available
                    if (!empty($available_languages) && count($available_languages) > 1) {
                        // Try to insert after first closing </p> tag (after intro)
                        $language_switcher_html = '<div class="launchmind-language-switcher-inline">';
                        $language_switcher_html .= '<span class="launchmind-language-label">' . esc_html__('Language:', 'launchmind-blog') . '</span>';
                        $language_switcher_html .= '<div class="launchmind-language-buttons">';
                        
                        foreach ($available_languages as $available_lang) {
                            // Build URL manually to ensure it works with custom rewrite rules
                            $base_url = home_url('/blog/' . $slug);
                            $current_url = add_query_arg(array('lang' => $available_lang), $base_url);
                            $is_active = $available_lang === $lang;
                            $language_switcher_html .= '<a href="' . esc_url($current_url) . '" ';
                            $language_switcher_html .= 'class="launchmind-language-button' . ($is_active ? ' launchmind-language-active' : '') . '" ';
                            $language_switcher_html .= 'title="' . esc_attr($language_names[$available_lang] ?? strtoupper($available_lang)) . '">';
                            $language_switcher_html .= '<span class="launchmind-language-flag">' . esc_html($language_flags[$available_lang] ?? '') . '</span>';
                            $language_switcher_html .= '<span class="launchmind-language-code">' . esc_html(strtoupper($available_lang)) . '</span>';
                            if ($is_active) {
                                $language_switcher_html .= '<span class="launchmind-language-check">✓</span>';
                            }
                            $language_switcher_html .= '</a>';
                        }
                        
                        $language_switcher_html .= '</div></div>';
                        
                        // Insert after first paragraph (look for </p> followed by content)
                        // Try multiple patterns to find a good insertion point after intro
                        $inserted = false;
                        
                        // Pattern 1: After first </p> followed by another <p> or heading
                        $pattern1 = '/(<\/p>\s*)(?=<(p|h[1-6]))/i';
                        if (preg_match($pattern1, $html_content, $matches, PREG_OFFSET_CAPTURE)) {
                            $insert_position = $matches[0][1] + strlen($matches[0][0]);
                            $html_content = substr_replace($html_content, $language_switcher_html, $insert_position, 0);
                            $inserted = true;
                        }
                        
                        // Pattern 2: After second </p> (if first pattern didn't work, try second paragraph)
                        if (!$inserted) {
                            $pattern2 = '/(<\/p>\s*<\/p>\s*)(?=<(p|h[1-6]|div|ul|ol))/i';
                            if (preg_match($pattern2, $html_content, $matches, PREG_OFFSET_CAPTURE)) {
                                $insert_position = $matches[0][1] + strlen($matches[0][0]);
                                $html_content = substr_replace($html_content, $language_switcher_html, $insert_position, 0);
                                $inserted = true;
                            }
                        }
                        
                        // Pattern 3: After first heading (h2 or h3) if paragraphs don't work
                        if (!$inserted) {
                            $pattern3 = '/(<\/h[2-3]>\s*)(?=<(p|h[1-6]|div))/i';
                            if (preg_match($pattern3, $html_content, $matches, PREG_OFFSET_CAPTURE)) {
                                $insert_position = $matches[0][1] + strlen($matches[0][0]);
                                $html_content = substr_replace($html_content, $language_switcher_html, $insert_position, 0);
                                $inserted = true;
                            }
                        }
                        
                        // Fallback: insert at the beginning if no pattern matches
                        if (!$inserted) {
                            $html_content = $language_switcher_html . $html_content;
                        }
                    }
                    
                    echo $html_content;
                    ?>
                </div>
                
                <?php if (!empty($post['tags'])): ?>
                    <div class="launchmind-post-tags">
                        <span class="launchmind-tags-label"><?php esc_html_e('Tags:', 'launchmind-blog'); ?></span>
                        <?php foreach ($post['tags'] as $tag): ?>
                            <span class="launchmind-tag"><?php echo esc_html($tag); ?></span>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                
                <div style="margin-top:3rem;text-align:center;">
                    <a href="/blog" class="launchmind-back-link" style="display:inline-flex;align-items:center;gap:0.5rem;color:var(--launchmind-primary);text-decoration:none;font-weight:600;">
                        ← <?php esc_html_e('Back to Blog', 'launchmind-blog'); ?>
                    </a>
                </div>
            </article>
        </main>
        <?php
        // Inject analytics tracking script
        $this->inject_tracking_script($slug);
        
        get_footer();
        
        // End output buffering and output the filtered HTML
        // Only end our own buffer (check level to avoid ending buffers from other plugins)
        try {
            $buffer_level = ob_get_level();
            // Only end buffer if we started one (level > 0) and it's safe to do so
            if ($buffer_level > 0) {
                // Flush our buffer (which will trigger the callback to filter HTML)
                ob_end_flush();
            }
        } catch (Exception $e) {
            // If buffer flush fails, log but don't break
            error_log('Launchmind Blog: Error flushing output buffer - ' . $e->getMessage());
        }
        
        // Clean up global variable as final safety measure
        if (isset($GLOBALS['launchmind_blog_post_data'])) {
            unset($GLOBALS['launchmind_blog_post_data']);
        }
        
        exit;
    }
    
    /**
     * Add SEO meta tags and structured data for Google & AI engines
     */
    private function add_seo_meta_tags($post, $slug, $lang, $post_url = null, $cover_image = null, $meta_description = null) {
        $site_url = home_url();
        
        // Use provided values or calculate them
        if ($post_url === null) {
            $post_url = home_url('/blog/' . $slug);
        }
        if ($meta_description === null) {
            $meta_description = !empty($post['seo']['description']) ? $post['seo']['description'] : (!empty($post['excerpt']) ? wp_strip_all_tags($post['excerpt']) : '');
        }
        $published_date = !empty($post['publishedAt']) ? date('c', strtotime($post['publishedAt'])) : date('c');
        $author = !empty($post['author']) ? $post['author'] : 'Launchmind Team';
        
        // Get cover image - use provided or calculate
        if ($cover_image === null) {
            $cover_image = '';
            if (!empty($post['coverImage'])) {
                $cover_image = $post['coverImage'];
                // Convert relative URLs to absolute
                if (strpos($cover_image, 'http') !== 0) {
                    $cover_image = home_url($cover_image);
                }
                $cover_image = esc_url($cover_image);
            }
            
            // Fallback: Try to extract first image from content if no coverImage
            if (empty($cover_image) && !empty($post['html'])) {
                // Look for <img> tags in HTML content
                if (preg_match('/<img[^>]+src=["\']([^"\']+)["\']/i', $post['html'], $matches)) {
                    $first_image = $matches[1];
                    // Convert relative URLs to absolute
                    if (strpos($first_image, 'http') !== 0) {
                        $first_image = home_url($first_image);
                    }
                    $cover_image = esc_url($first_image);
                }
            }
            
            // Final fallback: Use site icon or default
            if (empty($cover_image)) {
                $site_icon = get_site_icon_url(512); // Try to get site icon
                if ($site_icon) {
                    $cover_image = esc_url($site_icon);
                }
            }
        }
        
        // Meta description
        if (!empty($meta_description)) {
            echo '<meta name="description" content="' . esc_attr($meta_description) . '">' . "\n";
        }
        
        // Canonical URL - already added earlier with high priority, but include here as backup
        // Note: This is a duplicate but ensures canonical is set even if earlier hook fails
        echo '<!-- Launchmind Blog: Canonical URL -->' . "\n";
        echo '<link rel="canonical" href="' . esc_url($post_url) . '">' . "\n";
        
        // Open Graph tags (for social sharing and AI engines)
        // ALWAYS include title and image for proper link previews
        // Use multiple og:title tags to ensure one is picked up (some platforms read the last one)
        echo '<meta property="og:type" content="article">' . "\n";
        // Force the correct title - add it multiple times to override any existing tags
        echo '<meta property="og:title" content="' . esc_attr($post['title']) . '">' . "\n";
        // Also add as name attribute for compatibility
        echo '<meta name="og:title" content="' . esc_attr($post['title']) . '">' . "\n";
        if (!empty($meta_description)) {
            echo '<meta property="og:description" content="' . esc_attr($meta_description) . '">' . "\n";
        }
        echo '<meta property="og:url" content="' . esc_url($post_url) . '">' . "\n";
        
        // ALWAYS include image with dimensions (required by LinkedIn and Facebook)
        if (!empty($cover_image)) {
            echo '<meta property="og:image" content="' . $cover_image . '">' . "\n";
            echo '<meta property="og:image:width" content="1200">' . "\n";
            echo '<meta property="og:image:height" content="630">' . "\n";
            echo '<meta property="og:image:alt" content="' . esc_attr($post['title']) . '">' . "\n";
        }
        
        echo '<meta property="og:site_name" content="' . esc_attr(get_bloginfo('name')) . '">' . "\n";
        
        // Twitter Card tags
        echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
        echo '<meta name="twitter:title" content="' . esc_attr($post['title']) . '">' . "\n";
        if (!empty($meta_description)) {
            echo '<meta name="twitter:description" content="' . esc_attr($meta_description) . '">' . "\n";
        }
        if (!empty($cover_image)) {
            echo '<meta name="twitter:image" content="' . $cover_image . '">' . "\n";
        }
        
        // Structured Data (Schema.org JSON-LD) - Critical for AI engines
        $schema = array(
            '@context' => 'https://schema.org',
            '@type' => 'Article',
            'headline' => $post['title'],
            'description' => $meta_description,
            'url' => $post_url,
            'datePublished' => $published_date,
            'dateModified' => $published_date,
            'author' => array(
                '@type' => 'Person',
                'name' => $author
            ),
            'publisher' => array(
                '@type' => 'Organization',
                'name' => get_bloginfo('name'),
                'url' => $site_url
            )
        );
        
        if (!empty($cover_image)) {
            $schema['image'] = array(
                '@type' => 'ImageObject',
                'url' => $cover_image,
                'width' => 1200,
                'height' => 630
            );
        }
        
        if (!empty($post['keywords']) && is_array($post['keywords'])) {
            $schema['keywords'] = implode(', ', array_slice($post['keywords'], 0, 5));
        }
        
        echo '<script type="application/ld+json">' . "\n";
        echo wp_json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        echo "\n" . '</script>' . "\n";
    }
    
    /**
     * Inject tracking script for analytics
     * Tracks page views and clicks, detecting AI vs organic traffic sources
     */
    private function inject_tracking_script($slug) {
        // Check if tracking is enabled (default: true)
        $tracking_enabled = self::get_option('enable_analytics', true);
        if (!$tracking_enabled) {
            return;
        }
        
        $subscription_id = self::get_option('subscription_id', '');
        $api_key = self::get_option('api_key', '');
        
        ?>
        <script>
        (function() {
            'use strict';
            
            // AI and search source detection
            var ref = document.referrer || '';
            var refDomain = '';
            try { refDomain = ref ? new URL(ref).hostname.replace('www.', '') : ''; } catch(e) {}
            
            var aiSources = ['chatgpt.com','chat.openai.com','claude.ai','perplexity.ai','you.com','copilot.microsoft.com','bing.com/chat','gemini.google.com','phind.com','poe.com'];
            var isAI = aiSources.some(function(s) { return ref.indexOf(s) !== -1; });
            
            // Track page view
            var data = {
                subscription_id: '<?php echo esc_js($subscription_id); ?>',
                api_key: '<?php echo esc_js($api_key); ?>',
                article_slug: '<?php echo esc_js($slug); ?>',
                referrer: ref,
                referrer_domain: refDomain,
                is_ai_referrer: isAI,
                platform: 'wordpress',
                event_type: 'page_view'
            };
            
            // Use sendBeacon for reliable tracking (non-blocking)
            if (navigator.sendBeacon) {
                navigator.sendBeacon('https://launchmind.io/api/tracking/plugin-view', JSON.stringify(data));
            } else {
                // Fallback for older browsers
                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'https://launchmind.io/api/tracking/plugin-view', true);
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.send(JSON.stringify(data));
            }
            
            // Track all link clicks (both internal and external)
            // This captures clicks to client website from blog articles
            document.addEventListener('click', function(e) {
                var link = e.target.closest('a');
                if (!link) return;
                
                var href = link.href || '';
                // Skip empty links, anchors, javascript, and mailto
                if (!href || href.indexOf('#') === 0 || href.indexOf('javascript:') === 0 || href.indexOf('mailto:') === 0) return;
                // Skip clicks to the same page
                if (href === window.location.href) return;
                // Skip clicks to other blog posts (contain /blog/ in path)
                if (href.indexOf('/blog/') !== -1 && href !== window.location.href) return;
                
                var isExternal = href.indexOf('http') === 0 && href.indexOf(window.location.hostname) === -1;
                
                var clickData = {
                    subscription_id: '<?php echo esc_js($subscription_id); ?>',
                    api_key: '<?php echo esc_js($api_key); ?>',
                    article_slug: '<?php echo esc_js($slug); ?>',
                    target_url: href,
                    is_external: isExternal,
                    referrer: ref,
                    referrer_domain: refDomain,
                    is_ai_referrer: isAI,
                    platform: 'wordpress',
                    event_type: 'click'
                };
                
                if (navigator.sendBeacon) {
                    navigator.sendBeacon('https://launchmind.io/api/tracking/plugin-view', JSON.stringify(clickData));
                }
            }, true);
        })();
        </script>
        <?php
    }
}

// Initialize plugin
function launchmind_blog() {
    return Launchmind_Blog_Connector::get_instance();
}

// Start the plugin
launchmind_blog();

