#!/bin/bash

echo "=== Fixing Template Recognition ==="

# SSH into staging and fix template loading
ssh roodev@146.190.76.204 << 'EOF'
cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html

# First, let's check what WordPress thinks the template should be
echo "Checking page template assignment..."
PAGE_ID=5334
TEMPLATE=$(wp post meta get $PAGE_ID _wp_page_template)
echo "Page $PAGE_ID has template: $TEMPLATE"

# Clear the template and reassign it
echo "Clearing and reassigning template..."
wp post meta delete $PAGE_ID _wp_page_template
wp post meta add $PAGE_ID _wp_page_template "page-trainer-registration.php"

# Also try setting it as default first, then back
wp post meta update $PAGE_ID _wp_page_template "default"
wp post meta update $PAGE_ID _wp_page_template "page-trainer-registration.php"

# Let's also check if we need to use a different template path
echo -e "\nTrying alternate template assignment..."
wp post meta update $PAGE_ID _wp_page_template "astra-child-hvac/page-trainer-registration.php"

# Check result
TEMPLATE_AFTER=$(wp post meta get $PAGE_ID _wp_page_template)
echo "Template after update: $TEMPLATE_AFTER"

# Clear all caches
wp cache flush
wp breeze purge --cache=all
wp rewrite flush

# Also update the child theme functions to better handle templates
echo -e "\nUpdating child theme template handling..."
cat > wp-content/themes/astra-child-hvac/functions-template-fix.php << 'PHP'
<?php
// Force template loading for HVAC pages
add_filter('template_include', function($template) {
    if (is_page()) {
        $page_slug = get_post_field('post_name', get_queried_object());
        $page_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
        
        // Check if this is an HVAC page
        if (strpos($page_path, 'trainer') !== false || strpos($page_path, 'master-trainer') !== false) {
            // Map URLs to templates
            $template_map = array(
                'trainer/registration' => 'page-trainer-registration.php',
                'trainer/dashboard' => 'page-trainer-dashboard.php',
                'master-trainer/dashboard' => 'page-master-dashboard.php',
                'training-login' => 'page-trainer-login.php',
            );
            
            foreach ($template_map as $path => $template_file) {
                if (strpos($page_path, $path) !== false) {
                    $child_template = get_stylesheet_directory() . '/' . $template_file;
                    if (file_exists($child_template)) {
                        return $child_template;
                    }
                }
            }
        }
    }
    
    return $template;
}, 99);
PHP

# Include the fix in functions.php
echo -e "\n// Include template fix" >> wp-content/themes/astra-child-hvac/functions.php
echo "require_once('functions-template-fix.php');" >> wp-content/themes/astra-child-hvac/functions.php

echo -e "\nTemplate fix applied!"
EOF