import os
import re
import glob

# Files to ignore
ignore_files = ['google1c0f05a8f749c5ed.html']

for filepath in glob.glob('*.html'):
    if filepath in ignore_files:
        continue
        
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()
        
    # Extract page title and description
    title_match = re.search(r'<title>(.*?)</title>', content, re.IGNORECASE | re.DOTALL)
    desc_match = re.search(r'<meta\s+name=["\']description["\']\s+content=["\'](.*?)["\']', content, re.IGNORECASE | re.DOTALL)
    
    title = title_match.group(1).strip() if title_match else 'Best Computer Training Institute in Meerut'
    desc = desc_match.group(1).strip() if desc_match else 'ITMeerut is the best computer training institute in Meerut.'
    
    # Try to find the content between </nav> and <footer class="footer">
    # If not found, try to find between <body> and </footer>, etc.
    main_content_match = re.search(r'</nav>\s*(.*?)\s*<footer class="footer">', content, re.IGNORECASE | re.DOTALL)
    
    if main_content_match:
        main_content = main_content_match.group(1)
    else:
        # fallback, maybe no nav or footer
        main_content = content
        
    # Also replace old .html links to clean URLs in the main content
    main_content = re.sub(r'href=["\']([^"\']+)\.html["\']', r'href="/\1/"', main_content)
    
    new_content = f"""<?php
$pageTitle = "{title}";
$pageDesc = "{desc}";
include 'header.php';
?>

{main_content}

<?php include 'footer.php'; ?>"""

    # Write to new .php file
    new_filepath = filepath.replace('.html', '.php')
    with open(new_filepath, 'w', encoding='utf-8') as f:
        f.write(new_content)
        
    print(f"Converted {filepath} to {new_filepath}")
    
    # Remove old .html file
    os.remove(filepath)

print("All HTML files converted to PHP.")
