<?php
/**
 * Image Processor for StaticQ
 * 
 * Handles local image processing operations.
 * 
 * @package suspended-cloud/cloudflare-media-offload
 * @since 2.0.0
 */

if (!defined('ABSPATH')) {
    exit;
}

class SQMedia_Image_Processor {
    
    /**
     * Generate WebP version of an image
     */
    public static function generate_webp(string $source_path, string $dest_path = null, int $quality = null): ?string {
        if (!file_exists($source_path)) {
            return null;
        }
        
        if ($dest_path === null) {
            $dest_path = preg_replace('/\.(jpe?g|png|gif)$/i', '.webp', $source_path);
        }
        
        if ($quality === null) {
            $quality = SQMedia_Settings::get_quality_value();
        }
        
        $editor = wp_get_image_editor($source_path);
        
        if (is_wp_error($editor)) {
            sqmedia()->log('WebP generation failed: ' . $editor->get_error_message(), 'error');
            return null;
        }
        
        $editor->set_quality($quality);
        $result = $editor->save($dest_path, 'image/webp');

        if (is_wp_error($result)) {
            sqmedia()->log('WebP save failed: ' . $result->get_error_message(), 'error');
            return null;
        }

        return $result['path'];
    }
    
    /**
     * Resize an image
     */
    public static function resize(string $source_path, int $width, int $height, bool $crop = false): ?array {
        if (!file_exists($source_path)) {
            return null;
        }
        
        $editor = wp_get_image_editor($source_path);
        
        if (is_wp_error($editor)) {
            return null;
        }
        
        $resized = $editor->resize($width, $height, $crop);
        
        if (is_wp_error($resized)) {
            return null;
        }
        
        // Generate output filename
        $ext = pathinfo($source_path, PATHINFO_EXTENSION);
        $name = pathinfo($source_path, PATHINFO_FILENAME);
        $dir = dirname($source_path);
        
        $new_dims = $editor->get_size();
        $new_name = $name . '-' . $new_dims['width'] . 'x' . $new_dims['height'] . '.' . $ext;
        $dest_path = $dir . '/' . $new_name;
        
        $saved = $editor->save($dest_path);
        
        if (is_wp_error($saved)) {
            return null;
        }
        
        return [
            'path' => $saved['path'],
            'file' => $saved['file'],
            'width' => $saved['width'],
            'height' => $saved['height'],
            'mime_type' => $saved['mime-type'],
        ];
    }
    
    /**
     * Get image dimensions
     */
    public static function get_dimensions(string $path): ?array {
        if (!file_exists($path)) {
            return null;
        }
        
        $size = @getimagesize($path);
        
        if (!$size) {
            return null;
        }
        
        return [
            'width' => $size[0],
            'height' => $size[1],
            'mime_type' => $size['mime'],
        ];
    }
    
    /**
     * Check if image type supports WebP conversion
     */
    public static function supports_webp(string $mime_type): bool {
        switch ($mime_type) {
            case 'image/jpeg':
            case 'image/jpg':
                return true;
                
            case 'image/png':
                return SQMedia_Settings::is_webp_for_png();
                
            case 'image/gif':
                return SQMedia_Settings::is_webp_for_gif();
                
            default:
                return false;
        }
    }
    
    /**
     * Get WebP filename from original
     */
    public static function get_webp_filename(string $filename): string {
        return preg_replace('/\.(jpe?g|png|gif)$/i', '.webp', $filename);
    }
    
    /**
     * Optimize image quality
     */
    public static function optimize(string $path, int $quality = 82): bool {
        if (!file_exists($path)) {
            return false;
        }
        
        $editor = wp_get_image_editor($path);
        
        if (is_wp_error($editor)) {
            return false;
        }
        
        $editor->set_quality($quality);
        $result = $editor->save($path);
        
        return !is_wp_error($result);
    }
}
