#!/usr/bin/env python3
"""
Fix all broken images and mega menu in the SureCertificate website.

Problems:
1. All images show the same Unsplash photo because the CDN domain was replaced
   with a full Unsplash URL that contains the CDN filename as a path suffix.
   Fix: restore the original CDN domain properly.
2. Mega menu doesn't work because it relies on Tailwind CSS group-hover which
   isn't available in the locally hosted CSS from KH CDN.
   Fix: inject a lightweight JS snippet into header.php to handle hover.
"""

import os
import re

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

# The broken prefix that was incorrectly injected
BROKEN_CDN_PREFIX = 'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80/'
# Also handle HTML-encoded version
BROKEN_CDN_PREFIX_ENCODED = 'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?ixlib=rb-4.0.3&amp;auto=format&amp;fit=crop&amp;w=800&amp;q=80/'

# The correct CDN domain to restore
CORRECT_CDN = 'https://d2o2utebsixu4k.cloudfront.net'

# Also fix the broken preconnect link in header.php
BROKEN_PRECONNECT = 'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80/'
CORRECT_PRECONNECT = 'https://d2o2utebsixu4k.cloudfront.net/'

# Fix broken og:image and twitter:image meta tags
BROKEN_META_IMAGE = '../images.unsplash.com/photo-1516321318423-f06f85e504b3?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80/'
CORRECT_META_IMAGE = 'https://d2o2utebsixu4k.cloudfront.net/'

fixed_files = 0
total_replacements = 0

def fix_file(filepath):
    global fixed_files, total_replacements
    try:
        with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
        
        original = content
        replacements = 0
        
        # Fix broken CDN image URLs (unencoded)
        if BROKEN_CDN_PREFIX in content:
            count = content.count(BROKEN_CDN_PREFIX)
            content = content.replace(BROKEN_CDN_PREFIX, CORRECT_CDN + '/')
            replacements += count
        
        # Fix broken CDN image URLs (HTML-encoded & -> &amp;)
        if BROKEN_CDN_PREFIX_ENCODED in content:
            count = content.count(BROKEN_CDN_PREFIX_ENCODED)
            content = content.replace(BROKEN_CDN_PREFIX_ENCODED, CORRECT_CDN + '/')
            replacements += count
        
        # Fix broken relative image paths (../images.unsplash...)
        if BROKEN_META_IMAGE in content:
            count = content.count(BROKEN_META_IMAGE)
            content = content.replace(BROKEN_META_IMAGE, CORRECT_META_IMAGE)
            replacements += count
        
        # Fix broken preconnect href
        broken_preconnect_href = f'href="{BROKEN_CDN_PREFIX}"'
        correct_preconnect_href = f'href="{CORRECT_PRECONNECT}"'
        if broken_preconnect_href in content:
            count = content.count(broken_preconnect_href)
            content = content.replace(broken_preconnect_href, correct_preconnect_href)
            replacements += count
        
        if replacements > 0 and content != original:
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(content)
            fixed_files += 1
            total_replacements += replacements
            print(f"  Fixed {replacements} occurrences in: {os.path.relpath(filepath, BASE_DIR)}")
    
    except Exception as e:
        print(f"  ERROR processing {filepath}: {e}")

print("=" * 60)
print("Step 1: Fixing broken image CDN URLs across all PHP files")
print("=" * 60)

for root, dirs, files in os.walk(BASE_DIR):
    # Skip hidden dirs and node_modules etc
    dirs[:] = [d for d in dirs if not d.startswith('.') and d not in ['node_modules', '__pycache__']]
    for filename in files:
        if filename.endswith(('.php', '.html')):
            fix_file(os.path.join(root, filename))

print(f"\nDone! Fixed {total_replacements} image URL replacements across {fixed_files} files.\n")

# -----------------------------------------------------------------------
# Step 2: Fix the mega menu in header.php
# -----------------------------------------------------------------------
print("=" * 60)
print("Step 2: Fixing mega menu in header.php")
print("=" * 60)

header_path = os.path.join(BASE_DIR, 'header.php')

with open(header_path, 'r', encoding='utf-8') as f:
    header = f.read()

# Mega menu JS to inject before </head> OR at the very end of the file
# This JS handles the "All Courses" panel toggle AND the hover dropdowns
MEGA_MENU_JS = """
<!-- SureCertificate Mega Menu Fix -->
<style>
/* Fix mega menu for All Courses panel */
[data-megamenu-panel] { display: none !important; }
[data-megamenu-panel].mega-open { display: flex !important; }
/* Fix hover dropdowns */
.sc-dropdown { display: none !important; }
.sc-dropdown-trigger:hover .sc-dropdown,
.sc-dropdown-group:hover .sc-dropdown { display: block !important; }
</style>
<script>
(function() {
  document.addEventListener('DOMContentLoaded', function() {

    // ---- 1. "All Courses" mega panel (the big sidebar menu) ----
    // The trigger is the div with "All Courses" text + icon-menu
    var allCourseTriggers = document.querySelectorAll(
      '.cursor-pointer.rounded-lg.border.border-neutral-300'
    );
    allCourseTriggers.forEach(function(trigger) {
      var panel = trigger.parentElement
        ? trigger.parentElement.querySelector('.hidden[class*="absolute"]')
        : null;
      if (!panel) return;
      panel.style.display = 'none';
      trigger.addEventListener('click', function(e) {
        e.stopPropagation();
        var isOpen = panel.style.display === 'flex';
        panel.style.display = isOpen ? 'none' : 'flex';
      });
      document.addEventListener('click', function() {
        panel.style.display = 'none';
      });
      panel.addEventListener('click', function(e) { e.stopPropagation(); });
    });

    // ---- 2. Hover dropdowns (AI Courses, Enterprise, Resources) ----
    // These use Tailwind group-hover:block which doesn't work without Tailwind JIT
    // We replicate the behaviour with JS hover
    var groups = document.querySelectorAll('.group');
    groups.forEach(function(group) {
      var dropdown = group.querySelector(
        '.absolute.z-50.flex-col, .absolute.z-\\[50\\].flex-col'
      );
      if (!dropdown) return;

      // Force-remove "hidden" class and manage with display style
      dropdown.classList.remove('hidden');
      dropdown.style.display = 'none';

      group.addEventListener('mouseenter', function() {
        dropdown.style.display = 'flex';
        dropdown.style.flexDirection = 'column';
      });
      group.addEventListener('mouseleave', function() {
        dropdown.style.display = 'none';
      });
    });

  });
})();
</script>
"""

# Check if we already injected the fix
if 'SureCertificate Mega Menu Fix' in header:
    print("  Mega menu fix already present in header.php — skipping.")
else:
    # Inject just before </head>
    if '</head>' in header:
        header = header.replace('</head>', MEGA_MENU_JS + '</head>', 1)
        print("  Injected mega menu fix before </head>")
    else:
        # Append at the end
        header += MEGA_MENU_JS
        print("  Appended mega menu fix at end of header.php")

    with open(header_path, 'w', encoding='utf-8') as f:
        f.write(header)
    print("  header.php updated successfully.")

print("\nAll done! Summary:")
print(f"  - Image CDN URLs fixed: {total_replacements} occurrences in {fixed_files} files")
print("  - Mega menu JS fix: injected into header.php")
