<?php

/**
 * Image optimization hooks
 */

function kaz_optimize_image_upload($upload)
{
    // Bail if there was an upload error
    if (isset($upload['error'])) {
        return $upload;
    }

    $file_path = $upload['file'];
    $mime_type = $upload['type'];

    // Check if file is a supported image type (jpeg, png)
    if (in_array($mime_type, array('image/jpeg', 'image/jpg', 'image/png'))) {
        if (class_exists('Imagick')) {
            try {
                $image = new Imagick($file_path);
                $width = $image->getImageWidth();

                // Apply compression based on width
                if ($width > 1400) {
                    $image->setImageCompressionQuality(85);
                } else {
                    $image->setImageCompressionQuality(70);
                }

                // Convert to WebP
                $image->setImageFormat('webp');

                $path_info = pathinfo($file_path);
                $new_file_path = $path_info['dirname'] . '/' . $path_info['filename'] . '.webp';

                // Save new WebP file
                if ($image->writeImage($new_file_path)) {
                    // Destroy Imagick object
                    $image->clear();
                    $image->destroy();

                    // Delete the original file
                    if (file_exists($file_path) && $file_path !== $new_file_path) {
                        unlink($file_path);
                    }

                    // Update upload info
                    $upload['file'] = $new_file_path;

                    // Replace extension in URL
                    $old_url_extension = pathinfo($upload['url'], PATHINFO_EXTENSION);
                    $upload['url'] = substr($upload['url'], 0, -strlen($old_url_extension)) . 'webp';

                    $upload['type'] = 'image/webp';
                }
            } catch (Exception $e) {
                // If Imagick throws an exception, fail gracefully and keep the original file
            }
        }
    }

    return $upload;
}
add_filter('wp_handle_upload', 'kaz_optimize_image_upload');
