<?php
/**
 * Fix HTML Comments Script
 * 
 * This script fixes invalid HTML comments in certificate template files.
 * The main issue is that some templates use <\!-- which should be <!-- instead.
 * 
 * Usage: php fix-html-comments.php
 */

// Load WordPress if possible
if (file_exists(dirname(__DIR__) . '/wordpress/wp-load.php')) {
    require_once dirname(__DIR__) . '/wordpress/wp-load.php';
    $is_wp_loaded = true;
} else {
    $is_wp_loaded = false;
}

// Define the plugin directory
if ($is_wp_loaded && defined('WP_PLUGIN_DIR')) {
    $plugin_dir = WP_PLUGIN_DIR . '/hvac-community-events';
} else {
    $plugin_dir = dirname(__DIR__) . '/wordpress/wp-content/plugins/hvac-community-events';
}

// Define the templates directory
$templates_dir = $plugin_dir . '/templates/certificates';

// Check if the directory exists
if (!file_exists($templates_dir)) {
    echo "Error: Templates directory not found: {$templates_dir}\n";
    exit(1);
}

// Get all PHP files in the templates directory
$template_files = glob($templates_dir . '/*.php');

if (empty($template_files)) {
    echo "Error: No template files found in {$templates_dir}\n";
    exit(1);
}

echo "Found " . count($template_files) . " template files. Processing...\n";

// Process each template file
$total_fixed = 0;
foreach ($template_files as $file) {
    echo "Processing file: " . basename($file) . "...\n";
    
    // Read the file content
    $content = file_get_contents($file);
    if ($content === false) {
        echo "  Error: Could not read file: {$file}\n";
        continue;
    }
    
    // Check if the file contains invalid HTML comments
    if (strpos($content, '<\!--') !== false) {
        // Create a backup of the original file
        $backup_file = $file . '.bak.' . date('YmdHis');
        if (copy($file, $backup_file)) {
            echo "  Created backup: " . basename($backup_file) . "\n";
        } else {
            echo "  Warning: Could not create backup of {$file}\n";
        }
        
        // Replace invalid HTML comments
        $fixed_content = str_replace('<\!--', '<!--', $content);
        
        // Write the fixed content back to the file
        if (file_put_contents($file, $fixed_content) !== false) {
            echo "  Success: Fixed HTML comments in " . basename($file) . "\n";
            $total_fixed++;
        } else {
            echo "  Error: Could not write to file: {$file}\n";
        }
    } else {
        echo "  No invalid HTML comments found in " . basename($file) . "\n";
    }
}

echo "\nSummary: Fixed {$total_fixed} of " . count($template_files) . " template files.\n";

if ($is_wp_loaded) {
    echo "Clearing WordPress cache...\n";
    wp_cache_flush();
    echo "Cache cleared.\n";
}

echo "Done!\n";