<?php

/**
 * JCOGS Image Pro - GD-Specific Blur Filter
 * =========================================
 * High-performance blur implementation using GD's native imagefilter
 * 
 * @category   ExpressionEngine Add-on
 * @package    JCOGS Image Pro
 * @author     JCOGS Design <contact@jcogs.net>
 * @copyright  Copyright (c) 2021 - 2025 JCOGS Design
 * @license    https://jcogs.net/add-ons/license/jcogs_img_pro
 * @version    2.0.6
 * @link       https://JCOGS.net/
 * @since      2.0.0
 */

namespace JCOGSDesign\JCOGSImagePro\Filters\Gd;

use Imagine\Image\ImageInterface;
use Imagine\Gd\Imagine;

/**
 * GD-Specific Blur Filter Class
 * 
 * Uses PHP's native imagefilter function with IMG_FILTER_GAUSSIAN_BLUR
 * for optimal performance when working with GD image resources.
 */
class Blur
{
    /**
     * Apply GD-native blur filter
     * 
     * Uses imagefilter with IMG_FILTER_GAUSSIAN_BLUR for maximum performance.
     * 
     * @param ImageInterface $image Source image (must be GD image)
     * @param array $params Filter parameters
     * @return ImageInterface Processed image
     */
    public function apply(ImageInterface $image, array $params = []): ImageInterface
    {
        // Get the GD resource from the Imagine image
        $gd_resource = $image->getGdResource();
        
        if (!is_resource($gd_resource) && !is_object($gd_resource)) {
            throw new \RuntimeException('Invalid GD resource for blur filter');
        }
        
        // Get blur intensity from parameters (default 1)
        $intensity = isset($params['intensity']) ? (int) $params['intensity'] : 1;
        $intensity = max(1, min(10, $intensity)); // Clamp between 1-10
        
        // Apply GD gaussian blur multiple times for stronger effect
        for ($i = 0; $i < $intensity; $i++) {
            imagefilter($gd_resource, IMG_FILTER_GAUSSIAN_BLUR);
        }
        
        // Convert back to Imagine image format
        $imagine = new Imagine();
        return $imagine->load(stream_get_contents($this->gd_resource_to_stream($gd_resource)));
    }
    
    /**
     * Convert GD resource to stream for Imagine
     * 
     * @param resource $gd_resource
     * @return resource
     */
    private function gd_resource_to_stream($gd_resource)
    {
        $stream = fopen('php://temp', 'r+');
        
        // Save as PNG to preserve quality
        ob_start();
        imagepng($gd_resource);
        $image_data = ob_get_clean();
        
        fwrite($stream, $image_data);
        rewind($stream);
        
        return $stream;
    }
}
