#!/usr/bin/env python3
import subprocess, os

BASE = '/home/tomsjavajive.com/public_html'

# ── Fix 1: Remove wholesale and careers from footer ──────────
print("[1] Fixing footer...")
f = BASE + '/includes/footer.php'
with open(f) as fh:
    c = fh.read()

before = len(c)
c = c.replace('                        <li><a href="/wholesale.php">Wholesale</a></li>\n', '')
c = c.replace('                        <li><a href="/careers.php">Careers</a></li>\n', '')
# Also try without leading spaces
c = c.replace('<li><a href="/wholesale.php">Wholesale</a></li>\n', '')
c = c.replace('<li><a href="/careers.php">Careers</a></li>\n', '')

with open(f, 'w') as fh:
    fh.write(c)
removed = before - len(c)
print(f"  Footer: removed {removed} chars (wholesale + careers)")

# ── Fix 2: Check account pages for errors ───────────────────
print("\n[2] Checking account pages...")
for page in ['rewards', 'wishlist', 'reviews']:
    path = f'{BASE}/account/{page}.php'
    r = subprocess.run(
        ['/usr/local/lsws/lsphp85/bin/php', '-d', 'display_errors=1',
         '-d', 'error_reporting=32767', path],
        capture_output=True, text=True
    )
    output = r.stdout + r.stderr
    errors = [l for l in output.split('\n')
              if any(x in l for x in ['Fatal','Error','Undefined','undefined','Call to'])]
    if errors:
        print(f"  {page}.php ERRORS:")
        for e in errors[:3]:
            print(f"    {e[:120]}")
    else:
        # Check if page has actual HTML content
        has_html = '<' in r.stdout and len(r.stdout) > 100
        print(f"  {page}.php: {'OK - has content' if has_html else 'WARNING - minimal output'}")

# ── Fix 3: Check admin customers Modal ──────────────────────
print("\n[3] Checking admin customers...")
f2 = BASE + '/admin/customers.php'
with open(f2) as fh:
    c2 = fh.read()

print(f"  Modal.open present: {'Modal.open' in c2}")
print(f"  openCustomerModal present: {'openCustomerModal' in c2}")
print(f"  admin.js exists: {os.path.exists(BASE+'/admin/assets/admin.js')}")

# Check if admin.js has Modal object
if os.path.exists(BASE+'/admin/assets/admin.js'):
    with open(BASE+'/admin/assets/admin.js') as fh:
        js = fh.read()
    print(f"  Modal object in admin.js: {'Modal' in js}")
    print(f"  admin.js size: {len(js)} chars")
else:
    print("  admin.js MISSING - this is why customer modal doesn't work!")
    # Create a basic Modal object
    modal_js = """
// Modal helper
const Modal = {
    open: function(id) {
        const el = document.getElementById(id);
        if (el) { el.style.display = 'flex'; el.classList.add('active'); }
    },
    close: function(id) {
        const el = document.getElementById(id);
        if (el) { el.style.display = 'none'; el.classList.remove('active'); }
    }
};
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        document.querySelectorAll('.modal-overlay.active').forEach(m => {
            m.style.display = 'none'; m.classList.remove('active');
        });
    }
});
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal-overlay')) {
        e.target.style.display = 'none'; e.target.classList.remove('active');
    }
});
"""
    os.makedirs(BASE+'/admin/assets', exist_ok=True)
    with open(BASE+'/admin/assets/admin.js', 'w') as fh:
        fh.write(modal_js)
    print("  Created admin.js with Modal object")

# ── Fix 4: Check account page includes ─────────────────────
print("\n[4] Checking account page structure...")
for page in ['rewards', 'wishlist', 'reviews']:
    path = f'{BASE}/account/{page}.php'
    with open(path) as fh:
        content = fh.read()
    has_auth = 'CustomerAuth::require' in content
    has_header = "require_once" in content and 'header' in content
    has_footer = 'footer' in content
    print(f"  {page}.php: auth={has_auth}, header={has_header}, footer={has_footer}, size={len(content)}")

print("\nDone!")
