#!/usr/bin/env python3
"""
BULK FIX: Fix include paths in all inner PHP pages.
Current (broken): include $_SERVER['DOCUMENT_ROOT'] . '/header.php';
Fixed:            include $_SERVER['DOCUMENT_ROOT'] . '/aaa/header.php';

Same for footer.php.
"""
import os
import re

BASE = '/Applications/XAMPP/xamppfiles/htdocs/aaa'

REPLACEMENTS = [
    (
        "include $_SERVER['DOCUMENT_ROOT'] . '/header.php'",
        "include $_SERVER['DOCUMENT_ROOT'] . '/aaa/header.php'"
    ),
    (
        'include $_SERVER["DOCUMENT_ROOT"] . "/header.php"',
        'include $_SERVER["DOCUMENT_ROOT"] . "/aaa/header.php"'
    ),
    (
        "include $_SERVER['DOCUMENT_ROOT'] . '/footer.php'",
        "include $_SERVER['DOCUMENT_ROOT'] . '/aaa/footer.php'"
    ),
    (
        'include $_SERVER["DOCUMENT_ROOT"] . "/footer.php"',
        'include $_SERVER["DOCUMENT_ROOT"] . "/aaa/footer.php"'
    ),
    # Also handle config.php
    (
        "include $_SERVER['DOCUMENT_ROOT'] . '/config.php'",
        "include $_SERVER['DOCUMENT_ROOT'] . '/aaa/config.php'"
    ),
]

fixed_files = 0
total_replacements = 0

for root, dirs, files in os.walk(BASE):
    # Skip tmp, hidden dirs, script files
    dirs[:] = [d for d in dirs if not d.startswith('.')]
    for fname in files:
        if not fname.endswith('.php'):
            continue
        fpath = os.path.join(root, fname)
        try:
            with open(fpath, 'r', encoding='utf-8', errors='ignore') as f:
                content = f.read()
        except Exception:
            continue
        
        new_content = content
        file_changes = 0
        for old, new in REPLACEMENTS:
            if old in new_content:
                count = new_content.count(old)
                new_content = new_content.replace(old, new)
                file_changes += count
        
        if file_changes > 0:
            with open(fpath, 'w', encoding='utf-8') as f:
                f.write(new_content)
            fixed_files += 1
            total_replacements += file_changes
            rel = os.path.relpath(fpath, BASE)
            print(f"  Fixed {file_changes}x in {rel}")

print(f"\n=== Done: Fixed {total_replacements} includes in {fixed_files} files ===")
