<?php
/**
 * Comment Image Boost - Image Utilities (Free)
 * Core image processing functions used by both free and premium versions.
 *
 * @package CommentImageBoost
 * @version 1.0.16
 */

if (!defined('ABSPATH')) {
    die('You are not allowed to call this page directly.');
}

/**
 * Load image resource from file path based on MIME type
 *
 * @param string $file_path Path to the image file
 * @param string $mime_type MIME type of the image
 * @return resource|false Image resource or false on failure
 */
function ciboost_load_image($file_path, $mime_type) {
    try {
        switch ($mime_type) {
            case 'image/jpeg':
            case 'image/jpg':
                return @imagecreatefromjpeg($file_path);

            case 'image/png':
                return @imagecreatefrompng($file_path);

            case 'image/gif':
                return @imagecreatefromgif($file_path);

            case 'image/webp':
                if (function_exists('imagecreatefromwebp')) {
                    return @imagecreatefromwebp($file_path);
                }
                return false;

            default:
                return false;
        }
    } catch (Exception $e) {
        ciboost_log('Error loading image: ' . $e->getMessage());
        return false;
    }
}

/**
 * Fix image orientation based on EXIF data
 * Handles images from mobile devices that may be rotated
 *
 * @param string $file_path Path to the image file
 * @param resource $source Image resource
 * @return resource Corrected image resource
 */
function ciboost_fix_image_orientation($file_path, $source) {
    try {
        if (!function_exists('exif_read_data')) {
            return $source;
        }

        $exif = @exif_read_data($file_path);

        if (empty($exif['Orientation'])) {
            return $source;
        }

        switch ($exif['Orientation']) {
            case 3:
                $source = imagerotate($source, 180, 0);
                break;

            case 6:
                $source = imagerotate($source, -90, 0);
                break;

            case 8:
                $source = imagerotate($source, 90, 0);
                break;
        }

        ciboost_log('Image orientation fixed based on EXIF data');
        return $source;

    } catch (Exception $e) {
        ciboost_log('Error fixing image orientation: ' . $e->getMessage());
        return $source;
    }
}

/**
 * Save image resource to file based on MIME type
 *
 * @param resource $image Image resource
 * @param string $file_path Destination file path
 * @param string $mime_type MIME type of the image
 * @param int $quality Quality setting (0-100 for JPEG/WebP, 0-9 for PNG)
 * @param bool $progressive Enable progressive/interlaced encoding
 * @return bool True on success, false on failure
 */
function ciboost_save_image($image, $file_path, $mime_type, $quality = 85, $progressive = true) {
    try {
        // Enable progressive/interlaced images
        if ($progressive) {
            imageinterlace($image, 1);
        }

        $success = false;

        switch ($mime_type) {
            case 'image/jpeg':
            case 'image/jpg':
                // JPEG quality: 0-100 (higher is better)
                $jpeg_quality = max(0, min(100, $quality));
                $success = imagejpeg($image, $file_path, $jpeg_quality);
                break;

            case 'image/png':
                // PNG compression: 0-9 (0 = no compression, 9 = max compression)
                // Convert quality (0-100) to PNG compression level (0-9)
                $png_compression = floor((100 - $quality) / 11);
                $png_compression = max(0, min(9, $png_compression));

                // Preserve transparency
                imagealphablending($image, false);
                imagesavealpha($image, true);

                $success = imagepng($image, $file_path, $png_compression);
                break;

            case 'image/gif':
                // GIF doesn't support quality, just save
                // Preserve transparency
                imagealphablending($image, false);
                imagesavealpha($image, true);

                $success = imagegif($image, $file_path);
                break;

            case 'image/webp':
                if (function_exists('imagewebp')) {
                    $webp_quality = max(0, min(100, $quality));

                    // Preserve transparency for WebP
                    imagealphablending($image, false);
                    imagesavealpha($image, true);

                    $success = imagewebp($image, $file_path, $webp_quality);
                }
                break;
        }

        return $success;

    } catch (Exception $e) {
        ciboost_log('Error saving image: ' . $e->getMessage());
        return false;
    }
}

/**
 * Convert memory size string to bytes
 *
 * @param string $size Memory size (e.g., "256M", "1G")
 * @return int Size in bytes
 */
function ciboost_parse_memory_size($size) {
    $unit = strtoupper(substr($size, -1));
    $value = (int) $size;

    switch ($unit) {
        case 'G':
            $value *= 1024;
        case 'M':
            $value *= 1024;
        case 'K':
            $value *= 1024;
    }

    return $value;
}

/**
 * Strip embedded image metadata by re-saving the image resource.
 * This removes EXIF/GPS chunks from formats supported by GD while preserving pixels.
 *
 * @param string $file_path Path to the image file
 * @param int|null $quality Optional output quality
 * @return bool True on success, false on failure
 */
function ciboost_strip_image_metadata($file_path, $quality = null) {
    try {
        if (!extension_loaded('gd') || !$file_path || !file_exists($file_path)) {
            return false;
        }

        $image_info = @getimagesize($file_path);
        if ($image_info === false || empty($image_info['mime'])) {
            return false;
        }

        $mime_type = $image_info['mime'];
        if (!in_array($mime_type, array('image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'), true)) {
            return false;
        }

        $source = ciboost_load_image($file_path, $mime_type);
        if ($source === false || $source === null) {
            return false;
        }

        if ($quality === null) {
            $quality = 85;
        }

        $source = ciboost_fix_image_orientation($file_path, $source);
        $success = ciboost_save_image($source, $file_path, $mime_type, $quality, true);
        imagedestroy($source);

        if ($success) {
            ciboost_log('Image metadata stripped: ' . basename($file_path));
        }

        return $success;

    } catch (Exception $e) {
        ciboost_log('Error stripping image metadata: ' . $e->getMessage());
        return false;
    }
}
