<?php
/**
 * Image Optimization Script for Finggu Infotech
 * 
 * This script compresses and optimizes images in the assets directory.
 * It creates WebP versions of images while maintaining the original files.
 */

// Set error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check if Imagick is installed
if (!extension_loaded('imagick')) {
    die('Error: Imagick extension is not installed. Please install it first.');
}

// Configuration
$sourceDir = __DIR__ . '/assets/images/';
$quality = 85; // Image quality (0-100)
$maxWidth = 2000; // Maximum width for resizing large images
$maxHeight = 2000; // Maximum height for resizing large images

// Supported image formats
$supportedFormats = ['jpg', 'jpeg', 'png', 'gif'];

/**
 * Optimize an image
 */
function optimizeImage($sourcePath, $targetPath, $quality, $maxWidth, $maxHeight) {
    try {
        $extension = strtolower(pathinfo($sourcePath, PATHINFO_EXTENSION));
        $targetPath = str_replace('.' . $extension, '.webp', $targetPath);
        
        // Skip if WebP version already exists
        if (file_exists($targetPath)) {
            return "Skipped (WebP exists): " . basename($sourcePath) . "\n";
        }
        
        $image = new Imagick($sourcePath);
        
        // Convert to sRGB color space
        if ($image->getImageColorspace() !== Imagick::COLORSPACE_SRGB) {
            $image->transformImageColorspace(Imagick::COLORSPACE_SRGB);
        }
        
        // Strip metadata
        $image->stripImage();
        
        // Set image quality
        $image->setImageCompressionQuality($quality);
        
        // Set image format to WebP
        $image->setImageFormat('webp');
        
        // Set WebP specific options
        $image->setOption('webp:method', '6');  // Compression method (0-6, higher is better but slower)
        $image->setOption('webp:lossless', 'false');
        $image->setOption('webp:auto-filter', 'true');
        
        // Save the optimized image
        $image->writeImage($targetPath);
        $image->clear();
        $image->destroy();
        
        return "Optimized: " . basename($sourcePath) . " -> " . basename($targetPath) . "\n";
    } catch (Exception $e) {
        return "Error optimizing " . basename($sourcePath) . ": " . $e->getMessage() . "\n";
    }
}

// Process images in the directory
function processDirectory($dir, $quality, $maxWidth, $maxHeight) {
    global $supportedFormats;
    $result = "";
    
    if (!is_dir($dir)) {
        return "Directory not found: $dir\n";
    }
    
    $files = scandir($dir);
    
    foreach ($files as $file) {
        if ($file === '.' || $file === '..') {
            continue;
        }
        
        $path = $dir . '/' . $file;
        
        if (is_dir($path)) {
            // Recursively process subdirectories
            $result .= processDirectory($path, $quality, $maxWidth, $maxHeight);
        } else {
            // Process files
            $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
            
            if (in_array($extension, $supportedFormats)) {
                $result .= optimizeImage($path, $path, $quality, $maxWidth, $maxHeight);
            }
        }
    }
    
    return $result;
}

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

// Process the images directory
$result = processDirectory($sourceDir, $quality, $maxWidth, $maxHeight);

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

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

// Instructions for updating HTML to use WebP images
echo "\nTo use the optimized WebP images, update your HTML like this:\n";
echo "<picture>\n";
echo "  <source srcset='image.webp' type='image/webp'>\n";
echo "  <img src='image.jpg' alt='Description'>\n";
echo "</picture>\n";
?>
