<?php
// A function to resize an image, maintaining aspect ratio.
// It will resize to fit within the max_width and max_height boundaries.
function resizeImage($source_path, $destination_path, $max_width = 1200, $max_height = 1200, $quality = 85) {
    
    // Get original image dimensions and type
    list($width, $height, $type) = getimagesize($source_path);

    // If the image is already small enough, just copy it and return
    if ($width <= $max_width && $height <= $max_height) {
        return move_uploaded_file($source_path, $destination_path);
    }

    // Calculate new dimensions while preserving aspect ratio
    $ratio = $width / $height;
    if ($max_width / $max_height > $ratio) {
        $new_width = round($max_height * $ratio); // FIX: Explicitly round the float to an integer
        $new_height = $max_height;
    } else {
        $new_height = round($max_width / $ratio); // FIX: Explicitly round the float to an integer
        $new_width = $max_width;
    }

    // Create a new true color image (the canvas)
    $new_image = imagecreatetruecolor($new_width, $new_height);

    // Create image resource from the source file based on its type
    switch ($type) {
        case IMAGETYPE_JPEG:
            $source_image = imagecreatefromjpeg($source_path);
            break;
        case IMAGETYPE_PNG:
            $source_image = imagecreatefrompng($source_path);
            // Preserve transparency for PNGs
            imagealphablending($new_image, false);
            imagesavealpha($new_image, true);
            $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
            imagefilledrectangle($new_image, 0, 0, $new_width, $new_height, $transparent);
            break;
        case IMAGETYPE_GIF:
            $source_image = imagecreatefromgif($source_path);
            break;
        default:
            return false; // Unsupported image type
    }
    
    if (!$source_image) {
        return false;
    }

    // Copy and resize the old image to the new canvas
    imagecopyresampled($new_image, $source_image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    // Save the new image to the destination path
    $success = false;
    switch ($type) {
        case IMAGETYPE_JPEG:
            $success = imagejpeg($new_image, $destination_path, $quality);
            break;
        case IMAGETYPE_PNG:
            $success = imagepng($new_image, $destination_path, 9); // Compression level 0-9
            break;
        case IMAGETYPE_GIF:
            $success = imagegif($new_image, $destination_path);
            break;
    }

    // Free up memory
    imagedestroy($source_image);
    imagedestroy($new_image);

    return $success;
}
?>
