import os
import glob
import re

php_files = glob.glob('*.php')
# exclude header and footer from main processing loop
pages = [f for f in php_files if f not in ['header.php', 'footer.php']]

with open('header.php', 'r') as f:
    header_content = f.read()

with open('footer.php', 'r') as f:
    footer_content = f.read()

for page in pages:
    with open(page, 'r') as f:
        page_content = f.read()
    
    # Extract variables
    title_match = re.search(r'\$page_title\s*=\s*[\'"](.*?)[\'"];', page_content)
    page_title = title_match.group(1) if title_match else "Travel Touristo"
    # Unescape quotes
    page_title = page_title.replace("\\'", "'")
    
    disclaimer_match = re.search(r'\$footer_disclaimer\s*=\s*[\'"](.*?)[\'"];', page_content)
    footer_disclaimer = disclaimer_match.group(1) if disclaimer_match else ""
    # Unescape quotes
    footer_disclaimer = footer_disclaimer.replace("\\'", "'")
    
    # Extract body content (remove PHP blocks)
    # The body is everything between ?> and <?php include 'footer.php'; ?>
    body_match = re.search(r'\?>\s*(.*?)\s*<\?php include \'footer\.php\'; \?>', page_content, re.DOTALL)
    body_content = body_match.group(1) if body_match else ""
    
    # Process Header for this page
    # 1. Replace Title
    page_header = re.sub(r'<title>.*?</title>', f'<title>{page_title}</title>', header_content)
    # 2. Fix active states
    def fix_active(match):
        href = match.group(1)
        # Check if the href matches the current page (e.g. index.php)
        is_active = (href == page)
        active_class = ' class="active"' if is_active else ''
        return f'<a href="{href}"{active_class}'
    
    page_header = re.sub(r'<a href="([^"]+)"(?:\s*class="<\?php[^>]+>\s*\'active\'\s*:\s*\'\';\s*\?>")?', fix_active, page_header)
    page_header = page_header.replace('.php', '.html')
    
    # Process Footer for this page
    page_footer = footer_content
    # Replace dynamic disclaimer logic
    disclaimer_block = r'<\?php if\(isset\(\$footer_disclaimer\)\): \?>.*?<\?php endif; \?>'
    page_footer = re.sub(disclaimer_block, footer_disclaimer if footer_disclaimer else "<p><strong>Disclaimer:</strong> Travel Touristo is an independent travel and car rental comparison portal. We are not officially affiliated with, endorsed by, or partnered with Alamo, Avis, Budget, Enterprise, Hertz, Dollar, or any specific car rental brand mentioned on this site. All trademarks belong to their respective owners.</p>", page_footer, flags=re.DOTALL)
    page_footer = page_footer.replace('.php', '.html')
    
    # Process Body
    body_content = body_content.replace('.php', '.html')
    
    # Assemble HTML
    full_html = f"{page_header}\n{body_content}\n{page_footer}"
    
    html_filename = page.replace('.php', '.html')
    with open(html_filename, 'w') as f:
        f.write(full_html)

# Clean up PHP files
for file in php_files:
    os.remove(file)

print("Reverted back to HTML.")
