<?php
/*
  Plugin Name: WebP Image Converter XD
  Description: Transform your website's image quality and loading speed with WebP – the modern, high-efficiency image format. By converting your images to WebP, you'll enjoy smaller file sizes without compromising visual quality. Say goodbye to slow loading times and hello to faster, smoother user experiences. Embrace the power of WebP for a sleeker, more efficient website today!
  Version: 1.1
  Author: Xpert Dezine IT
  Author URI: https://facebook.com/xpertdezineit
  License: GPLv2 or later
  License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/

// Hook into the image upload process
add_filter('wp_handle_upload', 'wpwebp_convert_image_to_webp');

function wpwebp_convert_image_to_webp($upload) {
    $file_path = $upload['file'];
    $file_info = wp_check_filetype($file_path);

    // Check if the uploaded file is an image
    if (strpos($file_info['type'], 'image') !== false) {
        global $wp_filesystem;

        // Ensure WP_Filesystem is available
        if (empty($wp_filesystem)) {
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            WP_Filesystem();
        }

        // Get image size and create image resource
        list($width, $height) = getimagesize($file_path);
        $file_content = $wp_filesystem->get_contents($file_path);
        $image = imagecreatefromstring($file_content);

        // Prepare the new WEBP file path
        $webp_file_path = str_replace($file_info['ext'], 'webp', $file_path);

        // Check for file name conflicts and rename if necessary
        $base_name = wp_basename($webp_file_path, '.webp');
        $directory = dirname($webp_file_path);
        $counter = 1;

        while ($wp_filesystem->exists($webp_file_path)) {
            $webp_file_path = $directory . '/' . $base_name . '-' . $counter . '.webp';
            $counter++;
        }

        // Convert image to WEBP format
        imagewebp($image, $webp_file_path, 85); // Change 85 to desired quality (0-100)

        // Update the upload array with the new WEBP file path
        $upload['file'] = $webp_file_path;
        $upload['type'] = 'image/webp';

        // Clean up
        imagedestroy($image);
    }

    return $upload;
}
