import os
import re

def refactor_es_header_broad(root_dir, target_nav_path):
    for dirpath, _, filenames in os.walk(root_dir):
        for filename in filenames:
            if filename.endswith('.php'):
                filepath = os.path.join(dirpath, filename)
                
                try:
                    with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                        content = f.read()
                except Exception as e:
                    print(f"Skipping {filepath}: {e}")
                    continue
                
                original_content = content
                
                # Calculate correct relative path from current file directory to target nav file
                rel_path = os.path.relpath(target_nav_path, dirpath)
                rel_path_web = rel_path.replace('\\', '/')
                
                new_include = f"<?php include '{rel_path_web}'; ?>"
                
                # Broad regex to catch any variation containing es-header.php inside an include statement
                old_include_pattern = r'<\?php\s+(?:include|require)(?:_once)?\s*[\'"][^\'"]*es-header\.php[\'"];\s*\?>'
                content = re.sub(old_include_pattern, new_include, content, flags=re.IGNORECASE)

                if content != original_content:
                    with open(filepath, 'w', encoding='utf-8') as f:
                        f.write(content)
                    print(f"Successfully updated: {filepath} -> '{rel_path_web}'")

if __name__ == "__main__":
    target_directory = "." 
    nav_path = r"C:\Users\ijaco\web\engine\templates\partials\nav.php"
    
    print(f"Starting broad ES header refactoring in: {os.path.abspath(target_directory)}")
    refactor_es_header_broad(target_directory, nav_path)
    print("Refactoring complete.")