#!/bin/bash

echo "=== Disabling Conflicting Rewrite Rules ==="

# SSH into staging and comment out the problematic rules
ssh roodev@146.190.76.204 << 'EOF'
cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html

# Create a temporary fix by removing the conflicting rewrite rules
wp eval '
// Remove the trainer route rules that conflict with actual pages
remove_action("init", array(HVAC_Route_Manager::instance(), "register_rewrite_rules"), 5);

// Flush rewrite rules to clear them
flush_rewrite_rules();
'

# Now let's create a more targeted approach
echo "Creating targeted rewrite fix..."

# Create a mu-plugin to handle this properly
mkdir -p wp-content/mu-plugins

cat > wp-content/mu-plugins/hvac-fix-page-routing.php << 'PHP'
<?php
/**
 * Fix HVAC page routing conflicts
 * 
 * This ensures actual WordPress pages load instead of being caught by rewrite rules
 */

// Remove conflicting rewrite rules on init
add_action('init', function() {
    global $wp_rewrite;
    
    // Get current rules
    $rules = $wp_rewrite->rules;
    
    // Remove rules that conflict with actual pages
    $conflicting_patterns = array(
        'trainer/([^/]+)/?$',
        'master-trainer/([^/]+)/?$',
    );
    
    foreach ($conflicting_patterns as $pattern) {
        if (isset($rules[$pattern])) {
            unset($rules[$pattern]);
        }
    }
    
    $wp_rewrite->rules = $rules;
}, 999);

// Ensure pages load with their templates
add_filter('template_include', function($template) {
    global $wp_query;
    
    if (is_404()) {
        // Check if this should be a page
        $path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        $page = get_page_by_path($path);
        
        if ($page && $page->post_status === 'publish') {
            // Force WordPress to recognize this as a page
            $wp_query->is_404 = false;
            $wp_query->is_page = true;
            $wp_query->is_singular = true;
            $wp_query->queried_object = $page;
            $wp_query->queried_object_id = $page->ID;
            
            // Set up post data
            setup_postdata($page);
            
            // Get the correct template
            $page_template = get_page_template_slug($page->ID);
            if ($page_template) {
                $located = locate_template(array($page_template));
                if ($located) {
                    return $located;
                }
            }
            
            // Fall back to page.php
            return get_page_template();
        }
    }
    
    return $template;
}, 5);
PHP

# Flush everything
wp rewrite flush
wp cache flush

echo "Routing fix applied!"
EOF