<?php
/**
 * Fix Image Paths Script
 * 
 * This script updates all image paths in HTML/PHP files to use the correct base URL.
 */

$baseUrl = 'https://www.finggu.com';
$directories = [
    '.',  // Current directory
    'admin',
    'includes',
    'services'
];

$fileExtensions = ['php', 'html'];
$updatedFiles = 0;

// Patterns to match different types of image paths
$patterns = [
    // src="https://www.finggu.com/path/to/image.jpg"
    '/(src=["\'])(?!https?:\/\/|data:)([^"\']+)(["\'])/i',
    // src="https://www.finggu.com/path/to/image.jpg"
    '/(src=["\'])\/+([^"\']+)(["\'])/i',
    // url(https://www.finggu.com/path/to/image.jpg)
    '/(url\(["\']?)(?!https?:\/\/|data:)([^"\')]+)(["\']?\))/i',
    // url(https://www.finggu.com/path/to/image.jpg)
    '/(url\(["\']?)\/+([^"\')]+)(["\']?\))/i',
];

foreach ($directories as $directory) {
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
    
    foreach ($iterator as $file) {
        if ($file->isDir()) continue;
        
        $ext = strtolower(pathinfo($file->getPathname(), PATHINFO_EXTENSION));
        if (!in_array($ext, $fileExtensions)) continue;
        
        $content = file_get_contents($file->getPathname());
        $originalContent = $content;
        
        // Fix image paths
        foreach ($patterns as $pattern) {
            $content = preg_replace_callback($pattern, function($matches) use ($baseUrl) {
                $path = ltrim($matches[2], '/');
                return $matches[1] . rtrim($baseUrl, '/') . '/' . $path . $matches[3];
            }, $content);
        }
        
        // Save the file if changes were made
        if ($content !== $originalContent) {
            file_put_contents($file->getPathname(), $content);
            $updatedFiles++;
            echo "Updated: " . $file->getPathname() . "\n";
        }
    }
}

echo "\nDone! Updated $updatedFiles files.\n";
