<?php
// Define all folders that contain images
$target_folders = ['assets/img', 'uploads'];

foreach ($target_folders as $folder) {
    if (!is_dir($folder)) continue;

    $dir = new RecursiveDirectoryIterator($folder);
    foreach (new RecursiveIteratorIterator($dir) as $file) {
        // Skip directories and non-image files
        if ($file->isDir() || !in_array(strtolower($file->getExtension()), ['jpg', 'jpeg', 'png'])) {
            continue;
        }

        $source = $file->getPathname();
        $destination = preg_replace('/\.(jpg|jpeg|png)$/i', '.webp', $source);

        // Only convert if the WebP version doesn't exist yet
        if (!file_exists($destination)) {
            $info = getimagesize($source);
            if ($info['mime'] == 'image/png') {
                $image = imagecreatefrompng($source);
                imagepalettetotruecolor($image);
                imagealphablending($image, true);
                imagesavealpha($image, true);
            } else {
                $image = imagecreatefromjpeg($source);
            }
            
            imagewebp($image, $destination, 80);
            imagedestroy($image);
            echo "Converted: $source\n";
        }
    }
}
?>