<?php
/**
 * HVAC Page Content Fixer
 * 
 * Fixes common content issues in HVAC pages
 * 
 * @package HVAC_Community_Events
 * @since 2.0.0
 */

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

class HVAC_Page_Content_Fixer {
    
    /**
     * Fix escaped HTML comments in page content
     */
    public static function fix_escaped_html_comments() {
        global $wpdb;
        
        // Find all pages with escaped HTML comments
        $pages_with_escaped_comments = $wpdb->get_results(
            "SELECT ID, post_content 
             FROM {$wpdb->posts} 
             WHERE post_type = 'page' 
             AND post_content LIKE '%<\\\\!--%' 
             AND post_status = 'publish'"
        );
        
        foreach ($pages_with_escaped_comments as $page) {
            // Remove escaped HTML comments
            $clean_content = str_replace(
                array('<\!-- wp:shortcode -->', '<\!-- /wp:shortcode -->'),
                '',
                $page->post_content
            );
            
            // Also handle any other escaped variations
            $clean_content = preg_replace('/<\\\\!--.*?-->/', '', $clean_content);
            
            // Update the page if content changed
            if ($clean_content !== $page->post_content) {
                wp_update_post(array(
                    'ID' => $page->ID,
                    'post_content' => $clean_content
                ));
                
                error_log("HVAC: Fixed escaped HTML comments in page ID {$page->ID}");
            }
        }
        
        // Clear caches
        wp_cache_flush();
    }
    
    /**
     * Run all content fixes
     */
    public static function run_all_fixes() {
        self::fix_escaped_html_comments();
    }
}

// Hook into activation
add_action('hvac_plugin_activated', array('HVAC_Page_Content_Fixer', 'run_all_fixes'));

// Also run on admin init to catch any issues
add_action('admin_init', function() {
    // Only run once per day to avoid performance impact
    $last_run = get_transient('hvac_content_fixes_last_run');
    if (!$last_run) {
        HVAC_Page_Content_Fixer::run_all_fixes();
        set_transient('hvac_content_fixes_last_run', time(), DAY_IN_SECONDS);
    }
});