<?php
/**
 * HTML Image Updater for Finggu Infotech
 * 
 * This script updates image tags in HTML/PHP files to use modern formats (WebP) with fallbacks.
 * It also adds lazy loading and other performance optimizations.
 */

// Configuration
$directory = __DIR__; // Current directory
$imageDir = 'assets/images/';
$backup = true; // Create backup before making changes

// Supported image formats to process
$imageFormats = ['jpg', 'jpeg', 'png', 'gif'];

// File patterns to process
$filePatterns = ['*.php', '*.html'];

/**
 * Get WebP version of an image if it exists
 */
function getWebpPath($imagePath) {
    $webpPath = preg_replace('/\.(jpg|jpeg|png|gif)$/i', '.webp', $imagePath);
    return file_exists($webpPath) ? $webpPath : null;
}

/**
 * Process a single file
 */
function processFile($filePath) {
    global $imageDir, $backup;
    
    // Skip if not a file or not readable
    if (!is_file($filePath) || !is_readable($filePath)) {
        return "Skipped (not readable): $filePath\n";
    }
    
    // Read file content
    $content = file_get_contents($filePath);
    if ($content === false) {
        return "Error reading file: $filePath\n";
    }
    
    // Create backup if enabled
    if ($backup) {
        $backupPath = $filePath . '.bak';
        if (!file_exists($backupPath)) {
            file_put_contents($backupPath, $content);
        }
    }
    
    // Find all image tags
    $pattern = '/<img\s+([^>]*)src=[\'"]([^\'"]+)[\'"]([^>]*)>/i';
    $updated = 0;
    
    $newContent = preg_replace_callback($pattern, function($matches) use (&$updated) {
        $before = $matches[1];
        $src = $matches[2];
        $after = $matches[3];
        
        // Skip if already has a picture parent or is a data URI
        if (strpos($before, 'picture') !== false || strpos($src, 'data:image') === 0) {
            return $matches[0];
        }
        
        // Skip if not a local image
        if (strpos($src, 'http') === 0 || strpos($src, '//') === 0) {
            return $matches[0];
        }
        
        // Get file info
        $pathInfo = pathinfo($src);
        $extension = strtolower($pathInfo['extension'] ?? '');
        
        // Skip if not a supported image format
        if (!in_array($extension, ['jpg', 'jpeg', 'png', 'gif'])) {
            return $matches[0];
        }
        
        // Check if WebP version exists
        $webpPath = getWebpPath($src);
        
        if ($webpPath) {
            // Extract existing attributes
            $attributes = [];
            
            // Get existing alt text
            preg_match('/alt=[\'"]([^\'"]*)[\'"]/i', $after, $altMatch);
            $altText = $altMatch[1] ?? '';
            
            // Get existing class
            preg_match('/class=[\'"]([^\'"]*)[\'"]/i', $after, $classMatch);
            $class = $classMatch[1] ?? '';
            
            // Get existing width/height
            preg_match('/width=[\'"]([^\'"\s>]*)[\'"]/i', $after, $widthMatch);
            $width = $widthMatch[1] ?? '';
            
            preg_match('/height=[\'"]([^\'"\s>]*)[\'"]/i', $after, $heightMatch);
            $height = $heightMatch[1] ?? '';
            
            // Get loading attribute (or add lazy loading)
            preg_match('/loading=[\'"]([^\'"\s>]*)[\'"]/i', $after, $loadingMatch);
            $loading = $loadingMatch[1] ?? 'lazy';
            
            // Remove attributes that will be in the new img tag
            $after = preg_replace([
                '/\s*alt=[\'"][^\'"]*[\'"]/i',
                '/\s*class=[\'"][^\'"]*[\'"]/i',
                '/\s*width=[\'"][^\'"\s>]*[\'"]/i',
                '/\s*height=[\'"][^\'"\s>]*[\'"]/i',
                '/\s*loading=[\'"][^\'"\s>]*[\'"]/i'
            ], '', $after);
            
            // Build new picture element
            $newTag = "<picture>\n";
            $newTag .= "  <source srcset=\"$webpPath\" type=\"image/webp\">\n";
            $newTag .= "  <img src=\"$src\" alt=\"$altText\" class=\"$class\" loading=\"$loading\"";
            
            // Add width and height if they exist
            if ($width) $newTag .= " width=\"$width\"";
            if ($height) $newTag .= " height=\"$height\"";
            
            // Add remaining attributes and close tag
            $newTag .= "$after>";
            $newTag .= "\n</picture>";
            
            $updated++;
            return $newTag;
        }
        
        // If no WebP version, just add loading="lazy" if not present
        if (stripos($after, 'loading=') === false) {
            return "<img$before src=\"$src\"$after loading=\"lazy\">";
        }
        
        return $matches[0];
    }, $content);
    
    // Save changes if updates were made
    if ($newContent !== $content) {
        file_put_contents($filePath, $newContent);
        return "Updated $updated images in: $filePath\n";
    }
    
    return "No changes needed: $filePath\n";
}

/**
 * Process directory recursively
 */
function processDirectory($dir) {
    global $filePatterns;
    
    $result = "";
    
    // Skip certain directories
    $skipDirs = ['/vendor', '/node_modules', '/.git', '/admin', '/includes'];
    foreach ($skipDirs as $skipDir) {
        if (strpos($dir, $skipDir) !== false) {
            return "Skipped directory: $dir\n";
        }
    }
    
    // Process files matching patterns
    foreach ($filePatterns as $pattern) {
        $files = glob("$dir/$pattern");
        
        foreach ($files as $file) {
            $result .= processFile($file);
        }
    }
    
    // Process subdirectories
    $dirs = glob("$dir/*", GLOB_ONLYDIR);
    foreach ($dirs as $subdir) {
        $result .= processDirectory($subdir);
    }
    
    return $result;
}

// Run the script
header('Content-Type: text/plain');
echo "Starting HTML image optimization...\n";
$startTime = microtime(true);

// Process the directory
$result = processDirectory($directory);

$endTime = microtime(true);
$executionTime = round($endTime - $startTime, 2);

echo "\nOptimization complete!\n";
echo "Execution time: $executionTime seconds\n\n";
echo $result;

echo "\nTo complete the optimization, you should now run the optimize-images.php script to generate WebP versions of your images.\n";
?>
