<?php
/**
 * Plugin Name: ZedSuite WebP Converter
 * Description: Automatically converts uploaded JPEG and PNG images to WebP with 75% compression, adds them to the media library, and deletes the original file.
 * Version: 0.1.1
 * Author: Ze'ev Schurmann
 * License: GPL3 or later
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

add_filter('wp_handle_upload', 'zs_convert_to_webp', 10, 2);

function zs_convert_to_webp($upload, $context) {
    $file_path = $upload['file'];
    $file_type = $upload['type'];

    if (!in_array($file_type, ['image/jpeg', 'image/png'])) {
        return $upload; // Skip non-JPEG/PNG files
    }

    $image = ($file_type === 'image/jpeg') ? imagecreatefromjpeg($file_path) : imagecreatefrompng($file_path);
    if (!$image) {
        return $upload; // If image creation fails, return original upload
    }

    $webp_path = preg_replace('/\.(jpe?g|png)$/i', '.webp', $file_path);

    if (imagewebp($image, $webp_path, 75)) {
        imagedestroy($image);

        // Validate WebP file
        if (file_exists($webp_path) && getimagesize($webp_path)['mime'] === 'image/webp') {
            unlink($file_path); // Delete the original file

            // Update media library to point to the WebP file
            $upload['file'] = $webp_path;
            $upload['type'] = 'image/webp';
            $upload['url']  = preg_replace('/\.(jpe?g|png)$/i', '.webp', $upload['url']);
        } else {
            unlink($webp_path); // Remove invalid WebP file
            add_action('admin_notices', function () {
                echo '<div class="notice notice-error"><p><strong>Error:</strong> Image conversion to WebP failed. The original file has been kept.</p></div>';
            });
        }
    }

    return $upload;
}


